llama.cpp 338 KB

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