llama.cpp 385 KB

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