llama.cpp 298 KB

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