llama.cpp 339 KB

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