llama.cpp 284 KB

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