llama.cpp 361 KB

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