llama.cpp 372 KB

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