llama.cpp 422 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUBLAS
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #endif
  12. #ifdef GGML_USE_METAL
  13. # include "ggml-metal.h"
  14. #endif
  15. #ifdef GGML_USE_MPI
  16. # include "ggml-mpi.h"
  17. #endif
  18. #ifndef QK_K
  19. # ifdef GGML_QKK_64
  20. # define QK_K 64
  21. # else
  22. # define QK_K 256
  23. # endif
  24. #endif
  25. #ifdef __has_include
  26. #if __has_include(<unistd.h>)
  27. #include <unistd.h>
  28. #if defined(_POSIX_MAPPED_FILES)
  29. #include <sys/mman.h>
  30. #include <fcntl.h>
  31. #endif
  32. #if defined(_POSIX_MEMLOCK_RANGE)
  33. #include <sys/resource.h>
  34. #endif
  35. #endif
  36. #endif
  37. #if defined(_WIN32)
  38. #define WIN32_LEAN_AND_MEAN
  39. #ifndef NOMINMAX
  40. #define NOMINMAX
  41. #endif
  42. #include <windows.h>
  43. #include <io.h>
  44. #endif
  45. #include <algorithm>
  46. #include <array>
  47. #include <cassert>
  48. #include <cinttypes>
  49. #include <climits>
  50. #include <cmath>
  51. #include <cstdarg>
  52. #include <cstddef>
  53. #include <cstdint>
  54. #include <cstdio>
  55. #include <cstring>
  56. #include <ctime>
  57. #include <forward_list>
  58. #include <fstream>
  59. #include <functional>
  60. #include <initializer_list>
  61. #include <map>
  62. #include <memory>
  63. #include <mutex>
  64. #include <numeric>
  65. #include <queue>
  66. #include <random>
  67. #include <regex>
  68. #include <set>
  69. #include <sstream>
  70. #include <thread>
  71. #include <type_traits>
  72. #include <unordered_map>
  73. #if defined(_MSC_VER)
  74. #pragma warning(disable: 4244 4267) // possible loss of data
  75. #endif
  76. #ifdef __GNUC__
  77. #ifdef __MINGW32__
  78. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  79. #else
  80. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  81. #endif
  82. #else
  83. #define LLAMA_ATTRIBUTE_FORMAT(...)
  84. #endif
  85. #define LLAMA_MAX_NODES 8192
  86. #define LLAMA_MAX_EXPERTS 8
  87. //
  88. // logging
  89. //
  90. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  91. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  92. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  93. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  94. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  95. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  96. //
  97. // helpers
  98. //
  99. static size_t utf8_len(char src) {
  100. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  101. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  102. return lookup[highbits];
  103. }
  104. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  105. std::string result;
  106. for (size_t pos = 0; ; pos += search.length()) {
  107. auto new_pos = s.find(search, pos);
  108. if (new_pos == std::string::npos) {
  109. result += s.substr(pos, s.size() - pos);
  110. break;
  111. }
  112. result += s.substr(pos, new_pos - pos) + replace;
  113. pos = new_pos;
  114. }
  115. s = std::move(result);
  116. }
  117. static bool is_float_close(float a, float b, float abs_tol) {
  118. // Check for non-negative tolerance
  119. if (abs_tol < 0.0) {
  120. throw std::invalid_argument("Tolerance must be non-negative");
  121. }
  122. // Exact equality check
  123. if (a == b) {
  124. return true;
  125. }
  126. // Check for infinities
  127. if (std::isinf(a) || std::isinf(b)) {
  128. return false;
  129. }
  130. // Regular comparison using the provided absolute tolerance
  131. return std::fabs(b - a) <= abs_tol;
  132. }
  133. static void zeros(std::ofstream & file, size_t n) {
  134. char zero = 0;
  135. for (size_t i = 0; i < n; ++i) {
  136. file.write(&zero, 1);
  137. }
  138. }
  139. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  140. static std::string format(const char * fmt, ...) {
  141. va_list ap;
  142. va_list ap2;
  143. va_start(ap, fmt);
  144. va_copy(ap2, ap);
  145. int size = vsnprintf(NULL, 0, fmt, ap);
  146. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  147. std::vector<char> buf(size + 1);
  148. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  149. GGML_ASSERT(size2 == size);
  150. va_end(ap2);
  151. va_end(ap);
  152. return std::string(buf.data(), size);
  153. }
  154. //
  155. // gguf constants (sync with gguf.py)
  156. //
  157. enum llm_arch {
  158. LLM_ARCH_LLAMA,
  159. LLM_ARCH_FALCON,
  160. LLM_ARCH_BAICHUAN,
  161. LLM_ARCH_GPT2,
  162. LLM_ARCH_GPTJ,
  163. LLM_ARCH_GPTNEOX,
  164. LLM_ARCH_MPT,
  165. LLM_ARCH_STARCODER,
  166. LLM_ARCH_PERSIMMON,
  167. LLM_ARCH_REFACT,
  168. LLM_ARCH_BLOOM,
  169. LLM_ARCH_STABLELM,
  170. LLM_ARCH_QWEN,
  171. LLM_ARCH_QWEN2,
  172. LLM_ARCH_PHI2,
  173. LLM_ARCH_PLAMO,
  174. LLM_ARCH_CODESHELL,
  175. LLM_ARCH_UNKNOWN,
  176. };
  177. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  178. { LLM_ARCH_LLAMA, "llama" },
  179. { LLM_ARCH_FALCON, "falcon" },
  180. { LLM_ARCH_GPT2, "gpt2" },
  181. { LLM_ARCH_GPTJ, "gptj" },
  182. { LLM_ARCH_GPTNEOX, "gptneox" },
  183. { LLM_ARCH_MPT, "mpt" },
  184. { LLM_ARCH_BAICHUAN, "baichuan" },
  185. { LLM_ARCH_STARCODER, "starcoder" },
  186. { LLM_ARCH_PERSIMMON, "persimmon" },
  187. { LLM_ARCH_REFACT, "refact" },
  188. { LLM_ARCH_BLOOM, "bloom" },
  189. { LLM_ARCH_STABLELM, "stablelm" },
  190. { LLM_ARCH_QWEN, "qwen" },
  191. { LLM_ARCH_QWEN2, "qwen2" },
  192. { LLM_ARCH_PHI2, "phi2" },
  193. { LLM_ARCH_PLAMO, "plamo" },
  194. { LLM_ARCH_CODESHELL, "codeshell" },
  195. };
  196. enum llm_kv {
  197. LLM_KV_GENERAL_ARCHITECTURE,
  198. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  199. LLM_KV_GENERAL_ALIGNMENT,
  200. LLM_KV_GENERAL_NAME,
  201. LLM_KV_GENERAL_AUTHOR,
  202. LLM_KV_GENERAL_URL,
  203. LLM_KV_GENERAL_DESCRIPTION,
  204. LLM_KV_GENERAL_LICENSE,
  205. LLM_KV_GENERAL_SOURCE_URL,
  206. LLM_KV_GENERAL_SOURCE_HF_REPO,
  207. LLM_KV_CONTEXT_LENGTH,
  208. LLM_KV_EMBEDDING_LENGTH,
  209. LLM_KV_BLOCK_COUNT,
  210. LLM_KV_FEED_FORWARD_LENGTH,
  211. LLM_KV_USE_PARALLEL_RESIDUAL,
  212. LLM_KV_TENSOR_DATA_LAYOUT,
  213. LLM_KV_EXPERT_COUNT,
  214. LLM_KV_EXPERT_USED_COUNT,
  215. LLM_KV_ATTENTION_HEAD_COUNT,
  216. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  217. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  218. LLM_KV_ATTENTION_CLAMP_KQV,
  219. LLM_KV_ATTENTION_KEY_LENGTH,
  220. LLM_KV_ATTENTION_VALUE_LENGTH,
  221. LLM_KV_ATTENTION_LAYERNORM_EPS,
  222. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  223. LLM_KV_ROPE_DIMENSION_COUNT,
  224. LLM_KV_ROPE_FREQ_BASE,
  225. LLM_KV_ROPE_SCALE_LINEAR,
  226. LLM_KV_ROPE_SCALING_TYPE,
  227. LLM_KV_ROPE_SCALING_FACTOR,
  228. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  229. LLM_KV_ROPE_SCALING_FINETUNED,
  230. LLM_KV_TOKENIZER_MODEL,
  231. LLM_KV_TOKENIZER_LIST,
  232. LLM_KV_TOKENIZER_TOKEN_TYPE,
  233. LLM_KV_TOKENIZER_SCORES,
  234. LLM_KV_TOKENIZER_MERGES,
  235. LLM_KV_TOKENIZER_BOS_ID,
  236. LLM_KV_TOKENIZER_EOS_ID,
  237. LLM_KV_TOKENIZER_UNK_ID,
  238. LLM_KV_TOKENIZER_SEP_ID,
  239. LLM_KV_TOKENIZER_PAD_ID,
  240. LLM_KV_TOKENIZER_ADD_BOS,
  241. LLM_KV_TOKENIZER_ADD_EOS,
  242. LLM_KV_TOKENIZER_HF_JSON,
  243. LLM_KV_TOKENIZER_RWKV,
  244. };
  245. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  246. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  247. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  248. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  249. { LLM_KV_GENERAL_NAME, "general.name" },
  250. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  251. { LLM_KV_GENERAL_URL, "general.url" },
  252. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  253. { LLM_KV_GENERAL_LICENSE, "general.license" },
  254. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  255. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  256. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  257. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  258. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  259. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  260. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  261. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  262. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  263. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  264. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  265. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  266. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  267. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  268. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  269. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  270. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  271. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  272. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  273. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  274. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  275. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  276. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  277. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  278. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  279. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  280. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  281. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  282. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  283. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  284. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  285. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  286. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  287. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  288. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  289. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  290. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  291. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  292. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  293. };
  294. struct LLM_KV {
  295. LLM_KV(llm_arch arch) : arch(arch) {}
  296. llm_arch arch;
  297. std::string operator()(llm_kv kv) const {
  298. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  299. }
  300. };
  301. enum llm_tensor {
  302. LLM_TENSOR_TOKEN_EMBD,
  303. LLM_TENSOR_TOKEN_EMBD_NORM,
  304. LLM_TENSOR_POS_EMBD,
  305. LLM_TENSOR_OUTPUT,
  306. LLM_TENSOR_OUTPUT_NORM,
  307. LLM_TENSOR_ROPE_FREQS,
  308. LLM_TENSOR_ATTN_Q,
  309. LLM_TENSOR_ATTN_K,
  310. LLM_TENSOR_ATTN_V,
  311. LLM_TENSOR_ATTN_QKV,
  312. LLM_TENSOR_ATTN_OUT,
  313. LLM_TENSOR_ATTN_NORM,
  314. LLM_TENSOR_ATTN_NORM_2,
  315. LLM_TENSOR_ATTN_ROT_EMBD,
  316. LLM_TENSOR_FFN_GATE_INP,
  317. LLM_TENSOR_FFN_NORM,
  318. LLM_TENSOR_FFN_GATE,
  319. LLM_TENSOR_FFN_DOWN,
  320. LLM_TENSOR_FFN_UP,
  321. LLM_TENSOR_FFN_ACT,
  322. LLM_TENSOR_FFN_DOWN_EXP,
  323. LLM_TENSOR_FFN_GATE_EXP,
  324. LLM_TENSOR_FFN_UP_EXP,
  325. LLM_TENSOR_ATTN_Q_NORM,
  326. LLM_TENSOR_ATTN_K_NORM,
  327. };
  328. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  329. {
  330. LLM_ARCH_LLAMA,
  331. {
  332. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  333. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  334. { LLM_TENSOR_OUTPUT, "output" },
  335. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  336. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  337. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  338. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  339. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  340. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  341. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  342. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  343. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  344. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  345. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  346. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  347. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  348. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  349. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  350. },
  351. },
  352. {
  353. LLM_ARCH_BAICHUAN,
  354. {
  355. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  356. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  357. { LLM_TENSOR_OUTPUT, "output" },
  358. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  359. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  360. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  361. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  362. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  363. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  364. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  365. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  366. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  367. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  368. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  369. },
  370. },
  371. {
  372. LLM_ARCH_FALCON,
  373. {
  374. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  375. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  376. { LLM_TENSOR_OUTPUT, "output" },
  377. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  378. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  379. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  380. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  381. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  382. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  383. },
  384. },
  385. {
  386. LLM_ARCH_GPT2,
  387. {
  388. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  389. { LLM_TENSOR_POS_EMBD, "position_embd" },
  390. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  391. { LLM_TENSOR_OUTPUT, "output" },
  392. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  393. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  394. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  395. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  396. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  397. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  398. },
  399. },
  400. {
  401. LLM_ARCH_GPTJ,
  402. {
  403. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  404. },
  405. },
  406. {
  407. LLM_ARCH_GPTNEOX,
  408. {
  409. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  410. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  411. { LLM_TENSOR_OUTPUT, "output" },
  412. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  413. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  414. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  415. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  416. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  417. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  418. },
  419. },
  420. {
  421. LLM_ARCH_PERSIMMON,
  422. {
  423. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  424. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  425. { LLM_TENSOR_OUTPUT, "output"},
  426. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  427. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  428. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  429. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  430. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  431. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  432. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  433. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  434. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  435. },
  436. },
  437. {
  438. LLM_ARCH_MPT,
  439. {
  440. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  441. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  442. { LLM_TENSOR_OUTPUT, "output" },
  443. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  444. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  445. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  446. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  447. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  448. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  449. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  450. },
  451. },
  452. {
  453. LLM_ARCH_STARCODER,
  454. {
  455. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  456. { LLM_TENSOR_POS_EMBD, "position_embd" },
  457. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  458. { LLM_TENSOR_OUTPUT, "output" },
  459. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  460. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  461. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  462. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  463. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  464. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  465. },
  466. },
  467. {
  468. LLM_ARCH_REFACT,
  469. {
  470. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  471. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  472. { LLM_TENSOR_OUTPUT, "output" },
  473. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  474. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  475. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  476. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  477. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  478. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  479. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  480. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  481. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  482. },
  483. },
  484. {
  485. LLM_ARCH_BLOOM,
  486. {
  487. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  488. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  489. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  490. { LLM_TENSOR_OUTPUT, "output" },
  491. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  492. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  493. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  494. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  495. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  496. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  497. },
  498. },
  499. {
  500. LLM_ARCH_STABLELM,
  501. {
  502. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  503. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  504. { LLM_TENSOR_OUTPUT, "output" },
  505. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  506. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  507. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  508. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  509. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  510. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  511. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  512. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  513. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  514. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  515. },
  516. },
  517. {
  518. LLM_ARCH_QWEN,
  519. {
  520. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  521. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  522. { LLM_TENSOR_OUTPUT, "output" },
  523. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  524. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  525. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  526. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  527. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  528. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  529. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  530. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  531. },
  532. },
  533. {
  534. LLM_ARCH_QWEN2,
  535. {
  536. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  537. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  538. { LLM_TENSOR_OUTPUT, "output" },
  539. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  540. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  541. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  542. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  543. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  544. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  545. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  546. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  547. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  548. },
  549. },
  550. {
  551. LLM_ARCH_PHI2,
  552. {
  553. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  554. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  555. { LLM_TENSOR_OUTPUT, "output" },
  556. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  557. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  558. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  559. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  560. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  561. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  562. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  563. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  564. },
  565. },
  566. {
  567. LLM_ARCH_PLAMO,
  568. {
  569. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  570. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  571. { LLM_TENSOR_OUTPUT, "output" },
  572. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  573. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  574. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  575. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  576. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  577. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  578. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  579. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  580. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  581. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  582. },
  583. },
  584. {
  585. LLM_ARCH_CODESHELL,
  586. {
  587. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  588. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  589. { LLM_TENSOR_OUTPUT, "output" },
  590. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  591. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  592. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  593. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  594. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  595. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  596. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  597. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  598. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  599. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  600. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  601. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  602. },
  603. },
  604. {
  605. LLM_ARCH_UNKNOWN,
  606. {
  607. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  608. },
  609. },
  610. };
  611. static llm_arch llm_arch_from_string(const std::string & name) {
  612. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  613. if (kv.second == name) {
  614. return kv.first;
  615. }
  616. }
  617. return LLM_ARCH_UNKNOWN;
  618. }
  619. // helper to handle gguf constants
  620. // usage:
  621. //
  622. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  623. //
  624. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  625. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  626. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  627. //
  628. struct LLM_TN {
  629. LLM_TN(llm_arch arch) : arch(arch) {}
  630. llm_arch arch;
  631. std::string operator()(llm_tensor tensor) const {
  632. return LLM_TENSOR_NAMES[arch].at(tensor);
  633. }
  634. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  635. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  636. }
  637. std::string operator()(llm_tensor tensor, int bid) const {
  638. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  639. }
  640. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  641. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  642. }
  643. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  644. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  645. }
  646. };
  647. //
  648. // gguf helpers
  649. //
  650. static std::map<int8_t, std::string> LLAMA_ROPE_SCALING_TYPES = {
  651. { LLAMA_ROPE_SCALING_NONE, "none" },
  652. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  653. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  654. };
  655. static int8_t llama_rope_scaling_type_from_string(const std::string & name) {
  656. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  657. if (kv.second == name) {
  658. return kv.first;
  659. }
  660. }
  661. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  662. }
  663. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  664. switch (type) {
  665. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  666. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  667. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  668. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  669. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  670. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  671. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  672. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  673. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  674. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  675. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  676. default: return format("unknown type %d", type);
  677. }
  678. }
  679. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  680. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  681. switch (type) {
  682. case GGUF_TYPE_STRING:
  683. return gguf_get_val_str(ctx_gguf, i);
  684. case GGUF_TYPE_ARRAY:
  685. {
  686. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  687. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  688. const void * data = gguf_get_arr_data(ctx_gguf, i);
  689. std::stringstream ss;
  690. ss << "[";
  691. for (int j = 0; j < arr_n; j++) {
  692. if (arr_type == GGUF_TYPE_STRING) {
  693. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  694. // escape quotes
  695. replace_all(val, "\\", "\\\\");
  696. replace_all(val, "\"", "\\\"");
  697. ss << '"' << val << '"';
  698. } else if (arr_type == GGUF_TYPE_ARRAY) {
  699. ss << "???";
  700. } else {
  701. ss << gguf_data_to_str(arr_type, data, j);
  702. }
  703. if (j < arr_n - 1) {
  704. ss << ", ";
  705. }
  706. }
  707. ss << "]";
  708. return ss.str();
  709. }
  710. default:
  711. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  712. }
  713. }
  714. //
  715. // ggml helpers
  716. //
  717. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  718. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  719. if (plan.work_size > 0) {
  720. buf.resize(plan.work_size);
  721. plan.work_data = buf.data();
  722. }
  723. ggml_graph_compute(graph, &plan);
  724. }
  725. //
  726. // llama helpers
  727. //
  728. #if defined(_WIN32)
  729. static std::string llama_format_win_err(DWORD err) {
  730. LPSTR buf;
  731. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  732. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  733. if (!size) {
  734. return "FormatMessageA failed";
  735. }
  736. std::string ret(buf, size);
  737. LocalFree(buf);
  738. return ret;
  739. }
  740. #endif
  741. template <typename T>
  742. struct no_init {
  743. T value;
  744. no_init() { /* do nothing */ }
  745. };
  746. struct llama_file {
  747. // use FILE * so we don't have to re-open the file to mmap
  748. FILE * fp;
  749. size_t size;
  750. llama_file(const char * fname, const char * mode) {
  751. fp = std::fopen(fname, mode);
  752. if (fp == NULL) {
  753. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  754. }
  755. seek(0, SEEK_END);
  756. size = tell();
  757. seek(0, SEEK_SET);
  758. }
  759. size_t tell() const {
  760. #ifdef _WIN32
  761. __int64 ret = _ftelli64(fp);
  762. #else
  763. long ret = std::ftell(fp);
  764. #endif
  765. GGML_ASSERT(ret != -1); // this really shouldn't fail
  766. return (size_t) ret;
  767. }
  768. void seek(size_t offset, int whence) const {
  769. #ifdef _WIN32
  770. int ret = _fseeki64(fp, (__int64) offset, whence);
  771. #else
  772. int ret = std::fseek(fp, (long) offset, whence);
  773. #endif
  774. GGML_ASSERT(ret == 0); // same
  775. }
  776. void read_raw(void * ptr, size_t len) const {
  777. if (len == 0) {
  778. return;
  779. }
  780. errno = 0;
  781. std::size_t ret = std::fread(ptr, len, 1, fp);
  782. if (ferror(fp)) {
  783. throw std::runtime_error(format("read error: %s", strerror(errno)));
  784. }
  785. if (ret != 1) {
  786. throw std::runtime_error("unexpectedly reached end of file");
  787. }
  788. }
  789. uint32_t read_u32() const {
  790. uint32_t ret;
  791. read_raw(&ret, sizeof(ret));
  792. return ret;
  793. }
  794. void write_raw(const void * ptr, size_t len) const {
  795. if (len == 0) {
  796. return;
  797. }
  798. errno = 0;
  799. size_t ret = std::fwrite(ptr, len, 1, fp);
  800. if (ret != 1) {
  801. throw std::runtime_error(format("write error: %s", strerror(errno)));
  802. }
  803. }
  804. void write_u32(std::uint32_t val) const {
  805. write_raw(&val, sizeof(val));
  806. }
  807. ~llama_file() {
  808. if (fp) {
  809. std::fclose(fp);
  810. }
  811. }
  812. };
  813. struct llama_mmap {
  814. void * addr;
  815. size_t size;
  816. llama_mmap(const llama_mmap &) = delete;
  817. #ifdef _POSIX_MAPPED_FILES
  818. static constexpr bool SUPPORTED = true;
  819. // list of mapped fragments (first_offset, last_offset)
  820. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  821. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  822. size = file->size;
  823. int fd = fileno(file->fp);
  824. int flags = MAP_SHARED;
  825. // prefetch/readahead impairs performance on NUMA systems
  826. if (numa) { prefetch = 0; }
  827. #ifdef __linux__
  828. // advise the kernel to read the file sequentially (increases readahead)
  829. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  830. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  831. strerror(errno));
  832. }
  833. if (prefetch) { flags |= MAP_POPULATE; }
  834. #endif
  835. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  836. if (addr == MAP_FAILED) { // NOLINT
  837. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  838. }
  839. if (prefetch > 0) {
  840. // advise the kernel to preload the mapped memory
  841. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  842. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  843. strerror(errno));
  844. }
  845. }
  846. if (numa) {
  847. // advise the kernel not to use readahead
  848. // (because the next page might not belong on the same node)
  849. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  850. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  851. strerror(errno));
  852. }
  853. }
  854. // initialize list of mapped_fragments
  855. mapped_fragments.emplace_back(0, file->size);
  856. }
  857. static void align_range(size_t * first, size_t * last, size_t page_size) {
  858. // align first to the next page
  859. size_t offset_in_page = *first & (page_size - 1);
  860. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  861. *first += offset_to_page;
  862. // align last to the previous page
  863. *last = *last & ~(page_size - 1);
  864. if (*last <= *first) {
  865. *last = *first;
  866. }
  867. }
  868. // partially unmap the file in the range [first, last)
  869. void unmap_fragment(size_t first, size_t last) {
  870. // note: this function must not be called multiple times with overlapping ranges
  871. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  872. int page_size = sysconf(_SC_PAGESIZE);
  873. align_range(&first, &last, page_size);
  874. size_t len = last - first;
  875. if (len == 0) {
  876. return;
  877. }
  878. GGML_ASSERT(first % page_size == 0);
  879. GGML_ASSERT(last % page_size == 0);
  880. GGML_ASSERT(last > first);
  881. void * next_page_start = (uint8_t *) addr + first;
  882. // unmap the range
  883. if (munmap(next_page_start, len)) {
  884. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  885. }
  886. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  887. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  888. for (const auto & frag : mapped_fragments) {
  889. if (frag.first < first && frag.second > last) {
  890. // the range is in the middle of the fragment, split it
  891. new_mapped_fragments.emplace_back(frag.first, first);
  892. new_mapped_fragments.emplace_back(last, frag.second);
  893. } else if (frag.first < first && frag.second > first) {
  894. // the range starts in the middle of the fragment
  895. new_mapped_fragments.emplace_back(frag.first, first);
  896. } else if (frag.first < last && frag.second > last) {
  897. // the range ends in the middle of the fragment
  898. new_mapped_fragments.emplace_back(last, frag.second);
  899. } else if (frag.first >= first && frag.second <= last) {
  900. // the range covers the entire fragment
  901. } else {
  902. // the range is outside the fragment
  903. new_mapped_fragments.push_back(frag);
  904. }
  905. }
  906. mapped_fragments = std::move(new_mapped_fragments);
  907. }
  908. ~llama_mmap() {
  909. for (const auto & frag : mapped_fragments) {
  910. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  911. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  912. }
  913. }
  914. }
  915. #elif defined(_WIN32)
  916. static constexpr bool SUPPORTED = true;
  917. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  918. GGML_UNUSED(numa);
  919. size = file->size;
  920. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  921. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  922. if (hMapping == NULL) {
  923. DWORD error = GetLastError();
  924. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  925. }
  926. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  927. DWORD error = GetLastError();
  928. CloseHandle(hMapping);
  929. if (addr == NULL) {
  930. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  931. }
  932. if (prefetch > 0) {
  933. #if _WIN32_WINNT >= 0x602
  934. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  935. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  936. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  937. // may fail on pre-Windows 8 systems
  938. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  939. if (pPrefetchVirtualMemory) {
  940. // advise the kernel to preload the mapped memory
  941. WIN32_MEMORY_RANGE_ENTRY range;
  942. range.VirtualAddress = addr;
  943. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  944. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  945. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  946. llama_format_win_err(GetLastError()).c_str());
  947. }
  948. }
  949. #else
  950. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  951. #endif
  952. }
  953. }
  954. void unmap_fragment(size_t first, size_t last) {
  955. // not supported
  956. GGML_UNUSED(first);
  957. GGML_UNUSED(last);
  958. }
  959. ~llama_mmap() {
  960. if (!UnmapViewOfFile(addr)) {
  961. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  962. llama_format_win_err(GetLastError()).c_str());
  963. }
  964. }
  965. #else
  966. static constexpr bool SUPPORTED = false;
  967. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  968. GGML_UNUSED(file);
  969. GGML_UNUSED(prefetch);
  970. GGML_UNUSED(numa);
  971. throw std::runtime_error("mmap not supported");
  972. }
  973. void unmap_fragment(size_t first, size_t last) {
  974. GGML_UNUSED(first);
  975. GGML_UNUSED(last);
  976. throw std::runtime_error("mmap not supported");
  977. }
  978. #endif
  979. };
  980. // Represents some region of memory being locked using mlock or VirtualLock;
  981. // will automatically unlock on destruction.
  982. struct llama_mlock {
  983. void * addr = NULL;
  984. size_t size = 0;
  985. bool failed_already = false;
  986. llama_mlock() {}
  987. llama_mlock(const llama_mlock &) = delete;
  988. ~llama_mlock() {
  989. if (size) {
  990. raw_unlock(addr, size);
  991. }
  992. }
  993. void init(void * ptr) {
  994. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  995. addr = ptr;
  996. }
  997. void grow_to(size_t target_size) {
  998. GGML_ASSERT(addr);
  999. if (failed_already) {
  1000. return;
  1001. }
  1002. size_t granularity = lock_granularity();
  1003. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1004. if (target_size > size) {
  1005. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1006. size = target_size;
  1007. } else {
  1008. failed_already = true;
  1009. }
  1010. }
  1011. }
  1012. #ifdef _POSIX_MEMLOCK_RANGE
  1013. static constexpr bool SUPPORTED = true;
  1014. static size_t lock_granularity() {
  1015. return (size_t) sysconf(_SC_PAGESIZE);
  1016. }
  1017. #ifdef __APPLE__
  1018. #define MLOCK_SUGGESTION \
  1019. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1020. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  1021. #else
  1022. #define MLOCK_SUGGESTION \
  1023. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  1024. #endif
  1025. bool raw_lock(const void * addr, size_t size) const {
  1026. if (!mlock(addr, size)) {
  1027. return true;
  1028. }
  1029. char* errmsg = std::strerror(errno);
  1030. bool suggest = (errno == ENOMEM);
  1031. // Check if the resource limit is fine after all
  1032. struct rlimit lock_limit;
  1033. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1034. suggest = false;
  1035. }
  1036. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1037. suggest = false;
  1038. }
  1039. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1040. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1041. return false;
  1042. }
  1043. #undef MLOCK_SUGGESTION
  1044. static void raw_unlock(void * addr, size_t size) {
  1045. if (munlock(addr, size)) {
  1046. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1047. }
  1048. }
  1049. #elif defined(_WIN32)
  1050. static constexpr bool SUPPORTED = true;
  1051. static size_t lock_granularity() {
  1052. SYSTEM_INFO si;
  1053. GetSystemInfo(&si);
  1054. return (size_t) si.dwPageSize;
  1055. }
  1056. bool raw_lock(void * ptr, size_t len) const {
  1057. for (int tries = 1; ; tries++) {
  1058. if (VirtualLock(ptr, len)) {
  1059. return true;
  1060. }
  1061. if (tries == 2) {
  1062. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1063. len, size, llama_format_win_err(GetLastError()).c_str());
  1064. return false;
  1065. }
  1066. // It failed but this was only the first try; increase the working
  1067. // set size and try again.
  1068. SIZE_T min_ws_size, max_ws_size;
  1069. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1070. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1071. llama_format_win_err(GetLastError()).c_str());
  1072. return false;
  1073. }
  1074. // Per MSDN: "The maximum number of pages that a process can lock
  1075. // is equal to the number of pages in its minimum working set minus
  1076. // a small overhead."
  1077. // Hopefully a megabyte is enough overhead:
  1078. size_t increment = len + 1048576;
  1079. // The minimum must be <= the maximum, so we need to increase both:
  1080. min_ws_size += increment;
  1081. max_ws_size += increment;
  1082. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1083. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1084. llama_format_win_err(GetLastError()).c_str());
  1085. return false;
  1086. }
  1087. }
  1088. }
  1089. static void raw_unlock(void * ptr, size_t len) {
  1090. if (!VirtualUnlock(ptr, len)) {
  1091. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1092. llama_format_win_err(GetLastError()).c_str());
  1093. }
  1094. }
  1095. #else
  1096. static constexpr bool SUPPORTED = false;
  1097. static size_t lock_granularity() {
  1098. return (size_t) 65536;
  1099. }
  1100. bool raw_lock(const void * addr, size_t len) const {
  1101. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1102. return false;
  1103. }
  1104. static void raw_unlock(const void * addr, size_t len) {}
  1105. #endif
  1106. };
  1107. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1108. std::vector<char> result(8, 0);
  1109. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1110. if (n_tokens < 0) {
  1111. result.resize(-n_tokens);
  1112. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1113. GGML_ASSERT(check == -n_tokens);
  1114. }
  1115. else {
  1116. result.resize(n_tokens);
  1117. }
  1118. return std::string(result.data(), result.size());
  1119. }
  1120. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1121. ggml_backend_buffer_type_t buft = nullptr;
  1122. #if defined(GGML_USE_CUBLAS)
  1123. // host buffers should only be used when data is expected to be copied to/from the GPU
  1124. if (host_buffer) {
  1125. buft = ggml_backend_cuda_host_buffer_type();
  1126. }
  1127. #elif defined(GGML_USE_CPU_HBM)
  1128. buft = ggml_backend_cpu_hbm_buffer_type();
  1129. #endif
  1130. if (buft == nullptr) {
  1131. buft = ggml_backend_cpu_buffer_type();
  1132. }
  1133. return buft;
  1134. GGML_UNUSED(host_buffer);
  1135. }
  1136. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1137. ggml_backend_buffer_type_t buft = nullptr;
  1138. #ifdef GGML_USE_METAL
  1139. buft = ggml_backend_metal_buffer_type();
  1140. #elif defined(GGML_USE_CUBLAS)
  1141. buft = ggml_backend_cuda_buffer_type(gpu);
  1142. #elif defined(GGML_USE_CLBLAST)
  1143. buft = ggml_backend_opencl_buffer_type();
  1144. #endif
  1145. if (buft == nullptr) {
  1146. buft = llama_default_buffer_type_cpu(true);
  1147. }
  1148. return buft;
  1149. GGML_UNUSED(gpu);
  1150. }
  1151. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1152. ggml_backend_buffer_type_t buft = nullptr;
  1153. #ifdef GGML_USE_CUBLAS
  1154. if (ggml_backend_cuda_get_device_count() > 1) {
  1155. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1156. }
  1157. #endif
  1158. if (buft == nullptr) {
  1159. buft = llama_default_buffer_type_offload(fallback_gpu);
  1160. }
  1161. return buft;
  1162. GGML_UNUSED(tensor_split);
  1163. }
  1164. //
  1165. // globals
  1166. //
  1167. struct llama_state {
  1168. llama_state() {
  1169. #ifdef GGML_USE_METAL
  1170. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1171. #endif
  1172. }
  1173. // We save the log callback globally
  1174. ggml_log_callback log_callback = llama_log_callback_default;
  1175. void * log_callback_user_data = nullptr;
  1176. };
  1177. static llama_state g_state;
  1178. // available llama models
  1179. enum e_model {
  1180. MODEL_UNKNOWN,
  1181. MODEL_0_5B,
  1182. MODEL_1B,
  1183. MODEL_3B,
  1184. MODEL_4B,
  1185. MODEL_7B,
  1186. MODEL_8B,
  1187. MODEL_13B,
  1188. MODEL_15B,
  1189. MODEL_30B,
  1190. MODEL_34B,
  1191. MODEL_40B,
  1192. MODEL_65B,
  1193. MODEL_70B,
  1194. MODEL_SMALL,
  1195. MODEL_MEDIUM,
  1196. MODEL_LARGE,
  1197. MODEL_XL,
  1198. };
  1199. static const size_t kiB = 1024;
  1200. static const size_t MiB = 1024*kiB;
  1201. static const size_t GiB = 1024*MiB;
  1202. struct llama_hparams {
  1203. bool vocab_only;
  1204. uint32_t n_vocab;
  1205. uint32_t n_ctx_train; // context size the model was trained on
  1206. uint32_t n_embd;
  1207. uint32_t n_head;
  1208. uint32_t n_head_kv;
  1209. uint32_t n_layer;
  1210. uint32_t n_rot;
  1211. uint32_t n_embd_head_k; // dimension of keys (d_k). d_q is assumed to be the same, but there are n_head q heads, and only n_head_kv k-v heads
  1212. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1213. uint32_t n_ff;
  1214. uint32_t n_expert = 0;
  1215. uint32_t n_expert_used = 0;
  1216. float f_norm_eps;
  1217. float f_norm_rms_eps;
  1218. float rope_freq_base_train;
  1219. float rope_freq_scale_train;
  1220. uint32_t n_yarn_orig_ctx;
  1221. int8_t rope_scaling_type_train : 3;
  1222. bool rope_finetuned : 1;
  1223. float f_clamp_kqv;
  1224. float f_max_alibi_bias;
  1225. bool operator!=(const llama_hparams & other) const {
  1226. if (this->vocab_only != other.vocab_only) return true;
  1227. if (this->n_vocab != other.n_vocab) return true;
  1228. if (this->n_ctx_train != other.n_ctx_train) return true;
  1229. if (this->n_embd != other.n_embd) return true;
  1230. if (this->n_head != other.n_head) return true;
  1231. if (this->n_head_kv != other.n_head_kv) return true;
  1232. if (this->n_layer != other.n_layer) return true;
  1233. if (this->n_rot != other.n_rot) return true;
  1234. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1235. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1236. if (this->n_ff != other.n_ff) return true;
  1237. if (this->n_expert != other.n_expert) return true;
  1238. if (this->n_expert_used != other.n_expert_used) return true;
  1239. if (this->rope_finetuned != other.rope_finetuned) return true;
  1240. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1241. const float EPSILON = 1e-9f;
  1242. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1243. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1244. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1245. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1246. return false;
  1247. }
  1248. uint32_t n_gqa() const {
  1249. return n_head/n_head_kv;
  1250. }
  1251. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1252. return n_embd_head_k * n_head_kv;
  1253. }
  1254. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1255. return n_embd_head_v * n_head_kv;
  1256. }
  1257. };
  1258. struct llama_cparams {
  1259. uint32_t n_ctx; // context size used during inference
  1260. uint32_t n_batch;
  1261. uint32_t n_threads; // number of threads to use for generation
  1262. uint32_t n_threads_batch; // number of threads to use for batch processing
  1263. float rope_freq_base;
  1264. float rope_freq_scale;
  1265. uint32_t n_yarn_orig_ctx;
  1266. // These hyperparameters are not exposed in GGUF, because all
  1267. // existing YaRN models use the same values for them.
  1268. float yarn_ext_factor;
  1269. float yarn_attn_factor;
  1270. float yarn_beta_fast;
  1271. float yarn_beta_slow;
  1272. bool mul_mat_q;
  1273. bool offload_kqv;
  1274. ggml_backend_sched_eval_callback cb_eval;
  1275. void * cb_eval_user_data;
  1276. };
  1277. struct llama_layer {
  1278. // normalization
  1279. struct ggml_tensor * attn_norm;
  1280. struct ggml_tensor * attn_norm_b;
  1281. struct ggml_tensor * attn_norm_2;
  1282. struct ggml_tensor * attn_norm_2_b;
  1283. struct ggml_tensor * attn_q_norm;
  1284. struct ggml_tensor * attn_q_norm_b;
  1285. struct ggml_tensor * attn_k_norm;
  1286. struct ggml_tensor * attn_k_norm_b;
  1287. // attention
  1288. struct ggml_tensor * wq;
  1289. struct ggml_tensor * wk;
  1290. struct ggml_tensor * wv;
  1291. struct ggml_tensor * wo;
  1292. struct ggml_tensor * wqkv;
  1293. // attention bias
  1294. struct ggml_tensor * bq;
  1295. struct ggml_tensor * bk;
  1296. struct ggml_tensor * bv;
  1297. struct ggml_tensor * bo;
  1298. struct ggml_tensor * bqkv;
  1299. // normalization
  1300. struct ggml_tensor * ffn_norm;
  1301. struct ggml_tensor * ffn_norm_b;
  1302. // ff
  1303. struct ggml_tensor * ffn_gate; // w1
  1304. struct ggml_tensor * ffn_down; // w2
  1305. struct ggml_tensor * ffn_up; // w3
  1306. // ff MoE
  1307. struct ggml_tensor * ffn_gate_inp;
  1308. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1309. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1310. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1311. // ff bias
  1312. struct ggml_tensor * ffn_down_b; // b2
  1313. struct ggml_tensor * ffn_up_b; // b3
  1314. struct ggml_tensor * ffn_act;
  1315. };
  1316. struct llama_kv_cell {
  1317. llama_pos pos = -1;
  1318. llama_pos delta = 0;
  1319. std::set<llama_seq_id> seq_id;
  1320. bool has_seq_id(const llama_seq_id & id) const {
  1321. return seq_id.find(id) != seq_id.end();
  1322. }
  1323. };
  1324. // ring-buffer of cached KV data
  1325. struct llama_kv_cache {
  1326. bool has_shift = false;
  1327. // Note: The value of head isn't only used to optimize searching
  1328. // for a free KV slot. llama_decode_internal also uses it, so it
  1329. // cannot be freely changed after a slot has been allocated.
  1330. uint32_t head = 0;
  1331. uint32_t size = 0;
  1332. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1333. // computed before each graph build
  1334. uint32_t n = 0;
  1335. std::vector<llama_kv_cell> cells;
  1336. std::vector<struct ggml_tensor *> k_l; // per layer
  1337. std::vector<struct ggml_tensor *> v_l;
  1338. std::vector<struct ggml_context *> ctxs;
  1339. std::vector<ggml_backend_buffer_t> bufs;
  1340. size_t total_size() const {
  1341. size_t size = 0;
  1342. for (ggml_backend_buffer_t buf : bufs) {
  1343. size += ggml_backend_buffer_get_size(buf);
  1344. }
  1345. return size;
  1346. }
  1347. ~llama_kv_cache() {
  1348. for (struct ggml_context * ctx : ctxs) {
  1349. ggml_free(ctx);
  1350. }
  1351. for (ggml_backend_buffer_t buf : bufs) {
  1352. ggml_backend_buffer_free(buf);
  1353. }
  1354. }
  1355. };
  1356. struct llama_vocab {
  1357. using id = int32_t;
  1358. using token = std::string;
  1359. using ttype = llama_token_type;
  1360. struct token_data {
  1361. token text;
  1362. float score;
  1363. ttype type;
  1364. };
  1365. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1366. std::unordered_map<token, id> token_to_id;
  1367. std::vector<token_data> id_to_token;
  1368. std::unordered_map<token, id> special_tokens_cache;
  1369. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1370. // default LLaMA special tokens
  1371. id special_bos_id = 1;
  1372. id special_eos_id = 2;
  1373. id special_unk_id = 0;
  1374. id special_sep_id = -1;
  1375. id special_pad_id = -1;
  1376. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1377. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1378. id linefeed_id = 13;
  1379. id special_prefix_id = 32007;
  1380. id special_middle_id = 32009;
  1381. id special_suffix_id = 32008;
  1382. id special_eot_id = 32010;
  1383. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1384. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1385. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1386. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1387. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1388. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1389. if (it == bpe_ranks.end()) {
  1390. return -1;
  1391. }
  1392. return it->second;
  1393. }
  1394. };
  1395. struct llama_model {
  1396. e_model type = MODEL_UNKNOWN;
  1397. llm_arch arch = LLM_ARCH_UNKNOWN;
  1398. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1399. std::string name = "n/a";
  1400. llama_hparams hparams = {};
  1401. llama_vocab vocab;
  1402. struct ggml_tensor * tok_embd;
  1403. struct ggml_tensor * pos_embd;
  1404. struct ggml_tensor * tok_norm;
  1405. struct ggml_tensor * tok_norm_b;
  1406. struct ggml_tensor * output_norm;
  1407. struct ggml_tensor * output_norm_b;
  1408. struct ggml_tensor * output;
  1409. struct ggml_tensor * output_b;
  1410. std::vector<llama_layer> layers;
  1411. llama_split_mode split_mode;
  1412. int main_gpu;
  1413. int n_gpu_layers;
  1414. // gguf metadata
  1415. std::unordered_map<std::string, std::string> gguf_kv;
  1416. // layer -> buffer type mapping
  1417. struct layer_buft {
  1418. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1419. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1420. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1421. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1422. ggml_backend_buffer_type_t buft; // everything else
  1423. };
  1424. layer_buft buft_input;
  1425. layer_buft buft_output;
  1426. std::vector<layer_buft> buft_layer;
  1427. // contexts where the model tensors metadata is stored
  1428. std::vector<struct ggml_context *> ctxs;
  1429. // the model memory buffers for the tensor data
  1430. std::vector<ggml_backend_buffer_t> bufs;
  1431. // model memory mapped file
  1432. std::unique_ptr<llama_mmap> mapping;
  1433. // objects representing data potentially being locked in memory
  1434. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1435. llama_mlock mlock_mmap;
  1436. // for quantize-stats only
  1437. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1438. int64_t t_load_us = 0;
  1439. int64_t t_start_us = 0;
  1440. ~llama_model() {
  1441. for (struct ggml_context * ctx : ctxs) {
  1442. ggml_free(ctx);
  1443. }
  1444. for (ggml_backend_buffer_t buf : bufs) {
  1445. ggml_backend_buffer_free(buf);
  1446. }
  1447. }
  1448. };
  1449. struct llama_context {
  1450. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1451. ~llama_context() {
  1452. ggml_backend_sched_free(sched);
  1453. for (ggml_backend_t backend : backends) {
  1454. ggml_backend_free(backend);
  1455. }
  1456. }
  1457. llama_cparams cparams;
  1458. std::vector<ggml_backend_t> backends;
  1459. #ifdef GGML_USE_METAL
  1460. ggml_backend_t backend_metal = nullptr;
  1461. #endif
  1462. ggml_backend_t backend_cpu = nullptr;
  1463. const llama_model & model;
  1464. // key + value cache for the self attention
  1465. struct llama_kv_cache kv_self;
  1466. std::mt19937 rng;
  1467. bool has_evaluated_once = false;
  1468. int64_t t_start_us;
  1469. int64_t t_load_us;
  1470. int64_t t_sample_us = 0;
  1471. int64_t t_p_eval_us = 0;
  1472. int64_t t_eval_us = 0;
  1473. int32_t n_sample = 0; // number of tokens sampled
  1474. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1475. int32_t n_eval = 0; // number of eval calls
  1476. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1477. std::vector<float> logits;
  1478. #ifndef NDEBUG
  1479. // guard against access to unset logits
  1480. std::vector<bool> logits_valid;
  1481. #endif
  1482. bool logits_all = false;
  1483. // input embedding (1-dimensional array: [n_embd])
  1484. std::vector<float> embedding;
  1485. // memory buffers used to evaluate the model
  1486. std::vector<uint8_t> buf_compute_meta;
  1487. ggml_backend_sched_t sched = nullptr;
  1488. // allocator for the input tensors
  1489. ggml_tallocr * alloc = nullptr;
  1490. // temporary buffer for copying data to/from the backend
  1491. std::vector<no_init<uint8_t>> buf_copy;
  1492. #ifdef GGML_USE_MPI
  1493. ggml_mpi_context * ctx_mpi = NULL;
  1494. #endif
  1495. };
  1496. //
  1497. // kv cache helpers
  1498. //
  1499. static bool llama_kv_cache_init(
  1500. struct llama_kv_cache & cache,
  1501. const llama_model & model,
  1502. ggml_type ktype,
  1503. ggml_type vtype,
  1504. uint32_t n_ctx,
  1505. bool offload) {
  1506. const struct llama_hparams & hparams = model.hparams;
  1507. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1508. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1509. const int64_t n_layer = hparams.n_layer;
  1510. cache.has_shift = false;
  1511. cache.head = 0;
  1512. cache.size = n_ctx;
  1513. cache.used = 0;
  1514. cache.cells.clear();
  1515. cache.cells.resize(n_ctx);
  1516. #ifdef GGML_USE_CLBLAST
  1517. offload = false;
  1518. #endif
  1519. // count used buffer types
  1520. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1521. if (offload) {
  1522. for (int64_t i = 0; i < n_layer; ++i) {
  1523. buft_layer_count[model.buft_layer[i].buft]++;
  1524. }
  1525. } else {
  1526. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1527. }
  1528. // create a context for each buffer type
  1529. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1530. for (auto & it : buft_layer_count) {
  1531. int n_layers = it.second;
  1532. struct ggml_init_params params = {
  1533. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1534. /*.mem_buffer =*/ NULL,
  1535. /*.no_alloc =*/ true,
  1536. };
  1537. ggml_context * ctx = ggml_init(params);
  1538. if (!ctx) {
  1539. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1540. return false;
  1541. }
  1542. ctx_map[it.first] = ctx;
  1543. cache.ctxs.push_back(ctx);
  1544. }
  1545. cache.k_l.reserve(n_layer);
  1546. cache.v_l.reserve(n_layer);
  1547. for (int i = 0; i < (int) n_layer; i++) {
  1548. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1549. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1550. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1551. ggml_format_name(k, "cache_k_l%d", i);
  1552. ggml_format_name(v, "cache_v_l%d", i);
  1553. cache.k_l.push_back(k);
  1554. cache.v_l.push_back(v);
  1555. }
  1556. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1557. for (auto it : ctx_map) {
  1558. ggml_backend_buffer_type_t buft = it.first;
  1559. ggml_context * ctx = it.second;
  1560. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1561. if (!buf) {
  1562. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1563. return false;
  1564. }
  1565. ggml_backend_buffer_clear(buf, 0);
  1566. 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);
  1567. cache.bufs.push_back(buf);
  1568. }
  1569. return true;
  1570. }
  1571. // find an empty slot of size "n_tokens" in the cache
  1572. // updates the cache head
  1573. // Note: On success, it's important that cache.head points
  1574. // to the first cell of the slot.
  1575. static bool llama_kv_cache_find_slot(
  1576. struct llama_kv_cache & cache,
  1577. const struct llama_batch & batch) {
  1578. const uint32_t n_ctx = cache.size;
  1579. const uint32_t n_tokens = batch.n_tokens;
  1580. if (n_tokens > n_ctx) {
  1581. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1582. return false;
  1583. }
  1584. uint32_t n_tested = 0;
  1585. while (true) {
  1586. if (cache.head + n_tokens > n_ctx) {
  1587. n_tested += n_ctx - cache.head;
  1588. cache.head = 0;
  1589. continue;
  1590. }
  1591. bool found = true;
  1592. for (uint32_t i = 0; i < n_tokens; i++) {
  1593. if (cache.cells[cache.head + i].pos >= 0) {
  1594. found = false;
  1595. cache.head += i + 1;
  1596. n_tested += i + 1;
  1597. break;
  1598. }
  1599. }
  1600. if (found) {
  1601. break;
  1602. }
  1603. if (n_tested >= n_ctx) {
  1604. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1605. return false;
  1606. }
  1607. }
  1608. for (uint32_t i = 0; i < n_tokens; i++) {
  1609. cache.cells[cache.head + i].pos = batch.pos[i];
  1610. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1611. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1612. }
  1613. }
  1614. cache.used += n_tokens;
  1615. return true;
  1616. }
  1617. // find how many cells are currently in use
  1618. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1619. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1620. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1621. return i + 1;
  1622. }
  1623. }
  1624. return 0;
  1625. }
  1626. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1627. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1628. cache.cells[i].pos = -1;
  1629. cache.cells[i].seq_id.clear();
  1630. }
  1631. cache.head = 0;
  1632. cache.used = 0;
  1633. }
  1634. static void llama_kv_cache_seq_rm(
  1635. struct llama_kv_cache & cache,
  1636. llama_seq_id seq_id,
  1637. llama_pos p0,
  1638. llama_pos p1) {
  1639. uint32_t new_head = cache.size;
  1640. if (p0 < 0) p0 = 0;
  1641. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1642. for (uint32_t i = 0; i < cache.size; ++i) {
  1643. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1644. if (seq_id < 0) {
  1645. cache.cells[i].seq_id.clear();
  1646. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1647. cache.cells[i].seq_id.erase(seq_id);
  1648. } else {
  1649. continue;
  1650. }
  1651. if (cache.cells[i].seq_id.empty()) {
  1652. // keep count of the number of used cells
  1653. if (cache.cells[i].pos >= 0) cache.used--;
  1654. cache.cells[i].pos = -1;
  1655. if (new_head == cache.size) new_head = i;
  1656. }
  1657. }
  1658. }
  1659. // If we freed up a slot, set head to it so searching can start there.
  1660. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1661. }
  1662. static void llama_kv_cache_seq_cp(
  1663. struct llama_kv_cache & cache,
  1664. llama_seq_id seq_id_src,
  1665. llama_seq_id seq_id_dst,
  1666. llama_pos p0,
  1667. llama_pos p1) {
  1668. if (p0 < 0) p0 = 0;
  1669. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1670. cache.head = 0;
  1671. for (uint32_t i = 0; i < cache.size; ++i) {
  1672. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1673. cache.cells[i].seq_id.insert(seq_id_dst);
  1674. }
  1675. }
  1676. }
  1677. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1678. uint32_t new_head = cache.size;
  1679. for (uint32_t i = 0; i < cache.size; ++i) {
  1680. if (!cache.cells[i].has_seq_id(seq_id)) {
  1681. if (cache.cells[i].pos >= 0) cache.used--;
  1682. cache.cells[i].pos = -1;
  1683. cache.cells[i].seq_id.clear();
  1684. if (new_head == cache.size) new_head = i;
  1685. } else {
  1686. cache.cells[i].seq_id.clear();
  1687. cache.cells[i].seq_id.insert(seq_id);
  1688. }
  1689. }
  1690. // If we freed up a slot, set head to it so searching can start there.
  1691. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1692. }
  1693. static void llama_kv_cache_seq_shift(
  1694. struct llama_kv_cache & cache,
  1695. llama_seq_id seq_id,
  1696. llama_pos p0,
  1697. llama_pos p1,
  1698. llama_pos delta) {
  1699. uint32_t new_head = cache.size;
  1700. if (p0 < 0) p0 = 0;
  1701. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1702. for (uint32_t i = 0; i < cache.size; ++i) {
  1703. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1704. cache.has_shift = true;
  1705. cache.cells[i].pos += delta;
  1706. cache.cells[i].delta += delta;
  1707. if (cache.cells[i].pos < 0) {
  1708. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1709. cache.cells[i].pos = -1;
  1710. cache.cells[i].seq_id.clear();
  1711. if (new_head == cache.size) new_head = i;
  1712. }
  1713. }
  1714. }
  1715. // If we freed up a slot, set head to it so searching can start there.
  1716. // Otherwise we just start the next search from the beginning.
  1717. cache.head = new_head != cache.size ? new_head : 0;
  1718. }
  1719. static void llama_kv_cache_seq_div(
  1720. struct llama_kv_cache & cache,
  1721. llama_seq_id seq_id,
  1722. llama_pos p0,
  1723. llama_pos p1,
  1724. int d) {
  1725. if (p0 < 0) p0 = 0;
  1726. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1727. for (uint32_t i = 0; i < cache.size; ++i) {
  1728. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1729. cache.has_shift = true;
  1730. {
  1731. llama_pos p_old = cache.cells[i].pos;
  1732. cache.cells[i].pos /= d;
  1733. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1734. }
  1735. }
  1736. }
  1737. }
  1738. //
  1739. // model loading and saving
  1740. //
  1741. enum llama_fver {
  1742. GGUF_FILE_VERSION_V1 = 1,
  1743. GGUF_FILE_VERSION_V2 = 2,
  1744. GGUF_FILE_VERSION_V3 = 3,
  1745. };
  1746. static const char * llama_file_version_name(llama_fver version) {
  1747. switch (version) {
  1748. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1749. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1750. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1751. }
  1752. return "unknown";
  1753. }
  1754. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1755. char buf[256];
  1756. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1757. for (size_t i = 1; i < ne.size(); i++) {
  1758. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1759. }
  1760. return buf;
  1761. }
  1762. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1763. char buf[256];
  1764. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1765. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1766. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1767. }
  1768. return buf;
  1769. }
  1770. namespace GGUFMeta {
  1771. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1772. struct GKV_Base_Type {
  1773. static constexpr gguf_type gt = gt_;
  1774. static T getter(const gguf_context * ctx, const int kid) {
  1775. return gfun(ctx, kid);
  1776. }
  1777. };
  1778. template<typename T> struct GKV_Base;
  1779. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1780. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1781. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1782. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1783. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1784. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1785. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1786. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1787. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1788. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1789. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1790. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1791. template<> struct GKV_Base<std::string> {
  1792. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1793. static std::string getter(const gguf_context * ctx, const int kid) {
  1794. return gguf_get_val_str(ctx, kid);
  1795. }
  1796. };
  1797. struct ArrayInfo{
  1798. const gguf_type gt;
  1799. const size_t length;
  1800. const void * data;
  1801. };
  1802. template<> struct GKV_Base<ArrayInfo> {
  1803. public:
  1804. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1805. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1806. return ArrayInfo {
  1807. gguf_get_arr_type(ctx, k),
  1808. size_t(gguf_get_arr_n(ctx, k)),
  1809. gguf_get_arr_data(ctx, k),
  1810. };
  1811. }
  1812. };
  1813. template<typename T>
  1814. class GKV: public GKV_Base<T> {
  1815. GKV() = delete;
  1816. public:
  1817. static T get_kv(const gguf_context * ctx, const int k) {
  1818. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1819. if (kt != GKV::gt) {
  1820. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1821. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1822. }
  1823. return GKV::getter(ctx, k);
  1824. }
  1825. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  1826. switch (ty) {
  1827. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  1828. case LLAMA_KV_OVERRIDE_INT: return "int";
  1829. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  1830. }
  1831. return "unknown";
  1832. }
  1833. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  1834. if (!override) { return false; }
  1835. if (override->tag == expected_type) {
  1836. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  1837. __func__, override_type_to_str(override->tag), override->key);
  1838. switch (override->tag) {
  1839. case LLAMA_KV_OVERRIDE_BOOL: {
  1840. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  1841. } break;
  1842. case LLAMA_KV_OVERRIDE_INT: {
  1843. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  1844. } break;
  1845. case LLAMA_KV_OVERRIDE_FLOAT: {
  1846. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  1847. } break;
  1848. default:
  1849. // Shouldn't be possible to end up here, but just in case...
  1850. throw std::runtime_error(
  1851. format("Unsupported attempt to override %s type for metadata key %s\n",
  1852. override_type_to_str(override->tag), override->key));
  1853. }
  1854. return true;
  1855. }
  1856. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  1857. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  1858. return false;
  1859. }
  1860. template<typename OT>
  1861. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  1862. try_override(OT & target, const struct llama_model_kv_override *override) {
  1863. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  1864. target = override->bool_value;
  1865. return true;
  1866. }
  1867. return false;
  1868. }
  1869. template<typename OT>
  1870. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  1871. try_override(OT & target, const struct llama_model_kv_override *override) {
  1872. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  1873. target = override->int_value;
  1874. return true;
  1875. }
  1876. return false;
  1877. }
  1878. template<typename OT>
  1879. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  1880. try_override(T & target, const struct llama_model_kv_override *override) {
  1881. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  1882. target = override->float_value;
  1883. return true;
  1884. }
  1885. return false;
  1886. }
  1887. template<typename OT>
  1888. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  1889. try_override(T & target, const struct llama_model_kv_override *override) {
  1890. (void)target;
  1891. (void)override;
  1892. if (!override) { return false; }
  1893. // Currently, we should never end up here so it would be a bug if we do.
  1894. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  1895. override ? override->key : "NULL"));
  1896. }
  1897. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  1898. if (try_override<T>(target, override)) {
  1899. return true;
  1900. }
  1901. if (k < 0) { return false; }
  1902. target = get_kv(ctx, k);
  1903. return true;
  1904. }
  1905. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1906. return set(ctx, gguf_find_key(ctx, key), target, override);
  1907. }
  1908. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1909. return set(ctx, key.c_str(), target, override);
  1910. }
  1911. };
  1912. }
  1913. struct llama_model_loader {
  1914. int n_kv = 0;
  1915. int n_tensors = 0;
  1916. int n_created = 0;
  1917. int64_t n_elements = 0;
  1918. size_t n_bytes = 0;
  1919. bool use_mmap = false;
  1920. llama_file file;
  1921. llama_ftype ftype;
  1922. llama_fver fver;
  1923. std::unique_ptr<llama_mmap> mapping;
  1924. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  1925. struct gguf_context * ctx_gguf = NULL;
  1926. struct ggml_context * ctx_meta = NULL;
  1927. std::string arch_name;
  1928. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1929. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  1930. int trace = 0;
  1931. if (getenv("LLAMA_TRACE")) {
  1932. trace = atoi(getenv("LLAMA_TRACE"));
  1933. }
  1934. struct gguf_init_params params = {
  1935. /*.no_alloc = */ true,
  1936. /*.ctx = */ &ctx_meta,
  1937. };
  1938. if (param_overrides_p != nullptr) {
  1939. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  1940. kv_overrides.insert({std::string(p->key), *p});
  1941. }
  1942. }
  1943. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1944. if (!ctx_gguf) {
  1945. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1946. }
  1947. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  1948. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  1949. n_kv = gguf_get_n_kv(ctx_gguf);
  1950. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1951. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1952. for (int i = 0; i < n_tensors; i++) {
  1953. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1954. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1955. n_elements += ggml_nelements(t);
  1956. n_bytes += ggml_nbytes(t);
  1957. }
  1958. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1959. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1960. // determine file type based on the number of tensors for each quantization and print meta data
  1961. // TODO: make optional
  1962. {
  1963. std::map<enum ggml_type, uint32_t> n_type;
  1964. uint32_t n_type_max = 0;
  1965. enum ggml_type type_max = GGML_TYPE_F32;
  1966. for (int i = 0; i < n_tensors; i++) {
  1967. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  1968. n_type[type]++;
  1969. if (n_type_max < n_type[type]) {
  1970. n_type_max = n_type[type];
  1971. type_max = type;
  1972. }
  1973. if (trace > 0) {
  1974. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  1975. 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());
  1976. }
  1977. }
  1978. switch (type_max) {
  1979. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1980. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1981. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1982. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1983. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1984. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1985. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1986. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1987. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1988. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1989. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1990. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1991. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  1992. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  1993. default:
  1994. {
  1995. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1996. ftype = LLAMA_FTYPE_ALL_F32;
  1997. } break;
  1998. }
  1999. // this is a way to mark that we have "guessed" the file type
  2000. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2001. {
  2002. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2003. if (kid >= 0) {
  2004. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2005. }
  2006. }
  2007. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2008. for (int i = 0; i < n_kv; i++) {
  2009. const char * name = gguf_get_key(ctx_gguf, i);
  2010. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2011. const std::string type_name =
  2012. type == GGUF_TYPE_ARRAY
  2013. ? 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))
  2014. : gguf_type_name(type);
  2015. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2016. const size_t MAX_VALUE_LEN = 40;
  2017. if (value.size() > MAX_VALUE_LEN) {
  2018. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2019. }
  2020. replace_all(value, "\n", "\\n");
  2021. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2022. }
  2023. // print type counts
  2024. for (auto & kv : n_type) {
  2025. if (kv.second == 0) {
  2026. continue;
  2027. }
  2028. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2029. }
  2030. }
  2031. if (!llama_mmap::SUPPORTED) {
  2032. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2033. use_mmap = false;
  2034. }
  2035. this->use_mmap = use_mmap;
  2036. }
  2037. ~llama_model_loader() {
  2038. if (ctx_gguf) {
  2039. gguf_free(ctx_gguf);
  2040. }
  2041. if (ctx_meta) {
  2042. ggml_free(ctx_meta);
  2043. }
  2044. }
  2045. template<typename T>
  2046. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2047. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2048. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2049. if (kid < 0) {
  2050. if (required) {
  2051. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2052. }
  2053. return false;
  2054. }
  2055. struct GGUFMeta::ArrayInfo arr_info =
  2056. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2057. result = arr_info.length;
  2058. return true;
  2059. }
  2060. template<typename T>
  2061. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2062. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2063. return get_arr_n(llm_kv(kid), result, required);
  2064. }
  2065. template<typename T>
  2066. bool get_key(const std::string & key, T & result, const bool required = true) {
  2067. auto it = kv_overrides.find(key);
  2068. const struct llama_model_kv_override * override =
  2069. it != kv_overrides.end() ? &it->second : nullptr;
  2070. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2071. if (required && !found) {
  2072. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2073. }
  2074. return found;
  2075. }
  2076. template<typename T>
  2077. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2078. return get_key(llm_kv(kid), result, required);
  2079. }
  2080. std::string get_arch_name() const {
  2081. return arch_name;
  2082. }
  2083. enum llm_arch get_arch() const {
  2084. return llm_kv.arch;
  2085. }
  2086. const char * get_tensor_name(int i) const {
  2087. return gguf_get_tensor_name(ctx_gguf, i);
  2088. }
  2089. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2090. return ggml_get_tensor(ctx_meta, name);
  2091. }
  2092. struct ggml_tensor * get_tensor_meta(int i) const {
  2093. return get_tensor_meta(get_tensor_name(i));
  2094. }
  2095. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2096. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2097. ggml_set_name(tensor, ggml_get_name(meta));
  2098. n_created++;
  2099. return tensor;
  2100. }
  2101. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2102. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2103. if (cur == NULL) {
  2104. if (!required) {
  2105. return NULL;
  2106. }
  2107. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2108. }
  2109. {
  2110. bool is_ok = true;
  2111. for (size_t i = 0; i < ne.size(); ++i) {
  2112. if (ne[i] != cur->ne[i]) {
  2113. is_ok = false;
  2114. break;
  2115. }
  2116. }
  2117. if (!is_ok) {
  2118. throw std::runtime_error(
  2119. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2120. __func__, name.c_str(),
  2121. llama_format_tensor_shape(ne).c_str(),
  2122. llama_format_tensor_shape(cur).c_str()));
  2123. }
  2124. }
  2125. return create_tensor_for(ctx, cur);
  2126. }
  2127. void done_getting_tensors() const {
  2128. if (n_created != n_tensors) {
  2129. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2130. }
  2131. }
  2132. size_t file_offset(const char * name) const {
  2133. const int idx = gguf_find_tensor(ctx_gguf, name);
  2134. if (idx < 0) {
  2135. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2136. }
  2137. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2138. }
  2139. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2140. // prefetch the whole file - all the data is needed anyway
  2141. if (use_mmap) {
  2142. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2143. }
  2144. // compute the total size of all tensors for progress reporting
  2145. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2146. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2147. size_data += ggml_nbytes(cur);
  2148. }
  2149. if (use_mmap && mapping) {
  2150. if (lmlock) {
  2151. lmlock->init(mapping->addr);
  2152. }
  2153. mmap_used_first = mapping->size;
  2154. }
  2155. }
  2156. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2157. GGML_ASSERT(mapping);
  2158. *first = mapping->size;
  2159. *last = 0;
  2160. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2161. const size_t offs = file_offset(ggml_get_name(tensor));
  2162. *first = std::min(*first, offs);
  2163. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2164. }
  2165. }
  2166. // for backwards compatibility, does not support ggml-backend
  2167. void load_data_for(struct ggml_tensor * cur) const {
  2168. const size_t offs = file_offset(ggml_get_name(cur));
  2169. if (use_mmap && mapping) {
  2170. if (cur->data == nullptr) {
  2171. cur->data = (uint8_t *)mapping->addr + offs;
  2172. } else {
  2173. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2174. }
  2175. } else {
  2176. GGML_ASSERT(cur->data != nullptr);
  2177. file.seek(offs, SEEK_SET);
  2178. file.read_raw(cur->data, ggml_nbytes(cur));
  2179. }
  2180. }
  2181. size_t size_done = 0;
  2182. size_t size_data = 0;
  2183. size_t mmap_used_first = -1;
  2184. size_t mmap_used_last = 0;
  2185. // Returns false if cancelled by progress_callback
  2186. 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) {
  2187. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2188. std::vector<no_init<uint8_t>> read_buf;
  2189. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2190. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2191. if (!cur) {
  2192. // some tensors may be allocated in a different context
  2193. continue;
  2194. }
  2195. if (progress_callback) {
  2196. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2197. return false;
  2198. }
  2199. }
  2200. const size_t offs = file_offset(ggml_get_name(cur));
  2201. if (use_mmap && mapping) {
  2202. if (buf_mmap && cur->data == nullptr) {
  2203. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2204. if (lmlock) {
  2205. lmlock->grow_to(offs + ggml_nbytes(cur));
  2206. }
  2207. mmap_used_first = std::min(mmap_used_first, offs);
  2208. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2209. } else {
  2210. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2211. }
  2212. } else {
  2213. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2214. file.seek(offs, SEEK_SET);
  2215. file.read_raw(cur->data, ggml_nbytes(cur));
  2216. } else {
  2217. read_buf.resize(ggml_nbytes(cur));
  2218. file.seek(offs, SEEK_SET);
  2219. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2220. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2221. }
  2222. }
  2223. size_done += ggml_nbytes(cur);
  2224. }
  2225. // check if this is the last call and do final cleanup
  2226. if (size_done >= size_data) {
  2227. // unmap offloaded tensors and metadata
  2228. if (use_mmap && mapping) {
  2229. mapping->unmap_fragment(0, mmap_used_first);
  2230. if (mmap_used_last != 0) {
  2231. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2232. }
  2233. }
  2234. if (progress_callback) {
  2235. // Even though the model is done loading, we still honor
  2236. // cancellation since we need to free allocations.
  2237. return progress_callback(1.0f, progress_callback_user_data);
  2238. }
  2239. }
  2240. return true;
  2241. }
  2242. };
  2243. //
  2244. // load LLaMA models
  2245. //
  2246. static std::string llama_model_arch_name(llm_arch arch) {
  2247. auto it = LLM_ARCH_NAMES.find(arch);
  2248. if (it == LLM_ARCH_NAMES.end()) {
  2249. return "unknown";
  2250. }
  2251. return it->second;
  2252. }
  2253. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2254. if (ftype & LLAMA_FTYPE_GUESSED) {
  2255. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2256. }
  2257. switch (ftype) {
  2258. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2259. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2260. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2261. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2262. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2263. return "Q4_1, some F16";
  2264. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2265. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2266. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2267. // K-quants
  2268. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2269. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2270. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2271. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2272. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2273. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2274. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2275. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2276. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2277. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2278. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XSS - 2.0625 bpw";
  2279. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2280. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:return "Q3_K - Extra small";
  2281. default: return "unknown, may not work";
  2282. }
  2283. }
  2284. static const char * llama_model_type_name(e_model type) {
  2285. switch (type) {
  2286. case MODEL_1B: return "1B";
  2287. case MODEL_3B: return "3B";
  2288. case MODEL_7B: return "7B";
  2289. case MODEL_8B: return "8B";
  2290. case MODEL_13B: return "13B";
  2291. case MODEL_15B: return "15B";
  2292. case MODEL_30B: return "30B";
  2293. case MODEL_34B: return "34B";
  2294. case MODEL_40B: return "40B";
  2295. case MODEL_65B: return "65B";
  2296. case MODEL_70B: return "70B";
  2297. case MODEL_SMALL: return "0.1B";
  2298. case MODEL_MEDIUM: return "0.4B";
  2299. case MODEL_LARGE: return "0.8B";
  2300. case MODEL_XL: return "1.5B";
  2301. default: return "?B";
  2302. }
  2303. }
  2304. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2305. model.arch = ml.get_arch();
  2306. if (model.arch == LLM_ARCH_UNKNOWN) {
  2307. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2308. }
  2309. }
  2310. static void llm_load_hparams(
  2311. llama_model_loader & ml,
  2312. llama_model & model) {
  2313. auto & hparams = model.hparams;
  2314. const gguf_context * ctx = ml.ctx_gguf;
  2315. // get metadata as string
  2316. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2317. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2318. if (type == GGUF_TYPE_ARRAY) {
  2319. continue;
  2320. }
  2321. const char * name = gguf_get_key(ctx, i);
  2322. const std::string value = gguf_kv_to_str(ctx, i);
  2323. model.gguf_kv.emplace(name, value);
  2324. }
  2325. // get general kv
  2326. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2327. // get hparams kv
  2328. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2329. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2330. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2331. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2332. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2333. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2334. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2335. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2336. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2337. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2338. if (hparams.n_expert > 0) {
  2339. GGML_ASSERT(hparams.n_expert_used > 0);
  2340. } else {
  2341. GGML_ASSERT(hparams.n_expert_used == 0);
  2342. }
  2343. // n_head_kv is optional, default to n_head
  2344. hparams.n_head_kv = hparams.n_head;
  2345. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2346. bool rope_finetuned = false;
  2347. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2348. hparams.rope_finetuned = rope_finetuned;
  2349. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2350. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2351. // rope_freq_base (optional)
  2352. hparams.rope_freq_base_train = 10000.0f;
  2353. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2354. std::string rope_scaling("linear");
  2355. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2356. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2357. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2358. // rope_freq_scale (inverse of the kv) is optional
  2359. float ropescale = 0.0f;
  2360. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2361. // try the old key name
  2362. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2363. }
  2364. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2365. // sanity check for n_rot (optional)
  2366. {
  2367. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2368. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2369. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2370. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2371. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2372. }
  2373. }
  2374. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2375. // gpt-j n_rot = rotary_dim
  2376. }
  2377. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2378. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2379. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2380. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2381. // arch-specific KVs
  2382. switch (model.arch) {
  2383. case LLM_ARCH_LLAMA:
  2384. {
  2385. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2386. switch (hparams.n_layer) {
  2387. case 22: model.type = e_model::MODEL_1B; break;
  2388. case 26: model.type = e_model::MODEL_3B; break;
  2389. case 32: model.type = e_model::MODEL_7B; break;
  2390. case 40: model.type = e_model::MODEL_13B; break;
  2391. case 48: model.type = e_model::MODEL_34B; break;
  2392. case 60: model.type = e_model::MODEL_30B; break;
  2393. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2394. default: model.type = e_model::MODEL_UNKNOWN;
  2395. }
  2396. } break;
  2397. case LLM_ARCH_FALCON:
  2398. {
  2399. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2400. switch (hparams.n_layer) {
  2401. case 32: model.type = e_model::MODEL_7B; break;
  2402. case 60: model.type = e_model::MODEL_40B; break;
  2403. default: model.type = e_model::MODEL_UNKNOWN;
  2404. }
  2405. } break;
  2406. case LLM_ARCH_BAICHUAN:
  2407. {
  2408. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2409. switch (hparams.n_layer) {
  2410. case 32: model.type = e_model::MODEL_7B; break;
  2411. case 40: model.type = e_model::MODEL_13B; break;
  2412. default: model.type = e_model::MODEL_UNKNOWN;
  2413. }
  2414. } break;
  2415. case LLM_ARCH_STARCODER:
  2416. {
  2417. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2418. switch (hparams.n_layer) {
  2419. case 24: model.type = e_model::MODEL_1B; break;
  2420. case 36: model.type = e_model::MODEL_3B; break;
  2421. case 42: model.type = e_model::MODEL_7B; break;
  2422. case 40: model.type = e_model::MODEL_15B; break;
  2423. default: model.type = e_model::MODEL_UNKNOWN;
  2424. }
  2425. } break;
  2426. case LLM_ARCH_PERSIMMON:
  2427. {
  2428. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2429. switch (hparams.n_layer) {
  2430. case 36: model.type = e_model::MODEL_8B; break;
  2431. default: model.type = e_model::MODEL_UNKNOWN;
  2432. }
  2433. } break;
  2434. case LLM_ARCH_REFACT:
  2435. {
  2436. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2437. switch (hparams.n_layer) {
  2438. case 32: model.type = e_model::MODEL_1B; break;
  2439. default: model.type = e_model::MODEL_UNKNOWN;
  2440. }
  2441. } break;
  2442. case LLM_ARCH_BLOOM:
  2443. {
  2444. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2445. switch (hparams.n_layer) {
  2446. case 24: model.type = e_model::MODEL_1B; break;
  2447. case 30:
  2448. switch (hparams.n_embd) {
  2449. case 2560: model.type = e_model::MODEL_3B; break;
  2450. case 4096: model.type = e_model::MODEL_7B; break;
  2451. } break;
  2452. }
  2453. } break;
  2454. case LLM_ARCH_MPT:
  2455. {
  2456. hparams.f_clamp_kqv = 0.0f;
  2457. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2458. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2459. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2460. switch (hparams.n_layer) {
  2461. case 32: model.type = e_model::MODEL_7B; break;
  2462. case 48: model.type = e_model::MODEL_30B; break;
  2463. default: model.type = e_model::MODEL_UNKNOWN;
  2464. }
  2465. } break;
  2466. case LLM_ARCH_STABLELM:
  2467. {
  2468. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2469. switch (hparams.n_layer) {
  2470. case 32: model.type = e_model::MODEL_3B; break;
  2471. default: model.type = e_model::MODEL_UNKNOWN;
  2472. }
  2473. } break;
  2474. case LLM_ARCH_QWEN:
  2475. {
  2476. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2477. switch (hparams.n_layer) {
  2478. case 32: model.type = e_model::MODEL_7B; break;
  2479. case 40: model.type = e_model::MODEL_13B; break;
  2480. default: model.type = e_model::MODEL_UNKNOWN;
  2481. }
  2482. } break;
  2483. case LLM_ARCH_QWEN2:
  2484. {
  2485. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2486. switch (hparams.n_layer) {
  2487. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2488. case 32: model.type = e_model::MODEL_7B; break;
  2489. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2490. case 80: model.type = e_model::MODEL_70B; break;
  2491. default: model.type = e_model::MODEL_UNKNOWN;
  2492. }
  2493. } break;
  2494. case LLM_ARCH_PHI2:
  2495. {
  2496. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2497. switch (hparams.n_layer) {
  2498. case 24: model.type = e_model::MODEL_1B; break;
  2499. case 32: model.type = e_model::MODEL_3B; break;
  2500. default: model.type = e_model::MODEL_UNKNOWN;
  2501. }
  2502. } break;
  2503. case LLM_ARCH_PLAMO:
  2504. {
  2505. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2506. switch (hparams.n_layer) {
  2507. case 40: model.type = e_model::MODEL_13B; break;
  2508. default: model.type = e_model::MODEL_UNKNOWN;
  2509. }
  2510. } break;
  2511. case LLM_ARCH_GPT2:
  2512. {
  2513. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2514. switch (hparams.n_layer) {
  2515. case 12: model.type = e_model::MODEL_SMALL; break;
  2516. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2517. case 36: model.type = e_model::MODEL_LARGE; break;
  2518. case 48: model.type = e_model::MODEL_XL; break;
  2519. default: model.type = e_model::MODEL_UNKNOWN;
  2520. }
  2521. } break;
  2522. case LLM_ARCH_CODESHELL:
  2523. {
  2524. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2525. switch (hparams.n_layer) {
  2526. case 42: model.type = e_model::MODEL_SMALL; break;
  2527. default: model.type = e_model::MODEL_UNKNOWN;
  2528. }
  2529. } break;
  2530. default: (void)0;
  2531. }
  2532. model.ftype = ml.ftype;
  2533. }
  2534. // TODO: This should probably be in llama.h
  2535. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2536. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2537. static void llm_load_vocab(
  2538. llama_model_loader & ml,
  2539. llama_model & model) {
  2540. auto & vocab = model.vocab;
  2541. struct gguf_context * ctx = ml.ctx_gguf;
  2542. const auto kv = LLM_KV(model.arch);
  2543. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2544. if (token_idx == -1) {
  2545. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2546. }
  2547. const float * scores = nullptr;
  2548. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2549. if (score_idx != -1) {
  2550. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2551. }
  2552. const int * toktypes = nullptr;
  2553. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2554. if (toktype_idx != -1) {
  2555. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2556. }
  2557. // determine vocab type
  2558. {
  2559. std::string tokenizer_name;
  2560. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2561. if (tokenizer_name == "llama") {
  2562. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2563. // default special tokens
  2564. vocab.special_bos_id = 1;
  2565. vocab.special_eos_id = 2;
  2566. vocab.special_unk_id = 0;
  2567. vocab.special_sep_id = -1;
  2568. vocab.special_pad_id = -1;
  2569. } else if (tokenizer_name == "gpt2") {
  2570. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2571. // read bpe merges and populate bpe ranks
  2572. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2573. if (merges_keyidx == -1) {
  2574. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2575. }
  2576. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2577. for (int i = 0; i < n_merges; i++) {
  2578. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2579. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2580. std::string first;
  2581. std::string second;
  2582. const size_t pos = word.find(' ', 1);
  2583. if (pos != std::string::npos) {
  2584. first = word.substr(0, pos);
  2585. second = word.substr(pos + 1);
  2586. }
  2587. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2588. }
  2589. // default special tokens
  2590. vocab.special_bos_id = 11;
  2591. vocab.special_eos_id = 11;
  2592. vocab.special_unk_id = -1;
  2593. vocab.special_sep_id = -1;
  2594. vocab.special_pad_id = -1;
  2595. } else {
  2596. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2597. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2598. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2599. }
  2600. }
  2601. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2602. vocab.id_to_token.resize(n_vocab);
  2603. for (uint32_t i = 0; i < n_vocab; i++) {
  2604. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2605. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2606. vocab.token_to_id[word] = i;
  2607. auto & token_data = vocab.id_to_token[i];
  2608. token_data.text = std::move(word);
  2609. token_data.score = scores ? scores[i] : 0.0f;
  2610. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2611. }
  2612. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2613. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2614. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2615. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2616. } else {
  2617. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2618. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2619. vocab.linefeed_id = ids[0];
  2620. }
  2621. // special tokens
  2622. {
  2623. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2624. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2625. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2626. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2627. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2628. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2629. };
  2630. for (const auto & it : special_token_types) {
  2631. const std::string & key = kv(std::get<0>(it));
  2632. int32_t & id = std::get<1>(it);
  2633. uint32_t new_id;
  2634. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2635. continue;
  2636. }
  2637. if (new_id >= vocab.id_to_token.size()) {
  2638. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2639. __func__, key.c_str(), new_id, id);
  2640. } else {
  2641. id = new_id;
  2642. }
  2643. }
  2644. // Handle add_bos_token and add_eos_token
  2645. {
  2646. bool temp = true;
  2647. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2648. vocab.special_add_bos = int(temp);
  2649. }
  2650. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2651. vocab.special_add_eos = int(temp);
  2652. }
  2653. }
  2654. }
  2655. // build special tokens cache
  2656. {
  2657. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2658. // and will always be correctly labeled in 'added_tokens.json' etc.
  2659. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2660. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2661. // are special tokens.
  2662. // From testing, this appears to correlate 1:1 with special tokens.
  2663. //
  2664. // Counting special tokens and verifying in only one direction
  2665. // is sufficient to detect difference in those two sets.
  2666. //
  2667. uint32_t special_tokens_count_by_type = 0;
  2668. uint32_t special_tokens_count_from_verification = 0;
  2669. bool special_tokens_definition_mismatch = false;
  2670. for (const auto & t : vocab.token_to_id) {
  2671. const auto & token = t.first;
  2672. const auto & id = t.second;
  2673. // Count all non-normal tokens in the vocab while iterating
  2674. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2675. special_tokens_count_by_type++;
  2676. }
  2677. // Skip single character tokens
  2678. if (token.length() > 1) {
  2679. bool is_tokenizable = false;
  2680. // Split token string representation in two, in all possible ways
  2681. // and check if both halves can be matched to a valid token
  2682. for (unsigned i = 1; i < token.length();) {
  2683. const auto left = token.substr(0, i);
  2684. const auto right = token.substr(i);
  2685. // check if we didnt partition in the middle of a utf sequence
  2686. auto utf = utf8_len(left.at(left.length() - 1));
  2687. if (utf == 1) {
  2688. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2689. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2690. is_tokenizable = true;
  2691. break;
  2692. }
  2693. i++;
  2694. } else {
  2695. // skip over the rest of multibyte utf sequence
  2696. i += utf - 1;
  2697. }
  2698. }
  2699. if (!is_tokenizable) {
  2700. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2701. // it's faster to re-filter them here, since there are way less candidates now
  2702. // Calculate a total "utf" length of a token string representation
  2703. size_t utf8_str_len = 0;
  2704. for (unsigned i = 0; i < token.length();) {
  2705. utf8_str_len++;
  2706. i += utf8_len(token.at(i));
  2707. }
  2708. // And skip the ones which are one character
  2709. if (utf8_str_len > 1) {
  2710. // At this point what we have left are special tokens only
  2711. vocab.special_tokens_cache[token] = id;
  2712. // Count manually found special tokens
  2713. special_tokens_count_from_verification++;
  2714. // If this manually found special token is not marked as such, flag a mismatch
  2715. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2716. special_tokens_definition_mismatch = true;
  2717. }
  2718. }
  2719. }
  2720. }
  2721. }
  2722. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2723. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2724. __func__,
  2725. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2726. special_tokens_count_by_type, vocab.id_to_token.size()
  2727. );
  2728. } else {
  2729. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2730. __func__,
  2731. special_tokens_count_from_verification, vocab.id_to_token.size()
  2732. );
  2733. }
  2734. }
  2735. }
  2736. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2737. const auto & hparams = model.hparams;
  2738. const auto & vocab = model.vocab;
  2739. const auto rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2740. // hparams
  2741. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2742. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  2743. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  2744. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2745. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2746. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2747. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2748. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2749. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2750. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2751. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  2752. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  2753. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  2754. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2755. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  2756. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  2757. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2758. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2759. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2760. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2761. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2762. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  2763. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  2764. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type.c_str());
  2765. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2766. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2767. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  2768. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  2769. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2770. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2771. if (ml.n_elements >= 1e12) {
  2772. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  2773. } else if (ml.n_elements >= 1e9) {
  2774. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2775. } else if (ml.n_elements >= 1e6) {
  2776. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  2777. } else {
  2778. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  2779. }
  2780. if (ml.n_bytes < GiB) {
  2781. 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);
  2782. } else {
  2783. 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);
  2784. }
  2785. // general kv
  2786. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2787. // special tokens
  2788. 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() ); }
  2789. 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() ); }
  2790. 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() ); }
  2791. 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() ); }
  2792. 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() ); }
  2793. 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() ); }
  2794. }
  2795. // Returns false if cancelled by progress_callback
  2796. static bool llm_load_tensors(
  2797. llama_model_loader & ml,
  2798. llama_model & model,
  2799. int n_gpu_layers,
  2800. enum llama_split_mode split_mode,
  2801. int main_gpu,
  2802. const float * tensor_split,
  2803. bool use_mlock,
  2804. llama_progress_callback progress_callback,
  2805. void * progress_callback_user_data) {
  2806. model.t_start_us = ggml_time_us();
  2807. auto & hparams = model.hparams;
  2808. model.split_mode = split_mode;
  2809. model.main_gpu = main_gpu;
  2810. model.n_gpu_layers = n_gpu_layers;
  2811. const int64_t n_layer = hparams.n_layer;
  2812. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  2813. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  2814. model.buft_input = llama_default_buffer_type_cpu(true);
  2815. model.buft_layer.resize(n_layer);
  2816. // assign cpu layers
  2817. for (int64_t i = 0; i < i_gpu_start; ++i) {
  2818. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  2819. }
  2820. #ifdef GGML_USE_CUBLAS
  2821. if (split_mode == LLAMA_SPLIT_LAYER) {
  2822. // calculate the split points
  2823. int device_count = ggml_backend_cuda_get_device_count();
  2824. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  2825. float splits[GGML_CUDA_MAX_DEVICES];
  2826. if (all_zero) {
  2827. // default split, by free memory
  2828. for (int i = 0; i < device_count; ++i) {
  2829. size_t total;
  2830. size_t free;
  2831. ggml_backend_cuda_get_device_memory(i, &total, &free);
  2832. splits[i] = free;
  2833. }
  2834. } else {
  2835. std::copy(tensor_split, tensor_split + device_count, splits);
  2836. }
  2837. // sum and normalize the splits to get the split points
  2838. float split_sum = 0.0f;
  2839. for (int i = 0; i < device_count; ++i) {
  2840. split_sum += splits[i];
  2841. splits[i] = split_sum;
  2842. }
  2843. for (int i = 0; i < device_count; ++i) {
  2844. splits[i] /= split_sum;
  2845. }
  2846. // assign the repeating layers to the devices according to the splits
  2847. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  2848. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2849. int layer_gpu = std::upper_bound(splits, splits + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits;
  2850. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  2851. }
  2852. // assign the output layer
  2853. if (n_gpu_layers > n_layer) {
  2854. int layer_gpu = std::upper_bound(splits, splits + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits;
  2855. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  2856. } else {
  2857. model.buft_output = llama_default_buffer_type_cpu(true);
  2858. }
  2859. } else
  2860. #endif
  2861. {
  2862. ggml_backend_buffer_type_t split_buft;
  2863. if (split_mode == LLAMA_SPLIT_ROW) {
  2864. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  2865. } else {
  2866. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  2867. split_buft = llama_default_buffer_type_offload(main_gpu);
  2868. }
  2869. // assign the repeating layers
  2870. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2871. model.buft_layer[i] = {
  2872. split_buft,
  2873. llama_default_buffer_type_offload(main_gpu)
  2874. };
  2875. }
  2876. // assign the output layer
  2877. if (n_gpu_layers > n_layer) {
  2878. model.buft_output = {
  2879. split_buft,
  2880. llama_default_buffer_type_offload(main_gpu)
  2881. };
  2882. } else {
  2883. model.buft_output = llama_default_buffer_type_cpu(true);
  2884. }
  2885. }
  2886. // count used buffer types
  2887. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2888. buft_layer_count[model.buft_input.buft]++;
  2889. buft_layer_count[model.buft_input.buft_matrix]++;
  2890. buft_layer_count[model.buft_output.buft]++;
  2891. buft_layer_count[model.buft_output.buft_matrix]++;
  2892. for (int64_t i = 0; i < n_layer; ++i) {
  2893. buft_layer_count[model.buft_layer[i].buft]++;
  2894. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  2895. }
  2896. // create one context per buffer type
  2897. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  2898. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2899. for (auto & it : buft_layer_count) {
  2900. struct ggml_init_params params = {
  2901. /*.mem_size =*/ ctx_size,
  2902. /*.mem_buffer =*/ NULL,
  2903. /*.no_alloc =*/ true,
  2904. };
  2905. ggml_context * ctx = ggml_init(params);
  2906. if (!ctx) {
  2907. throw std::runtime_error(format("failed to create context"));
  2908. }
  2909. ctx_map[it.first] = ctx;
  2910. model.ctxs.push_back(ctx);
  2911. }
  2912. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  2913. // create tensors for the weights
  2914. {
  2915. const int64_t n_embd = hparams.n_embd;
  2916. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  2917. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  2918. const int64_t n_embd_gqa = n_embd_v_gqa;
  2919. const int64_t n_vocab = hparams.n_vocab;
  2920. const int64_t n_ff = hparams.n_ff;
  2921. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  2922. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  2923. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  2924. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  2925. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  2926. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  2927. model.layers.resize(n_layer);
  2928. const auto tn = LLM_TN(model.arch);
  2929. switch (model.arch) {
  2930. case LLM_ARCH_LLAMA:
  2931. case LLM_ARCH_REFACT:
  2932. {
  2933. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2934. // output
  2935. {
  2936. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {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.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2945. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2946. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2947. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2948. // optional bias tensors
  2949. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  2950. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  2951. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  2952. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  2953. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2954. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  2955. if (layer.ffn_gate_inp == nullptr) {
  2956. GGML_ASSERT(hparams.n_expert == 0);
  2957. GGML_ASSERT(hparams.n_expert_used == 0);
  2958. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  2959. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2960. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2961. } else {
  2962. GGML_ASSERT(hparams.n_expert > 0);
  2963. GGML_ASSERT(hparams.n_expert_used > 0);
  2964. // MoE branch
  2965. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  2966. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  2967. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  2968. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  2969. }
  2970. }
  2971. }
  2972. } break;
  2973. case LLM_ARCH_BAICHUAN:
  2974. {
  2975. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2976. {
  2977. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2978. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2979. }
  2980. for (int i = 0; i < n_layer; ++i) {
  2981. ggml_context * ctx_layer = ctx_for_layer(i);
  2982. ggml_context * ctx_split = ctx_for_layer_split(i);
  2983. auto & layer = model.layers[i];
  2984. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2985. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2986. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2987. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2988. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2989. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2990. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  2991. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2992. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2993. }
  2994. } break;
  2995. case LLM_ARCH_FALCON:
  2996. {
  2997. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2998. // output
  2999. {
  3000. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3001. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3002. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3003. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3004. } else {
  3005. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3006. ml.n_created--; // artificial tensor
  3007. }
  3008. }
  3009. for (int i = 0; i < n_layer; ++i) {
  3010. ggml_context * ctx_layer = ctx_for_layer(i);
  3011. ggml_context * ctx_split = ctx_for_layer_split(i);
  3012. auto & layer = model.layers[i];
  3013. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3014. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3015. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3016. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3017. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3018. }
  3019. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3020. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3021. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3022. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3023. }
  3024. } break;
  3025. case LLM_ARCH_STARCODER:
  3026. {
  3027. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3028. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3029. // output
  3030. {
  3031. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3032. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3033. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3034. }
  3035. for (int i = 0; i < n_layer; ++i) {
  3036. ggml_context * ctx_layer = ctx_for_layer(i);
  3037. ggml_context * ctx_split = ctx_for_layer_split(i);
  3038. auto & layer = model.layers[i];
  3039. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3040. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3041. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3042. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3043. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3044. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3045. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3046. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3047. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3048. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3049. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3050. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3051. }
  3052. } break;
  3053. case LLM_ARCH_PERSIMMON:
  3054. {
  3055. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3056. {
  3057. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3058. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3059. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3060. }
  3061. for (int i = 0; i < n_layer; ++i) {
  3062. ggml_context * ctx_layer = ctx_for_layer(i);
  3063. ggml_context * ctx_split = ctx_for_layer_split(i);
  3064. auto & layer = model.layers[i];
  3065. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3066. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3067. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3068. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3069. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3070. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3071. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3072. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3073. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3074. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3075. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3076. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3077. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3078. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3079. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3080. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3081. }
  3082. } break;
  3083. case LLM_ARCH_BLOOM:
  3084. {
  3085. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3086. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3087. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3088. // output
  3089. {
  3090. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3091. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3092. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3093. }
  3094. for (int i = 0; i < n_layer; ++i) {
  3095. ggml_context * ctx_layer = ctx_for_layer(i);
  3096. ggml_context * ctx_split = ctx_for_layer_split(i);
  3097. auto & layer = model.layers[i];
  3098. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3099. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3100. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3101. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3102. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3103. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3104. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3105. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3106. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3107. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3108. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3109. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3110. }
  3111. } break;
  3112. case LLM_ARCH_MPT:
  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 = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3119. }
  3120. for (int i = 0; i < n_layer; ++i) {
  3121. ggml_context * ctx_layer = ctx_for_layer(i);
  3122. ggml_context * ctx_split = ctx_for_layer_split(i);
  3123. auto & layer = model.layers[i];
  3124. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3125. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3126. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3127. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3128. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3129. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3130. // AWQ ScaleActivation layer
  3131. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3132. }
  3133. } break;
  3134. case LLM_ARCH_STABLELM:
  3135. {
  3136. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3137. // output
  3138. {
  3139. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3140. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3141. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3142. }
  3143. for (int i = 0; i < n_layer; ++i) {
  3144. ggml_context * ctx_layer = ctx_for_layer(i);
  3145. ggml_context * ctx_split = ctx_for_layer_split(i);
  3146. auto & layer = model.layers[i];
  3147. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3148. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3149. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3150. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3151. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3152. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3153. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3154. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3155. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3156. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3157. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3158. }
  3159. } break;
  3160. case LLM_ARCH_QWEN:
  3161. {
  3162. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3163. // output
  3164. {
  3165. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3166. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3167. }
  3168. for (int i = 0; i < n_layer; ++i) {
  3169. ggml_context * ctx_layer = ctx_for_layer(i);
  3170. ggml_context * ctx_split = ctx_for_layer_split(i);
  3171. auto & layer = model.layers[i];
  3172. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3173. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3174. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3175. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3176. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3177. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3178. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3179. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3180. }
  3181. } break;
  3182. case LLM_ARCH_QWEN2:
  3183. {
  3184. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3185. // output
  3186. {
  3187. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3188. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3189. }
  3190. for (int i = 0; i < n_layer; ++i) {
  3191. ggml_context * ctx_layer = ctx_for_layer(i);
  3192. ggml_context * ctx_split = ctx_for_layer_split(i);
  3193. auto & layer = model.layers[i];
  3194. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3195. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3196. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3197. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3198. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3199. // optional bias tensors
  3200. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3201. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3202. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3203. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3204. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3205. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3206. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3207. }
  3208. } break;
  3209. case LLM_ARCH_PHI2:
  3210. {
  3211. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3212. // output
  3213. {
  3214. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3215. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3216. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3217. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3218. }
  3219. for (int i = 0; i < n_layer; ++i) {
  3220. ggml_context * ctx_layer = ctx_for_layer(i);
  3221. ggml_context * ctx_split = ctx_for_layer_split(i);
  3222. auto & layer = model.layers[i];
  3223. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3224. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3225. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3226. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3227. if (layer.wqkv == nullptr) {
  3228. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3229. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3230. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3231. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3232. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3233. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3234. }
  3235. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3236. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3237. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3238. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3239. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3240. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3241. }
  3242. } break;
  3243. case LLM_ARCH_PLAMO:
  3244. {
  3245. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3246. // output
  3247. {
  3248. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3249. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3250. }
  3251. for (int i = 0; i < n_layer; ++i) {
  3252. ggml_context * ctx_layer = ctx_for_layer(i);
  3253. ggml_context * ctx_split = ctx_for_layer_split(i);
  3254. auto & layer = model.layers[i];
  3255. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3256. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3257. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3258. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3259. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3260. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3261. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3262. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3263. }
  3264. } break;
  3265. case LLM_ARCH_GPT2:
  3266. {
  3267. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3268. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3269. // output
  3270. {
  3271. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3272. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3273. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3274. }
  3275. for (int i = 0; i < n_layer; ++i) {
  3276. ggml_context * ctx_layer = ctx_for_layer(i);
  3277. ggml_context * ctx_split = ctx_for_layer_split(i);
  3278. auto & layer = model.layers[i];
  3279. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3280. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3281. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3282. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3283. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3284. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3285. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3286. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3287. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3288. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3289. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3290. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3291. }
  3292. } break;
  3293. case LLM_ARCH_CODESHELL:
  3294. {
  3295. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3296. // output
  3297. {
  3298. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3299. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3300. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3301. }
  3302. for (int i = 0; i < n_layer; ++i) {
  3303. ggml_context * ctx_layer = ctx_for_layer(i);
  3304. ggml_context * ctx_split = ctx_for_layer_split(i);
  3305. auto & layer = model.layers[i];
  3306. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3307. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3308. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3309. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3310. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3311. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3312. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3313. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3314. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3315. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3316. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3317. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3318. }
  3319. } break;
  3320. default:
  3321. throw std::runtime_error("unknown architecture");
  3322. }
  3323. }
  3324. ml.done_getting_tensors();
  3325. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3326. // create the backend buffers
  3327. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3328. for (auto & it : ctx_map) {
  3329. ggml_backend_buffer_type_t buft = it.first;
  3330. ggml_context * ctx = it.second;
  3331. ggml_backend_buffer_t buf = nullptr;
  3332. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3333. // 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
  3334. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3335. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3336. size_t first, last;
  3337. ml.get_mapping_range(&first, &last, ctx);
  3338. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3339. }
  3340. #ifdef GGML_USE_METAL
  3341. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3342. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3343. size_t first, last;
  3344. ml.get_mapping_range(&first, &last, ctx);
  3345. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3346. }
  3347. #endif
  3348. else {
  3349. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3350. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3351. model.mlock_bufs.emplace_back(new llama_mlock);
  3352. auto & mlock_buf = model.mlock_bufs.back();
  3353. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3354. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3355. }
  3356. }
  3357. if (buf == nullptr) {
  3358. throw std::runtime_error("failed to allocate buffer");
  3359. }
  3360. // indicate that this buffer contains weights
  3361. // 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
  3362. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3363. model.bufs.push_back(buf);
  3364. ctx_bufs.emplace_back(ctx, buf);
  3365. }
  3366. // print memory requirements
  3367. {
  3368. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3369. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3370. if (n_gpu_layers > (int) hparams.n_layer) {
  3371. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3372. }
  3373. const int max_backend_supported_layers = hparams.n_layer + 1;
  3374. const int max_offloadable_layers = hparams.n_layer + 1;
  3375. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3376. for (ggml_backend_buffer_t buf : model.bufs) {
  3377. 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);
  3378. }
  3379. }
  3380. // populate tensors_by_name
  3381. for (ggml_context * ctx : model.ctxs) {
  3382. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3383. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3384. }
  3385. }
  3386. // load tensor data
  3387. for (auto & it : ctx_bufs) {
  3388. ggml_context * ctx = it.first;
  3389. ggml_backend_buffer_t buf = it.second;
  3390. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3391. return false;
  3392. }
  3393. }
  3394. model.mapping = std::move(ml.mapping);
  3395. // loading time will be recalculate after the first eval, so
  3396. // we take page faults deferred by mmap() into consideration
  3397. model.t_load_us = ggml_time_us() - model.t_start_us;
  3398. return true;
  3399. }
  3400. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3401. static int llama_model_load(const std::string & fname, llama_model & model, const llama_model_params & params) {
  3402. try {
  3403. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3404. model.hparams.vocab_only = params.vocab_only;
  3405. llm_load_arch (ml, model);
  3406. llm_load_hparams(ml, model);
  3407. llm_load_vocab (ml, model);
  3408. llm_load_print_meta(ml, model);
  3409. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3410. throw std::runtime_error("vocab size mismatch");
  3411. }
  3412. if (params.vocab_only) {
  3413. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3414. return 0;
  3415. }
  3416. if (!llm_load_tensors(
  3417. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3418. params.progress_callback, params.progress_callback_user_data
  3419. )) {
  3420. return -2;
  3421. }
  3422. } catch (const std::exception & err) {
  3423. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3424. return -1;
  3425. }
  3426. return 0;
  3427. }
  3428. //
  3429. // llm_build
  3430. //
  3431. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3432. enum llm_rope_type {
  3433. LLM_ROPE,
  3434. LLM_ROPE_NEOX,
  3435. LLM_ROPE_GLM,
  3436. };
  3437. enum llm_ffn_op_type {
  3438. LLM_FFN_SILU,
  3439. LLM_FFN_GELU,
  3440. LLM_FFN_RELU,
  3441. LLM_FFN_RELU_SQR,
  3442. };
  3443. enum llm_ffn_gate_type {
  3444. LLM_FFN_SEQ,
  3445. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3446. };
  3447. enum llm_norm_type {
  3448. LLM_NORM,
  3449. LLM_NORM_RMS,
  3450. };
  3451. static struct ggml_tensor * llm_build_inp_embd(
  3452. struct ggml_context * ctx,
  3453. const llama_hparams & hparams,
  3454. const llama_batch & batch,
  3455. struct ggml_tensor * tok_embd,
  3456. const llm_build_cb & cb) {
  3457. const int64_t n_embd = hparams.n_embd;
  3458. struct ggml_tensor * inpL;
  3459. if (batch.token) {
  3460. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  3461. cb(inp_tokens, "inp_tokens", -1);
  3462. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens);
  3463. } else {
  3464. #ifdef GGML_USE_MPI
  3465. GGML_ASSERT(false && "not implemented");
  3466. #endif
  3467. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  3468. }
  3469. return inpL;
  3470. }
  3471. // Persimmon: n_rot = n_embd_head_k/2
  3472. // Other: n_rot = n_embd_head_k
  3473. static void llm_build_k_shift(
  3474. struct ggml_context * ctx,
  3475. const llama_hparams & hparams,
  3476. const llama_cparams & cparams,
  3477. const llama_kv_cache & kv,
  3478. struct ggml_cgraph * graph,
  3479. llm_rope_type type,
  3480. int64_t n_ctx,
  3481. float freq_base,
  3482. float freq_scale,
  3483. const llm_build_cb & cb) {
  3484. const int64_t n_layer = hparams.n_layer;
  3485. const int64_t n_head_kv = hparams.n_head_kv;
  3486. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3487. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3488. const int32_t n_rot = hparams.n_rot;
  3489. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3490. const float ext_factor = cparams.yarn_ext_factor;
  3491. const float attn_factor = cparams.yarn_attn_factor;
  3492. const float beta_fast = cparams.yarn_beta_fast;
  3493. const float beta_slow = cparams.yarn_beta_slow;
  3494. struct ggml_tensor * K_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_ctx);
  3495. cb(K_shift, "K_shift", -1);
  3496. int rope_type = 0;
  3497. switch (type) {
  3498. case LLM_ROPE: rope_type = 0; break;
  3499. case LLM_ROPE_NEOX: rope_type = 2; break;
  3500. case LLM_ROPE_GLM: rope_type = 4; break;
  3501. }
  3502. for (int il = 0; il < n_layer; ++il) {
  3503. struct ggml_tensor * tmp =
  3504. // we rotate only the first n_rot dimensions
  3505. ggml_rope_custom_inplace(ctx,
  3506. ggml_view_3d(ctx, kv.k_l[il],
  3507. n_embd_head_k, n_head_kv, n_ctx,
  3508. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3509. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3510. 0),
  3511. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3512. ext_factor, attn_factor, beta_fast, beta_slow);
  3513. cb(tmp, "K_shifted", il);
  3514. ggml_build_forward_expand(graph, tmp);
  3515. }
  3516. }
  3517. static void llm_build_kv_store(
  3518. struct ggml_context * ctx,
  3519. const llama_hparams & hparams,
  3520. const llama_kv_cache & kv,
  3521. struct ggml_cgraph * graph,
  3522. struct ggml_tensor * k_cur,
  3523. struct ggml_tensor * v_cur,
  3524. int64_t n_ctx,
  3525. int32_t n_tokens,
  3526. int32_t kv_head,
  3527. const llm_build_cb & cb,
  3528. int64_t il) {
  3529. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3530. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3531. // compute the transposed [n_tokens, n_embd] V matrix
  3532. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  3533. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3534. cb(v_cur_t, "v_cur_t", il);
  3535. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  3536. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  3537. cb(k_cache_view, "k_cache_view", il);
  3538. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  3539. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3540. (kv_head)*ggml_element_size(kv.v_l[il]));
  3541. cb(v_cache_view, "v_cache_view", il);
  3542. // important: storing RoPE-ed version of K in the KV cache!
  3543. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3544. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3545. }
  3546. static struct ggml_tensor * llm_build_norm(
  3547. struct ggml_context * ctx,
  3548. struct ggml_tensor * cur,
  3549. const llama_hparams & hparams,
  3550. struct ggml_tensor * mw,
  3551. struct ggml_tensor * mb,
  3552. llm_norm_type type,
  3553. const llm_build_cb & cb,
  3554. int il) {
  3555. switch (type) {
  3556. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3557. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3558. }
  3559. if (mw || mb) {
  3560. cb(cur, "norm", il);
  3561. }
  3562. if (mw) {
  3563. cur = ggml_mul(ctx, cur, mw);
  3564. if (mb) {
  3565. cb(cur, "norm_w", il);
  3566. }
  3567. }
  3568. if (mb) {
  3569. cur = ggml_add(ctx, cur, mb);
  3570. }
  3571. return cur;
  3572. }
  3573. static struct ggml_tensor * llm_build_ffn(
  3574. struct ggml_context * ctx,
  3575. struct ggml_tensor * cur,
  3576. struct ggml_tensor * up,
  3577. struct ggml_tensor * up_b,
  3578. struct ggml_tensor * gate,
  3579. struct ggml_tensor * gate_b,
  3580. struct ggml_tensor * down,
  3581. struct ggml_tensor * down_b,
  3582. struct ggml_tensor * act_scales,
  3583. llm_ffn_op_type type_op,
  3584. llm_ffn_gate_type type_gate,
  3585. const llm_build_cb & cb,
  3586. int il) {
  3587. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3588. cb(tmp, "ffn_up", il);
  3589. if (up_b) {
  3590. tmp = ggml_add(ctx, tmp, up_b);
  3591. cb(tmp, "ffn_up_b", il);
  3592. }
  3593. if (gate) {
  3594. switch (type_gate) {
  3595. case LLM_FFN_SEQ:
  3596. {
  3597. cur = ggml_mul_mat(ctx, gate, tmp);
  3598. cb(cur, "ffn_gate", il);
  3599. } break;
  3600. case LLM_FFN_PAR:
  3601. {
  3602. cur = ggml_mul_mat(ctx, gate, cur);
  3603. cb(cur, "ffn_gate", il);
  3604. } break;
  3605. }
  3606. if (gate_b) {
  3607. cur = ggml_add(ctx, cur, gate_b);
  3608. cb(cur, "ffn_gate_b", il);
  3609. }
  3610. } else {
  3611. cur = tmp;
  3612. }
  3613. switch (type_op) {
  3614. case LLM_FFN_SILU:
  3615. {
  3616. cur = ggml_silu(ctx, cur);
  3617. cb(cur, "ffn_silu", il);
  3618. } break;
  3619. case LLM_FFN_GELU:
  3620. {
  3621. cur = ggml_gelu(ctx, cur);
  3622. cb(cur, "ffn_gelu", il);
  3623. if (act_scales != NULL) {
  3624. cur = ggml_div(ctx, cur, act_scales);
  3625. cb(cur, "ffn_act", il);
  3626. }
  3627. } break;
  3628. case LLM_FFN_RELU:
  3629. {
  3630. cur = ggml_relu(ctx, cur);
  3631. cb(cur, "ffn_relu", il);
  3632. } break;
  3633. case LLM_FFN_RELU_SQR:
  3634. {
  3635. cur = ggml_relu(ctx, cur);
  3636. cb(cur, "ffn_relu", il);
  3637. cur = ggml_sqr(ctx, cur);
  3638. cb(cur, "ffn_sqr(relu)", il);
  3639. } break;
  3640. }
  3641. if (type_gate == LLM_FFN_PAR) {
  3642. cur = ggml_mul(ctx, cur, tmp);
  3643. cb(cur, "ffn_gate_par", il);
  3644. }
  3645. cur = ggml_mul_mat(ctx, down, cur);
  3646. if (down_b) {
  3647. cb(cur, "ffn_down", il);
  3648. }
  3649. if (down_b) {
  3650. cur = ggml_add(ctx, cur, down_b);
  3651. }
  3652. return cur;
  3653. }
  3654. // if max_alibi_bias > 0 then apply ALiBi
  3655. static struct ggml_tensor * llm_build_kqv(
  3656. struct ggml_context * ctx,
  3657. const llama_model & model,
  3658. const llama_hparams & hparams,
  3659. const llama_kv_cache & kv,
  3660. struct ggml_cgraph * graph,
  3661. struct ggml_tensor * wo,
  3662. struct ggml_tensor * wo_b,
  3663. struct ggml_tensor * q_cur,
  3664. struct ggml_tensor * kq_mask,
  3665. int64_t n_ctx,
  3666. int32_t n_tokens,
  3667. int32_t n_kv,
  3668. float max_alibi_bias,
  3669. float kq_scale,
  3670. const llm_build_cb & cb,
  3671. int il) {
  3672. const int64_t n_head = hparams.n_head;
  3673. const int64_t n_head_kv = hparams.n_head_kv;
  3674. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3675. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3676. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  3677. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3678. cb(q, "q", il);
  3679. struct ggml_tensor * k =
  3680. ggml_view_3d(ctx, kv.k_l[il],
  3681. n_embd_head_k, n_kv, n_head_kv,
  3682. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3683. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3684. 0);
  3685. cb(k, "k", il);
  3686. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3687. cb(kq, "kq", il);
  3688. if (model.arch == LLM_ARCH_PHI2) {
  3689. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  3690. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  3691. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  3692. }
  3693. if (max_alibi_bias > 0.0f) {
  3694. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  3695. kq = ggml_scale(ctx, kq, kq_scale);
  3696. cb(kq, "kq_scaled", il);
  3697. if (max_alibi_bias > 0.0f) {
  3698. // TODO: n_head or n_head_kv
  3699. // TODO: K-shift is likely not working
  3700. // TODO: change to ggml_add
  3701. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  3702. cb(kq, "kq_scaled_alibi", il);
  3703. }
  3704. kq = ggml_add(ctx, kq, kq_mask);
  3705. cb(kq, "kq_masked", il);
  3706. kq = ggml_soft_max(ctx, kq);
  3707. cb(kq, "kq_soft_max", il);
  3708. } else {
  3709. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale);
  3710. cb(kq, "kq_soft_max_ext", il);
  3711. }
  3712. // split cached v into n_head heads
  3713. struct ggml_tensor * v =
  3714. ggml_view_3d(ctx, kv.v_l[il],
  3715. n_kv, n_embd_head_v, n_head_kv,
  3716. ggml_element_size(kv.v_l[il])*n_ctx,
  3717. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  3718. 0);
  3719. cb(v, "v", il);
  3720. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3721. cb(kqv, "kqv", il);
  3722. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3723. cb(kqv_merged, "kqv_merged", il);
  3724. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  3725. cb(cur, "kqv_merged_cont", il);
  3726. ggml_build_forward_expand(graph, cur);
  3727. cur = ggml_mul_mat(ctx, wo, cur);
  3728. if (wo_b) {
  3729. cb(cur, "kqv_wo", il);
  3730. }
  3731. if (wo_b) {
  3732. cur = ggml_add(ctx, cur, wo_b);
  3733. }
  3734. return cur;
  3735. }
  3736. static struct ggml_tensor * llm_build_kv(
  3737. struct ggml_context * ctx,
  3738. const llama_model & model,
  3739. const llama_hparams & hparams,
  3740. const llama_kv_cache & kv,
  3741. struct ggml_cgraph * graph,
  3742. struct ggml_tensor * wo,
  3743. struct ggml_tensor * wo_b,
  3744. struct ggml_tensor * k_cur,
  3745. struct ggml_tensor * v_cur,
  3746. struct ggml_tensor * q_cur,
  3747. struct ggml_tensor * kq_mask,
  3748. int64_t n_ctx,
  3749. int32_t n_tokens,
  3750. int32_t kv_head,
  3751. int32_t n_kv,
  3752. float max_alibi_bias,
  3753. float kq_scale,
  3754. const llm_build_cb & cb,
  3755. int il) {
  3756. // these nodes are added to the graph together so that they are not reordered
  3757. // by doing so, the number of splits in the graph is reduced
  3758. ggml_build_forward_expand(graph, k_cur);
  3759. ggml_build_forward_expand(graph, v_cur);
  3760. ggml_build_forward_expand(graph, q_cur);
  3761. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  3762. struct ggml_tensor * cur;
  3763. cur = llm_build_kqv(ctx, model, hparams, kv, graph,
  3764. wo, wo_b,
  3765. q_cur, kq_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, kq_scale, cb, il);
  3766. cb(cur, "kqv_out", il);
  3767. return cur;
  3768. }
  3769. struct llm_build_context {
  3770. const llama_model & model;
  3771. const llama_hparams & hparams;
  3772. const llama_cparams & cparams;
  3773. const llama_batch & batch;
  3774. const llama_kv_cache & kv_self;
  3775. const int64_t n_embd;
  3776. const int64_t n_layer;
  3777. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  3778. const int64_t n_head;
  3779. const int64_t n_head_kv;
  3780. const int64_t n_embd_head_k;
  3781. const int64_t n_embd_k_gqa;
  3782. const int64_t n_embd_head_v;
  3783. const int64_t n_embd_v_gqa;
  3784. const int64_t n_expert;
  3785. const int64_t n_expert_used;
  3786. const float freq_base;
  3787. const float freq_scale;
  3788. const float ext_factor;
  3789. const float attn_factor;
  3790. const float beta_fast;
  3791. const float beta_slow;
  3792. const float norm_eps;
  3793. const float norm_rms_eps;
  3794. const int32_t n_tokens;
  3795. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  3796. const int32_t kv_head; // index of where we store new KV data in the cache
  3797. const int32_t n_orig_ctx;
  3798. const bool do_rope_shift;
  3799. const llm_build_cb & cb;
  3800. std::vector<uint8_t> & buf_compute_meta;
  3801. struct ggml_context * ctx0 = nullptr;
  3802. // TODO: consider making the entire interface noexcept
  3803. llm_build_context(
  3804. llama_context & lctx,
  3805. const llama_batch & batch,
  3806. const llm_build_cb & cb,
  3807. bool worst_case) :
  3808. model (lctx.model),
  3809. hparams (model.hparams),
  3810. cparams (lctx.cparams),
  3811. batch (batch),
  3812. kv_self (lctx.kv_self),
  3813. n_embd (hparams.n_embd),
  3814. n_layer (hparams.n_layer),
  3815. n_ctx (cparams.n_ctx),
  3816. n_head (hparams.n_head),
  3817. n_head_kv (hparams.n_head_kv),
  3818. n_embd_head_k (hparams.n_embd_head_k),
  3819. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  3820. n_embd_head_v (hparams.n_embd_head_v),
  3821. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  3822. n_expert (hparams.n_expert),
  3823. n_expert_used (hparams.n_expert_used),
  3824. freq_base (cparams.rope_freq_base),
  3825. freq_scale (cparams.rope_freq_scale),
  3826. ext_factor (cparams.yarn_ext_factor),
  3827. attn_factor (cparams.yarn_attn_factor),
  3828. beta_fast (cparams.yarn_beta_fast),
  3829. beta_slow (cparams.yarn_beta_slow),
  3830. norm_eps (hparams.f_norm_eps),
  3831. norm_rms_eps (hparams.f_norm_rms_eps),
  3832. n_tokens (batch.n_tokens),
  3833. n_kv (worst_case ? n_ctx : kv_self.n),
  3834. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  3835. n_orig_ctx (cparams.n_yarn_orig_ctx),
  3836. do_rope_shift (worst_case || kv_self.has_shift),
  3837. cb (cb),
  3838. buf_compute_meta (lctx.buf_compute_meta) {
  3839. // all initializations should be done in init()
  3840. }
  3841. void init() {
  3842. struct ggml_init_params params = {
  3843. /*.mem_size =*/ buf_compute_meta.size(),
  3844. /*.mem_buffer =*/ buf_compute_meta.data(),
  3845. /*.no_alloc =*/ true,
  3846. };
  3847. ctx0 = ggml_init(params);
  3848. }
  3849. void free() {
  3850. if (ctx0) {
  3851. ggml_free(ctx0);
  3852. ctx0 = nullptr;
  3853. }
  3854. }
  3855. struct ggml_cgraph * build_llama() {
  3856. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3857. const int64_t n_embd_head = hparams.n_embd_head_v;
  3858. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3859. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3860. struct ggml_tensor * cur;
  3861. struct ggml_tensor * inpL;
  3862. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3863. cb(inpL, "inp_embd", -1);
  3864. // inp_pos - contains the positions
  3865. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3866. cb(inp_pos, "inp_pos", -1);
  3867. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3868. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3869. cb(KQ_mask, "KQ_mask", -1);
  3870. // shift the entire K-cache if needed
  3871. if (do_rope_shift) {
  3872. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  3873. }
  3874. for (int il = 0; il < n_layer; ++il) {
  3875. struct ggml_tensor * inpSA = inpL;
  3876. // norm
  3877. cur = llm_build_norm(ctx0, inpL, hparams,
  3878. model.layers[il].attn_norm, NULL,
  3879. LLM_NORM_RMS, cb, il);
  3880. cb(cur, "attn_norm", il);
  3881. // self-attention
  3882. {
  3883. // compute Q and K and RoPE them
  3884. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3885. cb(Qcur, "Qcur", il);
  3886. if (model.layers[il].bq) {
  3887. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3888. cb(Qcur, "Qcur", il);
  3889. }
  3890. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3891. cb(Kcur, "Kcur", il);
  3892. if (model.layers[il].bk) {
  3893. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  3894. cb(Kcur, "Kcur", il);
  3895. }
  3896. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3897. cb(Vcur, "Vcur", il);
  3898. if (model.layers[il].bv) {
  3899. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  3900. cb(Vcur, "Vcur", il);
  3901. }
  3902. Qcur = ggml_rope_custom(
  3903. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  3904. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3905. ext_factor, attn_factor, beta_fast, beta_slow
  3906. );
  3907. cb(Qcur, "Qcur", il);
  3908. Kcur = ggml_rope_custom(
  3909. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  3910. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3911. ext_factor, attn_factor, beta_fast, beta_slow
  3912. );
  3913. cb(Kcur, "Kcur", il);
  3914. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  3915. model.layers[il].wo, model.layers[il].bo,
  3916. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3917. cb(cur, "kqv_out", il);
  3918. }
  3919. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3920. cb(ffn_inp, "ffn_inp", il);
  3921. // feed-forward network
  3922. if (model.layers[il].ffn_gate_inp == nullptr) {
  3923. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3924. model.layers[il].ffn_norm, NULL,
  3925. LLM_NORM_RMS, cb, il);
  3926. cb(cur, "ffn_norm", il);
  3927. cur = llm_build_ffn(ctx0, cur,
  3928. model.layers[il].ffn_up, NULL,
  3929. model.layers[il].ffn_gate, NULL,
  3930. model.layers[il].ffn_down, NULL,
  3931. NULL,
  3932. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3933. cb(cur, "ffn_out", il);
  3934. } else {
  3935. // MoE branch
  3936. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3937. model.layers[il].ffn_norm, NULL,
  3938. LLM_NORM_RMS, cb, il);
  3939. cb(cur, "ffn_norm", il);
  3940. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  3941. cb(logits, "ffn_moe_logits", il);
  3942. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  3943. cb(probs, "ffn_moe_probs", il);
  3944. // select experts
  3945. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  3946. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  3947. ggml_tensor * weights = ggml_get_rows(ctx0,
  3948. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  3949. cb(weights, "ffn_moe_weights", il);
  3950. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  3951. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  3952. cb(weights_sum, "ffn_moe_weights_sum", il);
  3953. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  3954. cb(weights, "ffn_moe_weights_norm", il);
  3955. // compute expert outputs
  3956. ggml_tensor * moe_out = nullptr;
  3957. for (int i = 0; i < n_expert_used; ++i) {
  3958. ggml_tensor * cur_expert;
  3959. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  3960. cb(cur_up, "ffn_moe_up", il);
  3961. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  3962. cb(cur_gate, "ffn_moe_gate", il);
  3963. cur_gate = ggml_silu(ctx0, cur_gate);
  3964. cb(cur_gate, "ffn_moe_silu", il);
  3965. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  3966. cb(cur_expert, "ffn_moe_gate_par", il);
  3967. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  3968. cb(cur_expert, "ffn_moe_down", il);
  3969. cur_expert = ggml_mul(ctx0, cur_expert,
  3970. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  3971. cb(cur_expert, "ffn_moe_weighted", il);
  3972. if (i == 0) {
  3973. moe_out = cur_expert;
  3974. } else {
  3975. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  3976. cb(moe_out, "ffn_moe_out", il);
  3977. }
  3978. }
  3979. cur = moe_out;
  3980. }
  3981. cur = ggml_add(ctx0, cur, ffn_inp);
  3982. cb(cur, "l_out", il);
  3983. // input for next layer
  3984. inpL = cur;
  3985. }
  3986. cur = inpL;
  3987. cur = llm_build_norm(ctx0, cur, hparams,
  3988. model.output_norm, NULL,
  3989. LLM_NORM_RMS, cb, -1);
  3990. cb(cur, "result_norm", -1);
  3991. // lm_head
  3992. cur = ggml_mul_mat(ctx0, model.output, cur);
  3993. cb(cur, "result_output", -1);
  3994. ggml_build_forward_expand(gf, cur);
  3995. return gf;
  3996. }
  3997. struct ggml_cgraph * build_baichuan() {
  3998. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3999. const int64_t n_embd_head = hparams.n_embd_head_v;
  4000. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4001. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4002. struct ggml_tensor * cur;
  4003. struct ggml_tensor * inpL;
  4004. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4005. cb(inpL, "inp_embd", -1);
  4006. // inp_pos - contains the positions
  4007. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4008. cb(inp_pos, "inp_pos", -1);
  4009. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4010. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4011. cb(KQ_mask, "KQ_mask", -1);
  4012. // shift the entire K-cache if needed
  4013. if (do_rope_shift) {
  4014. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4015. }
  4016. for (int il = 0; il < n_layer; ++il) {
  4017. struct ggml_tensor * inpSA = inpL;
  4018. cur = llm_build_norm(ctx0, inpL, hparams,
  4019. model.layers[il].attn_norm, NULL,
  4020. LLM_NORM_RMS, cb, il);
  4021. cb(cur, "attn_norm", il);
  4022. // self-attention
  4023. {
  4024. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4025. cb(Qcur, "Qcur", il);
  4026. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4027. cb(Kcur, "Kcur", il);
  4028. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4029. cb(Vcur, "Vcur", il);
  4030. switch (model.type) {
  4031. case MODEL_7B:
  4032. Qcur = ggml_rope_custom(
  4033. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4034. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4035. ext_factor, attn_factor, beta_fast, beta_slow
  4036. );
  4037. Kcur = ggml_rope_custom(
  4038. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4039. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4040. ext_factor, attn_factor, beta_fast, beta_slow
  4041. );
  4042. break;
  4043. case MODEL_13B:
  4044. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4045. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4046. break;
  4047. default:
  4048. GGML_ASSERT(false);
  4049. }
  4050. cb(Qcur, "Qcur", il);
  4051. cb(Kcur, "Kcur", il);
  4052. // apply ALiBi for 13B model
  4053. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  4054. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4055. model.layers[il].wo, NULL,
  4056. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4057. cb(cur, "kqv_out", il);
  4058. }
  4059. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4060. cb(ffn_inp, "ffn_inp", il);
  4061. // feed-forward network
  4062. {
  4063. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4064. model.layers[il].ffn_norm, NULL,
  4065. LLM_NORM_RMS, cb, il);
  4066. cb(cur, "ffn_norm", il);
  4067. cur = llm_build_ffn(ctx0, cur,
  4068. model.layers[il].ffn_up, NULL,
  4069. model.layers[il].ffn_gate, NULL,
  4070. model.layers[il].ffn_down, NULL,
  4071. NULL,
  4072. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4073. cb(cur, "ffn_out", il);
  4074. }
  4075. cur = ggml_add(ctx0, cur, ffn_inp);
  4076. cb(cur, "l_out", il);
  4077. // input for next layer
  4078. inpL = cur;
  4079. }
  4080. cur = inpL;
  4081. cur = llm_build_norm(ctx0, cur, hparams,
  4082. model.output_norm, NULL,
  4083. LLM_NORM_RMS, cb, -1);
  4084. cb(cur, "result_norm", -1);
  4085. // lm_head
  4086. cur = ggml_mul_mat(ctx0, model.output, cur);
  4087. cb(cur, "result_output", -1);
  4088. ggml_build_forward_expand(gf, cur);
  4089. return gf;
  4090. }
  4091. struct ggml_cgraph * build_falcon() {
  4092. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4093. const int64_t n_embd_head = hparams.n_embd_head_v;
  4094. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4095. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4096. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4097. struct ggml_tensor * cur;
  4098. struct ggml_tensor * inpL;
  4099. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4100. cb(inpL, "inp_embd", -1);
  4101. // inp_pos - contains the positions
  4102. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4103. cb(inp_pos, "inp_pos", -1);
  4104. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4105. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4106. cb(KQ_mask, "KQ_mask", -1);
  4107. // shift the entire K-cache if needed
  4108. if (do_rope_shift) {
  4109. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4110. }
  4111. for (int il = 0; il < n_layer; ++il) {
  4112. struct ggml_tensor * attn_norm;
  4113. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4114. model.layers[il].attn_norm,
  4115. model.layers[il].attn_norm_b,
  4116. LLM_NORM, cb, il);
  4117. cb(attn_norm, "attn_norm", il);
  4118. // self-attention
  4119. {
  4120. if (model.layers[il].attn_norm_2) {
  4121. // Falcon-40B
  4122. cur = llm_build_norm(ctx0, inpL, hparams,
  4123. model.layers[il].attn_norm_2,
  4124. model.layers[il].attn_norm_2_b,
  4125. LLM_NORM, cb, il);
  4126. cb(cur, "attn_norm_2", il);
  4127. } else {
  4128. cur = attn_norm;
  4129. }
  4130. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4131. cb(cur, "wqkv", il);
  4132. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4133. 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)));
  4134. 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)));
  4135. cb(Qcur, "Qcur", il);
  4136. cb(Kcur, "Kcur", il);
  4137. cb(Vcur, "Vcur", il);
  4138. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4139. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4140. // using mode = 2 for neox mode
  4141. Qcur = ggml_rope_custom(
  4142. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4143. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4144. );
  4145. cb(Qcur, "Qcur", il);
  4146. Kcur = ggml_rope_custom(
  4147. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4148. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4149. );
  4150. cb(Kcur, "Kcur", il);
  4151. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4152. model.layers[il].wo, NULL,
  4153. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4154. cb(cur, "kqv_out", il);
  4155. }
  4156. struct ggml_tensor * ffn_inp = cur;
  4157. // feed forward
  4158. {
  4159. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4160. model.layers[il].ffn_up, NULL,
  4161. NULL, NULL,
  4162. model.layers[il].ffn_down, NULL,
  4163. NULL,
  4164. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4165. cb(cur, "ffn_out", il);
  4166. }
  4167. cur = ggml_add(ctx0, cur, ffn_inp);
  4168. cb(cur, "l_out", il);
  4169. cur = ggml_add(ctx0, cur, inpL);
  4170. cb(cur, "l_out", il);
  4171. // input for next layer
  4172. inpL = cur;
  4173. }
  4174. cur = inpL;
  4175. // norm
  4176. cur = llm_build_norm(ctx0, cur, hparams,
  4177. model.output_norm,
  4178. model.output_norm_b,
  4179. LLM_NORM, cb, -1);
  4180. cb(cur, "result_norm", -1);
  4181. cur = ggml_mul_mat(ctx0, model.output, cur);
  4182. cb(cur, "result_output", -1);
  4183. ggml_build_forward_expand(gf, cur);
  4184. return gf;
  4185. }
  4186. struct ggml_cgraph * build_starcoder() {
  4187. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4188. const int64_t n_embd_head = hparams.n_embd_head_v;
  4189. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4190. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4191. struct ggml_tensor * cur;
  4192. struct ggml_tensor * pos;
  4193. struct ggml_tensor * inpL;
  4194. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4195. cb(inpL, "inp_embd", -1);
  4196. // inp_pos - contains the positions
  4197. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4198. cb(inp_pos, "inp_pos", -1);
  4199. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4200. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4201. cb(KQ_mask, "KQ_mask", -1);
  4202. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4203. cb(pos, "pos_embd", -1);
  4204. inpL = ggml_add(ctx0, inpL, pos);
  4205. cb(inpL, "inpL", -1);
  4206. for (int il = 0; il < n_layer; ++il) {
  4207. cur = llm_build_norm(ctx0, inpL, hparams,
  4208. model.layers[il].attn_norm,
  4209. model.layers[il].attn_norm_b,
  4210. LLM_NORM, cb, il);
  4211. cb(cur, "attn_norm", il);
  4212. // self-attention
  4213. {
  4214. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4215. cb(cur, "wqkv", il);
  4216. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4217. cb(cur, "bqkv", il);
  4218. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4219. 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)));
  4220. 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)));
  4221. cb(Qcur, "Qcur", il);
  4222. cb(Kcur, "Kcur", il);
  4223. cb(Vcur, "Vcur", il);
  4224. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4225. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4226. model.layers[il].wo, model.layers[il].bo,
  4227. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4228. cb(cur, "kqv_out", il);
  4229. }
  4230. // add the input
  4231. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4232. cb(ffn_inp, "ffn_inp", il);
  4233. // FF
  4234. {
  4235. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4236. model.layers[il].ffn_norm,
  4237. model.layers[il].ffn_norm_b,
  4238. LLM_NORM, cb, il);
  4239. cb(cur, "ffn_norm", il);
  4240. cur = llm_build_ffn(ctx0, cur,
  4241. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4242. NULL, NULL,
  4243. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4244. NULL,
  4245. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4246. cb(cur, "ffn_out", il);
  4247. }
  4248. inpL = ggml_add(ctx0, cur, ffn_inp);
  4249. cb(inpL, "l_out", il);
  4250. }
  4251. cur = llm_build_norm(ctx0, inpL, hparams,
  4252. model.output_norm,
  4253. model.output_norm_b,
  4254. LLM_NORM, cb, -1);
  4255. cb(cur, "result_norm", -1);
  4256. cur = ggml_mul_mat(ctx0, model.output, cur);
  4257. cb(cur, "result_output", -1);
  4258. ggml_build_forward_expand(gf, cur);
  4259. return gf;
  4260. }
  4261. struct ggml_cgraph * build_persimmon() {
  4262. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4263. const int64_t n_embd_head = hparams.n_embd_head_v;
  4264. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4265. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4266. struct ggml_tensor * cur;
  4267. struct ggml_tensor * inpL;
  4268. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4269. cb(inpL, "inp_embd", -1);
  4270. // inp_pos - contains the positions
  4271. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4272. cb(inp_pos, "inp_pos", -1);
  4273. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4274. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4275. cb(KQ_mask, "KQ_mask", -1);
  4276. if (do_rope_shift) {
  4277. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4278. }
  4279. for (int il = 0; il < n_layer; ++il) {
  4280. struct ggml_tensor * residual = inpL;
  4281. cur = llm_build_norm(ctx0, inpL, hparams,
  4282. model.layers[il].attn_norm,
  4283. model.layers[il].attn_norm_b,
  4284. LLM_NORM, cb, il);
  4285. cb(cur, "attn_norm", il);
  4286. // self attention
  4287. {
  4288. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4289. cb(cur, "wqkv", il);
  4290. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4291. cb(cur, "bqkv", il);
  4292. // split qkv
  4293. GGML_ASSERT(n_head_kv == n_head);
  4294. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4295. cb(tmpqkv, "tmpqkv", il);
  4296. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4297. cb(tmpqkv_perm, "tmpqkv", il);
  4298. struct ggml_tensor * tmpq = ggml_view_3d(
  4299. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4300. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4301. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4302. 0
  4303. );
  4304. cb(tmpq, "tmpq", il);
  4305. struct ggml_tensor * tmpk = ggml_view_3d(
  4306. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4307. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4308. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4309. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4310. );
  4311. cb(tmpk, "tmpk", il);
  4312. // Q/K Layernorm
  4313. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4314. model.layers[il].attn_q_norm,
  4315. model.layers[il].attn_q_norm_b,
  4316. LLM_NORM, cb, il);
  4317. cb(tmpq, "tmpq", il);
  4318. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4319. model.layers[il].attn_k_norm,
  4320. model.layers[il].attn_k_norm_b,
  4321. LLM_NORM, cb, il);
  4322. cb(tmpk, "tmpk", il);
  4323. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4324. struct ggml_tensor * qrot = ggml_view_3d(
  4325. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4326. ggml_element_size(tmpq) * n_embd_head,
  4327. ggml_element_size(tmpq) * n_embd_head * n_head,
  4328. 0
  4329. );
  4330. cb(qrot, "qrot", il);
  4331. struct ggml_tensor * krot = ggml_view_3d(
  4332. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4333. ggml_element_size(tmpk) * n_embd_head,
  4334. ggml_element_size(tmpk) * n_embd_head * n_head,
  4335. 0
  4336. );
  4337. cb(krot, "krot", il);
  4338. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4339. struct ggml_tensor * qpass = ggml_view_3d(
  4340. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4341. ggml_element_size(tmpq) * n_embd_head,
  4342. ggml_element_size(tmpq) * n_embd_head * n_head,
  4343. ggml_element_size(tmpq) * hparams.n_rot
  4344. );
  4345. cb(qpass, "qpass", il);
  4346. struct ggml_tensor * kpass = ggml_view_3d(
  4347. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4348. ggml_element_size(tmpk) * n_embd_head,
  4349. ggml_element_size(tmpk) * n_embd_head * n_head,
  4350. ggml_element_size(tmpk) * hparams.n_rot
  4351. );
  4352. cb(kpass, "kpass", il);
  4353. struct ggml_tensor * qrotated = ggml_rope_custom(
  4354. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4355. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4356. );
  4357. cb(qrotated, "qrotated", il);
  4358. struct ggml_tensor * krotated = ggml_rope_custom(
  4359. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4360. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4361. );
  4362. cb(krotated, "krotated", il);
  4363. // ggml currently only supports concatenation on dim=2
  4364. // so we need to permute qrot, qpass, concat, then permute back.
  4365. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4366. cb(qrotated, "qrotated", il);
  4367. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4368. cb(krotated, "krotated", il);
  4369. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4370. cb(qpass, "qpass", il);
  4371. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4372. cb(kpass, "kpass", il);
  4373. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4374. cb(Qcur, "Qcur", il);
  4375. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4376. cb(Kcur, "Kcur", il);
  4377. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4378. cb(Q, "Q", il);
  4379. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4380. cb(Kcur, "Kcur", il);
  4381. struct ggml_tensor * Vcur = ggml_view_3d(
  4382. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4383. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4384. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4385. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4386. );
  4387. cb(Vcur, "Vcur", il);
  4388. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4389. model.layers[il].wo, model.layers[il].bo,
  4390. Kcur, Vcur, Q, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4391. cb(cur, "kqv_out", il);
  4392. }
  4393. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4394. cb(ffn_inp, "ffn_inp", il);
  4395. // feed-forward network
  4396. {
  4397. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4398. model.layers[il].ffn_norm,
  4399. model.layers[il].ffn_norm_b,
  4400. LLM_NORM, cb, il);
  4401. cb(cur, "ffn_norm", il);
  4402. cur = llm_build_ffn(ctx0, cur,
  4403. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4404. NULL, NULL,
  4405. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4406. NULL,
  4407. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4408. cb(cur, "ffn_out", il);
  4409. }
  4410. cur = ggml_add(ctx0, cur, ffn_inp);
  4411. cb(cur, "l_out", il);
  4412. inpL = cur;
  4413. }
  4414. cur = inpL;
  4415. cur = llm_build_norm(ctx0, cur, hparams,
  4416. model.output_norm,
  4417. model.output_norm_b,
  4418. LLM_NORM, cb, -1);
  4419. cb(cur, "result_norm", -1);
  4420. cur = ggml_mul_mat(ctx0, model.output, cur);
  4421. cb(cur, "result_output", -1);
  4422. ggml_build_forward_expand(gf, cur);
  4423. return gf;
  4424. }
  4425. struct ggml_cgraph * build_refact() {
  4426. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4427. const int64_t n_embd_head = hparams.n_embd_head_v;
  4428. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4429. struct ggml_tensor * cur;
  4430. struct ggml_tensor * inpL;
  4431. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4432. cb(inpL, "inp_embd", -1);
  4433. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4434. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4435. cb(KQ_mask, "KQ_mask", -1);
  4436. for (int il = 0; il < n_layer; ++il) {
  4437. struct ggml_tensor * inpSA = inpL;
  4438. cur = llm_build_norm(ctx0, inpL, hparams,
  4439. model.layers[il].attn_norm, NULL,
  4440. LLM_NORM_RMS, cb, il);
  4441. cb(cur, "attn_norm", il);
  4442. // self-attention
  4443. {
  4444. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4445. cb(Qcur, "Qcur", il);
  4446. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4447. cb(Kcur, "Kcur", il);
  4448. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4449. cb(Vcur, "Vcur", il);
  4450. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4451. cb(Kcur, "Kcur", il);
  4452. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4453. cb(Qcur, "Qcur", il);
  4454. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4455. model.layers[il].wo, NULL,
  4456. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4457. cb(cur, "kqv_out", il);
  4458. }
  4459. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4460. cb(ffn_inp, "ffn_inp", il);
  4461. // feed-forward network
  4462. {
  4463. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4464. model.layers[il].ffn_norm, NULL,
  4465. LLM_NORM_RMS, cb, il);
  4466. cb(cur, "ffn_norm", il);
  4467. cur = llm_build_ffn(ctx0, cur,
  4468. model.layers[il].ffn_up, NULL,
  4469. model.layers[il].ffn_gate, NULL,
  4470. model.layers[il].ffn_down, NULL,
  4471. NULL,
  4472. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4473. cb(cur, "ffn_out", il);
  4474. }
  4475. cur = ggml_add(ctx0, cur, ffn_inp);
  4476. cb(cur, "l_out", il);
  4477. // input for next layer
  4478. inpL = cur;
  4479. }
  4480. cur = inpL;
  4481. cur = llm_build_norm(ctx0, cur, hparams,
  4482. model.output_norm, NULL,
  4483. LLM_NORM_RMS, cb, -1);
  4484. cb(cur, "result_norm", -1);
  4485. // lm_head
  4486. cur = ggml_mul_mat(ctx0, model.output, cur);
  4487. cb(cur, "result_output", -1);
  4488. ggml_build_forward_expand(gf, cur);
  4489. return gf;
  4490. }
  4491. struct ggml_cgraph * build_bloom() {
  4492. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4493. const int64_t n_embd_head = hparams.n_embd_head_v;
  4494. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4495. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4496. struct ggml_tensor * cur;
  4497. struct ggml_tensor * inpL;
  4498. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4499. cb(inpL, "inp_embd", -1);
  4500. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4501. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4502. cb(KQ_mask, "KQ_mask", -1);
  4503. inpL = llm_build_norm(ctx0, inpL, hparams,
  4504. model.tok_norm,
  4505. model.tok_norm_b,
  4506. LLM_NORM, cb, -1);
  4507. cb(inpL, "inp_norm", -1);
  4508. for (int il = 0; il < n_layer; ++il) {
  4509. cur = llm_build_norm(ctx0, inpL, hparams,
  4510. model.layers[il].attn_norm,
  4511. model.layers[il].attn_norm_b,
  4512. LLM_NORM, cb, il);
  4513. cb(cur, "attn_norm", il);
  4514. // self-attention
  4515. {
  4516. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4517. cb(cur, "wqkv", il);
  4518. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4519. cb(cur, "bqkv", il);
  4520. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4521. 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)));
  4522. 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)));
  4523. cb(Qcur, "Qcur", il);
  4524. cb(Kcur, "Kcur", il);
  4525. cb(Vcur, "Vcur", il);
  4526. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4527. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4528. model.layers[il].wo, model.layers[il].bo,
  4529. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4530. cb(cur, "kqv_out", il);
  4531. }
  4532. // Add the input
  4533. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4534. cb(ffn_inp, "ffn_inp", il);
  4535. // FF
  4536. {
  4537. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4538. model.layers[il].ffn_norm,
  4539. model.layers[il].ffn_norm_b,
  4540. LLM_NORM, cb, il);
  4541. cb(cur, "ffn_norm", il);
  4542. cur = llm_build_ffn(ctx0, cur,
  4543. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4544. NULL, NULL,
  4545. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4546. NULL,
  4547. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4548. cb(cur, "ffn_out", il);
  4549. }
  4550. inpL = ggml_add(ctx0, cur, ffn_inp);
  4551. cb(inpL, "l_out", il);
  4552. }
  4553. cur = llm_build_norm(ctx0, inpL, hparams,
  4554. model.output_norm,
  4555. model.output_norm_b,
  4556. LLM_NORM, cb, -1);
  4557. cb(cur, "result_norm", -1);
  4558. cur = ggml_mul_mat(ctx0, model.output, cur);
  4559. cb(cur, "result_output", -1);
  4560. ggml_build_forward_expand(gf, cur);
  4561. return gf;
  4562. }
  4563. struct ggml_cgraph * build_mpt() {
  4564. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4565. const int64_t n_embd_head = hparams.n_embd_head_v;
  4566. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4567. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4568. struct ggml_tensor * cur;
  4569. struct ggml_tensor * inpL;
  4570. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4571. cb(inpL, "inp_embd", -1);
  4572. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4573. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4574. cb(KQ_mask, "KQ_mask", -1);
  4575. for (int il = 0; il < n_layer; ++il) {
  4576. struct ggml_tensor * attn_norm;
  4577. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4578. model.layers[il].attn_norm,
  4579. NULL,
  4580. LLM_NORM, cb, il);
  4581. cb(attn_norm, "attn_norm", il);
  4582. // self-attention
  4583. {
  4584. cur = attn_norm;
  4585. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4586. cb(cur, "wqkv", il);
  4587. if (hparams.f_clamp_kqv > 0.0f) {
  4588. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4589. cb(cur, "wqkv_clamped", il);
  4590. }
  4591. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4592. 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)));
  4593. 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)));
  4594. cb(Qcur, "Qcur", il);
  4595. cb(Kcur, "Kcur", il);
  4596. cb(Vcur, "Vcur", il);
  4597. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4598. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4599. model.layers[il].wo, NULL,
  4600. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, hparams.f_max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4601. cb(cur, "kqv_out", il);
  4602. }
  4603. // Add the input
  4604. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4605. cb(ffn_inp, "ffn_inp", il);
  4606. // feed forward
  4607. {
  4608. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4609. model.layers[il].ffn_norm,
  4610. NULL,
  4611. LLM_NORM, cb, il);
  4612. cb(cur, "ffn_norm", il);
  4613. cur = llm_build_ffn(ctx0, cur,
  4614. model.layers[il].ffn_up, NULL,
  4615. NULL, NULL,
  4616. model.layers[il].ffn_down, NULL,
  4617. model.layers[il].ffn_act,
  4618. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4619. cb(cur, "ffn_out", il);
  4620. }
  4621. cur = ggml_add(ctx0, cur, ffn_inp);
  4622. cb(cur, "l_out", il);
  4623. // input for next layer
  4624. inpL = cur;
  4625. }
  4626. cur = inpL;
  4627. cur = llm_build_norm(ctx0, cur, hparams,
  4628. model.output_norm,
  4629. NULL,
  4630. LLM_NORM, cb, -1);
  4631. cb(cur, "result_norm", -1);
  4632. cur = ggml_mul_mat(ctx0, model.output, cur);
  4633. cb(cur, "result_output", -1);
  4634. ggml_build_forward_expand(gf, cur);
  4635. return gf;
  4636. }
  4637. struct ggml_cgraph * build_stablelm() {
  4638. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4639. const int64_t n_embd_head = hparams.n_embd_head_v;
  4640. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4641. struct ggml_tensor * cur;
  4642. struct ggml_tensor * inpL;
  4643. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4644. cb(inpL, "inp_embd", -1);
  4645. // inp_pos - contains the positions
  4646. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4647. cb(inp_pos, "inp_pos", -1);
  4648. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4649. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4650. cb(KQ_mask, "KQ_mask", -1);
  4651. // shift the entire K-cache if needed
  4652. if (do_rope_shift) {
  4653. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4654. }
  4655. for (int il = 0; il < n_layer; ++il) {
  4656. struct ggml_tensor * inpSA = inpL;
  4657. // norm
  4658. cur = llm_build_norm(ctx0, inpL, hparams,
  4659. model.layers[il].attn_norm,
  4660. model.layers[il].attn_norm_b,
  4661. LLM_NORM, cb, il);
  4662. cb(cur, "attn_norm", il);
  4663. // self-attention
  4664. {
  4665. // compute Q and K and RoPE them
  4666. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4667. cb(Qcur, "Qcur", il);
  4668. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4669. cb(Kcur, "Kcur", il);
  4670. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4671. cb(Vcur, "Vcur", il);
  4672. Qcur = ggml_rope_custom(
  4673. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4674. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4675. ext_factor, attn_factor, beta_fast, beta_slow
  4676. );
  4677. cb(Qcur, "Qcur", il);
  4678. Kcur = ggml_rope_custom(
  4679. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4680. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4681. ext_factor, attn_factor, beta_fast, beta_slow
  4682. );
  4683. cb(Kcur, "Kcur", il);
  4684. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4685. model.layers[il].wo, NULL,
  4686. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4687. cb(cur, "kqv_out", il);
  4688. }
  4689. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4690. cb(ffn_inp, "ffn_inp", il);
  4691. // feed-forward network
  4692. {
  4693. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4694. model.layers[il].ffn_norm,
  4695. model.layers[il].ffn_norm_b,
  4696. LLM_NORM, cb, il);
  4697. cb(cur, "ffn_norm", il);
  4698. cur = llm_build_ffn(ctx0, cur,
  4699. model.layers[il].ffn_up, NULL,
  4700. model.layers[il].ffn_gate, NULL,
  4701. model.layers[il].ffn_down, NULL,
  4702. NULL,
  4703. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4704. cb(cur, "ffn_out", il);
  4705. }
  4706. cur = ggml_add(ctx0, cur, ffn_inp);
  4707. cb(cur, "l_out", il);
  4708. // input for next layer
  4709. inpL = cur;
  4710. }
  4711. cur = inpL;
  4712. cur = llm_build_norm(ctx0, cur, hparams,
  4713. model.output_norm,
  4714. model.output_norm_b,
  4715. LLM_NORM, cb, -1);
  4716. cb(cur, "result_norm", -1);
  4717. // lm_head
  4718. cur = ggml_mul_mat(ctx0, model.output, cur);
  4719. cb(cur, "result_output", -1);
  4720. ggml_build_forward_expand(gf, cur);
  4721. return gf;
  4722. }
  4723. struct ggml_cgraph * build_qwen() {
  4724. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4725. const int64_t n_embd_head = hparams.n_embd_head_v;
  4726. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4727. struct ggml_tensor * cur;
  4728. struct ggml_tensor * inpL;
  4729. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4730. cb(inpL, "inp_embd", -1);
  4731. // inp_pos - contains the positions
  4732. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4733. cb(inp_pos, "inp_pos", -1);
  4734. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4735. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4736. cb(KQ_mask, "KQ_mask", -1);
  4737. // shift the entire K-cache if needed
  4738. if (do_rope_shift) {
  4739. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4740. }
  4741. for (int il = 0; il < n_layer; ++il) {
  4742. struct ggml_tensor * inpSA = inpL;
  4743. cur = llm_build_norm(ctx0, inpL, hparams,
  4744. model.layers[il].attn_norm, NULL,
  4745. LLM_NORM_RMS, cb, il);
  4746. cb(cur, "attn_norm", il);
  4747. // self-attention
  4748. {
  4749. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4750. cb(cur, "wqkv", il);
  4751. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4752. cb(cur, "bqkv", il);
  4753. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4754. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4755. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  4756. cb(Qcur, "Qcur", il);
  4757. cb(Kcur, "Kcur", il);
  4758. cb(Vcur, "Vcur", il);
  4759. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4760. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4761. // using mode = 2 for neox mode
  4762. Qcur = ggml_rope_custom(
  4763. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4764. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4765. );
  4766. cb(Qcur, "Qcur", il);
  4767. Kcur = ggml_rope_custom(
  4768. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4769. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4770. );
  4771. cb(Kcur, "Kcur", il);
  4772. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4773. model.layers[il].wo, NULL,
  4774. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4775. cb(cur, "kqv_out", il);
  4776. }
  4777. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4778. cb(ffn_inp, "ffn_inp", il);
  4779. // feed-forward forward
  4780. {
  4781. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4782. model.layers[il].ffn_norm, NULL,
  4783. LLM_NORM_RMS, cb, il);
  4784. cb(cur, "ffn_norm", il);
  4785. cur = llm_build_ffn(ctx0, cur,
  4786. model.layers[il].ffn_up, NULL,
  4787. model.layers[il].ffn_gate, NULL,
  4788. model.layers[il].ffn_down, NULL,
  4789. NULL,
  4790. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4791. cb(cur, "ffn_out", il);
  4792. }
  4793. cur = ggml_add(ctx0, cur, ffn_inp);
  4794. cb(cur, "l_out", il);
  4795. // input for next layer
  4796. inpL = cur;
  4797. }
  4798. cur = inpL;
  4799. cur = llm_build_norm(ctx0, cur, hparams,
  4800. model.output_norm, NULL,
  4801. LLM_NORM_RMS, cb, -1);
  4802. cb(cur, "result_norm", -1);
  4803. // lm_head
  4804. cur = ggml_mul_mat(ctx0, model.output, cur);
  4805. cb(cur, "result_output", -1);
  4806. ggml_build_forward_expand(gf, cur);
  4807. return gf;
  4808. }
  4809. struct ggml_cgraph * build_qwen2() {
  4810. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4811. const int64_t n_embd_head = hparams.n_embd_head_v;
  4812. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4813. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4814. struct ggml_tensor * cur;
  4815. struct ggml_tensor * inpL;
  4816. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4817. cb(inpL, "inp_embd", -1);
  4818. // inp_pos - contains the positions
  4819. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4820. cb(inp_pos, "inp_pos", -1);
  4821. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4822. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4823. cb(KQ_mask, "KQ_mask", -1);
  4824. // shift the entire K-cache if needed
  4825. if (do_rope_shift) {
  4826. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4827. }
  4828. for (int il = 0; il < n_layer; ++il) {
  4829. struct ggml_tensor * inpSA = inpL;
  4830. // norm
  4831. cur = llm_build_norm(ctx0, inpL, hparams,
  4832. model.layers[il].attn_norm, NULL,
  4833. LLM_NORM_RMS, cb, il);
  4834. cb(cur, "attn_norm", il);
  4835. // self-attention
  4836. {
  4837. // compute Q and K and RoPE them
  4838. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4839. cb(Qcur, "Qcur", il);
  4840. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4841. cb(Qcur, "Qcur", il);
  4842. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4843. cb(Kcur, "Kcur", il);
  4844. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4845. cb(Kcur, "Kcur", il);
  4846. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4847. cb(Vcur, "Vcur", il);
  4848. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4849. cb(Vcur, "Vcur", il);
  4850. // these nodes are added to the graph together so that they are not reordered
  4851. // by doing so, the number of splits in the graph is reduced
  4852. ggml_build_forward_expand(gf, Qcur);
  4853. ggml_build_forward_expand(gf, Kcur);
  4854. ggml_build_forward_expand(gf, Vcur);
  4855. Qcur = ggml_rope_custom(
  4856. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4857. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4858. ext_factor, attn_factor, beta_fast, beta_slow
  4859. );
  4860. cb(Qcur, "Qcur", il);
  4861. Kcur = ggml_rope_custom(
  4862. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4863. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4864. ext_factor, attn_factor, beta_fast, beta_slow
  4865. );
  4866. cb(Kcur, "Kcur", il);
  4867. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4868. model.layers[il].wo, model.layers[il].bo,
  4869. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4870. cb(cur, "kqv_out", il);
  4871. }
  4872. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4873. cb(ffn_inp, "ffn_inp", il);
  4874. // feed-forward network
  4875. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4876. model.layers[il].ffn_norm, NULL,
  4877. LLM_NORM_RMS, cb, il);
  4878. cb(cur, "ffn_norm", il);
  4879. cur = llm_build_ffn(ctx0, cur,
  4880. model.layers[il].ffn_up, NULL,
  4881. model.layers[il].ffn_gate, NULL,
  4882. model.layers[il].ffn_down, NULL,
  4883. NULL,
  4884. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4885. cb(cur, "ffn_out", il);
  4886. cur = ggml_add(ctx0, cur, ffn_inp);
  4887. cb(cur, "l_out", il);
  4888. // input for next layer
  4889. inpL = cur;
  4890. }
  4891. cur = inpL;
  4892. cur = llm_build_norm(ctx0, cur, hparams,
  4893. model.output_norm, NULL,
  4894. LLM_NORM_RMS, cb, -1);
  4895. cb(cur, "result_norm", -1);
  4896. // lm_head
  4897. cur = ggml_mul_mat(ctx0, model.output, cur);
  4898. cb(cur, "result_output", -1);
  4899. ggml_build_forward_expand(gf, cur);
  4900. return gf;
  4901. }
  4902. struct ggml_cgraph * build_phi2() {
  4903. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4904. const int64_t n_embd_head = hparams.n_embd_head_v;
  4905. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4906. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4907. struct ggml_tensor * cur;
  4908. struct ggml_tensor * attn_norm_output;
  4909. struct ggml_tensor * ffn_output;
  4910. struct ggml_tensor * inpL;
  4911. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4912. cb(inpL, "inp_embd", -1);
  4913. // inp_pos - contains the positions
  4914. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4915. cb(inp_pos, "inp_pos", -1);
  4916. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4917. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4918. cb(KQ_mask, "KQ_mask", -1);
  4919. // shift the entire K-cache if needed
  4920. if (do_rope_shift) {
  4921. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4922. }
  4923. for (int il = 0; il < n_layer; ++il) {
  4924. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  4925. model.layers[il].attn_norm,
  4926. model.layers[il].attn_norm_b,
  4927. LLM_NORM, cb, il);
  4928. cb(attn_norm_output, "attn_norm", il);
  4929. // self-attention
  4930. {
  4931. struct ggml_tensor * Qcur = nullptr;
  4932. struct ggml_tensor * Kcur = nullptr;
  4933. struct ggml_tensor * Vcur = nullptr;
  4934. if (model.layers[il].wqkv) {
  4935. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  4936. cb(cur, "wqkv", il);
  4937. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4938. cb(cur, "bqkv", il);
  4939. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4940. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4941. 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)));
  4942. } else {
  4943. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  4944. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  4945. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  4946. }
  4947. cb(Qcur, "Qcur", il);
  4948. cb(Kcur, "Kcur", il);
  4949. cb(Vcur, "Vcur", il);
  4950. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4951. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4952. Qcur = ggml_rope_custom(
  4953. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4954. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4955. );
  4956. cb(Qcur, "Qcur", il);
  4957. // with phi2, we scale the Q to avoid precision issues
  4958. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  4959. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  4960. cb(Qcur, "Qcur", il);
  4961. Kcur = ggml_rope_custom(
  4962. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4963. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4964. );
  4965. cb(Kcur, "Kcur", il);
  4966. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4967. model.layers[il].wo, model.layers[il].bo,
  4968. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f, cb, il);
  4969. cb(cur, "kqv_out", il);
  4970. }
  4971. // FF
  4972. {
  4973. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  4974. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4975. NULL, NULL,
  4976. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4977. NULL,
  4978. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4979. cb(ffn_output, "ffn_out", il);
  4980. }
  4981. cur = ggml_add(ctx0, cur, ffn_output);
  4982. cb(cur, "l_out", il);
  4983. cur = ggml_add(ctx0, cur, inpL);
  4984. cb(cur, "l_out", il);
  4985. inpL = cur;
  4986. }
  4987. cur = llm_build_norm(ctx0, inpL, hparams,
  4988. model.output_norm,
  4989. model.output_norm_b,
  4990. LLM_NORM, cb, -1);
  4991. cb(cur, "result_norm", -1);
  4992. cur = ggml_mul_mat(ctx0, model.output, cur);
  4993. cb(cur, "result_output_no_bias", -1);
  4994. cur = ggml_add(ctx0, cur, model.output_b);
  4995. cb(cur, "result_output", -1);
  4996. ggml_build_forward_expand(gf, cur);
  4997. return gf;
  4998. }
  4999. struct ggml_cgraph * build_plamo() {
  5000. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5001. const int64_t n_embd_head = hparams.n_embd_head_v;
  5002. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5003. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5004. struct ggml_tensor * cur;
  5005. struct ggml_tensor * inpL;
  5006. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  5007. cb(inpL, "inp_embd", -1);
  5008. // inp_pos - contains the positions
  5009. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5010. cb(inp_pos, "inp_pos", -1);
  5011. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5012. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  5013. cb(KQ_mask, "KQ_mask", -1);
  5014. // shift the entire K-cache if needed
  5015. if (do_rope_shift) {
  5016. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5017. }
  5018. for (int il = 0; il < n_layer; ++il) {
  5019. // norm
  5020. cur = llm_build_norm(ctx0, inpL, hparams,
  5021. model.layers[il].attn_norm, NULL,
  5022. LLM_NORM_RMS, cb, il);
  5023. cb(cur, "attn_norm", il);
  5024. struct ggml_tensor * attention_norm = cur;
  5025. // self-attention
  5026. {
  5027. // compute Q and K and RoPE them
  5028. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5029. cb(Qcur, "Qcur", il);
  5030. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5031. cb(Kcur, "Kcur", il);
  5032. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5033. cb(Vcur, "Vcur", il);
  5034. Qcur = ggml_rope_custom(
  5035. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5036. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5037. ext_factor, attn_factor, beta_fast, beta_slow);
  5038. cb(Qcur, "Qcur", il);
  5039. Kcur = ggml_rope_custom(
  5040. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5041. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5042. ext_factor, attn_factor, beta_fast, beta_slow);
  5043. cb(Kcur, "Kcur", il);
  5044. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5045. model.layers[il].wo, NULL,
  5046. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5047. cb(cur, "kqv_out", il);
  5048. }
  5049. struct ggml_tensor * sa_out = cur;
  5050. cur = attention_norm;
  5051. // feed-forward network
  5052. {
  5053. cur = llm_build_ffn(ctx0, cur,
  5054. model.layers[il].ffn_up, NULL,
  5055. model.layers[il].ffn_gate, NULL,
  5056. model.layers[il].ffn_down, NULL,
  5057. NULL,
  5058. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5059. cb(cur, "ffn_out", il);
  5060. }
  5061. cur = ggml_add(ctx0, cur, sa_out);
  5062. cb(cur, "l_out", il);
  5063. cur = ggml_add(ctx0, cur, inpL);
  5064. cb(cur, "l_out", il);
  5065. // input for next layer
  5066. inpL = cur;
  5067. }
  5068. cur = inpL;
  5069. cur = llm_build_norm(ctx0, cur, hparams,
  5070. model.output_norm, NULL,
  5071. LLM_NORM_RMS, cb, -1);
  5072. cb(cur, "result_norm", -1);
  5073. // lm_head
  5074. cur = ggml_mul_mat(ctx0, model.output, cur);
  5075. cb(cur, "result_output", -1);
  5076. ggml_build_forward_expand(gf, cur);
  5077. return gf;
  5078. }
  5079. struct ggml_cgraph * build_gpt2() {
  5080. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5081. const int64_t n_embd_head = hparams.n_embd_head_v;
  5082. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5083. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5084. struct ggml_tensor * cur;
  5085. struct ggml_tensor * pos;
  5086. struct ggml_tensor * inpL;
  5087. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  5088. cb(inpL, "inp_embd", -1);
  5089. // inp_pos - contains the positions
  5090. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5091. cb(inp_pos, "inp_pos", -1);
  5092. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5093. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  5094. cb(KQ_mask, "KQ_mask", -1);
  5095. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5096. cb(pos, "pos_embd", -1);
  5097. inpL = ggml_add(ctx0, inpL, pos);
  5098. cb(inpL, "inpL", -1);
  5099. for (int il = 0; il < n_layer; ++il) {
  5100. cur = llm_build_norm(ctx0, inpL, hparams,
  5101. model.layers[il].attn_norm,
  5102. model.layers[il].attn_norm_b,
  5103. LLM_NORM, cb, il);
  5104. cb(cur, "attn_norm", il);
  5105. // self-attention
  5106. {
  5107. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5108. cb(cur, "wqkv", il);
  5109. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5110. cb(cur, "bqkv", il);
  5111. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5112. 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)));
  5113. 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)));
  5114. cb(Qcur, "Qcur", il);
  5115. cb(Kcur, "Kcur", il);
  5116. cb(Vcur, "Vcur", il);
  5117. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5118. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5119. model.layers[il].wo, model.layers[il].bo,
  5120. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5121. cb(cur, "kqv_out", il);
  5122. }
  5123. // add the input
  5124. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5125. cb(ffn_inp, "ffn_inp", il);
  5126. // FF
  5127. {
  5128. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5129. model.layers[il].ffn_norm,
  5130. model.layers[il].ffn_norm_b,
  5131. LLM_NORM, cb, il);
  5132. cb(cur, "ffn_norm", il);
  5133. cur = llm_build_ffn(ctx0, cur,
  5134. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5135. NULL, NULL,
  5136. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5137. NULL,
  5138. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5139. cb(cur, "ffn_out", il);
  5140. }
  5141. inpL = ggml_add(ctx0, cur, ffn_inp);
  5142. cb(inpL, "l_out", il);
  5143. }
  5144. cur = llm_build_norm(ctx0, inpL, hparams,
  5145. model.output_norm,
  5146. model.output_norm_b,
  5147. LLM_NORM, cb, -1);
  5148. cb(cur, "result_norm", -1);
  5149. cur = ggml_mul_mat(ctx0, model.output, cur);
  5150. cb(cur, "result_output", -1);
  5151. ggml_build_forward_expand(gf, cur);
  5152. return gf;
  5153. }
  5154. struct ggml_cgraph * build_codeshell() {
  5155. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5156. const int64_t n_embd_head = hparams.n_embd_head_v;
  5157. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5158. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5159. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5160. struct ggml_tensor * cur;
  5161. struct ggml_tensor * inpL;
  5162. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  5163. cb(inpL, "inp_embd", -1);
  5164. // inp_pos - contains the positions
  5165. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5166. cb(inp_pos, "inp_pos", -1);
  5167. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5168. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  5169. cb(KQ_mask, "KQ_mask", -1);
  5170. // shift the entire K-cache if needed
  5171. if (do_rope_shift) {
  5172. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5173. }
  5174. for (int il = 0; il < n_layer; ++il) {
  5175. cur = llm_build_norm(ctx0, inpL, hparams,
  5176. model.layers[il].attn_norm,
  5177. model.layers[il].attn_norm_b,
  5178. LLM_NORM, cb, il);
  5179. cb(cur, "attn_norm", il);
  5180. // self-attention
  5181. {
  5182. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5183. cb(cur, "wqkv", il);
  5184. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5185. cb(cur, "bqkv", il);
  5186. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5187. struct ggml_tensor * tmpk = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5188. 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)));
  5189. cb(tmpq, "tmpq", il);
  5190. cb(tmpk, "tmpk", il);
  5191. cb(Vcur, "Vcur", il);
  5192. struct ggml_tensor * Qcur = ggml_rope_custom(
  5193. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5194. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5195. ext_factor, attn_factor, beta_fast, beta_slow
  5196. );
  5197. cb(Qcur, "Qcur", il);
  5198. struct ggml_tensor * Kcur = ggml_rope_custom(
  5199. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5200. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5201. ext_factor, attn_factor, beta_fast, beta_slow
  5202. );
  5203. cb(Kcur, "Kcur", il);
  5204. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5205. model.layers[il].wo, model.layers[il].bo,
  5206. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5207. cb(cur, "kqv_out", il);
  5208. }
  5209. // add the input
  5210. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5211. cb(ffn_inp, "ffn_inp", il);
  5212. // FF
  5213. {
  5214. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5215. model.layers[il].ffn_norm,
  5216. model.layers[il].ffn_norm_b,
  5217. LLM_NORM, cb, il);
  5218. cb(cur, "ffn_norm", il);
  5219. cur = llm_build_ffn(ctx0, cur,
  5220. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5221. NULL, NULL,
  5222. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5223. NULL,
  5224. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5225. cb(cur, "ffn_out", il);
  5226. }
  5227. inpL = ggml_add(ctx0, cur, ffn_inp);
  5228. cb(inpL, "l_out", il);
  5229. }
  5230. cur = llm_build_norm(ctx0, inpL, hparams,
  5231. model.output_norm,
  5232. model.output_norm_b,
  5233. LLM_NORM, cb, -1);
  5234. cb(cur, "result_norm", -1);
  5235. cur = ggml_mul_mat(ctx0, model.output, cur);
  5236. cb(cur, "result_output", -1);
  5237. ggml_build_forward_expand(gf, cur);
  5238. return gf;
  5239. }
  5240. };
  5241. static struct ggml_cgraph * llama_build_graph(
  5242. llama_context & lctx,
  5243. const llama_batch & batch) {
  5244. const auto & model = lctx.model;
  5245. // check if we should build the worst-case graph (for memory measurement)
  5246. const bool worst_case = ggml_tallocr_is_measure(lctx.alloc);
  5247. // keep track of the input that has already been allocated
  5248. bool alloc_inp_tokens = false;
  5249. bool alloc_inp_embd = false;
  5250. bool alloc_inp_pos = false;
  5251. bool alloc_inp_KQ_mask = false;
  5252. bool alloc_inp_K_shift = false;
  5253. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  5254. // TODO: improve handling of input and output tensors, then replace this with ggml_set_name
  5255. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  5256. if (il >= 0) {
  5257. ggml_format_name(cur, "%s-%d", name, il);
  5258. } else {
  5259. ggml_set_name(cur, name);
  5260. }
  5261. if (!lctx.cparams.offload_kqv) {
  5262. if (strcmp(name, "kqv_merged_cont") == 0) {
  5263. // all nodes between the KV store and the attention output are run on the CPU
  5264. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  5265. }
  5266. }
  5267. //
  5268. // allocate input tensors and set input data
  5269. //
  5270. if (!alloc_inp_tokens && strcmp(name, "inp_tokens") == 0) {
  5271. ggml_tallocr_alloc(lctx.alloc, cur);
  5272. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.token) {
  5273. const int64_t n_tokens = cur->ne[0];
  5274. ggml_backend_tensor_set(cur, batch.token, 0, n_tokens*ggml_element_size(cur));
  5275. }
  5276. alloc_inp_tokens = true;
  5277. }
  5278. if (!alloc_inp_embd && strcmp(name, "inp_embd") == 0 && batch.embd) {
  5279. ggml_tallocr_alloc(lctx.alloc, cur);
  5280. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.embd) {
  5281. const int64_t n_embd = cur->ne[0];
  5282. const int64_t n_tokens = cur->ne[1];
  5283. ggml_backend_tensor_set(cur, batch.embd, 0, n_tokens*n_embd*ggml_element_size(cur));
  5284. }
  5285. alloc_inp_embd = true;
  5286. }
  5287. if (!alloc_inp_pos && strcmp(name, "inp_pos") == 0) {
  5288. ggml_tallocr_alloc(lctx.alloc, cur);
  5289. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.pos) {
  5290. const int64_t n_tokens = cur->ne[0];
  5291. static_assert(std::is_same<llama_pos, int32_t>::value, "llama_pos must be int32_t");
  5292. ggml_backend_tensor_set(cur, batch.pos, 0, n_tokens*ggml_element_size(cur));
  5293. }
  5294. alloc_inp_pos = true;
  5295. }
  5296. if (!alloc_inp_KQ_mask && strcmp(name, "KQ_mask") == 0) {
  5297. ggml_tallocr_alloc(lctx.alloc, cur);
  5298. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5299. const int64_t n_kv = cur->ne[0];
  5300. const int64_t n_tokens = cur->ne[1];
  5301. float * data;
  5302. if (ggml_backend_buffer_is_host(cur->buffer)) {
  5303. data = (float *) cur->data;
  5304. } else {
  5305. lctx.buf_copy.resize(ggml_nbytes(cur));
  5306. data = (float *) lctx.buf_copy.data();
  5307. }
  5308. for (int h = 0; h < 1; ++h) {
  5309. for (int j = 0; j < n_tokens; ++j) {
  5310. const llama_pos pos = batch.pos[j];
  5311. const llama_seq_id seq_id = batch.seq_id[j][0];
  5312. for (int i = 0; i < n_kv; ++i) {
  5313. float f;
  5314. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  5315. f = -INFINITY;
  5316. } else {
  5317. f = 0;
  5318. }
  5319. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  5320. }
  5321. }
  5322. }
  5323. if (data != cur->data) {
  5324. ggml_backend_tensor_set(cur, data, 0, ggml_nbytes(cur));
  5325. }
  5326. }
  5327. alloc_inp_KQ_mask = true;
  5328. }
  5329. if (!alloc_inp_K_shift && strcmp(name, "K_shift") == 0) {
  5330. ggml_tallocr_alloc(lctx.alloc, cur);
  5331. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5332. const int64_t n_ctx = cur->ne[0];
  5333. int32_t * data;
  5334. if (ggml_backend_buffer_is_host(cur->buffer)) {
  5335. data = (int32_t *) cur->data;
  5336. } else {
  5337. lctx.buf_copy.resize(ggml_nbytes(cur));
  5338. data = (int32_t *) lctx.buf_copy.data();
  5339. }
  5340. for (int i = 0; i < n_ctx; ++i) {
  5341. data[i] = lctx.kv_self.cells[i].delta;
  5342. }
  5343. if (data != cur->data) {
  5344. ggml_backend_tensor_set(cur, data, 0, ggml_nbytes(cur));
  5345. }
  5346. }
  5347. alloc_inp_K_shift = true;
  5348. }
  5349. };
  5350. struct ggml_cgraph * result = NULL;
  5351. struct llm_build_context llm(lctx, batch, cb, worst_case);
  5352. llm.init();
  5353. switch (model.arch) {
  5354. case LLM_ARCH_LLAMA:
  5355. {
  5356. result = llm.build_llama();
  5357. } break;
  5358. case LLM_ARCH_BAICHUAN:
  5359. {
  5360. result = llm.build_baichuan();
  5361. } break;
  5362. case LLM_ARCH_FALCON:
  5363. {
  5364. result = llm.build_falcon();
  5365. } break;
  5366. case LLM_ARCH_STARCODER:
  5367. {
  5368. result = llm.build_starcoder();
  5369. } break;
  5370. case LLM_ARCH_PERSIMMON:
  5371. {
  5372. result = llm.build_persimmon();
  5373. } break;
  5374. case LLM_ARCH_REFACT:
  5375. {
  5376. result = llm.build_refact();
  5377. } break;
  5378. case LLM_ARCH_BLOOM:
  5379. {
  5380. result = llm.build_bloom();
  5381. } break;
  5382. case LLM_ARCH_MPT:
  5383. {
  5384. result = llm.build_mpt();
  5385. } break;
  5386. case LLM_ARCH_STABLELM:
  5387. {
  5388. result = llm.build_stablelm();
  5389. } break;
  5390. case LLM_ARCH_QWEN:
  5391. {
  5392. result = llm.build_qwen();
  5393. } break;
  5394. case LLM_ARCH_QWEN2:
  5395. {
  5396. result = llm.build_qwen2();
  5397. } break;
  5398. case LLM_ARCH_PHI2:
  5399. {
  5400. result = llm.build_phi2();
  5401. } break;
  5402. case LLM_ARCH_PLAMO:
  5403. {
  5404. result = llm.build_plamo();
  5405. } break;
  5406. case LLM_ARCH_GPT2:
  5407. {
  5408. result = llm.build_gpt2();
  5409. } break;
  5410. case LLM_ARCH_CODESHELL:
  5411. {
  5412. result = llm.build_codeshell();
  5413. } break;
  5414. default:
  5415. GGML_ASSERT(false);
  5416. }
  5417. llm.free();
  5418. return result;
  5419. }
  5420. // decode a batch of tokens by evaluating the transformer
  5421. //
  5422. // - lctx: llama context
  5423. // - batch: batch to evaluate
  5424. //
  5425. // return 0 on success
  5426. // return positive int on warning
  5427. // return negative int on error
  5428. //
  5429. static int llama_decode_internal(
  5430. llama_context & lctx,
  5431. llama_batch batch) {
  5432. const uint32_t n_tokens = batch.n_tokens;
  5433. if (n_tokens == 0) {
  5434. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  5435. return -1;
  5436. }
  5437. const auto & model = lctx.model;
  5438. const auto & hparams = model.hparams;
  5439. const auto & cparams = lctx.cparams;
  5440. const auto n_batch = cparams.n_batch;
  5441. GGML_ASSERT(n_tokens <= n_batch);
  5442. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  5443. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  5444. const int64_t t_start_us = ggml_time_us();
  5445. #ifdef GGML_USE_MPI
  5446. // TODO: needs fix after #3228
  5447. GGML_ASSERT(false && "not implemented");
  5448. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  5449. #endif
  5450. GGML_ASSERT(n_threads > 0);
  5451. auto & kv_self = lctx.kv_self;
  5452. const int64_t n_embd = hparams.n_embd;
  5453. const int64_t n_vocab = hparams.n_vocab;
  5454. // helpers for smoother batch API transition
  5455. // after deprecating the llama_eval calls, these will be removed
  5456. std::vector<llama_pos> pos;
  5457. std::vector<int32_t> n_seq_id;
  5458. std::vector<llama_seq_id *> seq_id_arr;
  5459. std::vector<std::vector<llama_seq_id>> seq_id;
  5460. if (batch.pos == nullptr) {
  5461. pos.resize(n_tokens);
  5462. for (uint32_t i = 0; i < n_tokens; i++) {
  5463. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  5464. }
  5465. batch.pos = pos.data();
  5466. }
  5467. if (batch.seq_id == nullptr) {
  5468. n_seq_id.resize(n_tokens);
  5469. seq_id.resize(n_tokens);
  5470. seq_id_arr.resize(n_tokens);
  5471. for (uint32_t i = 0; i < n_tokens; i++) {
  5472. n_seq_id[i] = 1;
  5473. seq_id[i].resize(1);
  5474. seq_id[i][0] = batch.all_seq_id;
  5475. seq_id_arr[i] = seq_id[i].data();
  5476. }
  5477. batch.n_seq_id = n_seq_id.data();
  5478. batch.seq_id = seq_id_arr.data();
  5479. }
  5480. // if we have enough unused cells before the current head ->
  5481. // better to start searching from the beginning of the cache, hoping to fill it
  5482. if (kv_self.head > kv_self.used + 2*n_tokens) {
  5483. kv_self.head = 0;
  5484. }
  5485. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  5486. return 1;
  5487. }
  5488. // a heuristic, to avoid attending the full cache if it is not yet utilized
  5489. // after enough generations, the benefit from this heuristic disappears
  5490. // if we start defragmenting the cache, the benefit from this will be more important
  5491. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  5492. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  5493. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  5494. ggml_backend_sched_reset(lctx.sched);
  5495. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  5496. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  5497. // the output is always the last tensor in the graph
  5498. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  5499. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  5500. // the embeddings could be the second to last tensor, or the third to last tensor
  5501. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  5502. if (strcmp(embeddings->name, "result_norm") != 0) {
  5503. embeddings = gf->nodes[gf->n_nodes - 3];
  5504. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  5505. }
  5506. // 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);
  5507. // for big prompts, if BLAS is enabled, it is better to use only one thread
  5508. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  5509. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  5510. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  5511. // with the BLAS calls. need a better solution
  5512. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  5513. n_threads = std::min(4, n_threads);
  5514. }
  5515. const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 1;
  5516. if (ggml_cpu_has_cublas() && fully_offloaded) {
  5517. n_threads = 1;
  5518. }
  5519. #ifdef GGML_USE_MPI
  5520. const int64_t n_layer = hparams.n_layer;
  5521. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  5522. #endif
  5523. #ifdef GGML_USE_METAL
  5524. if (ggml_backend_is_metal(lctx.backend_metal)) {
  5525. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  5526. }
  5527. #endif
  5528. if (lctx.backend_cpu != nullptr) {
  5529. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  5530. }
  5531. ggml_backend_sched_graph_compute(lctx.sched, gf);
  5532. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  5533. #ifdef GGML_USE_MPI
  5534. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  5535. #endif
  5536. // update the kv ring buffer
  5537. {
  5538. if (kv_self.has_shift) {
  5539. kv_self.has_shift = false;
  5540. for (uint32_t i = 0; i < kv_self.size; ++i) {
  5541. kv_self.cells[i].delta = 0;
  5542. }
  5543. }
  5544. kv_self.head += n_tokens;
  5545. // Ensure kv cache head points to a valid index.
  5546. if (kv_self.head >= kv_self.size) {
  5547. kv_self.head = 0;
  5548. }
  5549. }
  5550. #ifdef GGML_PERF
  5551. // print timing information per ggml operation (for debugging purposes)
  5552. // requires GGML_PERF to be defined
  5553. ggml_graph_print(gf);
  5554. #endif
  5555. // plot the computation graph in dot format (for debugging purposes)
  5556. //if (n_past%100 == 0) {
  5557. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  5558. //}
  5559. // extract logits
  5560. // TODO: do not compute and extract logits if only embeddings are needed
  5561. // need to update the graphs to skip "result_output"
  5562. {
  5563. auto & logits_out = lctx.logits;
  5564. #ifndef NDEBUG
  5565. auto & logits_valid = lctx.logits_valid;
  5566. logits_valid.clear();
  5567. logits_valid.resize(n_tokens);
  5568. logits_out.clear();
  5569. #endif
  5570. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  5571. GGML_ASSERT(res_backend != nullptr);
  5572. if (batch.logits) {
  5573. logits_out.resize(n_vocab * n_tokens);
  5574. for (uint32_t i = 0; i < n_tokens; i++) {
  5575. if (batch.logits[i] == 0) {
  5576. continue;
  5577. }
  5578. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  5579. #ifndef NDEBUG
  5580. logits_valid[i] = true;
  5581. #endif
  5582. }
  5583. } else if (lctx.logits_all) {
  5584. logits_out.resize(n_vocab * n_tokens);
  5585. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  5586. #ifndef NDEBUG
  5587. std::fill(logits_valid.begin(), logits_valid.end(), true);
  5588. #endif
  5589. } else {
  5590. logits_out.resize(n_vocab);
  5591. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  5592. #ifndef NDEBUG
  5593. logits_valid[0] = true;
  5594. #endif
  5595. }
  5596. ggml_backend_synchronize(res_backend);
  5597. }
  5598. // extract embeddings
  5599. if (!lctx.embedding.empty()) {
  5600. auto & embedding_out = lctx.embedding;
  5601. embedding_out.resize(n_embd);
  5602. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  5603. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), (n_embd*(n_tokens - 1))*sizeof(float), n_embd*sizeof(float));
  5604. ggml_backend_synchronize(embeddings_backend);
  5605. }
  5606. // measure the performance only for the single-token evals
  5607. if (n_tokens == 1) {
  5608. lctx.t_eval_us += ggml_time_us() - t_start_us;
  5609. lctx.n_eval++;
  5610. }
  5611. else if (n_tokens > 1) {
  5612. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  5613. lctx.n_p_eval += n_tokens;
  5614. }
  5615. // get a more accurate load time, upon first eval
  5616. // TODO: fix this
  5617. if (!lctx.has_evaluated_once) {
  5618. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  5619. lctx.has_evaluated_once = true;
  5620. }
  5621. return 0;
  5622. }
  5623. //
  5624. // tokenizer
  5625. //
  5626. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  5627. return vocab.type;
  5628. }
  5629. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  5630. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  5631. }
  5632. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  5633. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  5634. }
  5635. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  5636. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  5637. }
  5638. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  5639. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  5640. }
  5641. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  5642. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  5643. }
  5644. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  5645. GGML_ASSERT(llama_is_byte_token(vocab, id));
  5646. const auto& token_data = vocab.id_to_token.at(id);
  5647. switch (llama_vocab_get_type(vocab)) {
  5648. case LLAMA_VOCAB_TYPE_SPM: {
  5649. auto buf = token_data.text.substr(3, 2);
  5650. return strtol(buf.c_str(), NULL, 16);
  5651. }
  5652. case LLAMA_VOCAB_TYPE_BPE: {
  5653. GGML_ASSERT(false);
  5654. return unicode_to_bytes_bpe(token_data.text);
  5655. }
  5656. default:
  5657. GGML_ASSERT(false);
  5658. }
  5659. }
  5660. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  5661. static const char * hex = "0123456789ABCDEF";
  5662. switch (llama_vocab_get_type(vocab)) {
  5663. case LLAMA_VOCAB_TYPE_SPM: {
  5664. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  5665. return vocab.token_to_id.at(buf);
  5666. }
  5667. case LLAMA_VOCAB_TYPE_BPE: {
  5668. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  5669. }
  5670. default:
  5671. GGML_ASSERT(false);
  5672. }
  5673. }
  5674. static void llama_escape_whitespace(std::string & text) {
  5675. replace_all(text, " ", "\xe2\x96\x81");
  5676. }
  5677. static void llama_unescape_whitespace(std::string & word) {
  5678. replace_all(word, "\xe2\x96\x81", " ");
  5679. }
  5680. struct llm_symbol {
  5681. using index = int;
  5682. index prev;
  5683. index next;
  5684. const char * text;
  5685. size_t n;
  5686. };
  5687. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  5688. // SPM tokenizer
  5689. // original implementation:
  5690. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  5691. struct llm_bigram_spm {
  5692. struct comparator {
  5693. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  5694. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  5695. }
  5696. };
  5697. using queue_storage = std::vector<llm_bigram_spm>;
  5698. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  5699. llm_symbol::index left;
  5700. llm_symbol::index right;
  5701. float score;
  5702. size_t size;
  5703. };
  5704. struct llm_tokenizer_spm {
  5705. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  5706. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5707. // split string into utf8 chars
  5708. int index = 0;
  5709. size_t offs = 0;
  5710. while (offs < text.size()) {
  5711. llm_symbol sym;
  5712. size_t len = utf8_len(text[offs]);
  5713. sym.text = text.c_str() + offs;
  5714. sym.n = std::min(len, text.size() - offs);
  5715. offs += sym.n;
  5716. sym.prev = index - 1;
  5717. sym.next = offs == text.size() ? -1 : index + 1;
  5718. index++;
  5719. symbols.emplace_back(sym);
  5720. }
  5721. // seed the work queue with all possible 2-character tokens.
  5722. for (size_t i = 1; i < symbols.size(); ++i) {
  5723. try_add_bigram(i - 1, i);
  5724. }
  5725. // keep substituting the highest frequency pairs for as long as we can.
  5726. while (!work_queue.empty()) {
  5727. auto bigram = work_queue.top();
  5728. work_queue.pop();
  5729. auto & left_sym = symbols[bigram.left];
  5730. auto & right_sym = symbols[bigram.right];
  5731. // if one of the symbols already got merged, skip it.
  5732. if (left_sym.n == 0 || right_sym.n == 0 ||
  5733. left_sym.n + right_sym.n != bigram.size) {
  5734. continue;
  5735. }
  5736. // merge the right sym into the left one
  5737. left_sym.n += right_sym.n;
  5738. right_sym.n = 0;
  5739. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  5740. // remove the right sym from the chain
  5741. left_sym.next = right_sym.next;
  5742. if (right_sym.next >= 0) {
  5743. symbols[right_sym.next].prev = bigram.left;
  5744. }
  5745. // find more substitutions
  5746. try_add_bigram(left_sym.prev, bigram.left);
  5747. try_add_bigram(bigram.left, left_sym.next);
  5748. }
  5749. for (int i = 0; i != -1; i = symbols[i].next) {
  5750. auto & symbol = symbols[i];
  5751. resegment(symbol, output);
  5752. }
  5753. }
  5754. private:
  5755. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  5756. auto text = std::string(symbol.text, symbol.n);
  5757. auto token = vocab.token_to_id.find(text);
  5758. // Do we need to support is_unused?
  5759. if (token != vocab.token_to_id.end()) {
  5760. output.push_back((*token).second);
  5761. return;
  5762. }
  5763. const auto p = rev_merge.find(text);
  5764. if (p == rev_merge.end()) {
  5765. // output any symbols that did not form tokens as bytes.
  5766. for (int j = 0; j < (int)symbol.n; ++j) {
  5767. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  5768. output.push_back(token_id);
  5769. }
  5770. return;
  5771. }
  5772. resegment(symbols[p->second.first], output);
  5773. resegment(symbols[p->second.second], output);
  5774. }
  5775. void try_add_bigram(int left, int right) {
  5776. if (left == -1 || right == -1) {
  5777. return;
  5778. }
  5779. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  5780. auto token = vocab.token_to_id.find(text);
  5781. if (token == vocab.token_to_id.end()) {
  5782. return;
  5783. }
  5784. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  5785. return;
  5786. }
  5787. const auto & tok_data = vocab.id_to_token[(*token).second];
  5788. llm_bigram_spm bigram;
  5789. bigram.left = left;
  5790. bigram.right = right;
  5791. bigram.score = tok_data.score;
  5792. bigram.size = text.size();
  5793. work_queue.push(bigram);
  5794. // Do we need to support is_unused?
  5795. rev_merge[text] = std::make_pair(left, right);
  5796. }
  5797. const llama_vocab & vocab;
  5798. std::vector<llm_symbol> symbols;
  5799. llm_bigram_spm::queue work_queue;
  5800. std::map<std::string, std::pair<int, int>> rev_merge;
  5801. };
  5802. // BPE tokenizer
  5803. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  5804. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  5805. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  5806. struct llm_bigram_bpe {
  5807. struct comparator {
  5808. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  5809. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  5810. }
  5811. };
  5812. using queue_storage = std::vector<llm_bigram_bpe>;
  5813. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  5814. llm_symbol::index left;
  5815. llm_symbol::index right;
  5816. std::string text;
  5817. int rank;
  5818. size_t size;
  5819. };
  5820. struct llm_tokenizer_bpe {
  5821. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  5822. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5823. int final_prev_index = -1;
  5824. auto word_collection = bpe_gpt2_preprocess(text);
  5825. symbols_final.clear();
  5826. for (auto & word : word_collection) {
  5827. work_queue = llm_bigram_bpe::queue();
  5828. symbols.clear();
  5829. int index = 0;
  5830. size_t offset = 0;
  5831. while (offset < word.size()) {
  5832. llm_symbol sym;
  5833. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  5834. sym.text = word.c_str() + offset;
  5835. sym.n = char_len;
  5836. offset += sym.n;
  5837. sym.prev = index - 1;
  5838. sym.next = offset == word.size() ? -1 : index + 1;
  5839. index++;
  5840. symbols.emplace_back(sym);
  5841. }
  5842. for (size_t i = 1; i < symbols.size(); ++i) {
  5843. add_new_bigram(i - 1, i);
  5844. }
  5845. // build token(s)
  5846. while (!work_queue.empty()) {
  5847. auto bigram = work_queue.top();
  5848. work_queue.pop();
  5849. auto & left_symbol = symbols[bigram.left];
  5850. auto & right_symbol = symbols[bigram.right];
  5851. if (left_symbol.n == 0 || right_symbol.n == 0) {
  5852. continue;
  5853. }
  5854. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  5855. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  5856. if (left_token + right_token != bigram.text) {
  5857. continue; // Skip this bigram if it's outdated
  5858. }
  5859. // merge the right sym into the left one
  5860. left_symbol.n += right_symbol.n;
  5861. right_symbol.n = 0;
  5862. // remove the right sym from the chain
  5863. left_symbol.next = right_symbol.next;
  5864. if (right_symbol.next >= 0) {
  5865. symbols[right_symbol.next].prev = bigram.left;
  5866. }
  5867. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  5868. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  5869. }
  5870. // add the fnished tokens to the final list keeping correct order for next and prev
  5871. for (auto & sym : symbols) {
  5872. if (sym.n > 0) {
  5873. sym.prev = final_prev_index;
  5874. sym.next = -1;
  5875. if (final_prev_index != -1) {
  5876. symbols_final[final_prev_index].next = symbols_final.size();
  5877. }
  5878. symbols_final.emplace_back(sym);
  5879. final_prev_index = symbols_final.size() - 1;
  5880. }
  5881. }
  5882. }
  5883. symbols = symbols_final;
  5884. if (!symbols.empty()) {
  5885. for (int i = 0; i != -1; i = symbols[i].next) {
  5886. auto & symbol = symbols[i];
  5887. if (symbol.n == 0) {
  5888. continue;
  5889. }
  5890. const std::string str = std::string(symbol.text, symbol.n);
  5891. const auto token = vocab.token_to_id.find(str);
  5892. if (token == vocab.token_to_id.end()) {
  5893. for (auto j = str.begin(); j != str.end(); ++j) {
  5894. std::string byte_str(1, *j);
  5895. auto token_multibyte = vocab.token_to_id.find(byte_str);
  5896. if (token_multibyte == vocab.token_to_id.end()) {
  5897. throw std::runtime_error("ERROR: byte not found in vocab");
  5898. }
  5899. output.push_back((*token_multibyte).second);
  5900. }
  5901. } else {
  5902. output.push_back((*token).second);
  5903. }
  5904. }
  5905. }
  5906. }
  5907. private:
  5908. void add_new_bigram(int left, int right) {
  5909. if (left == -1 || right == -1) {
  5910. return;
  5911. }
  5912. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  5913. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  5914. int rank_found = -1;
  5915. rank_found = vocab.find_bpe_rank(left_token, right_token);
  5916. if (rank_found < 0) {
  5917. return;
  5918. }
  5919. llm_bigram_bpe bigram;
  5920. bigram.left = left;
  5921. bigram.right = right;
  5922. bigram.text = left_token + right_token;
  5923. bigram.size = left_token.size() + right_token.size();
  5924. bigram.rank = rank_found;
  5925. work_queue.push(bigram);
  5926. }
  5927. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  5928. std::vector<std::string> bpe_words;
  5929. std::vector<std::string> bpe_encoded_words;
  5930. std::string token = "";
  5931. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  5932. bool collecting_numeric = false;
  5933. bool collecting_letter = false;
  5934. bool collecting_special = false;
  5935. bool collecting_whitespace_lookahead = false;
  5936. bool collecting = false;
  5937. std::vector<std::string> text_utf;
  5938. text_utf.reserve(text.size());
  5939. bpe_words.reserve(text.size());
  5940. bpe_encoded_words.reserve(text.size());
  5941. auto cps = codepoints_from_utf8(text);
  5942. for (size_t i = 0; i < cps.size(); ++i)
  5943. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  5944. for (int i = 0; i < (int)text_utf.size(); i++) {
  5945. const std::string & utf_char = text_utf[i];
  5946. bool split_condition = false;
  5947. int bytes_remain = text_utf.size() - i;
  5948. // forward backward lookups
  5949. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  5950. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  5951. // handling contractions
  5952. if (!split_condition && bytes_remain >= 2) {
  5953. // 's|'t|'m|'d
  5954. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  5955. split_condition = true;
  5956. }
  5957. if (split_condition) {
  5958. if (token.size()) {
  5959. bpe_words.emplace_back(token); // push previous content as token
  5960. }
  5961. token = utf_char + utf_char_next;
  5962. bpe_words.emplace_back(token);
  5963. token = "";
  5964. i++;
  5965. continue;
  5966. }
  5967. }
  5968. if (!split_condition && bytes_remain >= 3) {
  5969. // 're|'ve|'ll
  5970. if (utf_char == "\'" && (
  5971. (utf_char_next == "r" && utf_char_next_next == "e") ||
  5972. (utf_char_next == "v" && utf_char_next_next == "e") ||
  5973. (utf_char_next == "l" && utf_char_next_next == "l"))
  5974. ) {
  5975. split_condition = true;
  5976. }
  5977. if (split_condition) {
  5978. // current token + next token can be defined
  5979. if (token.size()) {
  5980. bpe_words.emplace_back(token); // push previous content as token
  5981. }
  5982. token = utf_char + utf_char_next + utf_char_next_next;
  5983. bpe_words.emplace_back(token); // the contraction
  5984. token = "";
  5985. i += 2;
  5986. continue;
  5987. }
  5988. }
  5989. if (!split_condition && !collecting) {
  5990. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  5991. collecting_letter = true;
  5992. collecting = true;
  5993. }
  5994. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  5995. collecting_numeric = true;
  5996. collecting = true;
  5997. }
  5998. else if (
  5999. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  6000. (!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)
  6001. ) {
  6002. collecting_special = true;
  6003. collecting = true;
  6004. }
  6005. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  6006. collecting_whitespace_lookahead = true;
  6007. collecting = true;
  6008. }
  6009. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  6010. split_condition = true;
  6011. }
  6012. }
  6013. else if (!split_condition && collecting) {
  6014. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  6015. split_condition = true;
  6016. }
  6017. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  6018. split_condition = true;
  6019. }
  6020. 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)) {
  6021. split_condition = true;
  6022. }
  6023. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6024. split_condition = true;
  6025. }
  6026. }
  6027. if (utf_char_next == "") {
  6028. split_condition = true; // final
  6029. token += utf_char;
  6030. }
  6031. if (split_condition) {
  6032. if (token.size()) {
  6033. bpe_words.emplace_back(token);
  6034. }
  6035. token = utf_char;
  6036. collecting = false;
  6037. collecting_letter = false;
  6038. collecting_numeric = false;
  6039. collecting_special = false;
  6040. collecting_whitespace_lookahead = false;
  6041. }
  6042. else {
  6043. token += utf_char;
  6044. }
  6045. }
  6046. for (std::string & word : bpe_words) {
  6047. std::string encoded_token = "";
  6048. for (char & c : word) {
  6049. encoded_token += bytes_to_unicode_bpe(c);
  6050. }
  6051. bpe_encoded_words.emplace_back(encoded_token);
  6052. }
  6053. return bpe_encoded_words;
  6054. }
  6055. const llama_vocab & vocab;
  6056. std::vector<llm_symbol> symbols;
  6057. std::vector<llm_symbol> symbols_final;
  6058. llm_bigram_bpe::queue work_queue;
  6059. };
  6060. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  6061. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  6062. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  6063. } FRAGMENT_BUFFER_VARIANT_TYPE;
  6064. struct fragment_buffer_variant{
  6065. fragment_buffer_variant(llama_vocab::id _token)
  6066. :
  6067. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  6068. token(_token),
  6069. raw_text(_dummy),
  6070. offset(0),
  6071. length(0){}
  6072. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  6073. :
  6074. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  6075. token((llama_vocab::id)-1),
  6076. raw_text(_raw_text),
  6077. offset(_offset),
  6078. length(_length){
  6079. GGML_ASSERT( _offset >= 0 );
  6080. GGML_ASSERT( _length >= 1 );
  6081. GGML_ASSERT( offset + length <= raw_text.length() );
  6082. }
  6083. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  6084. const llama_vocab::id token;
  6085. const std::string _dummy;
  6086. const std::string & raw_text;
  6087. const uint64_t offset;
  6088. const uint64_t length;
  6089. };
  6090. // #define PRETOKENIZERDEBUG
  6091. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  6092. {
  6093. // for each special token
  6094. for (const auto & st: vocab.special_tokens_cache) {
  6095. const auto & special_token = st.first;
  6096. const auto & special_id = st.second;
  6097. // for each text fragment
  6098. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  6099. while (it != buffer.end()) {
  6100. auto & fragment = (*it);
  6101. // if a fragment is text ( not yet processed )
  6102. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  6103. auto * raw_text = &(fragment.raw_text);
  6104. auto raw_text_base_offset = fragment.offset;
  6105. auto raw_text_base_length = fragment.length;
  6106. // loop over the text
  6107. while (true) {
  6108. // find the first occurrence of a given special token in this fragment
  6109. // passing offset argument only limit the "search area" but match coordinates
  6110. // are still relative to the source full raw_text
  6111. auto match = raw_text->find(special_token, raw_text_base_offset);
  6112. // no occurrences found, stop processing this fragment for a given special token
  6113. if (match == std::string::npos) break;
  6114. // check if match is within bounds of offset <-> length
  6115. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  6116. #ifdef PRETOKENIZERDEBUG
  6117. 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());
  6118. #endif
  6119. auto source = std::distance(buffer.begin(), it);
  6120. // if match is further than base offset
  6121. // then we have some text to the left of it
  6122. if (match > raw_text_base_offset) {
  6123. // left
  6124. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  6125. const int64_t left_reminder_length = match - raw_text_base_offset;
  6126. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  6127. #ifdef PRETOKENIZERDEBUG
  6128. 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());
  6129. #endif
  6130. it++;
  6131. }
  6132. // special token
  6133. buffer.emplace_after(it, special_id);
  6134. it++;
  6135. // right
  6136. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  6137. const int64_t right_reminder_offset = match + special_token.length();
  6138. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  6139. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  6140. #ifdef PRETOKENIZERDEBUG
  6141. 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());
  6142. #endif
  6143. it++;
  6144. if (source == 0) {
  6145. buffer.erase_after(buffer.before_begin());
  6146. } else {
  6147. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6148. }
  6149. // repeat for the right side
  6150. raw_text_base_offset = right_reminder_offset;
  6151. raw_text_base_length = right_reminder_length;
  6152. #ifdef PRETOKENIZERDEBUG
  6153. 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());
  6154. #endif
  6155. } else {
  6156. if (source == 0) {
  6157. buffer.erase_after(buffer.before_begin());
  6158. } else {
  6159. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6160. }
  6161. break;
  6162. }
  6163. }
  6164. }
  6165. it++;
  6166. }
  6167. }
  6168. }
  6169. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  6170. std::vector<llama_vocab::id> output;
  6171. // OG tokenizer behavior:
  6172. //
  6173. // tokenizer.encode('', add_bos=True) returns [1]
  6174. // tokenizer.encode('', add_bos=False) returns []
  6175. if (bos && vocab.special_bos_id != -1) {
  6176. output.push_back(vocab.special_bos_id);
  6177. }
  6178. if (raw_text.empty()) {
  6179. return output;
  6180. }
  6181. std::forward_list<fragment_buffer_variant> fragment_buffer;
  6182. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  6183. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  6184. switch (vocab.type) {
  6185. case LLAMA_VOCAB_TYPE_SPM:
  6186. {
  6187. for (const auto & fragment: fragment_buffer)
  6188. {
  6189. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6190. {
  6191. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  6192. // TODO: It's likely possible to get rid of this string copy entirely
  6193. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  6194. // and passing 'add space prefix' as bool argument
  6195. //
  6196. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6197. if (&fragment == &fragment_buffer.front()) {
  6198. raw_text = " " + raw_text; // prefix with space if the first token is not special
  6199. }
  6200. #ifdef PRETOKENIZERDEBUG
  6201. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6202. #endif
  6203. llm_tokenizer_spm tokenizer(vocab);
  6204. llama_escape_whitespace(raw_text);
  6205. tokenizer.tokenize(raw_text, output);
  6206. }
  6207. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6208. {
  6209. output.push_back(fragment.token);
  6210. }
  6211. }
  6212. } break;
  6213. case LLAMA_VOCAB_TYPE_BPE:
  6214. {
  6215. for (const auto & fragment: fragment_buffer)
  6216. {
  6217. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6218. {
  6219. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6220. #ifdef PRETOKENIZERDEBUG
  6221. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6222. #endif
  6223. llm_tokenizer_bpe tokenizer(vocab);
  6224. tokenizer.tokenize(raw_text, output);
  6225. }
  6226. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6227. {
  6228. output.push_back(fragment.token);
  6229. }
  6230. }
  6231. } break;
  6232. }
  6233. return output;
  6234. }
  6235. //
  6236. // grammar - internal
  6237. //
  6238. struct llama_partial_utf8 {
  6239. uint32_t value; // bit value so far (unshifted)
  6240. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  6241. };
  6242. struct llama_grammar {
  6243. const std::vector<std::vector<llama_grammar_element>> rules;
  6244. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6245. // buffer for partially generated UTF-8 sequence from accepted tokens
  6246. llama_partial_utf8 partial_utf8;
  6247. };
  6248. struct llama_grammar_candidate {
  6249. size_t index;
  6250. const uint32_t * code_points;
  6251. llama_partial_utf8 partial_utf8;
  6252. };
  6253. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  6254. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  6255. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  6256. const std::string & src,
  6257. llama_partial_utf8 partial_start) {
  6258. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  6259. const char * pos = src.c_str();
  6260. std::vector<uint32_t> code_points;
  6261. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  6262. code_points.reserve(src.size() + 1);
  6263. uint32_t value = partial_start.value;
  6264. int n_remain = partial_start.n_remain;
  6265. // continue previous decode, if applicable
  6266. while (*pos != 0 && n_remain > 0) {
  6267. uint8_t next_byte = static_cast<uint8_t>(*pos);
  6268. if ((next_byte >> 6) != 2) {
  6269. // invalid sequence, abort
  6270. code_points.push_back(0);
  6271. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  6272. }
  6273. value = (value << 6) + (next_byte & 0x3F);
  6274. ++pos;
  6275. --n_remain;
  6276. }
  6277. if (partial_start.n_remain > 0 && n_remain == 0) {
  6278. code_points.push_back(value);
  6279. }
  6280. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  6281. while (*pos != 0) {
  6282. uint8_t first_byte = static_cast<uint8_t>(*pos);
  6283. uint8_t highbits = first_byte >> 4;
  6284. n_remain = lookup[highbits] - 1;
  6285. if (n_remain < 0) {
  6286. // invalid sequence, abort
  6287. code_points.clear();
  6288. code_points.push_back(0);
  6289. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  6290. }
  6291. uint8_t mask = (1 << (7 - n_remain)) - 1;
  6292. value = first_byte & mask;
  6293. ++pos;
  6294. while (*pos != 0 && n_remain > 0) {
  6295. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  6296. ++pos;
  6297. --n_remain;
  6298. }
  6299. if (n_remain == 0) {
  6300. code_points.push_back(value);
  6301. }
  6302. }
  6303. code_points.push_back(0);
  6304. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  6305. }
  6306. // returns true iff pos points to the end of one of the definitions of a rule
  6307. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  6308. switch (pos->type) {
  6309. case LLAMA_GRETYPE_END: return true; // NOLINT
  6310. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  6311. default: return false;
  6312. }
  6313. }
  6314. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  6315. // asserts that pos is pointing to a char range element
  6316. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  6317. const llama_grammar_element * pos,
  6318. const uint32_t chr) {
  6319. bool found = false;
  6320. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6321. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  6322. do {
  6323. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6324. // inclusive range, e.g. [a-z]
  6325. found = found || (pos->value <= chr && chr <= pos[1].value);
  6326. pos += 2;
  6327. } else {
  6328. // exact char match, e.g. [a] or "a"
  6329. found = found || pos->value == chr;
  6330. pos += 1;
  6331. }
  6332. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6333. return std::make_pair(found == is_positive_char, pos);
  6334. }
  6335. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  6336. // range at pos (regular or inverse range)
  6337. // asserts that pos is pointing to a char range element
  6338. static bool llama_grammar_match_partial_char(
  6339. const llama_grammar_element * pos,
  6340. const llama_partial_utf8 partial_utf8) {
  6341. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6342. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  6343. uint32_t partial_value = partial_utf8.value;
  6344. int n_remain = partial_utf8.n_remain;
  6345. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  6346. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  6347. return false;
  6348. }
  6349. // range of possible code points this partial UTF-8 sequence could complete to
  6350. uint32_t low = partial_value << (n_remain * 6);
  6351. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  6352. if (low == 0) {
  6353. if (n_remain == 2) {
  6354. low = 1 << 11;
  6355. } else if (n_remain == 3) {
  6356. low = 1 << 16;
  6357. }
  6358. }
  6359. do {
  6360. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6361. // inclusive range, e.g. [a-z]
  6362. if (pos->value <= high && low <= pos[1].value) {
  6363. return is_positive_char;
  6364. }
  6365. pos += 2;
  6366. } else {
  6367. // exact char match, e.g. [a] or "a"
  6368. if (low <= pos->value && pos->value <= high) {
  6369. return is_positive_char;
  6370. }
  6371. pos += 1;
  6372. }
  6373. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6374. return !is_positive_char;
  6375. }
  6376. // transforms a grammar pushdown stack into N possible stacks, all ending
  6377. // at a character range (terminal element)
  6378. static void llama_grammar_advance_stack(
  6379. const std::vector<std::vector<llama_grammar_element>> & rules,
  6380. const std::vector<const llama_grammar_element *> & stack,
  6381. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  6382. if (stack.empty()) {
  6383. new_stacks.emplace_back(stack);
  6384. return;
  6385. }
  6386. const llama_grammar_element * pos = stack.back();
  6387. switch (pos->type) {
  6388. case LLAMA_GRETYPE_RULE_REF: {
  6389. const size_t rule_id = static_cast<size_t>(pos->value);
  6390. const llama_grammar_element * subpos = rules[rule_id].data();
  6391. do {
  6392. // init new stack without the top (pos)
  6393. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6394. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  6395. // if this rule ref is followed by another element, add that to stack
  6396. new_stack.push_back(pos + 1);
  6397. }
  6398. if (!llama_grammar_is_end_of_sequence(subpos)) {
  6399. // if alternate is nonempty, add to stack
  6400. new_stack.push_back(subpos);
  6401. }
  6402. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6403. while (!llama_grammar_is_end_of_sequence(subpos)) {
  6404. // scan to end of alternate def
  6405. subpos++;
  6406. }
  6407. if (subpos->type == LLAMA_GRETYPE_ALT) {
  6408. // there's another alternate def of this rule to process
  6409. subpos++;
  6410. } else {
  6411. break;
  6412. }
  6413. } while (true);
  6414. break;
  6415. }
  6416. case LLAMA_GRETYPE_CHAR:
  6417. case LLAMA_GRETYPE_CHAR_NOT:
  6418. new_stacks.emplace_back(stack);
  6419. break;
  6420. default:
  6421. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  6422. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  6423. // those
  6424. GGML_ASSERT(false);
  6425. }
  6426. }
  6427. // takes a set of possible pushdown stacks on a grammar, which are required to
  6428. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  6429. // produces the N possible stacks if the given char is accepted at those
  6430. // positions
  6431. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  6432. const std::vector<std::vector<llama_grammar_element>> & rules,
  6433. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6434. const uint32_t chr) {
  6435. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  6436. for (const auto & stack : stacks) {
  6437. if (stack.empty()) {
  6438. continue;
  6439. }
  6440. auto match = llama_grammar_match_char(stack.back(), chr);
  6441. if (match.first) {
  6442. const llama_grammar_element * pos = match.second;
  6443. // update top of stack to next element, if any
  6444. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6445. if (!llama_grammar_is_end_of_sequence(pos)) {
  6446. new_stack.push_back(pos);
  6447. }
  6448. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6449. }
  6450. }
  6451. return new_stacks;
  6452. }
  6453. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6454. const std::vector<std::vector<llama_grammar_element>> & rules,
  6455. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6456. const std::vector<llama_grammar_candidate> & candidates);
  6457. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  6458. const std::vector<std::vector<llama_grammar_element>> & rules,
  6459. const std::vector<const llama_grammar_element *> & stack,
  6460. const std::vector<llama_grammar_candidate> & candidates) {
  6461. std::vector<llama_grammar_candidate> rejects;
  6462. if (stack.empty()) {
  6463. for (const auto & tok : candidates) {
  6464. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  6465. rejects.push_back(tok);
  6466. }
  6467. }
  6468. return rejects;
  6469. }
  6470. const llama_grammar_element * stack_pos = stack.back();
  6471. std::vector<llama_grammar_candidate> next_candidates;
  6472. for (const auto & tok : candidates) {
  6473. if (*tok.code_points == 0) {
  6474. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  6475. // that cannot satisfy this position in grammar
  6476. if (tok.partial_utf8.n_remain != 0 &&
  6477. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  6478. rejects.push_back(tok);
  6479. }
  6480. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  6481. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  6482. } else {
  6483. rejects.push_back(tok);
  6484. }
  6485. }
  6486. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  6487. // update top of stack to next element, if any
  6488. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  6489. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  6490. stack_after.push_back(stack_pos_after);
  6491. }
  6492. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  6493. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  6494. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  6495. for (const auto & tok : next_rejects) {
  6496. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  6497. }
  6498. return rejects;
  6499. }
  6500. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6501. const std::vector<std::vector<llama_grammar_element>> & rules,
  6502. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6503. const std::vector<llama_grammar_candidate> & candidates) {
  6504. GGML_ASSERT(!stacks.empty()); // REVIEW
  6505. if (candidates.empty()) {
  6506. return std::vector<llama_grammar_candidate>();
  6507. }
  6508. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  6509. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  6510. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  6511. }
  6512. return rejects;
  6513. }
  6514. //
  6515. // grammar - external
  6516. //
  6517. struct llama_grammar * llama_grammar_init(
  6518. const llama_grammar_element ** rules,
  6519. size_t n_rules,
  6520. size_t start_rule_index) {
  6521. const llama_grammar_element * pos;
  6522. // copy rule definitions into vectors
  6523. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  6524. for (size_t i = 0; i < n_rules; i++) {
  6525. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  6526. vec_rules[i].push_back(*pos);
  6527. }
  6528. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  6529. }
  6530. // loop over alternates of start rule to build initial stacks
  6531. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6532. pos = rules[start_rule_index];
  6533. do {
  6534. std::vector<const llama_grammar_element *> stack;
  6535. if (!llama_grammar_is_end_of_sequence(pos)) {
  6536. // if alternate is nonempty, add to stack
  6537. stack.push_back(pos);
  6538. }
  6539. llama_grammar_advance_stack(vec_rules, stack, stacks);
  6540. while (!llama_grammar_is_end_of_sequence(pos)) {
  6541. // scan to end of alternate def
  6542. pos++;
  6543. }
  6544. if (pos->type == LLAMA_GRETYPE_ALT) {
  6545. // there's another alternate def of this rule to process
  6546. pos++;
  6547. } else {
  6548. break;
  6549. }
  6550. } while (true);
  6551. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  6552. }
  6553. void llama_grammar_free(struct llama_grammar * grammar) {
  6554. delete grammar;
  6555. }
  6556. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  6557. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  6558. // redirect elements in stacks to point to new rules
  6559. for (size_t is = 0; is < result->stacks.size(); is++) {
  6560. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  6561. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  6562. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  6563. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  6564. result->stacks[is][ie] = &result->rules[ir0][ir1];
  6565. }
  6566. }
  6567. }
  6568. }
  6569. }
  6570. return result;
  6571. }
  6572. //
  6573. // sampling
  6574. //
  6575. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  6576. if (seed == LLAMA_DEFAULT_SEED) {
  6577. seed = time(NULL);
  6578. }
  6579. ctx->rng.seed(seed);
  6580. }
  6581. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  6582. GGML_ASSERT(candidates->size > 0);
  6583. const int64_t t_start_sample_us = ggml_time_us();
  6584. // Sort the logits in descending order
  6585. if (!candidates->sorted) {
  6586. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6587. return a.logit > b.logit;
  6588. });
  6589. candidates->sorted = true;
  6590. }
  6591. float max_l = candidates->data[0].logit;
  6592. float cum_sum = 0.0f;
  6593. for (size_t i = 0; i < candidates->size; ++i) {
  6594. float p = expf(candidates->data[i].logit - max_l);
  6595. candidates->data[i].p = p;
  6596. cum_sum += p;
  6597. }
  6598. for (size_t i = 0; i < candidates->size; ++i) {
  6599. candidates->data[i].p /= cum_sum;
  6600. }
  6601. if (ctx) {
  6602. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6603. }
  6604. }
  6605. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  6606. const int64_t t_start_sample_us = ggml_time_us();
  6607. k = std::max(k, (int) min_keep);
  6608. k = std::min(k, (int) candidates->size);
  6609. // Sort scores in descending order
  6610. if (!candidates->sorted) {
  6611. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  6612. return a.logit > b.logit;
  6613. };
  6614. if (k == (int) candidates->size) {
  6615. std::sort(candidates->data, candidates->data + candidates->size, comp);
  6616. } else {
  6617. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  6618. }
  6619. candidates->sorted = true;
  6620. }
  6621. candidates->size = k;
  6622. if (ctx) {
  6623. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6624. }
  6625. }
  6626. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6627. if (p >= 1.0f) {
  6628. return;
  6629. }
  6630. llama_sample_softmax(ctx, candidates);
  6631. const int64_t t_start_sample_us = ggml_time_us();
  6632. // Compute the cumulative probabilities
  6633. float cum_sum = 0.0f;
  6634. size_t last_idx = candidates->size;
  6635. for (size_t i = 0; i < candidates->size; ++i) {
  6636. cum_sum += candidates->data[i].p;
  6637. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  6638. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  6639. if (cum_sum >= p && i + 1 >= min_keep) {
  6640. last_idx = i + 1;
  6641. break;
  6642. }
  6643. }
  6644. // Resize the output vector to keep only the top-p tokens
  6645. candidates->size = last_idx;
  6646. if (ctx) {
  6647. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6648. }
  6649. }
  6650. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6651. if (p <= 0.0f || !candidates->size) {
  6652. return;
  6653. }
  6654. llama_sample_softmax(ctx, candidates);
  6655. const int64_t t_start_sample_us = ggml_time_us();
  6656. float scale = candidates->data[0].p; // scale by max prob
  6657. size_t i = 1; // first token always matches
  6658. for (; i < candidates->size; ++i) {
  6659. if (candidates->data[i].p < p * scale && i >= min_keep) {
  6660. break; // prob too small
  6661. }
  6662. }
  6663. // Resize the output vector to keep only the matching tokens
  6664. candidates->size = i;
  6665. if (ctx) {
  6666. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6667. }
  6668. }
  6669. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  6670. if (z >= 1.0f || candidates->size <= 2) {
  6671. return;
  6672. }
  6673. llama_sample_softmax(nullptr, candidates);
  6674. const int64_t t_start_sample_us = ggml_time_us();
  6675. // Compute the first and second derivatives
  6676. std::vector<float> first_derivatives(candidates->size - 1);
  6677. std::vector<float> second_derivatives(candidates->size - 2);
  6678. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  6679. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  6680. }
  6681. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6682. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  6683. }
  6684. // Calculate absolute value of second derivatives
  6685. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6686. second_derivatives[i] = std::abs(second_derivatives[i]);
  6687. }
  6688. // Normalize the second derivatives
  6689. {
  6690. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  6691. if (second_derivatives_sum > 1e-6f) {
  6692. for (float & value : second_derivatives) {
  6693. value /= second_derivatives_sum;
  6694. }
  6695. } else {
  6696. for (float & value : second_derivatives) {
  6697. value = 1.0f / second_derivatives.size();
  6698. }
  6699. }
  6700. }
  6701. float cum_sum = 0.0f;
  6702. size_t last_idx = candidates->size;
  6703. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6704. cum_sum += second_derivatives[i];
  6705. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  6706. if (cum_sum > z && i >= min_keep) {
  6707. last_idx = i;
  6708. break;
  6709. }
  6710. }
  6711. // Resize the output vector to keep only the tokens above the tail location
  6712. candidates->size = last_idx;
  6713. if (ctx) {
  6714. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6715. }
  6716. }
  6717. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6718. // Reference implementation:
  6719. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  6720. if (p >= 1.0f) {
  6721. return;
  6722. }
  6723. // Compute the softmax of logits and calculate entropy
  6724. llama_sample_softmax(nullptr, candidates);
  6725. const int64_t t_start_sample_us = ggml_time_us();
  6726. float entropy = 0.0f;
  6727. for (size_t i = 0; i < candidates->size; ++i) {
  6728. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  6729. }
  6730. // Compute the absolute difference between negative log probability and entropy for each candidate
  6731. std::vector<float> shifted_scores;
  6732. for (size_t i = 0; i < candidates->size; ++i) {
  6733. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  6734. shifted_scores.push_back(shifted_score);
  6735. }
  6736. // Sort tokens based on the shifted_scores and their corresponding indices
  6737. std::vector<size_t> indices(candidates->size);
  6738. std::iota(indices.begin(), indices.end(), 0);
  6739. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  6740. return shifted_scores[a] < shifted_scores[b];
  6741. });
  6742. // Compute the cumulative probabilities
  6743. float cum_sum = 0.0f;
  6744. size_t last_idx = indices.size();
  6745. for (size_t i = 0; i < indices.size(); ++i) {
  6746. size_t idx = indices[i];
  6747. cum_sum += candidates->data[idx].p;
  6748. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  6749. if (cum_sum > p && i >= min_keep - 1) {
  6750. last_idx = i + 1;
  6751. break;
  6752. }
  6753. }
  6754. // Resize the output vector to keep only the locally typical tokens
  6755. std::vector<llama_token_data> new_candidates;
  6756. for (size_t i = 0; i < last_idx; ++i) {
  6757. size_t idx = indices[i];
  6758. new_candidates.push_back(candidates->data[idx]);
  6759. }
  6760. // Replace the data in candidates with the new_candidates data
  6761. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  6762. candidates->size = new_candidates.size();
  6763. candidates->sorted = false;
  6764. if (ctx) {
  6765. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6766. }
  6767. }
  6768. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6769. const int64_t t_start_sample_us = ggml_time_us();
  6770. for (size_t i = 0; i < candidates_p->size; ++i) {
  6771. candidates_p->data[i].logit /= temp;
  6772. }
  6773. if (ctx) {
  6774. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6775. }
  6776. }
  6777. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6778. llama_sample_temp(ctx, candidates_p, temp);
  6779. }
  6780. void llama_sample_repetition_penalties(
  6781. struct llama_context * ctx,
  6782. llama_token_data_array * candidates,
  6783. const llama_token * last_tokens,
  6784. size_t penalty_last_n,
  6785. float penalty_repeat,
  6786. float penalty_freq,
  6787. float penalty_present) {
  6788. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  6789. return;
  6790. }
  6791. const int64_t t_start_sample_us = ggml_time_us();
  6792. // Create a frequency map to count occurrences of each token in last_tokens
  6793. std::unordered_map<llama_token, int> token_count;
  6794. for (size_t i = 0; i < penalty_last_n; ++i) {
  6795. token_count[last_tokens[i]]++;
  6796. }
  6797. // Apply frequency and presence penalties to the candidates
  6798. for (size_t i = 0; i < candidates->size; ++i) {
  6799. const auto token_iter = token_count.find(candidates->data[i].id);
  6800. if (token_iter == token_count.end()) {
  6801. continue;
  6802. }
  6803. const int count = token_iter->second;
  6804. // 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.
  6805. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  6806. if (candidates->data[i].logit <= 0) {
  6807. candidates->data[i].logit *= penalty_repeat;
  6808. } else {
  6809. candidates->data[i].logit /= penalty_repeat;
  6810. }
  6811. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  6812. }
  6813. candidates->sorted = false;
  6814. if (ctx) {
  6815. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6816. }
  6817. }
  6818. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  6819. GGML_ASSERT(ctx);
  6820. const int64_t t_start_sample_us = ggml_time_us();
  6821. bool allow_eos = false;
  6822. for (const auto & stack : grammar->stacks) {
  6823. if (stack.empty()) {
  6824. allow_eos = true;
  6825. break;
  6826. }
  6827. }
  6828. const llama_token eos = llama_token_eos(&ctx->model);
  6829. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  6830. candidates_decoded.reserve(candidates->size);
  6831. std::vector<llama_grammar_candidate> candidates_grammar;
  6832. candidates_grammar.reserve(candidates->size);
  6833. for (size_t i = 0; i < candidates->size; ++i) {
  6834. const llama_token id = candidates->data[i].id;
  6835. const std::string piece = llama_token_to_piece(ctx, id);
  6836. if (id == eos) {
  6837. if (!allow_eos) {
  6838. candidates->data[i].logit = -INFINITY;
  6839. }
  6840. } else if (piece.empty() || piece[0] == 0) {
  6841. candidates->data[i].logit = -INFINITY;
  6842. } else {
  6843. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  6844. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  6845. }
  6846. }
  6847. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  6848. for (const auto & reject : rejects) {
  6849. candidates->data[reject.index].logit = -INFINITY;
  6850. }
  6851. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6852. }
  6853. static void llama_log_softmax(float * array, size_t size) {
  6854. float max_l = *std::max_element(array, array + size);
  6855. float sum = 0.f;
  6856. for (size_t i = 0; i < size; ++i) {
  6857. float p = expf(array[i] - max_l);
  6858. sum += p;
  6859. array[i] = p;
  6860. }
  6861. for (size_t i = 0; i < size; ++i) {
  6862. array[i] = logf(array[i] / sum);
  6863. }
  6864. }
  6865. void llama_sample_apply_guidance(
  6866. struct llama_context * ctx,
  6867. float * logits,
  6868. float * logits_guidance,
  6869. float scale) {
  6870. GGML_ASSERT(ctx);
  6871. const auto t_start_sample_us = ggml_time_us();
  6872. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  6873. llama_log_softmax(logits, n_vocab);
  6874. llama_log_softmax(logits_guidance, n_vocab);
  6875. for (int i = 0; i < n_vocab; ++i) {
  6876. auto & l = logits[i];
  6877. const auto & g = logits_guidance[i];
  6878. l = scale * (l - g) + g;
  6879. }
  6880. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6881. }
  6882. void llama_sample_classifier_free_guidance(
  6883. struct llama_context * ctx,
  6884. llama_token_data_array * candidates,
  6885. struct llama_context * guidance_ctx,
  6886. float scale) {
  6887. GGML_ASSERT(ctx);
  6888. int64_t t_start_sample_us;
  6889. t_start_sample_us = ggml_time_us();
  6890. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  6891. GGML_ASSERT(n_vocab == candidates->size);
  6892. GGML_ASSERT(!candidates->sorted);
  6893. std::vector<float> logits_base(n_vocab);
  6894. for (size_t i = 0; i < n_vocab; ++i) {
  6895. logits_base[i] = candidates->data[i].logit;
  6896. }
  6897. float * logits_guidance = llama_get_logits(guidance_ctx);
  6898. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6899. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  6900. t_start_sample_us = ggml_time_us();
  6901. for (size_t i = 0; i < n_vocab; ++i) {
  6902. candidates->data[i].logit = logits_base[i];
  6903. }
  6904. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6905. }
  6906. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  6907. GGML_ASSERT(ctx);
  6908. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  6909. int64_t t_start_sample_us;
  6910. t_start_sample_us = ggml_time_us();
  6911. llama_sample_softmax(nullptr, candidates);
  6912. // Estimate s_hat using the most probable m tokens
  6913. float s_hat = 0.0;
  6914. float sum_ti_bi = 0.0;
  6915. float sum_ti_sq = 0.0;
  6916. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  6917. float t_i = logf(float(i + 2) / float(i + 1));
  6918. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  6919. sum_ti_bi += t_i * b_i;
  6920. sum_ti_sq += t_i * t_i;
  6921. }
  6922. s_hat = sum_ti_bi / sum_ti_sq;
  6923. // Compute k from the estimated s_hat and target surprise value
  6924. float epsilon_hat = s_hat - 1;
  6925. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  6926. // Sample the next word X using top-k sampling
  6927. llama_sample_top_k(nullptr, candidates, int(k), 1);
  6928. if (ctx) {
  6929. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6930. }
  6931. llama_token X = llama_sample_token(ctx, candidates);
  6932. t_start_sample_us = ggml_time_us();
  6933. // Compute error as the difference between observed surprise and target surprise value
  6934. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6935. return candidate.id == X;
  6936. }));
  6937. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6938. float e = observed_surprise - tau;
  6939. // Update mu using the learning rate and error
  6940. *mu = *mu - eta * e;
  6941. if (ctx) {
  6942. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6943. }
  6944. return X;
  6945. }
  6946. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  6947. int64_t t_start_sample_us;
  6948. t_start_sample_us = ggml_time_us();
  6949. llama_sample_softmax(ctx, candidates);
  6950. // Truncate the words with surprise values greater than mu
  6951. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6952. return -log2f(candidate.p) > *mu;
  6953. }));
  6954. if (candidates->size == 0) {
  6955. candidates->size = 1;
  6956. }
  6957. if (ctx) {
  6958. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6959. }
  6960. // Normalize the probabilities of the remaining words
  6961. llama_sample_softmax(ctx, candidates);
  6962. // Sample the next word X from the remaining words
  6963. llama_token X = llama_sample_token(ctx, candidates);
  6964. t_start_sample_us = ggml_time_us();
  6965. // Compute error as the difference between observed surprise and target surprise value
  6966. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6967. return candidate.id == X;
  6968. }));
  6969. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6970. float e = observed_surprise - tau;
  6971. // Update mu using the learning rate and error
  6972. *mu = *mu - eta * e;
  6973. if (ctx) {
  6974. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6975. }
  6976. return X;
  6977. }
  6978. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  6979. const int64_t t_start_sample_us = ggml_time_us();
  6980. // Find max element
  6981. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6982. return a.logit < b.logit;
  6983. });
  6984. llama_token result = max_iter->id;
  6985. if (ctx) {
  6986. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6987. ctx->n_sample++;
  6988. }
  6989. return result;
  6990. }
  6991. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  6992. GGML_ASSERT(ctx);
  6993. const int64_t t_start_sample_us = ggml_time_us();
  6994. llama_sample_softmax(nullptr, candidates);
  6995. std::vector<float> probs;
  6996. probs.reserve(candidates->size);
  6997. for (size_t i = 0; i < candidates->size; ++i) {
  6998. probs.push_back(candidates->data[i].p);
  6999. }
  7000. std::discrete_distribution<> dist(probs.begin(), probs.end());
  7001. auto & rng = ctx->rng;
  7002. int idx = dist(rng);
  7003. llama_token result = candidates->data[idx].id;
  7004. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7005. ctx->n_sample++;
  7006. return result;
  7007. }
  7008. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  7009. const int64_t t_start_sample_us = ggml_time_us();
  7010. if (token == llama_token_eos(&ctx->model)) {
  7011. for (const auto & stack : grammar->stacks) {
  7012. if (stack.empty()) {
  7013. return;
  7014. }
  7015. }
  7016. GGML_ASSERT(false);
  7017. }
  7018. const std::string piece = llama_token_to_piece(ctx, token);
  7019. // Note terminating 0 in decoded string
  7020. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  7021. const auto & code_points = decoded.first;
  7022. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  7023. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  7024. }
  7025. grammar->partial_utf8 = decoded.second;
  7026. GGML_ASSERT(!grammar->stacks.empty());
  7027. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7028. }
  7029. //
  7030. // Beam search
  7031. //
  7032. struct llama_beam {
  7033. std::vector<llama_token> tokens;
  7034. float p; // Cumulative beam probability (renormalized relative to all beams)
  7035. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  7036. // Sort beams by probability. In case of ties, prefer beams at eob.
  7037. bool operator<(const llama_beam & rhs) const {
  7038. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  7039. }
  7040. // Shift off first n tokens and discard them.
  7041. void shift_tokens(const size_t n) {
  7042. if (n) {
  7043. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  7044. tokens.resize(tokens.size() - n);
  7045. }
  7046. }
  7047. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  7048. };
  7049. // A struct for calculating logit-related info.
  7050. struct llama_logit_info {
  7051. const float * const logits;
  7052. const int n_vocab;
  7053. const float max_l;
  7054. const float normalizer;
  7055. struct sum_exp {
  7056. float max_l;
  7057. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  7058. };
  7059. llama_logit_info(llama_context * ctx)
  7060. : logits(llama_get_logits(ctx))
  7061. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  7062. , max_l(*std::max_element(logits, logits + n_vocab))
  7063. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  7064. { }
  7065. llama_token_data get_token_data(const llama_token token_id) const {
  7066. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  7067. return {token_id, logits[token_id], p};
  7068. }
  7069. // Return top k token_data by logit.
  7070. std::vector<llama_token_data> top_k(size_t k) {
  7071. std::vector<llama_token_data> min_heap; // min-heap by logit
  7072. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  7073. min_heap.reserve(k_min);
  7074. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  7075. min_heap.push_back(get_token_data(token_id));
  7076. }
  7077. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  7078. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  7079. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  7080. if (min_heap.front().logit < logits[token_id]) {
  7081. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  7082. min_heap.back().id = token_id;
  7083. min_heap.back().logit = logits[token_id];
  7084. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  7085. }
  7086. }
  7087. return min_heap;
  7088. }
  7089. float probability_from_logit(float logit) const {
  7090. return normalizer * std::exp(logit - max_l);
  7091. }
  7092. };
  7093. struct llama_beam_search_data {
  7094. llama_context * ctx;
  7095. size_t n_beams;
  7096. int n_past;
  7097. int n_predict;
  7098. std::vector<llama_beam> beams;
  7099. std::vector<llama_beam> next_beams;
  7100. // Re-calculated on each loop iteration
  7101. size_t common_prefix_length;
  7102. // Used to communicate to/from callback on beams state.
  7103. std::vector<llama_beam_view> beam_views;
  7104. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  7105. : ctx(ctx)
  7106. , n_beams(n_beams)
  7107. , n_past(n_past)
  7108. , n_predict(n_predict)
  7109. , beam_views(n_beams) {
  7110. beams.reserve(n_beams);
  7111. next_beams.reserve(n_beams);
  7112. }
  7113. // Collapse beams to a single beam given by index.
  7114. void collapse_beams(const size_t beam_idx) {
  7115. if (0u < beam_idx) {
  7116. std::swap(beams[0], beams[beam_idx]);
  7117. }
  7118. beams.resize(1);
  7119. }
  7120. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  7121. // The repetitive patterns below reflect the 2 stages of heaps:
  7122. // * Gather elements until the vector is full, then call std::make_heap() on it.
  7123. // * If the heap is full and a new element is found that should be included, pop the
  7124. // least element to the back(), replace it with the new, then push it into the heap.
  7125. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  7126. // Min-heaps use a greater-than comparator.
  7127. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  7128. if (beam.eob) {
  7129. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  7130. if (next_beams.size() < n_beams) {
  7131. next_beams.push_back(std::move(beam));
  7132. if (next_beams.size() == n_beams) {
  7133. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7134. }
  7135. } else if (next_beams.front().p < beam.p) {
  7136. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7137. next_beams.back() = std::move(beam);
  7138. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7139. }
  7140. } else {
  7141. // beam is not at end-of-sentence, so branch with next top_k tokens.
  7142. if (!beam.tokens.empty()) {
  7143. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  7144. }
  7145. llama_logit_info logit_info(ctx);
  7146. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  7147. size_t i=0;
  7148. if (next_beams.size() < n_beams) {
  7149. for (; next_beams.size() < n_beams ; ++i) {
  7150. llama_beam next_beam = beam;
  7151. next_beam.tokens.push_back(next_tokens[i].id);
  7152. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7153. next_beams.push_back(std::move(next_beam));
  7154. }
  7155. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7156. } else {
  7157. for (; next_beams.front().p == 0.0f ; ++i) {
  7158. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7159. next_beams.back() = beam;
  7160. next_beams.back().tokens.push_back(next_tokens[i].id);
  7161. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7162. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7163. }
  7164. }
  7165. for (; i < n_beams ; ++i) {
  7166. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  7167. if (next_beams.front().p < next_p) {
  7168. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7169. next_beams.back() = beam;
  7170. next_beams.back().tokens.push_back(next_tokens[i].id);
  7171. next_beams.back().p = next_p;
  7172. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7173. }
  7174. }
  7175. }
  7176. }
  7177. // Find common_prefix_length based on beams.
  7178. // Requires beams is not empty.
  7179. size_t find_common_prefix_length() {
  7180. size_t common_prefix_length = beams[0].tokens.size();
  7181. for (size_t i = 1 ; i < beams.size() ; ++i) {
  7182. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  7183. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  7184. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  7185. common_prefix_length = j;
  7186. break;
  7187. }
  7188. }
  7189. }
  7190. return common_prefix_length;
  7191. }
  7192. // Construct beams_state to send back to caller via the callback function.
  7193. // Side effect: set common_prefix_length = find_common_prefix_length();
  7194. llama_beams_state get_beams_state(const bool last_call) {
  7195. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7196. beam_views[i] = beams[i].view();
  7197. }
  7198. common_prefix_length = find_common_prefix_length();
  7199. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  7200. }
  7201. // Loop:
  7202. // * while i < n_predict, AND
  7203. // * any of the beams have not yet reached end-of-beam (eob), AND
  7204. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  7205. // (since all other beam probabilities can only decrease)
  7206. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  7207. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  7208. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  7209. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  7210. !beams[top_beam_index()].eob ; ++i) {
  7211. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  7212. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  7213. if (common_prefix_length) {
  7214. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  7215. n_past += common_prefix_length;
  7216. }
  7217. // Zero-out next_beam probabilities to place them last in following min-heap.
  7218. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  7219. for (llama_beam & beam : beams) {
  7220. beam.shift_tokens(common_prefix_length);
  7221. fill_next_beams_by_top_probabilities(beam);
  7222. }
  7223. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  7224. beams.swap(next_beams);
  7225. renormalize_beam_probabilities(beams);
  7226. }
  7227. collapse_beams(top_beam_index());
  7228. callback(callback_data, get_beams_state(true));
  7229. }
  7230. // As beams grow, the cumulative probabilities decrease.
  7231. // Renormalize them to avoid floating point underflow.
  7232. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  7233. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  7234. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  7235. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  7236. }
  7237. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  7238. size_t top_beam_index() {
  7239. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  7240. }
  7241. // Copy (p,eob) for each beam which may have been changed by the callback.
  7242. void update_beams_from_beam_views() {
  7243. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7244. beams[i].p = beam_views[i].p;
  7245. beams[i].eob = beam_views[i].eob;
  7246. }
  7247. }
  7248. };
  7249. void llama_beam_search(llama_context * ctx,
  7250. llama_beam_search_callback_fn_t callback, void * callback_data,
  7251. size_t n_beams, int n_past, int n_predict) {
  7252. assert(ctx);
  7253. const int64_t t_start_sample_us = ggml_time_us();
  7254. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  7255. beam_search_data.loop(callback, callback_data);
  7256. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7257. ctx->n_sample++;
  7258. }
  7259. //
  7260. // quantization
  7261. //
  7262. struct quantize_state_internal {
  7263. const llama_model & model;
  7264. const llama_model_quantize_params * params;
  7265. int n_attention_wv = 0;
  7266. int n_ffn_down = 0;
  7267. int n_ffn_gate = 0;
  7268. int n_ffn_up = 0;
  7269. int i_attention_wv = 0;
  7270. int i_ffn_down = 0;
  7271. int i_ffn_gate = 0;
  7272. int i_ffn_up = 0;
  7273. int n_k_quantized = 0;
  7274. int n_fallback = 0;
  7275. bool has_imatrix = false;
  7276. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  7277. : model(model)
  7278. , params(params)
  7279. {}
  7280. };
  7281. static void llama_convert_tensor_internal(
  7282. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  7283. const size_t nelements, const int nthread
  7284. ) {
  7285. if (output.size() < nelements) {
  7286. output.resize(nelements);
  7287. }
  7288. float * f32_output = (float *) output.data();
  7289. ggml_type_traits_t qtype;
  7290. if (ggml_is_quantized(tensor->type)) {
  7291. qtype = ggml_internal_get_type_traits(tensor->type);
  7292. if (qtype.to_float == NULL) {
  7293. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  7294. }
  7295. } else if (tensor->type != GGML_TYPE_F16) {
  7296. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  7297. }
  7298. if (nthread < 2) {
  7299. if (tensor->type == GGML_TYPE_F16) {
  7300. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  7301. } else if (ggml_is_quantized(tensor->type)) {
  7302. qtype.to_float(tensor->data, f32_output, nelements);
  7303. } else {
  7304. GGML_ASSERT(false); // unreachable
  7305. }
  7306. return;
  7307. }
  7308. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  7309. size_t block_size_bytes = ggml_type_size(tensor->type);
  7310. GGML_ASSERT(nelements % block_size == 0);
  7311. size_t nblocks = nelements / block_size;
  7312. size_t blocks_per_thread = nblocks / nthread;
  7313. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  7314. size_t in_buff_offs = 0;
  7315. size_t out_buff_offs = 0;
  7316. for (int tnum = 0; tnum < nthread; tnum++) {
  7317. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  7318. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  7319. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  7320. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  7321. if (typ == GGML_TYPE_F16) {
  7322. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  7323. } else {
  7324. qtype.to_float(inbuf, outbuf, nels);
  7325. }
  7326. };
  7327. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  7328. in_buff_offs += thr_block_bytes;
  7329. out_buff_offs += thr_elems;
  7330. }
  7331. for (auto & w : workers) { w.join(); }
  7332. workers.clear();
  7333. }
  7334. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  7335. const std::string name = ggml_get_name(tensor);
  7336. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7337. const llm_arch arch = qs.model.arch;
  7338. const auto tn = LLM_TN(arch);
  7339. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  7340. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  7341. };
  7342. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  7343. int nx = tensor->ne[0];
  7344. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  7345. new_type = GGML_TYPE_Q8_0;
  7346. }
  7347. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7348. new_type = GGML_TYPE_Q5_K;
  7349. }
  7350. else if (new_type != GGML_TYPE_Q8_0) {
  7351. new_type = GGML_TYPE_Q6_K;
  7352. }
  7353. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7354. if (name.find("attn_v.weight") != std::string::npos) {
  7355. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  7356. else new_type = GGML_TYPE_Q2_K;
  7357. ++qs.i_attention_wv;
  7358. }
  7359. else if (name.find("ffn_down") != std::string::npos) {
  7360. if (qs.i_ffn_down < qs.n_ffn_down/8) new_type = GGML_TYPE_Q2_K;
  7361. ++qs.i_ffn_down;
  7362. }
  7363. else if (name == "token_embd.weight") new_type = GGML_TYPE_Q2_K;
  7364. } else if (name.find("attn_v.weight") != std::string::npos) {
  7365. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  7366. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  7367. }
  7368. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  7369. new_type = GGML_TYPE_Q4_K;
  7370. }
  7371. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7372. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7373. }
  7374. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7375. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  7376. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  7377. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  7378. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  7379. (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;
  7380. if (qs.model.type == MODEL_70B) {
  7381. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  7382. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  7383. // nearly negligible increase in model size by quantizing this tensor with more bits:
  7384. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  7385. }
  7386. if (qs.model.hparams.n_expert == 8) {
  7387. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7388. // TODO: explore better strategies
  7389. new_type = GGML_TYPE_Q8_0;
  7390. }
  7391. ++qs.i_attention_wv;
  7392. } else if (name.find("attn_k.weight") != std::string::npos) {
  7393. if (qs.model.hparams.n_expert == 8) {
  7394. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7395. // TODO: explore better strategies
  7396. new_type = GGML_TYPE_Q8_0;
  7397. }
  7398. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7399. new_type = GGML_TYPE_Q2_K;
  7400. }
  7401. } else if (name.find("ffn_down") != std::string::npos) {
  7402. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  7403. int i_layer, n_layer;
  7404. if (n_expert == 1) {
  7405. i_layer = qs.i_ffn_down;
  7406. n_layer = qs.n_ffn_down;
  7407. } else {
  7408. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  7409. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  7410. // for getting the current layer as I initially thought, and we need to resort to parsing the
  7411. // tensor name.
  7412. n_layer = qs.n_ffn_down / n_expert;
  7413. if (sscanf(name.c_str(), "blk.%d.ffn_down", &i_layer) != 1) {
  7414. throw std::runtime_error(format("Failed to determine layer for tensor %s", name.c_str()));
  7415. }
  7416. if (i_layer < 0 || i_layer >= n_layer) {
  7417. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name.c_str(), n_layer));
  7418. }
  7419. }
  7420. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7421. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7422. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  7423. }
  7424. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7425. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  7426. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  7427. : GGML_TYPE_Q3_K;
  7428. }
  7429. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  7430. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  7431. }
  7432. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7433. if (arch == LLM_ARCH_FALCON) {
  7434. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  7435. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7436. } else {
  7437. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7438. }
  7439. }
  7440. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7441. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  7442. new_type = GGML_TYPE_Q5_K;
  7443. }
  7444. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  7445. && qs.has_imatrix && i_layer < n_layer/8) {
  7446. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  7447. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  7448. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  7449. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  7450. }
  7451. ++qs.i_ffn_down;
  7452. } else if (name.find("attn_output.weight") != std::string::npos) {
  7453. if (arch != LLM_ARCH_FALCON) {
  7454. if (qs.model.hparams.n_expert == 8) {
  7455. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS ||
  7456. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ||
  7457. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7458. new_type = GGML_TYPE_Q5_K;
  7459. }
  7460. } else {
  7461. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  7462. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  7463. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7464. }
  7465. } else {
  7466. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7467. }
  7468. }
  7469. else if (name.find("attn_qkv.weight") != std::string::npos) {
  7470. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7471. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  7472. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  7473. }
  7474. else if (name.find("ffn_gate") != std::string::npos) {
  7475. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(qs.i_ffn_gate, qs.n_ffn_gate)) {
  7476. new_type = GGML_TYPE_Q2_K;
  7477. }
  7478. ++qs.i_ffn_gate;
  7479. }
  7480. else if (name.find("ffn_up") != std::string::npos) {
  7481. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(qs.i_ffn_up, qs.n_ffn_up)) {
  7482. new_type = GGML_TYPE_Q2_K;
  7483. }
  7484. ++qs.i_ffn_up;
  7485. }
  7486. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7487. //}
  7488. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  7489. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  7490. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7491. //}
  7492. // This can be used to reduce the size of the Q5_K_S model.
  7493. // The associated PPL increase is fully in line with the size reduction
  7494. //else {
  7495. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  7496. //}
  7497. bool convert_incompatible_tensor = false;
  7498. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  7499. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  7500. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS) {
  7501. int nx = tensor->ne[0];
  7502. int ny = tensor->ne[1];
  7503. if (nx % QK_K != 0) {
  7504. 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));
  7505. convert_incompatible_tensor = true;
  7506. } else {
  7507. ++qs.n_k_quantized;
  7508. }
  7509. }
  7510. if (convert_incompatible_tensor) {
  7511. switch (new_type) {
  7512. case GGML_TYPE_IQ2_XXS:
  7513. case GGML_TYPE_IQ2_XS:
  7514. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  7515. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  7516. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  7517. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  7518. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  7519. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  7520. }
  7521. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  7522. ++qs.n_fallback;
  7523. }
  7524. return new_type;
  7525. }
  7526. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  7527. ggml_type quantized_type;
  7528. llama_ftype ftype = params->ftype;
  7529. switch (params->ftype) {
  7530. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  7531. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  7532. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  7533. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  7534. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  7535. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  7536. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  7537. // K-quants
  7538. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  7539. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  7540. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:
  7541. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  7542. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  7543. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  7544. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  7545. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  7546. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  7547. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  7548. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  7549. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:quantized_type = GGML_TYPE_IQ2_XXS; break;
  7550. case LLAMA_FTYPE_MOSTLY_IQ2_XS :quantized_type = GGML_TYPE_IQ2_XS; break;
  7551. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  7552. }
  7553. int nthread = params->nthread;
  7554. if (nthread <= 0) {
  7555. nthread = std::thread::hardware_concurrency();
  7556. }
  7557. // mmap consistently increases speed Linux, and also increases speed on Windows with
  7558. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  7559. #if defined(__linux__) || defined(_WIN32)
  7560. constexpr bool use_mmap = true;
  7561. #else
  7562. constexpr bool use_mmap = false;
  7563. #endif
  7564. llama_model_loader ml(fname_inp, use_mmap, NULL);
  7565. ml.init_mapping(false); // no prefetching?
  7566. llama_model model;
  7567. llm_load_arch(ml, model);
  7568. llm_load_hparams(ml, model);
  7569. struct quantize_state_internal qs(model, params);
  7570. if (params->only_copy) {
  7571. ftype = model.ftype;
  7572. }
  7573. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  7574. if (params->imatrix) {
  7575. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  7576. if (imatrix_data) {
  7577. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  7578. qs.has_imatrix = true;
  7579. }
  7580. }
  7581. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  7582. struct gguf_context * ctx_out = gguf_init_empty();
  7583. // copy the KV pairs from the input file
  7584. gguf_set_kv (ctx_out, ml.ctx_gguf);
  7585. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  7586. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  7587. for (int i = 0; i < ml.n_tensors; ++i) {
  7588. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7589. const std::string name = ggml_get_name(meta);
  7590. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7591. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  7592. ++qs.n_attention_wv;
  7593. }
  7594. else if (name.find("ffn_down") != std::string::npos) {
  7595. ++qs.n_ffn_down;
  7596. }
  7597. else if (name.find("ffn_gate") != std::string::npos) {
  7598. ++qs.n_ffn_gate;
  7599. }
  7600. else if (name.find("ffn_up") != std::string::npos) {
  7601. ++qs.n_ffn_up;
  7602. }
  7603. }
  7604. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  7605. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  7606. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  7607. }
  7608. size_t total_size_org = 0;
  7609. size_t total_size_new = 0;
  7610. std::vector<int64_t> hist_all(1 << 4, 0);
  7611. std::vector<std::thread> workers;
  7612. workers.reserve(nthread);
  7613. std::mutex mutex;
  7614. int idx = 0;
  7615. std::vector<no_init<uint8_t>> read_data;
  7616. std::vector<no_init<uint8_t>> work;
  7617. std::vector<no_init<float>> f32_conv_buf;
  7618. // populate the original tensors so we get an initial meta data
  7619. for (int i = 0; i < ml.n_tensors; ++i) {
  7620. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7621. gguf_add_tensor(ctx_out, meta);
  7622. }
  7623. std::ofstream fout(fname_out, std::ios::binary);
  7624. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  7625. const size_t meta_size = gguf_get_meta_size(ctx_out);
  7626. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  7627. // placeholder for the meta data
  7628. ::zeros(fout, meta_size);
  7629. for (int i = 0; i < ml.n_tensors; ++i) {
  7630. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  7631. const std::string name = ggml_get_name(tensor);
  7632. if (!ml.use_mmap) {
  7633. if (read_data.size() < ggml_nbytes(tensor)) {
  7634. read_data.resize(ggml_nbytes(tensor));
  7635. }
  7636. tensor->data = read_data.data();
  7637. }
  7638. ml.load_data_for(tensor);
  7639. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  7640. ++idx, ml.n_tensors,
  7641. ggml_get_name(tensor),
  7642. llama_format_tensor_shape(tensor).c_str(),
  7643. ggml_type_name(tensor->type));
  7644. // This used to be a regex, but <regex> has an extreme cost to compile times.
  7645. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  7646. // quantize only 2D tensors
  7647. quantize &= (ggml_n_dims(tensor) == 2);
  7648. quantize &= params->quantize_output_tensor || name != "output.weight";
  7649. quantize &= !params->only_copy;
  7650. // do not quantize expert gating tensors
  7651. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  7652. enum ggml_type new_type;
  7653. void * new_data;
  7654. size_t new_size;
  7655. if (quantize) {
  7656. new_type = quantized_type;
  7657. if (!params->pure) {
  7658. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  7659. }
  7660. // If we've decided to quantize to the same type the tensor is already
  7661. // in then there's nothing to do.
  7662. quantize = tensor->type != new_type;
  7663. }
  7664. if (!quantize) {
  7665. new_type = tensor->type;
  7666. new_data = tensor->data;
  7667. new_size = ggml_nbytes(tensor);
  7668. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  7669. } else {
  7670. const size_t nelements = ggml_nelements(tensor);
  7671. const float * imatrix = nullptr;
  7672. if (imatrix_data) {
  7673. auto it = imatrix_data->find(tensor->name);
  7674. if (it == imatrix_data->end()) {
  7675. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  7676. } else {
  7677. if (it->second.size() == (size_t)tensor->ne[0]) {
  7678. imatrix = it->second.data();
  7679. } else {
  7680. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  7681. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  7682. }
  7683. }
  7684. }
  7685. if ((new_type == GGML_TYPE_IQ2_XXS ||
  7686. new_type == GGML_TYPE_IQ2_XS ||
  7687. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  7688. LLAMA_LOG_ERROR("\n\n============================================================\n");
  7689. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  7690. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  7691. LLAMA_LOG_ERROR("============================================================\n\n");
  7692. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  7693. }
  7694. float * f32_data;
  7695. if (tensor->type == GGML_TYPE_F32) {
  7696. f32_data = (float *) tensor->data;
  7697. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  7698. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  7699. } else {
  7700. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  7701. f32_data = (float *) f32_conv_buf.data();
  7702. }
  7703. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  7704. fflush(stdout);
  7705. if (work.size() < nelements * 4) {
  7706. work.resize(nelements * 4); // upper bound on size
  7707. }
  7708. new_data = work.data();
  7709. std::array<int64_t, 1 << 4> hist_cur = {};
  7710. const int n_per_row = tensor->ne[0];
  7711. const int nrows = nelements / n_per_row;
  7712. static const int min_chunk_size = 32 * 512;
  7713. 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);
  7714. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  7715. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  7716. if (nthread_use < 2) {
  7717. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  7718. } else {
  7719. int counter = 0;
  7720. new_size = 0;
  7721. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  7722. nrows, n_per_row, imatrix]() {
  7723. std::array<int64_t, 1 << 4> local_hist = {};
  7724. const int nrows_per_chunk = chunk_size / n_per_row;
  7725. size_t local_size = 0;
  7726. while (true) {
  7727. std::unique_lock<std::mutex> lock(mutex);
  7728. int first_row = counter; counter += nrows_per_chunk;
  7729. if (first_row >= nrows) {
  7730. if (local_size > 0) {
  7731. for (int j=0; j<int(local_hist.size()); ++j) {
  7732. hist_cur[j] += local_hist[j];
  7733. }
  7734. new_size += local_size;
  7735. }
  7736. break;
  7737. }
  7738. lock.unlock();
  7739. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  7740. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  7741. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  7742. }
  7743. };
  7744. for (int it = 0; it < nthread_use - 1; ++it) {
  7745. workers.emplace_back(compute);
  7746. }
  7747. compute();
  7748. for (auto & w : workers) { w.join(); }
  7749. workers.clear();
  7750. }
  7751. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  7752. int64_t tot_count = 0;
  7753. for (size_t i = 0; i < hist_cur.size(); i++) {
  7754. hist_all[i] += hist_cur[i];
  7755. tot_count += hist_cur[i];
  7756. }
  7757. if (tot_count > 0) {
  7758. LLAMA_LOG_INFO(" | hist: ");
  7759. for (size_t i = 0; i < hist_cur.size(); i++) {
  7760. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  7761. }
  7762. }
  7763. LLAMA_LOG_INFO("\n");
  7764. }
  7765. total_size_org += ggml_nbytes(tensor);
  7766. total_size_new += new_size;
  7767. // update the gguf meta data as we go
  7768. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  7769. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  7770. // write tensor data + padding
  7771. fout.write((const char *) new_data, new_size);
  7772. zeros(fout, GGML_PAD(new_size, align) - new_size);
  7773. }
  7774. // go back to beginning of file and write the updated meta data
  7775. {
  7776. fout.seekp(0);
  7777. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  7778. gguf_get_meta_data(ctx_out, data.data());
  7779. fout.write((const char *) data.data(), data.size());
  7780. }
  7781. fout.close();
  7782. gguf_free(ctx_out);
  7783. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  7784. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  7785. // print histogram for all tensors
  7786. {
  7787. int64_t sum_all = 0;
  7788. for (size_t i = 0; i < hist_all.size(); i++) {
  7789. sum_all += hist_all[i];
  7790. }
  7791. if (sum_all > 0) {
  7792. LLAMA_LOG_INFO("%s: hist: ", __func__);
  7793. for (size_t i = 0; i < hist_all.size(); i++) {
  7794. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  7795. }
  7796. LLAMA_LOG_INFO("\n");
  7797. }
  7798. }
  7799. if (qs.n_fallback > 0) {
  7800. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  7801. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  7802. }
  7803. }
  7804. static int llama_apply_lora_from_file_internal(
  7805. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  7806. ) {
  7807. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  7808. const int64_t t_start_lora_us = ggml_time_us();
  7809. llama_file fin(path_lora, "rb");
  7810. // verify magic and version
  7811. {
  7812. uint32_t magic = fin.read_u32();
  7813. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  7814. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  7815. return 1;
  7816. }
  7817. uint32_t format_version = fin.read_u32();
  7818. if (format_version != 1) {
  7819. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  7820. return 1;
  7821. }
  7822. }
  7823. int32_t lora_r = fin.read_u32();
  7824. int32_t lora_alpha = fin.read_u32();
  7825. float scaling = scale * (float)lora_alpha / (float)lora_r;
  7826. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  7827. // load base model
  7828. std::unique_ptr<llama_model_loader> ml;
  7829. if (path_base_model) {
  7830. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  7831. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  7832. ml->init_mapping(/*prefetch*/ false); // no prefetching
  7833. }
  7834. struct tensor_meta {
  7835. std::string name;
  7836. ggml_type type;
  7837. int32_t ne[2];
  7838. size_t offset;
  7839. };
  7840. std::map<std::string, tensor_meta> tensor_meta_map;
  7841. // load all tensor meta
  7842. while (true) {
  7843. if (fin.tell() == fin.size) {
  7844. // eof
  7845. break;
  7846. }
  7847. int32_t n_dims;
  7848. int32_t name_len;
  7849. int32_t ftype;
  7850. fin.read_raw(&n_dims, sizeof(n_dims));
  7851. fin.read_raw(&name_len, sizeof(name_len));
  7852. fin.read_raw(&ftype, sizeof(ftype));
  7853. if (n_dims != 1 && n_dims != 2) {
  7854. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  7855. return 1;
  7856. }
  7857. int32_t ne[2] = { 1, 1 };
  7858. for (int i = 0; i < n_dims; ++i) {
  7859. fin.read_raw(&ne[i], sizeof(ne[i]));
  7860. }
  7861. std::string name;
  7862. {
  7863. GGML_ASSERT(name_len < GGML_MAX_NAME);
  7864. char buf[GGML_MAX_NAME];
  7865. fin.read_raw(buf, name_len);
  7866. name = std::string(buf, name_len);
  7867. }
  7868. // check for lora suffix
  7869. std::string lora_suffix;
  7870. if (name.length() > 6) {
  7871. lora_suffix = name.substr(name.length() - 6);
  7872. }
  7873. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  7874. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  7875. return 1;
  7876. }
  7877. // tensor type
  7878. ggml_type wtype;
  7879. switch (ftype) {
  7880. case 0: wtype = GGML_TYPE_F32; break;
  7881. case 1: wtype = GGML_TYPE_F16; break;
  7882. default:
  7883. {
  7884. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  7885. __func__, ftype);
  7886. return false;
  7887. }
  7888. }
  7889. // data offset
  7890. size_t offset = fin.tell();
  7891. offset = (offset + 31) & -32;
  7892. // skip tensor data
  7893. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  7894. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  7895. }
  7896. bool warned = false;
  7897. int n_tensors = 0;
  7898. // apply
  7899. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  7900. if (backend_cpu == nullptr) {
  7901. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  7902. return 1;
  7903. }
  7904. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  7905. std::vector<no_init<uint8_t>> read_buf;
  7906. for (const auto & it : model.tensors_by_name) {
  7907. const std::string & base_name = it.first;
  7908. ggml_tensor * model_t = it.second;
  7909. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  7910. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  7911. continue;
  7912. }
  7913. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  7914. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  7915. ggml_init_params lora_init_params = {
  7916. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  7917. /* .mem_buffer */ nullptr,
  7918. /* .no_alloc */ true,
  7919. };
  7920. ggml_context * lora_ctx = ggml_init(lora_init_params);
  7921. if (lora_ctx == nullptr) {
  7922. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  7923. ggml_backend_free(backend_cpu);
  7924. return 1;
  7925. }
  7926. // create tensors
  7927. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  7928. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  7929. ggml_set_name(loraA, metaA.name.c_str());
  7930. ggml_set_name(loraB, metaB.name.c_str());
  7931. ggml_tensor * base_t;
  7932. if (ml) {
  7933. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  7934. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  7935. return 1;
  7936. }
  7937. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  7938. } else {
  7939. base_t = ggml_dup_tensor(lora_ctx, model_t);
  7940. }
  7941. ggml_set_name(base_t, base_name.c_str());
  7942. // allocate in backend buffer
  7943. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  7944. if (lora_buf == nullptr) {
  7945. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  7946. return 1;
  7947. }
  7948. // load tensor data
  7949. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  7950. read_buf.resize(ggml_nbytes(tensor));
  7951. fin.seek(tensor_meta.offset, SEEK_SET);
  7952. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  7953. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  7954. };
  7955. load_tensor(metaA, loraA);
  7956. load_tensor(metaB, loraB);
  7957. // load base model tensor data
  7958. if (ml) {
  7959. ml->load_data_for(base_t);
  7960. } else {
  7961. ggml_backend_tensor_copy(model_t, base_t);
  7962. }
  7963. if (ggml_is_quantized(base_t->type) && !warned) {
  7964. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  7965. "use a f16 or f32 base model with --lora-base\n", __func__);
  7966. warned = true;
  7967. }
  7968. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  7969. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  7970. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  7971. ggml_free(lora_ctx);
  7972. ggml_backend_buffer_free(lora_buf);
  7973. ggml_backend_free(backend_cpu);
  7974. return 1;
  7975. }
  7976. auto build_lora_graph = [&]() {
  7977. // w = w + BA*s
  7978. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  7979. ggml_set_name(BA, "BA");
  7980. if (scaling != 1.0f) {
  7981. BA = ggml_scale(lora_ctx, BA, scaling);
  7982. ggml_set_name(BA, "BA_scaled");
  7983. }
  7984. ggml_tensor * r;
  7985. r = ggml_add_inplace(lora_ctx, base_t, BA);
  7986. ggml_set_name(r, "r_add");
  7987. if (base_t->type != model_t->type) {
  7988. // convert the result to the model type
  7989. r = ggml_cast(lora_ctx, r, model_t->type);
  7990. ggml_set_name(r, "r_cast");
  7991. }
  7992. return r;
  7993. };
  7994. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  7995. ggml_tensor * r = build_lora_graph();
  7996. ggml_build_forward_expand(gf, r);
  7997. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  7998. if (graph_buf == nullptr) {
  7999. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  8000. ggml_free(lora_ctx);
  8001. ggml_backend_buffer_free(lora_buf);
  8002. ggml_backend_free(backend_cpu);
  8003. return 1;
  8004. }
  8005. ggml_backend_graph_compute(backend_cpu, gf);
  8006. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  8007. #if 0
  8008. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  8009. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  8010. // sched compute
  8011. ggml_build_forward_expand(gf, build_graph());
  8012. ggml_backend_sched_init_measure(sched, gf);
  8013. // create the graph again, since the previous one was destroyed by the measure
  8014. ggml_graph_clear(gf);
  8015. ggml_build_forward_expand(gf, build_graph());
  8016. ggml_backend_sched_graph_compute(sched, gf);
  8017. ggml_backend_sched_free(sched);
  8018. #endif
  8019. ggml_backend_buffer_free(lora_buf);
  8020. ggml_backend_buffer_free(graph_buf);
  8021. ggml_free(lora_ctx);
  8022. n_tensors++;
  8023. if (n_tensors % 4 == 0) {
  8024. LLAMA_LOG_INFO(".");
  8025. }
  8026. }
  8027. ggml_backend_free(backend_cpu);
  8028. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  8029. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  8030. return 0;
  8031. }
  8032. //
  8033. // interface implementation
  8034. //
  8035. struct llama_model_params llama_model_default_params() {
  8036. struct llama_model_params result = {
  8037. /*.n_gpu_layers =*/ 0,
  8038. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  8039. /*.main_gpu =*/ 0,
  8040. /*.tensor_split =*/ nullptr,
  8041. /*.progress_callback =*/ nullptr,
  8042. /*.progress_callback_user_data =*/ nullptr,
  8043. /*.kv_overrides =*/ nullptr,
  8044. /*.vocab_only =*/ false,
  8045. /*.use_mmap =*/ true,
  8046. /*.use_mlock =*/ false,
  8047. };
  8048. #ifdef GGML_USE_METAL
  8049. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  8050. result.n_gpu_layers = 999;
  8051. #endif
  8052. return result;
  8053. }
  8054. struct llama_context_params llama_context_default_params() {
  8055. struct llama_context_params result = {
  8056. /*.seed =*/ LLAMA_DEFAULT_SEED,
  8057. /*.n_ctx =*/ 512,
  8058. /*.n_batch =*/ 512,
  8059. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  8060. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  8061. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  8062. /*.rope_freq_base =*/ 0.0f,
  8063. /*.rope_freq_scale =*/ 0.0f,
  8064. /*.yarn_ext_factor =*/ -1.0f,
  8065. /*.yarn_attn_factor =*/ 1.0f,
  8066. /*.yarn_beta_fast =*/ 32.0f,
  8067. /*.yarn_beta_slow =*/ 1.0f,
  8068. /*.yarn_orig_ctx =*/ 0,
  8069. /*.cb_eval =*/ nullptr,
  8070. /*.cb_eval_user_data =*/ nullptr,
  8071. /*.type_k =*/ GGML_TYPE_F16,
  8072. /*.type_v =*/ GGML_TYPE_F16,
  8073. /*.mul_mat_q =*/ true,
  8074. /*.logits_all =*/ false,
  8075. /*.embedding =*/ false,
  8076. /*.offload_kqv =*/ true,
  8077. };
  8078. return result;
  8079. }
  8080. struct llama_model_quantize_params llama_model_quantize_default_params() {
  8081. struct llama_model_quantize_params result = {
  8082. /*.nthread =*/ 0,
  8083. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  8084. /*.allow_requantize =*/ false,
  8085. /*.quantize_output_tensor =*/ true,
  8086. /*.only_copy =*/ false,
  8087. /*.pure =*/ false,
  8088. /*.imatrix =*/ nullptr,
  8089. };
  8090. return result;
  8091. }
  8092. int32_t llama_max_devices(void) {
  8093. return LLAMA_MAX_DEVICES;
  8094. }
  8095. bool llama_mmap_supported(void) {
  8096. return llama_mmap::SUPPORTED;
  8097. }
  8098. bool llama_mlock_supported(void) {
  8099. return llama_mlock::SUPPORTED;
  8100. }
  8101. void llama_backend_init(bool numa) {
  8102. ggml_time_init();
  8103. // needed to initialize f16 tables
  8104. {
  8105. struct ggml_init_params params = { 0, NULL, false };
  8106. struct ggml_context * ctx = ggml_init(params);
  8107. ggml_free(ctx);
  8108. }
  8109. if (numa) {
  8110. ggml_numa_init();
  8111. }
  8112. #ifdef GGML_USE_MPI
  8113. ggml_mpi_backend_init();
  8114. #endif
  8115. }
  8116. void llama_backend_free(void) {
  8117. #ifdef GGML_USE_MPI
  8118. ggml_mpi_backend_free();
  8119. #endif
  8120. ggml_quantize_free();
  8121. }
  8122. int64_t llama_time_us(void) {
  8123. return ggml_time_us();
  8124. }
  8125. struct llama_model * llama_load_model_from_file(
  8126. const char * path_model,
  8127. struct llama_model_params params) {
  8128. ggml_time_init();
  8129. llama_model * model = new llama_model;
  8130. unsigned cur_percentage = 0;
  8131. if (params.progress_callback == NULL) {
  8132. params.progress_callback_user_data = &cur_percentage;
  8133. params.progress_callback = [](float progress, void * ctx) {
  8134. unsigned * cur_percentage_p = (unsigned *) ctx;
  8135. unsigned percentage = (unsigned) (100 * progress);
  8136. while (percentage > *cur_percentage_p) {
  8137. *cur_percentage_p = percentage;
  8138. LLAMA_LOG_INFO(".");
  8139. if (percentage >= 100) {
  8140. LLAMA_LOG_INFO("\n");
  8141. }
  8142. }
  8143. return true;
  8144. };
  8145. }
  8146. int status = llama_model_load(path_model, *model, params);
  8147. GGML_ASSERT(status <= 0);
  8148. if (status < 0) {
  8149. if (status == -1) {
  8150. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  8151. } else if (status == -2) {
  8152. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  8153. }
  8154. delete model;
  8155. return nullptr;
  8156. }
  8157. return model;
  8158. }
  8159. void llama_free_model(struct llama_model * model) {
  8160. delete model;
  8161. }
  8162. struct llama_context * llama_new_context_with_model(
  8163. struct llama_model * model,
  8164. struct llama_context_params params) {
  8165. if (!model) {
  8166. return nullptr;
  8167. }
  8168. llama_context * ctx = new llama_context(*model);
  8169. const auto & hparams = model->hparams;
  8170. auto & cparams = ctx->cparams;
  8171. cparams.n_batch = params.n_batch;
  8172. cparams.n_threads = params.n_threads;
  8173. cparams.n_threads_batch = params.n_threads_batch;
  8174. cparams.yarn_ext_factor = params.yarn_ext_factor;
  8175. cparams.yarn_attn_factor = params.yarn_attn_factor;
  8176. cparams.yarn_beta_fast = params.yarn_beta_fast;
  8177. cparams.yarn_beta_slow = params.yarn_beta_slow;
  8178. cparams.mul_mat_q = params.mul_mat_q;
  8179. cparams.offload_kqv = params.offload_kqv;
  8180. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  8181. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  8182. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  8183. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  8184. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  8185. hparams.n_ctx_train;
  8186. cparams.cb_eval = params.cb_eval;
  8187. cparams.cb_eval_user_data = params.cb_eval_user_data;
  8188. auto rope_scaling_type = params.rope_scaling_type;
  8189. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  8190. rope_scaling_type = hparams.rope_scaling_type_train;
  8191. }
  8192. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  8193. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  8194. }
  8195. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  8196. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  8197. }
  8198. if (params.seed == LLAMA_DEFAULT_SEED) {
  8199. params.seed = time(NULL);
  8200. }
  8201. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  8202. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  8203. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  8204. ctx->rng = std::mt19937(params.seed);
  8205. ctx->logits_all = params.logits_all;
  8206. const ggml_type type_k = params.type_k;
  8207. const ggml_type type_v = params.type_v;
  8208. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  8209. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  8210. if (!hparams.vocab_only) {
  8211. // initialize backends
  8212. #ifdef GGML_USE_METAL
  8213. if (model->n_gpu_layers > 0) {
  8214. ctx->backend_metal = ggml_backend_metal_init();
  8215. if (ctx->backend_metal == nullptr) {
  8216. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  8217. llama_free(ctx);
  8218. return nullptr;
  8219. }
  8220. ctx->backends.push_back(ctx->backend_metal);
  8221. }
  8222. #elif defined(GGML_USE_CUBLAS)
  8223. if (model->n_gpu_layers > 0) {
  8224. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  8225. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  8226. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  8227. if (backend == nullptr) {
  8228. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  8229. llama_free(ctx);
  8230. return nullptr;
  8231. }
  8232. ctx->backends.push_back(backend);
  8233. } else {
  8234. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  8235. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  8236. ggml_backend_t backend = ggml_backend_cuda_init(device);
  8237. if (backend == nullptr) {
  8238. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  8239. llama_free(ctx);
  8240. return nullptr;
  8241. }
  8242. ctx->backends.push_back(backend);
  8243. }
  8244. }
  8245. }
  8246. #endif
  8247. ctx->backend_cpu = ggml_backend_cpu_init();
  8248. if (ctx->backend_cpu == nullptr) {
  8249. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  8250. llama_free(ctx);
  8251. return nullptr;
  8252. }
  8253. ctx->backends.push_back(ctx->backend_cpu);
  8254. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  8255. cparams.n_ctx, cparams.offload_kqv)) {
  8256. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  8257. llama_free(ctx);
  8258. return nullptr;
  8259. }
  8260. {
  8261. size_t memory_size_k = 0;
  8262. size_t memory_size_v = 0;
  8263. for (auto & k : ctx->kv_self.k_l) {
  8264. memory_size_k += ggml_nbytes(k);
  8265. }
  8266. for (auto & v : ctx->kv_self.v_l) {
  8267. memory_size_v += ggml_nbytes(v);
  8268. }
  8269. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  8270. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  8271. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  8272. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  8273. }
  8274. // resized during inference, reserve maximum
  8275. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  8276. if (params.embedding){
  8277. ctx->embedding.resize(hparams.n_embd);
  8278. }
  8279. {
  8280. // buffer types used for the compute buffer of each backend
  8281. std::vector<ggml_backend_buffer_type_t> backend_buft;
  8282. for (auto * backend : ctx->backends) {
  8283. if (ggml_backend_is_cpu(backend)) {
  8284. // use host buffers for the CPU backend compute buffer
  8285. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  8286. } else {
  8287. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  8288. }
  8289. }
  8290. // buffer used to store the computation graph and the tensor meta data
  8291. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  8292. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  8293. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8294. // build worst-case graph
  8295. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  8296. int n_past = cparams.n_ctx - n_tokens;
  8297. 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
  8298. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  8299. // initialize scheduler with the worst-case graph
  8300. ggml_backend_sched_init_measure(ctx->sched, gf);
  8301. // note: the number of splits during measure is higher than during inference due to the kv shift
  8302. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  8303. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  8304. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8305. for (ggml_backend_t backend : ctx->backends) {
  8306. ggml_backend_buffer_t buf = ggml_backend_sched_get_buffer(ctx->sched, backend);
  8307. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  8308. ggml_backend_buffer_name(buf),
  8309. ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  8310. }
  8311. }
  8312. }
  8313. #ifdef GGML_USE_MPI
  8314. ctx->ctx_mpi = ggml_mpi_init();
  8315. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  8316. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  8317. // TODO: needs fix after #3228
  8318. GGML_ASSERT(false && "not implemented");
  8319. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  8320. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  8321. llama_backend_free();
  8322. exit(1);
  8323. }
  8324. #endif
  8325. return ctx;
  8326. }
  8327. void llama_free(struct llama_context * ctx) {
  8328. delete ctx;
  8329. }
  8330. const llama_model * llama_get_model(const struct llama_context * ctx) {
  8331. return &ctx->model;
  8332. }
  8333. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  8334. return ctx->cparams.n_ctx;
  8335. }
  8336. uint32_t llama_n_batch(const struct llama_context * ctx) {
  8337. return ctx->cparams.n_batch;
  8338. }
  8339. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  8340. return model->vocab.type;
  8341. }
  8342. int32_t llama_n_vocab(const struct llama_model * model) {
  8343. return model->vocab.id_to_token.size();
  8344. }
  8345. int32_t llama_n_ctx_train(const struct llama_model * model) {
  8346. return model->hparams.n_ctx_train;
  8347. }
  8348. int32_t llama_n_embd(const struct llama_model * model) {
  8349. return model->hparams.n_embd;
  8350. }
  8351. float llama_rope_freq_scale_train(const struct llama_model * model) {
  8352. return model->hparams.rope_freq_scale_train;
  8353. }
  8354. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  8355. const auto & it = model->gguf_kv.find(key);
  8356. if (it == model->gguf_kv.end()) {
  8357. if (buf_size > 0) {
  8358. buf[0] = '\0';
  8359. }
  8360. return -1;
  8361. }
  8362. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8363. }
  8364. int32_t llama_model_meta_count(const struct llama_model * model) {
  8365. return (int)model->gguf_kv.size();
  8366. }
  8367. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  8368. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8369. if (buf_size > 0) {
  8370. buf[0] = '\0';
  8371. }
  8372. return -1;
  8373. }
  8374. auto it = model->gguf_kv.begin();
  8375. std::advance(it, i);
  8376. return snprintf(buf, buf_size, "%s", it->first.c_str());
  8377. }
  8378. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  8379. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8380. if (buf_size > 0) {
  8381. buf[0] = '\0';
  8382. }
  8383. return -1;
  8384. }
  8385. auto it = model->gguf_kv.begin();
  8386. std::advance(it, i);
  8387. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8388. }
  8389. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  8390. return snprintf(buf, buf_size, "%s %s %s",
  8391. llama_model_arch_name(model->arch).c_str(),
  8392. llama_model_type_name(model->type),
  8393. llama_model_ftype_name(model->ftype).c_str());
  8394. }
  8395. uint64_t llama_model_size(const struct llama_model * model) {
  8396. uint64_t size = 0;
  8397. for (const auto & it : model->tensors_by_name) {
  8398. size += ggml_nbytes(it.second);
  8399. }
  8400. return size;
  8401. }
  8402. uint64_t llama_model_n_params(const struct llama_model * model) {
  8403. uint64_t nparams = 0;
  8404. for (const auto & it : model->tensors_by_name) {
  8405. nparams += ggml_nelements(it.second);
  8406. }
  8407. return nparams;
  8408. }
  8409. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  8410. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  8411. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  8412. return it.first == name;
  8413. });
  8414. if (it == model->tensors_by_name.end()) {
  8415. return nullptr;
  8416. }
  8417. return it->second;
  8418. }
  8419. uint32_t llama_model_quantize(
  8420. const char * fname_inp,
  8421. const char * fname_out,
  8422. const llama_model_quantize_params * params) {
  8423. try {
  8424. llama_model_quantize_internal(fname_inp, fname_out, params);
  8425. return 0;
  8426. } catch (const std::exception & err) {
  8427. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  8428. return 1;
  8429. }
  8430. }
  8431. 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) {
  8432. try {
  8433. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  8434. } catch (const std::exception & err) {
  8435. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8436. return 1;
  8437. }
  8438. }
  8439. 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) {
  8440. try {
  8441. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  8442. } catch (const std::exception & err) {
  8443. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8444. return 1;
  8445. }
  8446. }
  8447. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  8448. struct llama_kv_cache_view result = {
  8449. /*.n_cells = */ 0,
  8450. /*.n_max_seq = */ n_max_seq,
  8451. /*.token_count = */ 0,
  8452. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  8453. /*.max_contiguous = */ 0,
  8454. /*.max_contiguous_idx = */ -1,
  8455. /*.cells = */ nullptr,
  8456. /*.cells_sequences = */ nullptr,
  8457. };
  8458. return result;
  8459. }
  8460. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  8461. if (view->cells != nullptr) {
  8462. free(view->cells);
  8463. view->cells = nullptr;
  8464. }
  8465. if (view->cells_sequences != nullptr) {
  8466. free(view->cells_sequences);
  8467. view->cells_sequences = nullptr;
  8468. }
  8469. }
  8470. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  8471. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  8472. view->n_cells = int32_t(ctx->kv_self.size);
  8473. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  8474. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  8475. view->cells = (struct llama_kv_cache_view_cell *)p;
  8476. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  8477. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  8478. view->cells_sequences = (llama_seq_id *)p;
  8479. }
  8480. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  8481. llama_kv_cache_view_cell * c_curr = view->cells;
  8482. llama_seq_id * cs_curr = view->cells_sequences;
  8483. int32_t used_cells = 0;
  8484. int32_t token_count = 0;
  8485. int32_t curr_contig_idx = -1;
  8486. uint32_t max_contig = 0;
  8487. int32_t max_contig_idx = -1;
  8488. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  8489. const size_t curr_size = kv_cells[i].seq_id.size();
  8490. token_count += curr_size;
  8491. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  8492. if (curr_size > 0) {
  8493. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  8494. max_contig = i - curr_contig_idx;
  8495. max_contig_idx = curr_contig_idx;
  8496. }
  8497. curr_contig_idx = -1;
  8498. } else if (curr_contig_idx < 0) {
  8499. curr_contig_idx = i;
  8500. }
  8501. int seq_idx = 0;
  8502. for (const llama_seq_id it : kv_cells[i].seq_id) {
  8503. if (seq_idx >= view->n_max_seq) {
  8504. break;
  8505. }
  8506. cs_curr[seq_idx] = it;
  8507. seq_idx++;
  8508. }
  8509. if (seq_idx != 0) {
  8510. used_cells++;
  8511. }
  8512. for (; seq_idx < view->n_max_seq; seq_idx++) {
  8513. cs_curr[seq_idx] = -1;
  8514. }
  8515. }
  8516. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  8517. max_contig_idx = curr_contig_idx;
  8518. max_contig = kv_cells.size() - curr_contig_idx;
  8519. }
  8520. view->max_contiguous = max_contig;
  8521. view->max_contiguous_idx = max_contig_idx;
  8522. view->token_count = token_count;
  8523. view->used_cells = used_cells;
  8524. if (uint32_t(used_cells) != ctx->kv_self.used) {
  8525. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  8526. __func__, ctx->kv_self.used, used_cells);
  8527. }
  8528. }
  8529. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  8530. int result = 0;
  8531. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  8532. result += ctx->kv_self.cells[i].seq_id.size();
  8533. }
  8534. return result;
  8535. }
  8536. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  8537. return ctx->kv_self.used;
  8538. }
  8539. void llama_kv_cache_clear(struct llama_context * ctx) {
  8540. llama_kv_cache_clear(ctx->kv_self);
  8541. }
  8542. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  8543. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  8544. }
  8545. 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) {
  8546. if (seq_id_src == seq_id_dst) {
  8547. return;
  8548. }
  8549. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  8550. }
  8551. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  8552. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  8553. }
  8554. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  8555. if (delta == 0) {
  8556. return;
  8557. }
  8558. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  8559. }
  8560. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  8561. if (d == 1) {
  8562. return;
  8563. }
  8564. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  8565. }
  8566. // Returns the *maximum* size of the state
  8567. size_t llama_get_state_size(const struct llama_context * ctx) {
  8568. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  8569. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  8570. const size_t s_rng_size = sizeof(size_t);
  8571. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  8572. const size_t s_logits_size = sizeof(size_t);
  8573. // assume worst case for logits although only currently set ones are serialized
  8574. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  8575. const size_t s_embedding_size = sizeof(size_t);
  8576. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  8577. const size_t s_kv_size = sizeof(size_t);
  8578. const size_t s_kv_ntok = sizeof(int);
  8579. const size_t s_kv = ctx->kv_self.total_size();
  8580. const size_t s_total = (
  8581. + s_rng_size
  8582. + s_rng
  8583. + s_logits_size
  8584. + s_logits
  8585. + s_embedding_size
  8586. + s_embedding
  8587. + s_kv_size
  8588. + s_kv_ntok
  8589. + s_kv
  8590. );
  8591. return s_total;
  8592. }
  8593. // llama_context_data
  8594. struct llama_data_context {
  8595. virtual void write(const void * src, size_t size) = 0;
  8596. virtual size_t get_size_written() = 0;
  8597. virtual ~llama_data_context() = default;
  8598. };
  8599. struct llama_data_buffer_context : llama_data_context {
  8600. uint8_t * ptr;
  8601. size_t size_written = 0;
  8602. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  8603. void write(const void * src, size_t size) override {
  8604. memcpy(ptr, src, size);
  8605. ptr += size;
  8606. size_written += size;
  8607. }
  8608. size_t get_size_written() override {
  8609. return size_written;
  8610. }
  8611. };
  8612. struct llama_data_file_context : llama_data_context {
  8613. llama_file * file;
  8614. size_t size_written = 0;
  8615. llama_data_file_context(llama_file * f) : file(f) {}
  8616. void write(const void * src, size_t size) override {
  8617. file->write_raw(src, size);
  8618. size_written += size;
  8619. }
  8620. size_t get_size_written() override {
  8621. return size_written;
  8622. }
  8623. };
  8624. /** copy state data into either a buffer or file depending on the passed in context
  8625. *
  8626. * file context:
  8627. * llama_file file("/path", "wb");
  8628. * llama_data_file_context data_ctx(&file);
  8629. * llama_copy_state_data(ctx, &data_ctx);
  8630. *
  8631. * buffer context:
  8632. * std::vector<uint8_t> buf(max_size, 0);
  8633. * llama_data_buffer_context data_ctx(&buf.data());
  8634. * llama_copy_state_data(ctx, &data_ctx);
  8635. *
  8636. */
  8637. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  8638. // copy rng
  8639. {
  8640. std::ostringstream rng_ss;
  8641. rng_ss << ctx->rng;
  8642. const std::string & rng_str = rng_ss.str();
  8643. const size_t rng_size = rng_str.size();
  8644. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  8645. data_ctx->write(&rng_size, sizeof(rng_size));
  8646. data_ctx->write(rng_str.data(), rng_size);
  8647. }
  8648. // copy logits
  8649. {
  8650. const size_t logits_size = ctx->logits.size();
  8651. data_ctx->write(&logits_size, sizeof(logits_size));
  8652. if (logits_size) {
  8653. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  8654. }
  8655. }
  8656. // copy embeddings
  8657. {
  8658. const size_t embedding_size = ctx->embedding.size();
  8659. data_ctx->write(&embedding_size, sizeof(embedding_size));
  8660. if (embedding_size) {
  8661. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  8662. }
  8663. }
  8664. // copy kv cache
  8665. {
  8666. const auto & kv_self = ctx->kv_self;
  8667. const auto & hparams = ctx->model.hparams;
  8668. const auto & cparams = ctx->cparams;
  8669. const auto n_layer = hparams.n_layer;
  8670. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  8671. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  8672. const auto n_ctx = cparams.n_ctx;
  8673. const size_t kv_buf_size = kv_self.total_size();
  8674. const uint32_t kv_head = kv_self.head;
  8675. const uint32_t kv_size = kv_self.size;
  8676. const uint32_t kv_used = kv_self.used;
  8677. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  8678. data_ctx->write(&kv_head, sizeof(kv_head));
  8679. data_ctx->write(&kv_size, sizeof(kv_size));
  8680. data_ctx->write(&kv_used, sizeof(kv_used));
  8681. if (kv_buf_size) {
  8682. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8683. std::vector<uint8_t> tmp_buf;
  8684. for (int il = 0; il < (int) n_layer; ++il) {
  8685. tmp_buf.resize(elt_size*n_embd_k_gqa*kv_head);
  8686. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  8687. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8688. // v is not contiguous, copy row by row
  8689. tmp_buf.resize(elt_size*kv_head);
  8690. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8691. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*elt_size*n_ctx, tmp_buf.size());
  8692. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8693. }
  8694. }
  8695. }
  8696. for (uint32_t i = 0; i < kv_size; ++i) {
  8697. const auto & cell = kv_self.cells[i];
  8698. const llama_pos pos = cell.pos;
  8699. const size_t seq_id_size = cell.seq_id.size();
  8700. data_ctx->write(&pos, sizeof(pos));
  8701. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  8702. for (auto seq_id : cell.seq_id) {
  8703. data_ctx->write(&seq_id, sizeof(seq_id));
  8704. }
  8705. }
  8706. }
  8707. }
  8708. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  8709. llama_data_buffer_context data_ctx(dst);
  8710. llama_copy_state_data_internal(ctx, &data_ctx);
  8711. return data_ctx.get_size_written();
  8712. }
  8713. // Sets the state reading from the specified source address
  8714. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  8715. uint8_t * inp = src;
  8716. // set rng
  8717. {
  8718. size_t rng_size;
  8719. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  8720. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  8721. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  8722. std::istringstream rng_ss(rng_str);
  8723. rng_ss >> ctx->rng;
  8724. GGML_ASSERT(!rng_ss.fail());
  8725. }
  8726. // set logits
  8727. {
  8728. size_t logits_size;
  8729. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  8730. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  8731. if (logits_size) {
  8732. ctx->logits.resize(logits_size);
  8733. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  8734. inp += logits_size * sizeof(float);
  8735. }
  8736. }
  8737. // set embeddings
  8738. {
  8739. size_t embedding_size;
  8740. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  8741. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  8742. if (embedding_size) {
  8743. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  8744. inp += embedding_size * sizeof(float);
  8745. }
  8746. }
  8747. // set kv cache
  8748. {
  8749. const auto & kv_self = ctx->kv_self;
  8750. const auto & hparams = ctx->model.hparams;
  8751. const auto & cparams = ctx->cparams;
  8752. const int n_layer = hparams.n_layer;
  8753. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  8754. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  8755. const int n_ctx = cparams.n_ctx;
  8756. size_t kv_buf_size;
  8757. uint32_t kv_head;
  8758. uint32_t kv_size;
  8759. uint32_t kv_used;
  8760. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  8761. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  8762. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  8763. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  8764. if (kv_buf_size) {
  8765. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  8766. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8767. for (int il = 0; il < (int) n_layer; ++il) {
  8768. size_t k_size = elt_size*n_embd_k_gqa*kv_head;
  8769. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  8770. inp += k_size;
  8771. // v is not contiguous, copy row by row
  8772. size_t v_row_size = elt_size*kv_head;
  8773. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8774. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*elt_size*n_ctx, v_row_size);
  8775. inp += v_row_size;
  8776. }
  8777. }
  8778. }
  8779. ctx->kv_self.head = kv_head;
  8780. ctx->kv_self.size = kv_size;
  8781. ctx->kv_self.used = kv_used;
  8782. ctx->kv_self.cells.resize(kv_size);
  8783. for (uint32_t i = 0; i < kv_size; ++i) {
  8784. llama_pos pos;
  8785. size_t seq_id_size;
  8786. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  8787. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  8788. ctx->kv_self.cells[i].pos = pos;
  8789. llama_seq_id seq_id;
  8790. for (size_t j = 0; j < seq_id_size; ++j) {
  8791. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  8792. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  8793. }
  8794. }
  8795. }
  8796. const size_t nread = inp - src;
  8797. const size_t max_size = llama_get_state_size(ctx);
  8798. GGML_ASSERT(nread <= max_size);
  8799. return nread;
  8800. }
  8801. 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) {
  8802. llama_file file(path_session, "rb");
  8803. // sanity checks
  8804. {
  8805. const uint32_t magic = file.read_u32();
  8806. const uint32_t version = file.read_u32();
  8807. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  8808. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  8809. return false;
  8810. }
  8811. llama_hparams session_hparams;
  8812. file.read_raw(&session_hparams, sizeof(llama_hparams));
  8813. if (session_hparams != ctx->model.hparams) {
  8814. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  8815. return false;
  8816. }
  8817. }
  8818. // load the prompt
  8819. {
  8820. const uint32_t n_token_count = file.read_u32();
  8821. if (n_token_count > n_token_capacity) {
  8822. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  8823. return false;
  8824. }
  8825. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  8826. *n_token_count_out = n_token_count;
  8827. }
  8828. // restore the context state
  8829. {
  8830. const size_t n_state_size_cur = file.size - file.tell();
  8831. const size_t n_state_size_max = llama_get_state_size(ctx);
  8832. if (n_state_size_cur > n_state_size_max) {
  8833. 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);
  8834. return false;
  8835. }
  8836. std::vector<uint8_t> state_data(n_state_size_max);
  8837. file.read_raw(state_data.data(), n_state_size_cur);
  8838. llama_set_state_data(ctx, state_data.data());
  8839. }
  8840. return true;
  8841. }
  8842. 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) {
  8843. try {
  8844. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  8845. } catch (const std::exception & err) {
  8846. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  8847. return false;
  8848. }
  8849. }
  8850. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  8851. llama_file file(path_session, "wb");
  8852. file.write_u32(LLAMA_SESSION_MAGIC);
  8853. file.write_u32(LLAMA_SESSION_VERSION);
  8854. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  8855. // save the prompt
  8856. file.write_u32((uint32_t) n_token_count);
  8857. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  8858. // save the context state using stream saving
  8859. llama_data_file_context data_ctx(&file);
  8860. llama_copy_state_data_internal(ctx, &data_ctx);
  8861. return true;
  8862. }
  8863. int llama_eval(
  8864. struct llama_context * ctx,
  8865. llama_token * tokens,
  8866. int32_t n_tokens,
  8867. int32_t n_past) {
  8868. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8869. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  8870. if (ret < 0) {
  8871. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8872. }
  8873. return ret;
  8874. }
  8875. int llama_eval_embd(
  8876. struct llama_context * ctx,
  8877. float * embd,
  8878. int32_t n_tokens,
  8879. int32_t n_past) {
  8880. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8881. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  8882. const int ret = llama_decode_internal(*ctx, batch);
  8883. if (ret < 0) {
  8884. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8885. }
  8886. return ret;
  8887. }
  8888. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  8889. ctx->cparams.n_threads = n_threads;
  8890. ctx->cparams.n_threads_batch = n_threads_batch;
  8891. }
  8892. struct llama_batch llama_batch_get_one(
  8893. llama_token * tokens,
  8894. int32_t n_tokens,
  8895. llama_pos pos_0,
  8896. llama_seq_id seq_id) {
  8897. return {
  8898. /*n_tokens =*/ n_tokens,
  8899. /*tokens =*/ tokens,
  8900. /*embd =*/ nullptr,
  8901. /*pos =*/ nullptr,
  8902. /*n_seq_id =*/ nullptr,
  8903. /*seq_id =*/ nullptr,
  8904. /*logits =*/ nullptr,
  8905. /*all_pos_0 =*/ pos_0,
  8906. /*all_pos_1 =*/ 1,
  8907. /*all_seq_id =*/ seq_id,
  8908. };
  8909. }
  8910. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd, int32_t n_seq_max) {
  8911. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  8912. if (embd) {
  8913. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  8914. } else {
  8915. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  8916. }
  8917. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  8918. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens);
  8919. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * n_tokens);
  8920. for (int i = 0; i < n_tokens; ++i) {
  8921. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  8922. }
  8923. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  8924. return batch;
  8925. }
  8926. void llama_batch_free(struct llama_batch batch) {
  8927. if (batch.token) free(batch.token);
  8928. if (batch.embd) free(batch.embd);
  8929. if (batch.pos) free(batch.pos);
  8930. if (batch.n_seq_id) free(batch.n_seq_id);
  8931. if (batch.seq_id) {
  8932. for (int i = 0; i < batch.n_tokens; ++i) {
  8933. free(batch.seq_id[i]);
  8934. }
  8935. free(batch.seq_id);
  8936. }
  8937. if (batch.logits) free(batch.logits);
  8938. }
  8939. int32_t llama_decode(
  8940. struct llama_context * ctx,
  8941. struct llama_batch batch) {
  8942. const int ret = llama_decode_internal(*ctx, batch);
  8943. if (ret < 0) {
  8944. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8945. }
  8946. return ret;
  8947. }
  8948. float * llama_get_logits(struct llama_context * ctx) {
  8949. return ctx->logits.data();
  8950. }
  8951. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  8952. assert(ctx->logits_valid.at(i));
  8953. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  8954. }
  8955. float * llama_get_embeddings(struct llama_context * ctx) {
  8956. return ctx->embedding.data();
  8957. }
  8958. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  8959. return model->vocab.id_to_token[token].text.c_str();
  8960. }
  8961. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  8962. return model->vocab.id_to_token[token].score;
  8963. }
  8964. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  8965. return model->vocab.id_to_token[token].type;
  8966. }
  8967. llama_token llama_token_bos(const struct llama_model * model) {
  8968. return model->vocab.special_bos_id;
  8969. }
  8970. llama_token llama_token_eos(const struct llama_model * model) {
  8971. return model->vocab.special_eos_id;
  8972. }
  8973. llama_token llama_token_nl(const struct llama_model * model) {
  8974. return model->vocab.linefeed_id;
  8975. }
  8976. int32_t llama_add_bos_token(const struct llama_model * model) {
  8977. return model->vocab.special_add_bos;
  8978. }
  8979. int32_t llama_add_eos_token(const struct llama_model * model) {
  8980. return model->vocab.special_add_eos;
  8981. }
  8982. llama_token llama_token_prefix(const struct llama_model * model) {
  8983. return model->vocab.special_prefix_id;
  8984. }
  8985. llama_token llama_token_middle(const struct llama_model * model) {
  8986. return model->vocab.special_middle_id;
  8987. }
  8988. llama_token llama_token_suffix(const struct llama_model * model) {
  8989. return model->vocab.special_suffix_id;
  8990. }
  8991. llama_token llama_token_eot(const struct llama_model * model) {
  8992. return model->vocab.special_eot_id;
  8993. }
  8994. int32_t llama_tokenize(
  8995. const struct llama_model * model,
  8996. const char * text,
  8997. int32_t text_len,
  8998. llama_token * tokens,
  8999. int32_t n_max_tokens,
  9000. bool add_bos,
  9001. bool special) {
  9002. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  9003. if (n_max_tokens < (int) res.size()) {
  9004. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  9005. return -((int) res.size());
  9006. }
  9007. for (size_t i = 0; i < res.size(); i++) {
  9008. tokens[i] = res[i];
  9009. }
  9010. return res.size();
  9011. }
  9012. static std::string llama_decode_text(const std::string & text) {
  9013. std::string decoded_text;
  9014. auto unicode_sequences = codepoints_from_utf8(text);
  9015. for (auto& unicode_sequence : unicode_sequences) {
  9016. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  9017. }
  9018. return decoded_text;
  9019. }
  9020. // does not write null-terminator to buf
  9021. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  9022. if (0 <= token && token < llama_n_vocab(model)) {
  9023. switch (llama_vocab_get_type(model->vocab)) {
  9024. case LLAMA_VOCAB_TYPE_SPM: {
  9025. // NOTE: we accept all unsupported token types,
  9026. // suppressing them like CONTROL tokens.
  9027. if (llama_is_normal_token(model->vocab, token)) {
  9028. std::string result = model->vocab.id_to_token[token].text;
  9029. llama_unescape_whitespace(result);
  9030. if (length < (int) result.length()) {
  9031. return -(int) result.length();
  9032. }
  9033. memcpy(buf, result.c_str(), result.length());
  9034. return result.length();
  9035. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9036. std::string result = model->vocab.id_to_token[token].text;
  9037. if (length < (int) result.length()) {
  9038. return -result.length();
  9039. }
  9040. memcpy(buf, result.c_str(), result.length());
  9041. return result.length();
  9042. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  9043. if (length < 3) {
  9044. return -3;
  9045. }
  9046. memcpy(buf, "\xe2\x96\x85", 3);
  9047. return 3;
  9048. } else if (llama_is_control_token(model->vocab, token)) {
  9049. ;
  9050. } else if (llama_is_byte_token(model->vocab, token)) {
  9051. if (length < 1) {
  9052. return -1;
  9053. }
  9054. buf[0] = llama_token_to_byte(model->vocab, token);
  9055. return 1;
  9056. }
  9057. break;
  9058. }
  9059. case LLAMA_VOCAB_TYPE_BPE: {
  9060. // NOTE: we accept all unsupported token types,
  9061. // suppressing them like CONTROL tokens.
  9062. if (llama_is_normal_token(model->vocab, token)) {
  9063. std::string result = model->vocab.id_to_token[token].text;
  9064. result = llama_decode_text(result);
  9065. if (length < (int) result.length()) {
  9066. return -(int) result.length();
  9067. }
  9068. memcpy(buf, result.c_str(), result.length());
  9069. return result.length();
  9070. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9071. std::string result = model->vocab.id_to_token[token].text;
  9072. if (length < (int) result.length()) {
  9073. return -result.length();
  9074. }
  9075. memcpy(buf, result.c_str(), result.length());
  9076. return result.length();
  9077. } else if (llama_is_control_token(model->vocab, token)) {
  9078. ;
  9079. }
  9080. break;
  9081. }
  9082. default:
  9083. GGML_ASSERT(false);
  9084. }
  9085. }
  9086. return 0;
  9087. }
  9088. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  9089. struct llama_timings result = {
  9090. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  9091. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  9092. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  9093. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  9094. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  9095. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  9096. /*.n_sample =*/ std::max(1, ctx->n_sample),
  9097. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  9098. /*.n_eval =*/ std::max(1, ctx->n_eval),
  9099. };
  9100. return result;
  9101. }
  9102. void llama_print_timings(struct llama_context * ctx) {
  9103. const llama_timings timings = llama_get_timings(ctx);
  9104. LLAMA_LOG_INFO("\n");
  9105. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  9106. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9107. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  9108. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  9109. __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);
  9110. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9111. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  9112. 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));
  9113. }
  9114. void llama_reset_timings(struct llama_context * ctx) {
  9115. ctx->t_start_us = ggml_time_us();
  9116. ctx->t_sample_us = ctx->n_sample = 0;
  9117. ctx->t_eval_us = ctx->n_eval = 0;
  9118. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  9119. }
  9120. const char * llama_print_system_info(void) {
  9121. static std::string s;
  9122. s = "";
  9123. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  9124. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  9125. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  9126. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  9127. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  9128. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  9129. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  9130. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  9131. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  9132. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  9133. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  9134. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  9135. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  9136. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  9137. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  9138. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  9139. return s.c_str();
  9140. }
  9141. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  9142. fprintf(stream, "\n");
  9143. fprintf(stream, "###########\n");
  9144. fprintf(stream, "# Timings #\n");
  9145. fprintf(stream, "###########\n");
  9146. fprintf(stream, "\n");
  9147. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  9148. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  9149. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  9150. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  9151. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  9152. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  9153. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  9154. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  9155. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  9156. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  9157. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  9158. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  9159. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  9160. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  9161. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  9162. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  9163. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  9164. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  9165. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  9166. }
  9167. // For internal test use
  9168. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  9169. struct llama_context * ctx
  9170. ) {
  9171. return ctx->model.tensors_by_name;
  9172. }
  9173. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  9174. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  9175. g_state.log_callback_user_data = user_data;
  9176. #ifdef GGML_USE_METAL
  9177. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  9178. #endif
  9179. }
  9180. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  9181. va_list args_copy;
  9182. va_copy(args_copy, args);
  9183. char buffer[128];
  9184. int len = vsnprintf(buffer, 128, format, args);
  9185. if (len < 128) {
  9186. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  9187. } else {
  9188. char* buffer2 = new char[len+1];
  9189. vsnprintf(buffer2, len+1, format, args_copy);
  9190. buffer2[len] = 0;
  9191. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  9192. delete[] buffer2;
  9193. }
  9194. va_end(args_copy);
  9195. }
  9196. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  9197. va_list args;
  9198. va_start(args, format);
  9199. llama_log_internal_v(level, format, args);
  9200. va_end(args);
  9201. }
  9202. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  9203. (void) level;
  9204. (void) user_data;
  9205. fputs(text, stderr);
  9206. fflush(stderr);
  9207. }