llama.cpp 440 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUBLAS
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #endif
  16. #ifdef GGML_USE_METAL
  17. # include "ggml-metal.h"
  18. #endif
  19. #ifdef GGML_USE_MPI
  20. # include "ggml-mpi.h"
  21. #endif
  22. #ifndef QK_K
  23. # ifdef GGML_QKK_64
  24. # define QK_K 64
  25. # else
  26. # define QK_K 256
  27. # endif
  28. #endif
  29. #ifdef __has_include
  30. #if __has_include(<unistd.h>)
  31. #include <unistd.h>
  32. #if defined(_POSIX_MAPPED_FILES)
  33. #include <sys/mman.h>
  34. #include <fcntl.h>
  35. #endif
  36. #if defined(_POSIX_MEMLOCK_RANGE)
  37. #include <sys/resource.h>
  38. #endif
  39. #endif
  40. #endif
  41. #if defined(_WIN32)
  42. #define WIN32_LEAN_AND_MEAN
  43. #ifndef NOMINMAX
  44. #define NOMINMAX
  45. #endif
  46. #include <windows.h>
  47. #include <io.h>
  48. #endif
  49. #include <algorithm>
  50. #include <array>
  51. #include <cassert>
  52. #include <cfloat>
  53. #include <cinttypes>
  54. #include <climits>
  55. #include <cmath>
  56. #include <cstdarg>
  57. #include <cstddef>
  58. #include <cstdint>
  59. #include <cstdio>
  60. #include <cstring>
  61. #include <ctime>
  62. #include <forward_list>
  63. #include <fstream>
  64. #include <functional>
  65. #include <initializer_list>
  66. #include <map>
  67. #include <memory>
  68. #include <mutex>
  69. #include <numeric>
  70. #include <queue>
  71. #include <random>
  72. #include <regex>
  73. #include <set>
  74. #include <sstream>
  75. #include <thread>
  76. #include <type_traits>
  77. #include <unordered_map>
  78. #if defined(_MSC_VER)
  79. #pragma warning(disable: 4244 4267) // possible loss of data
  80. #endif
  81. #ifdef __GNUC__
  82. #ifdef __MINGW32__
  83. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  84. #else
  85. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  86. #endif
  87. #else
  88. #define LLAMA_ATTRIBUTE_FORMAT(...)
  89. #endif
  90. #define LLAMA_MAX_NODES 8192
  91. #define LLAMA_MAX_EXPERTS 8
  92. //
  93. // logging
  94. //
  95. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  96. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  97. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  98. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  99. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  100. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  101. //
  102. // helpers
  103. //
  104. static size_t utf8_len(char src) {
  105. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  106. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  107. return lookup[highbits];
  108. }
  109. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  110. std::string result;
  111. for (size_t pos = 0; ; pos += search.length()) {
  112. auto new_pos = s.find(search, pos);
  113. if (new_pos == std::string::npos) {
  114. result += s.substr(pos, s.size() - pos);
  115. break;
  116. }
  117. result += s.substr(pos, new_pos - pos) + replace;
  118. pos = new_pos;
  119. }
  120. s = std::move(result);
  121. }
  122. static bool is_float_close(float a, float b, float abs_tol) {
  123. // Check for non-negative tolerance
  124. if (abs_tol < 0.0) {
  125. throw std::invalid_argument("Tolerance must be non-negative");
  126. }
  127. // Exact equality check
  128. if (a == b) {
  129. return true;
  130. }
  131. // Check for infinities
  132. if (std::isinf(a) || std::isinf(b)) {
  133. return false;
  134. }
  135. // Regular comparison using the provided absolute tolerance
  136. return std::fabs(b - a) <= abs_tol;
  137. }
  138. static void zeros(std::ofstream & file, size_t n) {
  139. char zero = 0;
  140. for (size_t i = 0; i < n; ++i) {
  141. file.write(&zero, 1);
  142. }
  143. }
  144. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  145. static std::string format(const char * fmt, ...) {
  146. va_list ap;
  147. va_list ap2;
  148. va_start(ap, fmt);
  149. va_copy(ap2, ap);
  150. int size = vsnprintf(NULL, 0, fmt, ap);
  151. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  152. std::vector<char> buf(size + 1);
  153. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  154. GGML_ASSERT(size2 == size);
  155. va_end(ap2);
  156. va_end(ap);
  157. return std::string(buf.data(), size);
  158. }
  159. //
  160. // gguf constants (sync with gguf.py)
  161. //
  162. enum llm_arch {
  163. LLM_ARCH_LLAMA,
  164. LLM_ARCH_FALCON,
  165. LLM_ARCH_BAICHUAN,
  166. LLM_ARCH_GPT2,
  167. LLM_ARCH_GPTJ,
  168. LLM_ARCH_GPTNEOX,
  169. LLM_ARCH_MPT,
  170. LLM_ARCH_STARCODER,
  171. LLM_ARCH_PERSIMMON,
  172. LLM_ARCH_REFACT,
  173. LLM_ARCH_BLOOM,
  174. LLM_ARCH_STABLELM,
  175. LLM_ARCH_QWEN,
  176. LLM_ARCH_QWEN2,
  177. LLM_ARCH_PHI2,
  178. LLM_ARCH_PLAMO,
  179. LLM_ARCH_CODESHELL,
  180. LLM_ARCH_ORION,
  181. LLM_ARCH_UNKNOWN,
  182. };
  183. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  184. { LLM_ARCH_LLAMA, "llama" },
  185. { LLM_ARCH_FALCON, "falcon" },
  186. { LLM_ARCH_GPT2, "gpt2" },
  187. { LLM_ARCH_GPTJ, "gptj" },
  188. { LLM_ARCH_GPTNEOX, "gptneox" },
  189. { LLM_ARCH_MPT, "mpt" },
  190. { LLM_ARCH_BAICHUAN, "baichuan" },
  191. { LLM_ARCH_STARCODER, "starcoder" },
  192. { LLM_ARCH_PERSIMMON, "persimmon" },
  193. { LLM_ARCH_REFACT, "refact" },
  194. { LLM_ARCH_BLOOM, "bloom" },
  195. { LLM_ARCH_STABLELM, "stablelm" },
  196. { LLM_ARCH_QWEN, "qwen" },
  197. { LLM_ARCH_QWEN2, "qwen2" },
  198. { LLM_ARCH_PHI2, "phi2" },
  199. { LLM_ARCH_PLAMO, "plamo" },
  200. { LLM_ARCH_CODESHELL, "codeshell" },
  201. { LLM_ARCH_ORION, "orion" },
  202. };
  203. enum llm_kv {
  204. LLM_KV_GENERAL_ARCHITECTURE,
  205. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  206. LLM_KV_GENERAL_ALIGNMENT,
  207. LLM_KV_GENERAL_NAME,
  208. LLM_KV_GENERAL_AUTHOR,
  209. LLM_KV_GENERAL_URL,
  210. LLM_KV_GENERAL_DESCRIPTION,
  211. LLM_KV_GENERAL_LICENSE,
  212. LLM_KV_GENERAL_SOURCE_URL,
  213. LLM_KV_GENERAL_SOURCE_HF_REPO,
  214. LLM_KV_CONTEXT_LENGTH,
  215. LLM_KV_EMBEDDING_LENGTH,
  216. LLM_KV_BLOCK_COUNT,
  217. LLM_KV_FEED_FORWARD_LENGTH,
  218. LLM_KV_USE_PARALLEL_RESIDUAL,
  219. LLM_KV_TENSOR_DATA_LAYOUT,
  220. LLM_KV_EXPERT_COUNT,
  221. LLM_KV_EXPERT_USED_COUNT,
  222. LLM_KV_ATTENTION_HEAD_COUNT,
  223. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  224. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  225. LLM_KV_ATTENTION_CLAMP_KQV,
  226. LLM_KV_ATTENTION_KEY_LENGTH,
  227. LLM_KV_ATTENTION_VALUE_LENGTH,
  228. LLM_KV_ATTENTION_LAYERNORM_EPS,
  229. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  230. LLM_KV_ROPE_DIMENSION_COUNT,
  231. LLM_KV_ROPE_FREQ_BASE,
  232. LLM_KV_ROPE_SCALE_LINEAR,
  233. LLM_KV_ROPE_SCALING_TYPE,
  234. LLM_KV_ROPE_SCALING_FACTOR,
  235. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  236. LLM_KV_ROPE_SCALING_FINETUNED,
  237. LLM_KV_TOKENIZER_MODEL,
  238. LLM_KV_TOKENIZER_LIST,
  239. LLM_KV_TOKENIZER_TOKEN_TYPE,
  240. LLM_KV_TOKENIZER_SCORES,
  241. LLM_KV_TOKENIZER_MERGES,
  242. LLM_KV_TOKENIZER_BOS_ID,
  243. LLM_KV_TOKENIZER_EOS_ID,
  244. LLM_KV_TOKENIZER_UNK_ID,
  245. LLM_KV_TOKENIZER_SEP_ID,
  246. LLM_KV_TOKENIZER_PAD_ID,
  247. LLM_KV_TOKENIZER_ADD_BOS,
  248. LLM_KV_TOKENIZER_ADD_EOS,
  249. LLM_KV_TOKENIZER_HF_JSON,
  250. LLM_KV_TOKENIZER_RWKV,
  251. };
  252. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  253. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  254. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  255. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  256. { LLM_KV_GENERAL_NAME, "general.name" },
  257. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  258. { LLM_KV_GENERAL_URL, "general.url" },
  259. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  260. { LLM_KV_GENERAL_LICENSE, "general.license" },
  261. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  262. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  263. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  264. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  265. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  266. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  267. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  268. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  269. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  270. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  271. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  272. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  273. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  274. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  275. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  276. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  277. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  278. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  279. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  280. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  281. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  282. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  283. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  284. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  285. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  286. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  287. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  288. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  289. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  290. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  291. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  292. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  293. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  294. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  295. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  296. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  297. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  298. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  299. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  300. };
  301. struct LLM_KV {
  302. LLM_KV(llm_arch arch) : arch(arch) {}
  303. llm_arch arch;
  304. std::string operator()(llm_kv kv) const {
  305. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  306. }
  307. };
  308. enum llm_tensor {
  309. LLM_TENSOR_TOKEN_EMBD,
  310. LLM_TENSOR_TOKEN_EMBD_NORM,
  311. LLM_TENSOR_POS_EMBD,
  312. LLM_TENSOR_OUTPUT,
  313. LLM_TENSOR_OUTPUT_NORM,
  314. LLM_TENSOR_ROPE_FREQS,
  315. LLM_TENSOR_ATTN_Q,
  316. LLM_TENSOR_ATTN_K,
  317. LLM_TENSOR_ATTN_V,
  318. LLM_TENSOR_ATTN_QKV,
  319. LLM_TENSOR_ATTN_OUT,
  320. LLM_TENSOR_ATTN_NORM,
  321. LLM_TENSOR_ATTN_NORM_2,
  322. LLM_TENSOR_ATTN_ROT_EMBD,
  323. LLM_TENSOR_FFN_GATE_INP,
  324. LLM_TENSOR_FFN_NORM,
  325. LLM_TENSOR_FFN_GATE,
  326. LLM_TENSOR_FFN_DOWN,
  327. LLM_TENSOR_FFN_UP,
  328. LLM_TENSOR_FFN_ACT,
  329. LLM_TENSOR_FFN_DOWN_EXP,
  330. LLM_TENSOR_FFN_GATE_EXP,
  331. LLM_TENSOR_FFN_UP_EXP,
  332. LLM_TENSOR_ATTN_Q_NORM,
  333. LLM_TENSOR_ATTN_K_NORM,
  334. };
  335. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  336. {
  337. LLM_ARCH_LLAMA,
  338. {
  339. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  340. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  341. { LLM_TENSOR_OUTPUT, "output" },
  342. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  343. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  344. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  345. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  346. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  347. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  348. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  349. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  350. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  351. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  352. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  353. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  354. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  355. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  356. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  357. },
  358. },
  359. {
  360. LLM_ARCH_BAICHUAN,
  361. {
  362. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  363. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  364. { LLM_TENSOR_OUTPUT, "output" },
  365. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  366. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  367. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  368. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  369. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  370. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  371. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  372. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  373. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  374. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  375. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  376. },
  377. },
  378. {
  379. LLM_ARCH_FALCON,
  380. {
  381. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  382. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  383. { LLM_TENSOR_OUTPUT, "output" },
  384. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  385. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  386. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  387. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  388. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  389. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  390. },
  391. },
  392. {
  393. LLM_ARCH_GPT2,
  394. {
  395. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  396. { LLM_TENSOR_POS_EMBD, "position_embd" },
  397. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  398. { LLM_TENSOR_OUTPUT, "output" },
  399. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  400. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  401. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  402. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  403. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  404. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  405. },
  406. },
  407. {
  408. LLM_ARCH_GPTJ,
  409. {
  410. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  411. },
  412. },
  413. {
  414. LLM_ARCH_GPTNEOX,
  415. {
  416. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  417. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  418. { LLM_TENSOR_OUTPUT, "output" },
  419. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  420. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  421. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  422. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  423. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  424. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  425. },
  426. },
  427. {
  428. LLM_ARCH_PERSIMMON,
  429. {
  430. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  431. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  432. { LLM_TENSOR_OUTPUT, "output"},
  433. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  434. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  435. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  436. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  437. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  438. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  439. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  440. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  441. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  442. },
  443. },
  444. {
  445. LLM_ARCH_MPT,
  446. {
  447. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  448. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  449. { LLM_TENSOR_OUTPUT, "output" },
  450. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  451. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  452. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  453. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  454. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  455. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  456. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  457. },
  458. },
  459. {
  460. LLM_ARCH_STARCODER,
  461. {
  462. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  463. { LLM_TENSOR_POS_EMBD, "position_embd" },
  464. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  465. { LLM_TENSOR_OUTPUT, "output" },
  466. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  467. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  468. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  469. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  470. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  471. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  472. },
  473. },
  474. {
  475. LLM_ARCH_REFACT,
  476. {
  477. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  478. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  479. { LLM_TENSOR_OUTPUT, "output" },
  480. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  481. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  482. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  483. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  484. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  485. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  486. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  487. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  488. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  489. },
  490. },
  491. {
  492. LLM_ARCH_BLOOM,
  493. {
  494. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  495. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  496. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  497. { LLM_TENSOR_OUTPUT, "output" },
  498. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  499. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  500. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  501. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  502. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  503. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  504. },
  505. },
  506. {
  507. LLM_ARCH_STABLELM,
  508. {
  509. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  510. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  511. { LLM_TENSOR_OUTPUT, "output" },
  512. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  513. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  514. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  515. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  516. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  517. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  518. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  519. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  520. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  521. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  522. },
  523. },
  524. {
  525. LLM_ARCH_QWEN,
  526. {
  527. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  528. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  529. { LLM_TENSOR_OUTPUT, "output" },
  530. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  531. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  532. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  533. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  534. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  535. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  536. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  537. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  538. },
  539. },
  540. {
  541. LLM_ARCH_QWEN2,
  542. {
  543. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  544. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  545. { LLM_TENSOR_OUTPUT, "output" },
  546. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  547. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  548. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  549. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  550. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  551. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  552. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  553. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  554. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  555. },
  556. },
  557. {
  558. LLM_ARCH_PHI2,
  559. {
  560. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  561. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  562. { LLM_TENSOR_OUTPUT, "output" },
  563. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  564. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  565. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  566. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  567. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  568. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  569. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  570. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  571. },
  572. },
  573. {
  574. LLM_ARCH_PLAMO,
  575. {
  576. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  577. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  578. { LLM_TENSOR_OUTPUT, "output" },
  579. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  580. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  581. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  582. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  583. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  584. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  585. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  586. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  587. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  588. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  589. },
  590. },
  591. {
  592. LLM_ARCH_CODESHELL,
  593. {
  594. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  595. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  596. { LLM_TENSOR_OUTPUT, "output" },
  597. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  598. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  599. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  600. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  601. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  602. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  603. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  604. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  605. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  606. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  607. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  608. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  609. },
  610. },
  611. {
  612. LLM_ARCH_ORION,
  613. {
  614. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  615. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  616. { LLM_TENSOR_OUTPUT, "output" },
  617. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  618. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  619. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  620. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  621. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  622. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  623. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  624. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  625. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  626. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  627. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  628. },
  629. },
  630. {
  631. LLM_ARCH_UNKNOWN,
  632. {
  633. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  634. },
  635. },
  636. };
  637. static llm_arch llm_arch_from_string(const std::string & name) {
  638. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  639. if (kv.second == name) {
  640. return kv.first;
  641. }
  642. }
  643. return LLM_ARCH_UNKNOWN;
  644. }
  645. // helper to handle gguf constants
  646. // usage:
  647. //
  648. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  649. //
  650. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  651. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  652. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  653. //
  654. struct LLM_TN {
  655. LLM_TN(llm_arch arch) : arch(arch) {}
  656. llm_arch arch;
  657. std::string operator()(llm_tensor tensor) const {
  658. return LLM_TENSOR_NAMES[arch].at(tensor);
  659. }
  660. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  661. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  662. }
  663. std::string operator()(llm_tensor tensor, int bid) const {
  664. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  665. }
  666. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  667. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  668. }
  669. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  670. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  671. }
  672. };
  673. //
  674. // gguf helpers
  675. //
  676. static std::map<int8_t, std::string> LLAMA_ROPE_SCALING_TYPES = {
  677. { LLAMA_ROPE_SCALING_NONE, "none" },
  678. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  679. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  680. };
  681. static int8_t llama_rope_scaling_type_from_string(const std::string & name) {
  682. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  683. if (kv.second == name) {
  684. return kv.first;
  685. }
  686. }
  687. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  688. }
  689. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  690. switch (type) {
  691. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  692. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  693. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  694. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  695. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  696. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  697. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  698. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  699. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  700. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  701. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  702. default: return format("unknown type %d", type);
  703. }
  704. }
  705. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  706. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  707. switch (type) {
  708. case GGUF_TYPE_STRING:
  709. return gguf_get_val_str(ctx_gguf, i);
  710. case GGUF_TYPE_ARRAY:
  711. {
  712. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  713. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  714. const void * data = gguf_get_arr_data(ctx_gguf, i);
  715. std::stringstream ss;
  716. ss << "[";
  717. for (int j = 0; j < arr_n; j++) {
  718. if (arr_type == GGUF_TYPE_STRING) {
  719. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  720. // escape quotes
  721. replace_all(val, "\\", "\\\\");
  722. replace_all(val, "\"", "\\\"");
  723. ss << '"' << val << '"';
  724. } else if (arr_type == GGUF_TYPE_ARRAY) {
  725. ss << "???";
  726. } else {
  727. ss << gguf_data_to_str(arr_type, data, j);
  728. }
  729. if (j < arr_n - 1) {
  730. ss << ", ";
  731. }
  732. }
  733. ss << "]";
  734. return ss.str();
  735. }
  736. default:
  737. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  738. }
  739. }
  740. //
  741. // ggml helpers
  742. //
  743. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  744. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  745. if (plan.work_size > 0) {
  746. buf.resize(plan.work_size);
  747. plan.work_data = buf.data();
  748. }
  749. ggml_graph_compute(graph, &plan);
  750. }
  751. //
  752. // llama helpers
  753. //
  754. #if defined(_WIN32)
  755. static std::string llama_format_win_err(DWORD err) {
  756. LPSTR buf;
  757. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  758. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  759. if (!size) {
  760. return "FormatMessageA failed";
  761. }
  762. std::string ret(buf, size);
  763. LocalFree(buf);
  764. return ret;
  765. }
  766. #endif
  767. template <typename T>
  768. struct no_init {
  769. T value;
  770. no_init() { /* do nothing */ }
  771. };
  772. struct llama_file {
  773. // use FILE * so we don't have to re-open the file to mmap
  774. FILE * fp;
  775. size_t size;
  776. llama_file(const char * fname, const char * mode) {
  777. fp = std::fopen(fname, mode);
  778. if (fp == NULL) {
  779. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  780. }
  781. seek(0, SEEK_END);
  782. size = tell();
  783. seek(0, SEEK_SET);
  784. }
  785. size_t tell() const {
  786. #ifdef _WIN32
  787. __int64 ret = _ftelli64(fp);
  788. #else
  789. long ret = std::ftell(fp);
  790. #endif
  791. GGML_ASSERT(ret != -1); // this really shouldn't fail
  792. return (size_t) ret;
  793. }
  794. void seek(size_t offset, int whence) const {
  795. #ifdef _WIN32
  796. int ret = _fseeki64(fp, (__int64) offset, whence);
  797. #else
  798. int ret = std::fseek(fp, (long) offset, whence);
  799. #endif
  800. GGML_ASSERT(ret == 0); // same
  801. }
  802. void read_raw(void * ptr, size_t len) const {
  803. if (len == 0) {
  804. return;
  805. }
  806. errno = 0;
  807. std::size_t ret = std::fread(ptr, len, 1, fp);
  808. if (ferror(fp)) {
  809. throw std::runtime_error(format("read error: %s", strerror(errno)));
  810. }
  811. if (ret != 1) {
  812. throw std::runtime_error("unexpectedly reached end of file");
  813. }
  814. }
  815. uint32_t read_u32() const {
  816. uint32_t ret;
  817. read_raw(&ret, sizeof(ret));
  818. return ret;
  819. }
  820. void write_raw(const void * ptr, size_t len) const {
  821. if (len == 0) {
  822. return;
  823. }
  824. errno = 0;
  825. size_t ret = std::fwrite(ptr, len, 1, fp);
  826. if (ret != 1) {
  827. throw std::runtime_error(format("write error: %s", strerror(errno)));
  828. }
  829. }
  830. void write_u32(std::uint32_t val) const {
  831. write_raw(&val, sizeof(val));
  832. }
  833. ~llama_file() {
  834. if (fp) {
  835. std::fclose(fp);
  836. }
  837. }
  838. };
  839. struct llama_mmap {
  840. void * addr;
  841. size_t size;
  842. llama_mmap(const llama_mmap &) = delete;
  843. #ifdef _POSIX_MAPPED_FILES
  844. static constexpr bool SUPPORTED = true;
  845. // list of mapped fragments (first_offset, last_offset)
  846. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  847. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  848. size = file->size;
  849. int fd = fileno(file->fp);
  850. int flags = MAP_SHARED;
  851. // prefetch/readahead impairs performance on NUMA systems
  852. if (numa) { prefetch = 0; }
  853. #ifdef __linux__
  854. // advise the kernel to read the file sequentially (increases readahead)
  855. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  856. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  857. strerror(errno));
  858. }
  859. if (prefetch) { flags |= MAP_POPULATE; }
  860. #endif
  861. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  862. if (addr == MAP_FAILED) { // NOLINT
  863. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  864. }
  865. if (prefetch > 0) {
  866. // advise the kernel to preload the mapped memory
  867. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  868. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  869. strerror(errno));
  870. }
  871. }
  872. if (numa) {
  873. // advise the kernel not to use readahead
  874. // (because the next page might not belong on the same node)
  875. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  876. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  877. strerror(errno));
  878. }
  879. }
  880. // initialize list of mapped_fragments
  881. mapped_fragments.emplace_back(0, file->size);
  882. }
  883. static void align_range(size_t * first, size_t * last, size_t page_size) {
  884. // align first to the next page
  885. size_t offset_in_page = *first & (page_size - 1);
  886. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  887. *first += offset_to_page;
  888. // align last to the previous page
  889. *last = *last & ~(page_size - 1);
  890. if (*last <= *first) {
  891. *last = *first;
  892. }
  893. }
  894. // partially unmap the file in the range [first, last)
  895. void unmap_fragment(size_t first, size_t last) {
  896. // note: this function must not be called multiple times with overlapping ranges
  897. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  898. int page_size = sysconf(_SC_PAGESIZE);
  899. align_range(&first, &last, page_size);
  900. size_t len = last - first;
  901. if (len == 0) {
  902. return;
  903. }
  904. GGML_ASSERT(first % page_size == 0);
  905. GGML_ASSERT(last % page_size == 0);
  906. GGML_ASSERT(last > first);
  907. void * next_page_start = (uint8_t *) addr + first;
  908. // unmap the range
  909. if (munmap(next_page_start, len)) {
  910. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  911. }
  912. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  913. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  914. for (const auto & frag : mapped_fragments) {
  915. if (frag.first < first && frag.second > last) {
  916. // the range is in the middle of the fragment, split it
  917. new_mapped_fragments.emplace_back(frag.first, first);
  918. new_mapped_fragments.emplace_back(last, frag.second);
  919. } else if (frag.first < first && frag.second > first) {
  920. // the range starts in the middle of the fragment
  921. new_mapped_fragments.emplace_back(frag.first, first);
  922. } else if (frag.first < last && frag.second > last) {
  923. // the range ends in the middle of the fragment
  924. new_mapped_fragments.emplace_back(last, frag.second);
  925. } else if (frag.first >= first && frag.second <= last) {
  926. // the range covers the entire fragment
  927. } else {
  928. // the range is outside the fragment
  929. new_mapped_fragments.push_back(frag);
  930. }
  931. }
  932. mapped_fragments = std::move(new_mapped_fragments);
  933. }
  934. ~llama_mmap() {
  935. for (const auto & frag : mapped_fragments) {
  936. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  937. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  938. }
  939. }
  940. }
  941. #elif defined(_WIN32)
  942. static constexpr bool SUPPORTED = true;
  943. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  944. GGML_UNUSED(numa);
  945. size = file->size;
  946. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  947. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  948. if (hMapping == NULL) {
  949. DWORD error = GetLastError();
  950. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  951. }
  952. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  953. DWORD error = GetLastError();
  954. CloseHandle(hMapping);
  955. if (addr == NULL) {
  956. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  957. }
  958. if (prefetch > 0) {
  959. #if _WIN32_WINNT >= 0x602
  960. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  961. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  962. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  963. // may fail on pre-Windows 8 systems
  964. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  965. if (pPrefetchVirtualMemory) {
  966. // advise the kernel to preload the mapped memory
  967. WIN32_MEMORY_RANGE_ENTRY range;
  968. range.VirtualAddress = addr;
  969. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  970. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  971. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  972. llama_format_win_err(GetLastError()).c_str());
  973. }
  974. }
  975. #else
  976. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  977. #endif
  978. }
  979. }
  980. void unmap_fragment(size_t first, size_t last) {
  981. // not supported
  982. GGML_UNUSED(first);
  983. GGML_UNUSED(last);
  984. }
  985. ~llama_mmap() {
  986. if (!UnmapViewOfFile(addr)) {
  987. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  988. llama_format_win_err(GetLastError()).c_str());
  989. }
  990. }
  991. #else
  992. static constexpr bool SUPPORTED = false;
  993. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  994. GGML_UNUSED(file);
  995. GGML_UNUSED(prefetch);
  996. GGML_UNUSED(numa);
  997. throw std::runtime_error("mmap not supported");
  998. }
  999. void unmap_fragment(size_t first, size_t last) {
  1000. GGML_UNUSED(first);
  1001. GGML_UNUSED(last);
  1002. throw std::runtime_error("mmap not supported");
  1003. }
  1004. #endif
  1005. };
  1006. // Represents some region of memory being locked using mlock or VirtualLock;
  1007. // will automatically unlock on destruction.
  1008. struct llama_mlock {
  1009. void * addr = NULL;
  1010. size_t size = 0;
  1011. bool failed_already = false;
  1012. llama_mlock() {}
  1013. llama_mlock(const llama_mlock &) = delete;
  1014. ~llama_mlock() {
  1015. if (size) {
  1016. raw_unlock(addr, size);
  1017. }
  1018. }
  1019. void init(void * ptr) {
  1020. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1021. addr = ptr;
  1022. }
  1023. void grow_to(size_t target_size) {
  1024. GGML_ASSERT(addr);
  1025. if (failed_already) {
  1026. return;
  1027. }
  1028. size_t granularity = lock_granularity();
  1029. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1030. if (target_size > size) {
  1031. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1032. size = target_size;
  1033. } else {
  1034. failed_already = true;
  1035. }
  1036. }
  1037. }
  1038. #ifdef _POSIX_MEMLOCK_RANGE
  1039. static constexpr bool SUPPORTED = true;
  1040. static size_t lock_granularity() {
  1041. return (size_t) sysconf(_SC_PAGESIZE);
  1042. }
  1043. #ifdef __APPLE__
  1044. #define MLOCK_SUGGESTION \
  1045. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1046. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  1047. #else
  1048. #define MLOCK_SUGGESTION \
  1049. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  1050. #endif
  1051. bool raw_lock(const void * addr, size_t size) const {
  1052. if (!mlock(addr, size)) {
  1053. return true;
  1054. }
  1055. char* errmsg = std::strerror(errno);
  1056. bool suggest = (errno == ENOMEM);
  1057. // Check if the resource limit is fine after all
  1058. struct rlimit lock_limit;
  1059. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1060. suggest = false;
  1061. }
  1062. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1063. suggest = false;
  1064. }
  1065. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1066. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1067. return false;
  1068. }
  1069. #undef MLOCK_SUGGESTION
  1070. static void raw_unlock(void * addr, size_t size) {
  1071. if (munlock(addr, size)) {
  1072. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1073. }
  1074. }
  1075. #elif defined(_WIN32)
  1076. static constexpr bool SUPPORTED = true;
  1077. static size_t lock_granularity() {
  1078. SYSTEM_INFO si;
  1079. GetSystemInfo(&si);
  1080. return (size_t) si.dwPageSize;
  1081. }
  1082. bool raw_lock(void * ptr, size_t len) const {
  1083. for (int tries = 1; ; tries++) {
  1084. if (VirtualLock(ptr, len)) {
  1085. return true;
  1086. }
  1087. if (tries == 2) {
  1088. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1089. len, size, llama_format_win_err(GetLastError()).c_str());
  1090. return false;
  1091. }
  1092. // It failed but this was only the first try; increase the working
  1093. // set size and try again.
  1094. SIZE_T min_ws_size, max_ws_size;
  1095. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1096. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1097. llama_format_win_err(GetLastError()).c_str());
  1098. return false;
  1099. }
  1100. // Per MSDN: "The maximum number of pages that a process can lock
  1101. // is equal to the number of pages in its minimum working set minus
  1102. // a small overhead."
  1103. // Hopefully a megabyte is enough overhead:
  1104. size_t increment = len + 1048576;
  1105. // The minimum must be <= the maximum, so we need to increase both:
  1106. min_ws_size += increment;
  1107. max_ws_size += increment;
  1108. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1109. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1110. llama_format_win_err(GetLastError()).c_str());
  1111. return false;
  1112. }
  1113. }
  1114. }
  1115. static void raw_unlock(void * ptr, size_t len) {
  1116. if (!VirtualUnlock(ptr, len)) {
  1117. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1118. llama_format_win_err(GetLastError()).c_str());
  1119. }
  1120. }
  1121. #else
  1122. static constexpr bool SUPPORTED = false;
  1123. static size_t lock_granularity() {
  1124. return (size_t) 65536;
  1125. }
  1126. bool raw_lock(const void * addr, size_t len) const {
  1127. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1128. return false;
  1129. }
  1130. static void raw_unlock(const void * addr, size_t len) {}
  1131. #endif
  1132. };
  1133. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1134. std::vector<char> result(8, 0);
  1135. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1136. if (n_tokens < 0) {
  1137. result.resize(-n_tokens);
  1138. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1139. GGML_ASSERT(check == -n_tokens);
  1140. }
  1141. else {
  1142. result.resize(n_tokens);
  1143. }
  1144. return std::string(result.data(), result.size());
  1145. }
  1146. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1147. ggml_backend_buffer_type_t buft = nullptr;
  1148. #if defined(GGML_USE_CUBLAS)
  1149. // host buffers should only be used when data is expected to be copied to/from the GPU
  1150. if (host_buffer) {
  1151. buft = ggml_backend_cuda_host_buffer_type();
  1152. }
  1153. #elif defined(GGML_USE_SYCL)
  1154. buft = ggml_backend_sycl_host_buffer_type();
  1155. #elif defined(GGML_USE_CPU_HBM)
  1156. buft = ggml_backend_cpu_hbm_buffer_type();
  1157. #elif defined(GGML_USE_VULKAN)
  1158. if (host_buffer) {
  1159. buft = ggml_backend_vk_host_buffer_type();
  1160. }
  1161. #endif
  1162. if (buft == nullptr) {
  1163. buft = ggml_backend_cpu_buffer_type();
  1164. }
  1165. return buft;
  1166. GGML_UNUSED(host_buffer);
  1167. }
  1168. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1169. ggml_backend_buffer_type_t buft = nullptr;
  1170. #ifdef GGML_USE_METAL
  1171. buft = ggml_backend_metal_buffer_type();
  1172. #elif defined(GGML_USE_CUBLAS)
  1173. buft = ggml_backend_cuda_buffer_type(gpu);
  1174. #elif defined(GGML_USE_VULKAN)
  1175. buft = ggml_backend_vk_buffer_type();
  1176. #elif defined(GGML_USE_SYCL)
  1177. buft = ggml_backend_sycl_buffer_type(gpu);
  1178. #elif defined(GGML_USE_CLBLAST)
  1179. buft = ggml_backend_opencl_buffer_type();
  1180. #endif
  1181. if (buft == nullptr) {
  1182. buft = llama_default_buffer_type_cpu(true);
  1183. }
  1184. return buft;
  1185. GGML_UNUSED(gpu);
  1186. }
  1187. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1188. ggml_backend_buffer_type_t buft = nullptr;
  1189. #ifdef GGML_USE_CUBLAS
  1190. if (ggml_backend_cuda_get_device_count() > 1) {
  1191. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1192. }
  1193. #endif
  1194. if (buft == nullptr) {
  1195. buft = llama_default_buffer_type_offload(fallback_gpu);
  1196. }
  1197. return buft;
  1198. GGML_UNUSED(tensor_split);
  1199. }
  1200. //
  1201. // globals
  1202. //
  1203. struct llama_state {
  1204. llama_state() {
  1205. #ifdef GGML_USE_METAL
  1206. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1207. #endif
  1208. }
  1209. // We save the log callback globally
  1210. ggml_log_callback log_callback = llama_log_callback_default;
  1211. void * log_callback_user_data = nullptr;
  1212. };
  1213. static llama_state g_state;
  1214. // available llama models
  1215. enum e_model {
  1216. MODEL_UNKNOWN,
  1217. MODEL_0_5B,
  1218. MODEL_1B,
  1219. MODEL_3B,
  1220. MODEL_4B,
  1221. MODEL_7B,
  1222. MODEL_8B,
  1223. MODEL_13B,
  1224. MODEL_14B,
  1225. MODEL_15B,
  1226. MODEL_30B,
  1227. MODEL_34B,
  1228. MODEL_40B,
  1229. MODEL_65B,
  1230. MODEL_70B,
  1231. MODEL_SMALL,
  1232. MODEL_MEDIUM,
  1233. MODEL_LARGE,
  1234. MODEL_XL,
  1235. };
  1236. static const size_t kiB = 1024;
  1237. static const size_t MiB = 1024*kiB;
  1238. static const size_t GiB = 1024*MiB;
  1239. struct llama_hparams {
  1240. bool vocab_only;
  1241. uint32_t n_vocab;
  1242. uint32_t n_ctx_train; // context size the model was trained on
  1243. uint32_t n_embd;
  1244. uint32_t n_head;
  1245. uint32_t n_head_kv;
  1246. uint32_t n_layer;
  1247. uint32_t n_rot;
  1248. uint32_t n_embd_head_k; // dimension of keys (d_k). d_q is assumed to be the same, but there are n_head q heads, and only n_head_kv k-v heads
  1249. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1250. uint32_t n_ff;
  1251. uint32_t n_expert = 0;
  1252. uint32_t n_expert_used = 0;
  1253. float f_norm_eps;
  1254. float f_norm_rms_eps;
  1255. float rope_freq_base_train;
  1256. float rope_freq_scale_train;
  1257. uint32_t n_yarn_orig_ctx;
  1258. int8_t rope_scaling_type_train : 3;
  1259. bool rope_finetuned : 1;
  1260. float f_clamp_kqv;
  1261. float f_max_alibi_bias;
  1262. bool operator!=(const llama_hparams & other) const {
  1263. if (this->vocab_only != other.vocab_only) return true;
  1264. if (this->n_vocab != other.n_vocab) return true;
  1265. if (this->n_ctx_train != other.n_ctx_train) return true;
  1266. if (this->n_embd != other.n_embd) return true;
  1267. if (this->n_head != other.n_head) return true;
  1268. if (this->n_head_kv != other.n_head_kv) return true;
  1269. if (this->n_layer != other.n_layer) return true;
  1270. if (this->n_rot != other.n_rot) return true;
  1271. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1272. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1273. if (this->n_ff != other.n_ff) return true;
  1274. if (this->n_expert != other.n_expert) return true;
  1275. if (this->n_expert_used != other.n_expert_used) return true;
  1276. if (this->rope_finetuned != other.rope_finetuned) return true;
  1277. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1278. const float EPSILON = 1e-9f;
  1279. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1280. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1281. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1282. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1283. return false;
  1284. }
  1285. uint32_t n_gqa() const {
  1286. return n_head/n_head_kv;
  1287. }
  1288. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1289. return n_embd_head_k * n_head_kv;
  1290. }
  1291. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1292. return n_embd_head_v * n_head_kv;
  1293. }
  1294. };
  1295. struct llama_cparams {
  1296. uint32_t n_ctx; // context size used during inference
  1297. uint32_t n_batch;
  1298. uint32_t n_threads; // number of threads to use for generation
  1299. uint32_t n_threads_batch; // number of threads to use for batch processing
  1300. float rope_freq_base;
  1301. float rope_freq_scale;
  1302. uint32_t n_yarn_orig_ctx;
  1303. // These hyperparameters are not exposed in GGUF, because all
  1304. // existing YaRN models use the same values for them.
  1305. float yarn_ext_factor;
  1306. float yarn_attn_factor;
  1307. float yarn_beta_fast;
  1308. float yarn_beta_slow;
  1309. bool mul_mat_q;
  1310. bool offload_kqv;
  1311. ggml_backend_sched_eval_callback cb_eval;
  1312. void * cb_eval_user_data;
  1313. };
  1314. struct llama_layer {
  1315. // normalization
  1316. struct ggml_tensor * attn_norm;
  1317. struct ggml_tensor * attn_norm_b;
  1318. struct ggml_tensor * attn_norm_2;
  1319. struct ggml_tensor * attn_norm_2_b;
  1320. struct ggml_tensor * attn_q_norm;
  1321. struct ggml_tensor * attn_q_norm_b;
  1322. struct ggml_tensor * attn_k_norm;
  1323. struct ggml_tensor * attn_k_norm_b;
  1324. // attention
  1325. struct ggml_tensor * wq;
  1326. struct ggml_tensor * wk;
  1327. struct ggml_tensor * wv;
  1328. struct ggml_tensor * wo;
  1329. struct ggml_tensor * wqkv;
  1330. // attention bias
  1331. struct ggml_tensor * bq;
  1332. struct ggml_tensor * bk;
  1333. struct ggml_tensor * bv;
  1334. struct ggml_tensor * bo;
  1335. struct ggml_tensor * bqkv;
  1336. // normalization
  1337. struct ggml_tensor * ffn_norm;
  1338. struct ggml_tensor * ffn_norm_b;
  1339. // ff
  1340. struct ggml_tensor * ffn_gate; // w1
  1341. struct ggml_tensor * ffn_down; // w2
  1342. struct ggml_tensor * ffn_up; // w3
  1343. // ff MoE
  1344. struct ggml_tensor * ffn_gate_inp;
  1345. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1346. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1347. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1348. // ff bias
  1349. struct ggml_tensor * ffn_down_b; // b2
  1350. struct ggml_tensor * ffn_up_b; // b3
  1351. struct ggml_tensor * ffn_act;
  1352. };
  1353. struct llama_kv_cell {
  1354. llama_pos pos = -1;
  1355. llama_pos delta = 0;
  1356. std::set<llama_seq_id> seq_id;
  1357. bool has_seq_id(const llama_seq_id & id) const {
  1358. return seq_id.find(id) != seq_id.end();
  1359. }
  1360. };
  1361. // ring-buffer of cached KV data
  1362. struct llama_kv_cache {
  1363. bool has_shift = false;
  1364. // Note: The value of head isn't only used to optimize searching
  1365. // for a free KV slot. llama_decode_internal also uses it, so it
  1366. // cannot be freely changed after a slot has been allocated.
  1367. uint32_t head = 0;
  1368. uint32_t size = 0;
  1369. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1370. // computed before each graph build
  1371. uint32_t n = 0;
  1372. std::vector<llama_kv_cell> cells;
  1373. std::vector<struct ggml_tensor *> k_l; // per layer
  1374. std::vector<struct ggml_tensor *> v_l;
  1375. std::vector<struct ggml_context *> ctxs;
  1376. std::vector<ggml_backend_buffer_t> bufs;
  1377. size_t total_size() const {
  1378. size_t size = 0;
  1379. for (ggml_backend_buffer_t buf : bufs) {
  1380. size += ggml_backend_buffer_get_size(buf);
  1381. }
  1382. return size;
  1383. }
  1384. ~llama_kv_cache() {
  1385. for (struct ggml_context * ctx : ctxs) {
  1386. ggml_free(ctx);
  1387. }
  1388. for (ggml_backend_buffer_t buf : bufs) {
  1389. ggml_backend_buffer_free(buf);
  1390. }
  1391. }
  1392. };
  1393. struct llama_vocab {
  1394. using id = int32_t;
  1395. using token = std::string;
  1396. using ttype = llama_token_type;
  1397. struct token_data {
  1398. token text;
  1399. float score;
  1400. ttype type;
  1401. };
  1402. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1403. std::unordered_map<token, id> token_to_id;
  1404. std::vector<token_data> id_to_token;
  1405. std::unordered_map<token, id> special_tokens_cache;
  1406. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1407. // default LLaMA special tokens
  1408. id special_bos_id = 1;
  1409. id special_eos_id = 2;
  1410. id special_unk_id = 0;
  1411. id special_sep_id = -1;
  1412. id special_pad_id = -1;
  1413. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1414. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1415. id linefeed_id = 13;
  1416. id special_prefix_id = 32007;
  1417. id special_middle_id = 32009;
  1418. id special_suffix_id = 32008;
  1419. id special_eot_id = 32010;
  1420. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1421. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1422. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1423. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1424. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1425. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1426. if (it == bpe_ranks.end()) {
  1427. return -1;
  1428. }
  1429. return it->second;
  1430. }
  1431. };
  1432. struct llama_model {
  1433. e_model type = MODEL_UNKNOWN;
  1434. llm_arch arch = LLM_ARCH_UNKNOWN;
  1435. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1436. std::string name = "n/a";
  1437. llama_hparams hparams = {};
  1438. llama_vocab vocab;
  1439. struct ggml_tensor * tok_embd;
  1440. struct ggml_tensor * pos_embd;
  1441. struct ggml_tensor * tok_norm;
  1442. struct ggml_tensor * tok_norm_b;
  1443. struct ggml_tensor * output_norm;
  1444. struct ggml_tensor * output_norm_b;
  1445. struct ggml_tensor * output;
  1446. struct ggml_tensor * output_b;
  1447. std::vector<llama_layer> layers;
  1448. llama_split_mode split_mode;
  1449. int main_gpu;
  1450. int n_gpu_layers;
  1451. // gguf metadata
  1452. std::unordered_map<std::string, std::string> gguf_kv;
  1453. // layer -> buffer type mapping
  1454. struct layer_buft {
  1455. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1456. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1457. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1458. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1459. ggml_backend_buffer_type_t buft; // everything else
  1460. };
  1461. layer_buft buft_input;
  1462. layer_buft buft_output;
  1463. std::vector<layer_buft> buft_layer;
  1464. // contexts where the model tensors metadata is stored
  1465. std::vector<struct ggml_context *> ctxs;
  1466. // the model memory buffers for the tensor data
  1467. std::vector<ggml_backend_buffer_t> bufs;
  1468. // model memory mapped file
  1469. std::unique_ptr<llama_mmap> mapping;
  1470. // objects representing data potentially being locked in memory
  1471. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1472. llama_mlock mlock_mmap;
  1473. // for quantize-stats only
  1474. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1475. int64_t t_load_us = 0;
  1476. int64_t t_start_us = 0;
  1477. ~llama_model() {
  1478. for (struct ggml_context * ctx : ctxs) {
  1479. ggml_free(ctx);
  1480. }
  1481. for (ggml_backend_buffer_t buf : bufs) {
  1482. ggml_backend_buffer_free(buf);
  1483. }
  1484. }
  1485. };
  1486. struct llama_context {
  1487. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1488. ~llama_context() {
  1489. ggml_backend_sched_free(sched);
  1490. for (ggml_backend_t backend : backends) {
  1491. ggml_backend_free(backend);
  1492. }
  1493. ggml_backend_buffer_free(buf_input);
  1494. ggml_free(ctx_input);
  1495. }
  1496. llama_cparams cparams;
  1497. std::vector<ggml_backend_t> backends;
  1498. #ifdef GGML_USE_METAL
  1499. ggml_backend_t backend_metal = nullptr;
  1500. #endif
  1501. ggml_backend_t backend_cpu = nullptr;
  1502. const llama_model & model;
  1503. // key + value cache for the self attention
  1504. struct llama_kv_cache kv_self;
  1505. std::mt19937 rng;
  1506. bool has_evaluated_once = false;
  1507. int64_t t_start_us;
  1508. int64_t t_load_us;
  1509. int64_t t_sample_us = 0;
  1510. int64_t t_p_eval_us = 0;
  1511. int64_t t_eval_us = 0;
  1512. int32_t n_sample = 0; // number of tokens sampled
  1513. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1514. int32_t n_eval = 0; // number of eval calls
  1515. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1516. std::vector<float> logits;
  1517. #ifndef NDEBUG
  1518. // guard against access to unset logits
  1519. std::vector<bool> logits_valid;
  1520. #endif
  1521. bool logits_all = false;
  1522. // input embedding (1-dimensional array: [n_embd])
  1523. std::vector<float> embedding;
  1524. // memory buffers used to evaluate the model
  1525. std::vector<uint8_t> buf_compute_meta;
  1526. ggml_backend_sched_t sched = nullptr;
  1527. // allocator for the input tensors
  1528. ggml_tallocr * alloc = nullptr;
  1529. // input tensors
  1530. ggml_backend_buffer_t buf_input = nullptr;
  1531. ggml_context * ctx_input = nullptr;
  1532. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1533. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1534. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1535. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1536. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1537. #ifdef GGML_USE_MPI
  1538. ggml_mpi_context * ctx_mpi = NULL;
  1539. #endif
  1540. };
  1541. //
  1542. // kv cache helpers
  1543. //
  1544. static bool llama_kv_cache_init(
  1545. struct llama_kv_cache & cache,
  1546. const llama_model & model,
  1547. ggml_type ktype,
  1548. ggml_type vtype,
  1549. uint32_t n_ctx,
  1550. bool offload) {
  1551. const struct llama_hparams & hparams = model.hparams;
  1552. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1553. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1554. const int64_t n_layer = hparams.n_layer;
  1555. cache.has_shift = false;
  1556. cache.head = 0;
  1557. cache.size = n_ctx;
  1558. cache.used = 0;
  1559. cache.cells.clear();
  1560. cache.cells.resize(n_ctx);
  1561. #ifdef GGML_USE_CLBLAST
  1562. offload = false;
  1563. #endif
  1564. // count used buffer types
  1565. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1566. if (offload) {
  1567. for (int64_t i = 0; i < n_layer; ++i) {
  1568. buft_layer_count[model.buft_layer[i].buft]++;
  1569. }
  1570. } else {
  1571. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1572. }
  1573. // create a context for each buffer type
  1574. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1575. for (auto & it : buft_layer_count) {
  1576. int n_layers = it.second;
  1577. struct ggml_init_params params = {
  1578. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1579. /*.mem_buffer =*/ NULL,
  1580. /*.no_alloc =*/ true,
  1581. };
  1582. ggml_context * ctx = ggml_init(params);
  1583. if (!ctx) {
  1584. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1585. return false;
  1586. }
  1587. ctx_map[it.first] = ctx;
  1588. cache.ctxs.push_back(ctx);
  1589. }
  1590. cache.k_l.reserve(n_layer);
  1591. cache.v_l.reserve(n_layer);
  1592. for (int i = 0; i < (int) n_layer; i++) {
  1593. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1594. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1595. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1596. ggml_format_name(k, "cache_k_l%d", i);
  1597. ggml_format_name(v, "cache_v_l%d", i);
  1598. cache.k_l.push_back(k);
  1599. cache.v_l.push_back(v);
  1600. }
  1601. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1602. for (auto it : ctx_map) {
  1603. ggml_backend_buffer_type_t buft = it.first;
  1604. ggml_context * ctx = it.second;
  1605. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1606. if (!buf) {
  1607. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1608. return false;
  1609. }
  1610. ggml_backend_buffer_clear(buf, 0);
  1611. LLAMA_LOG_INFO("%s: %10s KV buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf)/1024.0/1024.0);
  1612. cache.bufs.push_back(buf);
  1613. }
  1614. return true;
  1615. }
  1616. // find an empty slot of size "n_tokens" in the cache
  1617. // updates the cache head
  1618. // Note: On success, it's important that cache.head points
  1619. // to the first cell of the slot.
  1620. static bool llama_kv_cache_find_slot(
  1621. struct llama_kv_cache & cache,
  1622. const struct llama_batch & batch) {
  1623. const uint32_t n_ctx = cache.size;
  1624. const uint32_t n_tokens = batch.n_tokens;
  1625. if (n_tokens > n_ctx) {
  1626. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1627. return false;
  1628. }
  1629. uint32_t n_tested = 0;
  1630. while (true) {
  1631. if (cache.head + n_tokens > n_ctx) {
  1632. n_tested += n_ctx - cache.head;
  1633. cache.head = 0;
  1634. continue;
  1635. }
  1636. bool found = true;
  1637. for (uint32_t i = 0; i < n_tokens; i++) {
  1638. if (cache.cells[cache.head + i].pos >= 0) {
  1639. found = false;
  1640. cache.head += i + 1;
  1641. n_tested += i + 1;
  1642. break;
  1643. }
  1644. }
  1645. if (found) {
  1646. break;
  1647. }
  1648. if (n_tested >= n_ctx) {
  1649. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1650. return false;
  1651. }
  1652. }
  1653. for (uint32_t i = 0; i < n_tokens; i++) {
  1654. cache.cells[cache.head + i].pos = batch.pos[i];
  1655. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1656. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1657. }
  1658. }
  1659. cache.used += n_tokens;
  1660. return true;
  1661. }
  1662. // find how many cells are currently in use
  1663. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1664. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1665. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1666. return i + 1;
  1667. }
  1668. }
  1669. return 0;
  1670. }
  1671. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1672. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1673. cache.cells[i].pos = -1;
  1674. cache.cells[i].seq_id.clear();
  1675. }
  1676. cache.head = 0;
  1677. cache.used = 0;
  1678. }
  1679. static void llama_kv_cache_seq_rm(
  1680. struct llama_kv_cache & cache,
  1681. llama_seq_id seq_id,
  1682. llama_pos p0,
  1683. llama_pos p1) {
  1684. uint32_t new_head = cache.size;
  1685. if (p0 < 0) p0 = 0;
  1686. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1687. for (uint32_t i = 0; i < cache.size; ++i) {
  1688. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1689. if (seq_id < 0) {
  1690. cache.cells[i].seq_id.clear();
  1691. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1692. cache.cells[i].seq_id.erase(seq_id);
  1693. } else {
  1694. continue;
  1695. }
  1696. if (cache.cells[i].seq_id.empty()) {
  1697. // keep count of the number of used cells
  1698. if (cache.cells[i].pos >= 0) cache.used--;
  1699. cache.cells[i].pos = -1;
  1700. if (new_head == cache.size) new_head = i;
  1701. }
  1702. }
  1703. }
  1704. // If we freed up a slot, set head to it so searching can start there.
  1705. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1706. }
  1707. static void llama_kv_cache_seq_cp(
  1708. struct llama_kv_cache & cache,
  1709. llama_seq_id seq_id_src,
  1710. llama_seq_id seq_id_dst,
  1711. llama_pos p0,
  1712. llama_pos p1) {
  1713. if (p0 < 0) p0 = 0;
  1714. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1715. cache.head = 0;
  1716. for (uint32_t i = 0; i < cache.size; ++i) {
  1717. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1718. cache.cells[i].seq_id.insert(seq_id_dst);
  1719. }
  1720. }
  1721. }
  1722. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1723. uint32_t new_head = cache.size;
  1724. for (uint32_t i = 0; i < cache.size; ++i) {
  1725. if (!cache.cells[i].has_seq_id(seq_id)) {
  1726. if (cache.cells[i].pos >= 0) cache.used--;
  1727. cache.cells[i].pos = -1;
  1728. cache.cells[i].seq_id.clear();
  1729. if (new_head == cache.size) new_head = i;
  1730. } else {
  1731. cache.cells[i].seq_id.clear();
  1732. cache.cells[i].seq_id.insert(seq_id);
  1733. }
  1734. }
  1735. // If we freed up a slot, set head to it so searching can start there.
  1736. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1737. }
  1738. static void llama_kv_cache_seq_shift(
  1739. struct llama_kv_cache & cache,
  1740. llama_seq_id seq_id,
  1741. llama_pos p0,
  1742. llama_pos p1,
  1743. llama_pos delta) {
  1744. uint32_t new_head = cache.size;
  1745. if (p0 < 0) p0 = 0;
  1746. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1747. for (uint32_t i = 0; i < cache.size; ++i) {
  1748. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1749. cache.has_shift = true;
  1750. cache.cells[i].pos += delta;
  1751. cache.cells[i].delta += delta;
  1752. if (cache.cells[i].pos < 0) {
  1753. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1754. cache.cells[i].pos = -1;
  1755. cache.cells[i].seq_id.clear();
  1756. if (new_head == cache.size) new_head = i;
  1757. }
  1758. }
  1759. }
  1760. // If we freed up a slot, set head to it so searching can start there.
  1761. // Otherwise we just start the next search from the beginning.
  1762. cache.head = new_head != cache.size ? new_head : 0;
  1763. }
  1764. static void llama_kv_cache_seq_div(
  1765. struct llama_kv_cache & cache,
  1766. llama_seq_id seq_id,
  1767. llama_pos p0,
  1768. llama_pos p1,
  1769. int d) {
  1770. if (p0 < 0) p0 = 0;
  1771. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1772. for (uint32_t i = 0; i < cache.size; ++i) {
  1773. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1774. cache.has_shift = true;
  1775. {
  1776. llama_pos p_old = cache.cells[i].pos;
  1777. cache.cells[i].pos /= d;
  1778. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1779. }
  1780. }
  1781. }
  1782. }
  1783. //
  1784. // model loading and saving
  1785. //
  1786. enum llama_fver {
  1787. GGUF_FILE_VERSION_V1 = 1,
  1788. GGUF_FILE_VERSION_V2 = 2,
  1789. GGUF_FILE_VERSION_V3 = 3,
  1790. };
  1791. static const char * llama_file_version_name(llama_fver version) {
  1792. switch (version) {
  1793. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1794. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1795. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1796. }
  1797. return "unknown";
  1798. }
  1799. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1800. char buf[256];
  1801. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1802. for (size_t i = 1; i < ne.size(); i++) {
  1803. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1804. }
  1805. return buf;
  1806. }
  1807. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1808. char buf[256];
  1809. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1810. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1811. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1812. }
  1813. return buf;
  1814. }
  1815. namespace GGUFMeta {
  1816. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1817. struct GKV_Base_Type {
  1818. static constexpr gguf_type gt = gt_;
  1819. static T getter(const gguf_context * ctx, const int kid) {
  1820. return gfun(ctx, kid);
  1821. }
  1822. };
  1823. template<typename T> struct GKV_Base;
  1824. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1825. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1826. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1827. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1828. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1829. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1830. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1831. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1832. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1833. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1834. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1835. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1836. template<> struct GKV_Base<std::string> {
  1837. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1838. static std::string getter(const gguf_context * ctx, const int kid) {
  1839. return gguf_get_val_str(ctx, kid);
  1840. }
  1841. };
  1842. struct ArrayInfo{
  1843. const gguf_type gt;
  1844. const size_t length;
  1845. const void * data;
  1846. };
  1847. template<> struct GKV_Base<ArrayInfo> {
  1848. public:
  1849. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1850. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1851. return ArrayInfo {
  1852. gguf_get_arr_type(ctx, k),
  1853. size_t(gguf_get_arr_n(ctx, k)),
  1854. gguf_get_arr_data(ctx, k),
  1855. };
  1856. }
  1857. };
  1858. template<typename T>
  1859. class GKV: public GKV_Base<T> {
  1860. GKV() = delete;
  1861. public:
  1862. static T get_kv(const gguf_context * ctx, const int k) {
  1863. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1864. if (kt != GKV::gt) {
  1865. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1866. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1867. }
  1868. return GKV::getter(ctx, k);
  1869. }
  1870. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  1871. switch (ty) {
  1872. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  1873. case LLAMA_KV_OVERRIDE_INT: return "int";
  1874. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  1875. }
  1876. return "unknown";
  1877. }
  1878. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  1879. if (!override) { return false; }
  1880. if (override->tag == expected_type) {
  1881. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  1882. __func__, override_type_to_str(override->tag), override->key);
  1883. switch (override->tag) {
  1884. case LLAMA_KV_OVERRIDE_BOOL: {
  1885. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  1886. } break;
  1887. case LLAMA_KV_OVERRIDE_INT: {
  1888. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  1889. } break;
  1890. case LLAMA_KV_OVERRIDE_FLOAT: {
  1891. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  1892. } break;
  1893. default:
  1894. // Shouldn't be possible to end up here, but just in case...
  1895. throw std::runtime_error(
  1896. format("Unsupported attempt to override %s type for metadata key %s\n",
  1897. override_type_to_str(override->tag), override->key));
  1898. }
  1899. return true;
  1900. }
  1901. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  1902. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  1903. return false;
  1904. }
  1905. template<typename OT>
  1906. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  1907. try_override(OT & target, const struct llama_model_kv_override *override) {
  1908. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  1909. target = override->bool_value;
  1910. return true;
  1911. }
  1912. return false;
  1913. }
  1914. template<typename OT>
  1915. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  1916. try_override(OT & target, const struct llama_model_kv_override *override) {
  1917. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  1918. target = override->int_value;
  1919. return true;
  1920. }
  1921. return false;
  1922. }
  1923. template<typename OT>
  1924. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  1925. try_override(T & target, const struct llama_model_kv_override *override) {
  1926. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  1927. target = override->float_value;
  1928. return true;
  1929. }
  1930. return false;
  1931. }
  1932. template<typename OT>
  1933. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  1934. try_override(T & target, const struct llama_model_kv_override *override) {
  1935. (void)target;
  1936. (void)override;
  1937. if (!override) { return false; }
  1938. // Currently, we should never end up here so it would be a bug if we do.
  1939. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  1940. override ? override->key : "NULL"));
  1941. }
  1942. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  1943. if (try_override<T>(target, override)) {
  1944. return true;
  1945. }
  1946. if (k < 0) { return false; }
  1947. target = get_kv(ctx, k);
  1948. return true;
  1949. }
  1950. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1951. return set(ctx, gguf_find_key(ctx, key), target, override);
  1952. }
  1953. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1954. return set(ctx, key.c_str(), target, override);
  1955. }
  1956. };
  1957. }
  1958. struct llama_model_loader {
  1959. int n_kv = 0;
  1960. int n_tensors = 0;
  1961. int n_created = 0;
  1962. int64_t n_elements = 0;
  1963. size_t n_bytes = 0;
  1964. bool use_mmap = false;
  1965. llama_file file;
  1966. llama_ftype ftype;
  1967. llama_fver fver;
  1968. std::unique_ptr<llama_mmap> mapping;
  1969. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  1970. struct gguf_context * ctx_gguf = NULL;
  1971. struct ggml_context * ctx_meta = NULL;
  1972. std::string arch_name;
  1973. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1974. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  1975. int trace = 0;
  1976. if (getenv("LLAMA_TRACE")) {
  1977. trace = atoi(getenv("LLAMA_TRACE"));
  1978. }
  1979. struct gguf_init_params params = {
  1980. /*.no_alloc = */ true,
  1981. /*.ctx = */ &ctx_meta,
  1982. };
  1983. if (param_overrides_p != nullptr) {
  1984. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  1985. kv_overrides.insert({std::string(p->key), *p});
  1986. }
  1987. }
  1988. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1989. if (!ctx_gguf) {
  1990. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1991. }
  1992. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  1993. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  1994. n_kv = gguf_get_n_kv(ctx_gguf);
  1995. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1996. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1997. for (int i = 0; i < n_tensors; i++) {
  1998. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1999. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2000. n_elements += ggml_nelements(t);
  2001. n_bytes += ggml_nbytes(t);
  2002. }
  2003. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2004. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2005. // determine file type based on the number of tensors for each quantization and print meta data
  2006. // TODO: make optional
  2007. {
  2008. std::map<enum ggml_type, uint32_t> n_type;
  2009. uint32_t n_type_max = 0;
  2010. enum ggml_type type_max = GGML_TYPE_F32;
  2011. for (int i = 0; i < n_tensors; i++) {
  2012. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2013. n_type[type]++;
  2014. if (n_type_max < n_type[type]) {
  2015. n_type_max = n_type[type];
  2016. type_max = type;
  2017. }
  2018. if (trace > 0) {
  2019. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2020. LLAMA_LOG_INFO("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, ggml_get_name(meta), ggml_type_name(type), llama_format_tensor_shape(meta).c_str());
  2021. }
  2022. }
  2023. switch (type_max) {
  2024. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2025. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2026. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2027. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2028. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2029. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2030. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2031. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2032. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2033. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2034. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2035. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2036. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2037. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2038. default:
  2039. {
  2040. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2041. ftype = LLAMA_FTYPE_ALL_F32;
  2042. } break;
  2043. }
  2044. // this is a way to mark that we have "guessed" the file type
  2045. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2046. {
  2047. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2048. if (kid >= 0) {
  2049. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2050. }
  2051. }
  2052. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2053. for (int i = 0; i < n_kv; i++) {
  2054. const char * name = gguf_get_key(ctx_gguf, i);
  2055. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2056. const std::string type_name =
  2057. type == GGUF_TYPE_ARRAY
  2058. ? 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))
  2059. : gguf_type_name(type);
  2060. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2061. const size_t MAX_VALUE_LEN = 40;
  2062. if (value.size() > MAX_VALUE_LEN) {
  2063. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2064. }
  2065. replace_all(value, "\n", "\\n");
  2066. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2067. }
  2068. // print type counts
  2069. for (auto & kv : n_type) {
  2070. if (kv.second == 0) {
  2071. continue;
  2072. }
  2073. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2074. }
  2075. }
  2076. if (!llama_mmap::SUPPORTED) {
  2077. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2078. use_mmap = false;
  2079. }
  2080. this->use_mmap = use_mmap;
  2081. }
  2082. ~llama_model_loader() {
  2083. if (ctx_gguf) {
  2084. gguf_free(ctx_gguf);
  2085. }
  2086. if (ctx_meta) {
  2087. ggml_free(ctx_meta);
  2088. }
  2089. }
  2090. template<typename T>
  2091. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2092. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2093. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2094. if (kid < 0) {
  2095. if (required) {
  2096. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2097. }
  2098. return false;
  2099. }
  2100. struct GGUFMeta::ArrayInfo arr_info =
  2101. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2102. result = arr_info.length;
  2103. return true;
  2104. }
  2105. template<typename T>
  2106. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2107. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2108. return get_arr_n(llm_kv(kid), result, required);
  2109. }
  2110. template<typename T>
  2111. bool get_key(const std::string & key, T & result, const bool required = true) {
  2112. auto it = kv_overrides.find(key);
  2113. const struct llama_model_kv_override * override =
  2114. it != kv_overrides.end() ? &it->second : nullptr;
  2115. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2116. if (required && !found) {
  2117. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2118. }
  2119. return found;
  2120. }
  2121. template<typename T>
  2122. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2123. return get_key(llm_kv(kid), result, required);
  2124. }
  2125. std::string get_arch_name() const {
  2126. return arch_name;
  2127. }
  2128. enum llm_arch get_arch() const {
  2129. return llm_kv.arch;
  2130. }
  2131. const char * get_tensor_name(int i) const {
  2132. return gguf_get_tensor_name(ctx_gguf, i);
  2133. }
  2134. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2135. return ggml_get_tensor(ctx_meta, name);
  2136. }
  2137. struct ggml_tensor * get_tensor_meta(int i) const {
  2138. return get_tensor_meta(get_tensor_name(i));
  2139. }
  2140. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2141. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2142. ggml_set_name(tensor, ggml_get_name(meta));
  2143. n_created++;
  2144. return tensor;
  2145. }
  2146. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2147. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2148. if (cur == NULL) {
  2149. if (!required) {
  2150. return NULL;
  2151. }
  2152. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2153. }
  2154. {
  2155. bool is_ok = true;
  2156. for (size_t i = 0; i < ne.size(); ++i) {
  2157. if (ne[i] != cur->ne[i]) {
  2158. is_ok = false;
  2159. break;
  2160. }
  2161. }
  2162. if (!is_ok) {
  2163. throw std::runtime_error(
  2164. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2165. __func__, name.c_str(),
  2166. llama_format_tensor_shape(ne).c_str(),
  2167. llama_format_tensor_shape(cur).c_str()));
  2168. }
  2169. }
  2170. return create_tensor_for(ctx, cur);
  2171. }
  2172. void done_getting_tensors() const {
  2173. if (n_created != n_tensors) {
  2174. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2175. }
  2176. }
  2177. size_t file_offset(const char * name) const {
  2178. const int idx = gguf_find_tensor(ctx_gguf, name);
  2179. if (idx < 0) {
  2180. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2181. }
  2182. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2183. }
  2184. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2185. // prefetch the whole file - all the data is needed anyway
  2186. if (use_mmap) {
  2187. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2188. }
  2189. // compute the total size of all tensors for progress reporting
  2190. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2191. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2192. size_data += ggml_nbytes(cur);
  2193. }
  2194. if (use_mmap && mapping) {
  2195. if (lmlock) {
  2196. lmlock->init(mapping->addr);
  2197. }
  2198. mmap_used_first = mapping->size;
  2199. }
  2200. }
  2201. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2202. GGML_ASSERT(mapping);
  2203. *first = mapping->size;
  2204. *last = 0;
  2205. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2206. const size_t offs = file_offset(ggml_get_name(tensor));
  2207. *first = std::min(*first, offs);
  2208. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2209. }
  2210. }
  2211. // for backwards compatibility, does not support ggml-backend
  2212. void load_data_for(struct ggml_tensor * cur) const {
  2213. const size_t offs = file_offset(ggml_get_name(cur));
  2214. if (use_mmap && mapping) {
  2215. if (cur->data == nullptr) {
  2216. cur->data = (uint8_t *)mapping->addr + offs;
  2217. } else {
  2218. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2219. }
  2220. } else {
  2221. GGML_ASSERT(cur->data != nullptr);
  2222. file.seek(offs, SEEK_SET);
  2223. file.read_raw(cur->data, ggml_nbytes(cur));
  2224. }
  2225. }
  2226. size_t size_done = 0;
  2227. size_t size_data = 0;
  2228. size_t mmap_used_first = -1;
  2229. size_t mmap_used_last = 0;
  2230. // Returns false if cancelled by progress_callback
  2231. bool load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, ggml_backend_buffer_t buf_mmap, llama_mlock * lmlock) {
  2232. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2233. std::vector<no_init<uint8_t>> read_buf;
  2234. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2235. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2236. if (!cur) {
  2237. // some tensors may be allocated in a different context
  2238. continue;
  2239. }
  2240. if (progress_callback) {
  2241. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2242. return false;
  2243. }
  2244. }
  2245. const size_t offs = file_offset(ggml_get_name(cur));
  2246. if (use_mmap && mapping) {
  2247. if (buf_mmap && cur->data == nullptr) {
  2248. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2249. if (lmlock) {
  2250. lmlock->grow_to(offs + ggml_nbytes(cur));
  2251. }
  2252. mmap_used_first = std::min(mmap_used_first, offs);
  2253. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2254. } else {
  2255. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2256. }
  2257. } else {
  2258. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2259. file.seek(offs, SEEK_SET);
  2260. file.read_raw(cur->data, ggml_nbytes(cur));
  2261. } else {
  2262. read_buf.resize(ggml_nbytes(cur));
  2263. file.seek(offs, SEEK_SET);
  2264. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2265. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2266. }
  2267. }
  2268. size_done += ggml_nbytes(cur);
  2269. }
  2270. // check if this is the last call and do final cleanup
  2271. if (size_done >= size_data) {
  2272. // unmap offloaded tensors and metadata
  2273. if (use_mmap && mapping) {
  2274. mapping->unmap_fragment(0, mmap_used_first);
  2275. if (mmap_used_last != 0) {
  2276. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2277. }
  2278. }
  2279. if (progress_callback) {
  2280. // Even though the model is done loading, we still honor
  2281. // cancellation since we need to free allocations.
  2282. return progress_callback(1.0f, progress_callback_user_data);
  2283. }
  2284. }
  2285. return true;
  2286. }
  2287. };
  2288. //
  2289. // load LLaMA models
  2290. //
  2291. static std::string llama_model_arch_name(llm_arch arch) {
  2292. auto it = LLM_ARCH_NAMES.find(arch);
  2293. if (it == LLM_ARCH_NAMES.end()) {
  2294. return "unknown";
  2295. }
  2296. return it->second;
  2297. }
  2298. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2299. if (ftype & LLAMA_FTYPE_GUESSED) {
  2300. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2301. }
  2302. switch (ftype) {
  2303. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2304. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2305. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2306. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2307. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2308. return "Q4_1, some F16";
  2309. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2310. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2311. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2312. // K-quants
  2313. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2314. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2315. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2316. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2317. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2318. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2319. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2320. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2321. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2322. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2323. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XSS - 2.0625 bpw";
  2324. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2325. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:return "Q3_K - Extra small";
  2326. default: return "unknown, may not work";
  2327. }
  2328. }
  2329. static const char * llama_model_type_name(e_model type) {
  2330. switch (type) {
  2331. case MODEL_1B: return "1B";
  2332. case MODEL_3B: return "3B";
  2333. case MODEL_7B: return "7B";
  2334. case MODEL_8B: return "8B";
  2335. case MODEL_13B: return "13B";
  2336. case MODEL_14B: return "14B";
  2337. case MODEL_15B: return "15B";
  2338. case MODEL_30B: return "30B";
  2339. case MODEL_34B: return "34B";
  2340. case MODEL_40B: return "40B";
  2341. case MODEL_65B: return "65B";
  2342. case MODEL_70B: return "70B";
  2343. case MODEL_SMALL: return "0.1B";
  2344. case MODEL_MEDIUM: return "0.4B";
  2345. case MODEL_LARGE: return "0.8B";
  2346. case MODEL_XL: return "1.5B";
  2347. default: return "?B";
  2348. }
  2349. }
  2350. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2351. model.arch = ml.get_arch();
  2352. if (model.arch == LLM_ARCH_UNKNOWN) {
  2353. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2354. }
  2355. }
  2356. static void llm_load_hparams(
  2357. llama_model_loader & ml,
  2358. llama_model & model) {
  2359. auto & hparams = model.hparams;
  2360. const gguf_context * ctx = ml.ctx_gguf;
  2361. // get metadata as string
  2362. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2363. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2364. if (type == GGUF_TYPE_ARRAY) {
  2365. continue;
  2366. }
  2367. const char * name = gguf_get_key(ctx, i);
  2368. const std::string value = gguf_kv_to_str(ctx, i);
  2369. model.gguf_kv.emplace(name, value);
  2370. }
  2371. // get general kv
  2372. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2373. // get hparams kv
  2374. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2375. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2376. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2377. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2378. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2379. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2380. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2381. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2382. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2383. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2384. if (hparams.n_expert > 0) {
  2385. GGML_ASSERT(hparams.n_expert_used > 0);
  2386. } else {
  2387. GGML_ASSERT(hparams.n_expert_used == 0);
  2388. }
  2389. // n_head_kv is optional, default to n_head
  2390. hparams.n_head_kv = hparams.n_head;
  2391. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2392. bool rope_finetuned = false;
  2393. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2394. hparams.rope_finetuned = rope_finetuned;
  2395. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2396. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2397. // rope_freq_base (optional)
  2398. hparams.rope_freq_base_train = 10000.0f;
  2399. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2400. std::string rope_scaling("linear");
  2401. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2402. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2403. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2404. // rope_freq_scale (inverse of the kv) is optional
  2405. float ropescale = 0.0f;
  2406. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2407. // try the old key name
  2408. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2409. }
  2410. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2411. // sanity check for n_rot (optional)
  2412. {
  2413. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2414. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2415. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2416. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2417. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2418. }
  2419. }
  2420. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2421. // gpt-j n_rot = rotary_dim
  2422. }
  2423. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2424. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2425. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2426. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2427. // arch-specific KVs
  2428. switch (model.arch) {
  2429. case LLM_ARCH_LLAMA:
  2430. {
  2431. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2432. switch (hparams.n_layer) {
  2433. case 22: model.type = e_model::MODEL_1B; break;
  2434. case 26: model.type = e_model::MODEL_3B; break;
  2435. case 32: model.type = e_model::MODEL_7B; break;
  2436. case 40: model.type = e_model::MODEL_13B; break;
  2437. case 48: model.type = e_model::MODEL_34B; break;
  2438. case 60: model.type = e_model::MODEL_30B; break;
  2439. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2440. default: model.type = e_model::MODEL_UNKNOWN;
  2441. }
  2442. } break;
  2443. case LLM_ARCH_FALCON:
  2444. {
  2445. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2446. switch (hparams.n_layer) {
  2447. case 32: model.type = e_model::MODEL_7B; break;
  2448. case 60: model.type = e_model::MODEL_40B; break;
  2449. default: model.type = e_model::MODEL_UNKNOWN;
  2450. }
  2451. } break;
  2452. case LLM_ARCH_BAICHUAN:
  2453. {
  2454. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2455. switch (hparams.n_layer) {
  2456. case 32: model.type = e_model::MODEL_7B; break;
  2457. case 40: model.type = e_model::MODEL_13B; break;
  2458. default: model.type = e_model::MODEL_UNKNOWN;
  2459. }
  2460. } break;
  2461. case LLM_ARCH_STARCODER:
  2462. {
  2463. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2464. switch (hparams.n_layer) {
  2465. case 24: model.type = e_model::MODEL_1B; break;
  2466. case 36: model.type = e_model::MODEL_3B; break;
  2467. case 42: model.type = e_model::MODEL_7B; break;
  2468. case 40: model.type = e_model::MODEL_15B; break;
  2469. default: model.type = e_model::MODEL_UNKNOWN;
  2470. }
  2471. } break;
  2472. case LLM_ARCH_PERSIMMON:
  2473. {
  2474. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2475. switch (hparams.n_layer) {
  2476. case 36: model.type = e_model::MODEL_8B; break;
  2477. default: model.type = e_model::MODEL_UNKNOWN;
  2478. }
  2479. } break;
  2480. case LLM_ARCH_REFACT:
  2481. {
  2482. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2483. switch (hparams.n_layer) {
  2484. case 32: model.type = e_model::MODEL_1B; break;
  2485. default: model.type = e_model::MODEL_UNKNOWN;
  2486. }
  2487. } break;
  2488. case LLM_ARCH_BLOOM:
  2489. {
  2490. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2491. switch (hparams.n_layer) {
  2492. case 24: model.type = e_model::MODEL_1B; break;
  2493. case 30:
  2494. switch (hparams.n_embd) {
  2495. case 2560: model.type = e_model::MODEL_3B; break;
  2496. case 4096: model.type = e_model::MODEL_7B; break;
  2497. } break;
  2498. }
  2499. } break;
  2500. case LLM_ARCH_MPT:
  2501. {
  2502. hparams.f_clamp_kqv = 0.0f;
  2503. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2504. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2505. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2506. switch (hparams.n_layer) {
  2507. case 32: model.type = e_model::MODEL_7B; break;
  2508. case 48: model.type = e_model::MODEL_30B; break;
  2509. default: model.type = e_model::MODEL_UNKNOWN;
  2510. }
  2511. } break;
  2512. case LLM_ARCH_STABLELM:
  2513. {
  2514. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2515. switch (hparams.n_layer) {
  2516. case 24: model.type = e_model::MODEL_1B; break;
  2517. case 32: model.type = e_model::MODEL_3B; break;
  2518. default: model.type = e_model::MODEL_UNKNOWN;
  2519. }
  2520. } break;
  2521. case LLM_ARCH_QWEN:
  2522. {
  2523. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2524. switch (hparams.n_layer) {
  2525. case 32: model.type = e_model::MODEL_7B; break;
  2526. case 40: model.type = e_model::MODEL_13B; break;
  2527. default: model.type = e_model::MODEL_UNKNOWN;
  2528. }
  2529. } break;
  2530. case LLM_ARCH_QWEN2:
  2531. {
  2532. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2533. switch (hparams.n_layer) {
  2534. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2535. case 32: model.type = e_model::MODEL_7B; break;
  2536. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2537. case 80: model.type = e_model::MODEL_70B; break;
  2538. default: model.type = e_model::MODEL_UNKNOWN;
  2539. }
  2540. } break;
  2541. case LLM_ARCH_PHI2:
  2542. {
  2543. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2544. switch (hparams.n_layer) {
  2545. case 24: model.type = e_model::MODEL_1B; break;
  2546. case 32: model.type = e_model::MODEL_3B; break;
  2547. default: model.type = e_model::MODEL_UNKNOWN;
  2548. }
  2549. } break;
  2550. case LLM_ARCH_PLAMO:
  2551. {
  2552. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2553. switch (hparams.n_layer) {
  2554. case 40: model.type = e_model::MODEL_13B; break;
  2555. default: model.type = e_model::MODEL_UNKNOWN;
  2556. }
  2557. } break;
  2558. case LLM_ARCH_GPT2:
  2559. {
  2560. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2561. switch (hparams.n_layer) {
  2562. case 12: model.type = e_model::MODEL_SMALL; break;
  2563. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2564. case 36: model.type = e_model::MODEL_LARGE; break;
  2565. case 48: model.type = e_model::MODEL_XL; break;
  2566. default: model.type = e_model::MODEL_UNKNOWN;
  2567. }
  2568. } break;
  2569. case LLM_ARCH_CODESHELL:
  2570. {
  2571. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2572. switch (hparams.n_layer) {
  2573. case 42: model.type = e_model::MODEL_SMALL; break;
  2574. default: model.type = e_model::MODEL_UNKNOWN;
  2575. }
  2576. } break;
  2577. case LLM_ARCH_ORION:
  2578. {
  2579. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2580. switch (hparams.n_layer) {
  2581. case 40: model.type = e_model::MODEL_14B; break;
  2582. default: model.type = e_model::MODEL_UNKNOWN;
  2583. }
  2584. } break;
  2585. default: (void)0;
  2586. }
  2587. model.ftype = ml.ftype;
  2588. }
  2589. // TODO: This should probably be in llama.h
  2590. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2591. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2592. static void llm_load_vocab(
  2593. llama_model_loader & ml,
  2594. llama_model & model) {
  2595. auto & vocab = model.vocab;
  2596. struct gguf_context * ctx = ml.ctx_gguf;
  2597. const auto kv = LLM_KV(model.arch);
  2598. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2599. if (token_idx == -1) {
  2600. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2601. }
  2602. const float * scores = nullptr;
  2603. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2604. if (score_idx != -1) {
  2605. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2606. }
  2607. const int * toktypes = nullptr;
  2608. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2609. if (toktype_idx != -1) {
  2610. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2611. }
  2612. // determine vocab type
  2613. {
  2614. std::string tokenizer_name;
  2615. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2616. if (tokenizer_name == "llama") {
  2617. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2618. // default special tokens
  2619. vocab.special_bos_id = 1;
  2620. vocab.special_eos_id = 2;
  2621. vocab.special_unk_id = 0;
  2622. vocab.special_sep_id = -1;
  2623. vocab.special_pad_id = -1;
  2624. } else if (tokenizer_name == "gpt2") {
  2625. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2626. // read bpe merges and populate bpe ranks
  2627. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2628. if (merges_keyidx == -1) {
  2629. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2630. }
  2631. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2632. for (int i = 0; i < n_merges; i++) {
  2633. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2634. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2635. std::string first;
  2636. std::string second;
  2637. const size_t pos = word.find(' ', 1);
  2638. if (pos != std::string::npos) {
  2639. first = word.substr(0, pos);
  2640. second = word.substr(pos + 1);
  2641. }
  2642. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2643. }
  2644. // default special tokens
  2645. vocab.special_bos_id = 11;
  2646. vocab.special_eos_id = 11;
  2647. vocab.special_unk_id = -1;
  2648. vocab.special_sep_id = -1;
  2649. vocab.special_pad_id = -1;
  2650. } else {
  2651. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2652. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2653. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2654. }
  2655. }
  2656. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2657. vocab.id_to_token.resize(n_vocab);
  2658. for (uint32_t i = 0; i < n_vocab; i++) {
  2659. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2660. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2661. vocab.token_to_id[word] = i;
  2662. auto & token_data = vocab.id_to_token[i];
  2663. token_data.text = std::move(word);
  2664. token_data.score = scores ? scores[i] : 0.0f;
  2665. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2666. }
  2667. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2668. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2669. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2670. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2671. } else {
  2672. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2673. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2674. vocab.linefeed_id = ids[0];
  2675. }
  2676. // special tokens
  2677. {
  2678. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2679. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2680. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2681. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2682. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2683. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2684. };
  2685. for (const auto & it : special_token_types) {
  2686. const std::string & key = kv(std::get<0>(it));
  2687. int32_t & id = std::get<1>(it);
  2688. uint32_t new_id;
  2689. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2690. continue;
  2691. }
  2692. if (new_id >= vocab.id_to_token.size()) {
  2693. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2694. __func__, key.c_str(), new_id, id);
  2695. } else {
  2696. id = new_id;
  2697. }
  2698. }
  2699. // Handle add_bos_token and add_eos_token
  2700. {
  2701. bool temp = true;
  2702. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2703. vocab.special_add_bos = int(temp);
  2704. }
  2705. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2706. vocab.special_add_eos = int(temp);
  2707. }
  2708. }
  2709. }
  2710. // build special tokens cache
  2711. {
  2712. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2713. // and will always be correctly labeled in 'added_tokens.json' etc.
  2714. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2715. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2716. // are special tokens.
  2717. // From testing, this appears to correlate 1:1 with special tokens.
  2718. //
  2719. // Counting special tokens and verifying in only one direction
  2720. // is sufficient to detect difference in those two sets.
  2721. //
  2722. uint32_t special_tokens_count_by_type = 0;
  2723. uint32_t special_tokens_count_from_verification = 0;
  2724. bool special_tokens_definition_mismatch = false;
  2725. for (const auto & t : vocab.token_to_id) {
  2726. const auto & token = t.first;
  2727. const auto & id = t.second;
  2728. // Count all non-normal tokens in the vocab while iterating
  2729. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2730. special_tokens_count_by_type++;
  2731. }
  2732. // Skip single character tokens
  2733. if (token.length() > 1) {
  2734. bool is_tokenizable = false;
  2735. // Split token string representation in two, in all possible ways
  2736. // and check if both halves can be matched to a valid token
  2737. for (unsigned i = 1; i < token.length();) {
  2738. const auto left = token.substr(0, i);
  2739. const auto right = token.substr(i);
  2740. // check if we didnt partition in the middle of a utf sequence
  2741. auto utf = utf8_len(left.at(left.length() - 1));
  2742. if (utf == 1) {
  2743. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2744. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2745. is_tokenizable = true;
  2746. break;
  2747. }
  2748. i++;
  2749. } else {
  2750. // skip over the rest of multibyte utf sequence
  2751. i += utf - 1;
  2752. }
  2753. }
  2754. if (!is_tokenizable) {
  2755. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2756. // it's faster to re-filter them here, since there are way less candidates now
  2757. // Calculate a total "utf" length of a token string representation
  2758. size_t utf8_str_len = 0;
  2759. for (unsigned i = 0; i < token.length();) {
  2760. utf8_str_len++;
  2761. i += utf8_len(token.at(i));
  2762. }
  2763. // And skip the ones which are one character
  2764. if (utf8_str_len > 1) {
  2765. // At this point what we have left are special tokens only
  2766. vocab.special_tokens_cache[token] = id;
  2767. // Count manually found special tokens
  2768. special_tokens_count_from_verification++;
  2769. // If this manually found special token is not marked as such, flag a mismatch
  2770. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2771. special_tokens_definition_mismatch = true;
  2772. }
  2773. }
  2774. }
  2775. }
  2776. }
  2777. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2778. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2779. __func__,
  2780. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2781. special_tokens_count_by_type, vocab.id_to_token.size()
  2782. );
  2783. } else {
  2784. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2785. __func__,
  2786. special_tokens_count_from_verification, vocab.id_to_token.size()
  2787. );
  2788. }
  2789. }
  2790. }
  2791. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2792. const auto & hparams = model.hparams;
  2793. const auto & vocab = model.vocab;
  2794. const auto rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2795. // hparams
  2796. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2797. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  2798. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  2799. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2800. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2801. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2802. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2803. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2804. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2805. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2806. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  2807. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  2808. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  2809. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2810. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  2811. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  2812. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2813. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2814. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2815. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2816. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2817. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  2818. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  2819. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type.c_str());
  2820. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2821. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2822. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  2823. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  2824. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2825. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2826. if (ml.n_elements >= 1e12) {
  2827. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  2828. } else if (ml.n_elements >= 1e9) {
  2829. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2830. } else if (ml.n_elements >= 1e6) {
  2831. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  2832. } else {
  2833. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  2834. }
  2835. if (ml.n_bytes < GiB) {
  2836. 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);
  2837. } else {
  2838. 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);
  2839. }
  2840. // general kv
  2841. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2842. // special tokens
  2843. 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() ); }
  2844. 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() ); }
  2845. 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() ); }
  2846. 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() ); }
  2847. 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() ); }
  2848. 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() ); }
  2849. }
  2850. // Returns false if cancelled by progress_callback
  2851. static bool llm_load_tensors(
  2852. llama_model_loader & ml,
  2853. llama_model & model,
  2854. int n_gpu_layers,
  2855. enum llama_split_mode split_mode,
  2856. int main_gpu,
  2857. const float * tensor_split,
  2858. bool use_mlock,
  2859. llama_progress_callback progress_callback,
  2860. void * progress_callback_user_data) {
  2861. model.t_start_us = ggml_time_us();
  2862. auto & hparams = model.hparams;
  2863. model.split_mode = split_mode;
  2864. model.main_gpu = main_gpu;
  2865. model.n_gpu_layers = n_gpu_layers;
  2866. const int64_t n_layer = hparams.n_layer;
  2867. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  2868. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  2869. model.buft_input = llama_default_buffer_type_cpu(true);
  2870. model.buft_layer.resize(n_layer);
  2871. // assign cpu layers
  2872. for (int64_t i = 0; i < i_gpu_start; ++i) {
  2873. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  2874. }
  2875. #ifdef GGML_USE_CUBLAS
  2876. if (split_mode == LLAMA_SPLIT_LAYER) {
  2877. // calculate the split points
  2878. int device_count = ggml_backend_cuda_get_device_count();
  2879. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  2880. float splits[GGML_CUDA_MAX_DEVICES];
  2881. if (all_zero) {
  2882. // default split, by free memory
  2883. for (int i = 0; i < device_count; ++i) {
  2884. size_t total;
  2885. size_t free;
  2886. ggml_backend_cuda_get_device_memory(i, &total, &free);
  2887. splits[i] = free;
  2888. }
  2889. } else {
  2890. std::copy(tensor_split, tensor_split + device_count, splits);
  2891. }
  2892. // sum and normalize the splits to get the split points
  2893. float split_sum = 0.0f;
  2894. for (int i = 0; i < device_count; ++i) {
  2895. split_sum += splits[i];
  2896. splits[i] = split_sum;
  2897. }
  2898. for (int i = 0; i < device_count; ++i) {
  2899. splits[i] /= split_sum;
  2900. }
  2901. // assign the repeating layers to the devices according to the splits
  2902. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  2903. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2904. int layer_gpu = std::upper_bound(splits, splits + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits;
  2905. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  2906. }
  2907. // assign the output layer
  2908. if (n_gpu_layers > n_layer) {
  2909. int layer_gpu = std::upper_bound(splits, splits + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits;
  2910. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  2911. } else {
  2912. model.buft_output = llama_default_buffer_type_cpu(true);
  2913. }
  2914. } else
  2915. #endif
  2916. {
  2917. ggml_backend_buffer_type_t split_buft;
  2918. if (split_mode == LLAMA_SPLIT_ROW) {
  2919. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  2920. } else {
  2921. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  2922. split_buft = llama_default_buffer_type_offload(main_gpu);
  2923. }
  2924. // assign the repeating layers
  2925. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2926. model.buft_layer[i] = {
  2927. split_buft,
  2928. llama_default_buffer_type_offload(main_gpu)
  2929. };
  2930. }
  2931. // assign the output layer
  2932. if (n_gpu_layers > n_layer) {
  2933. model.buft_output = {
  2934. split_buft,
  2935. llama_default_buffer_type_offload(main_gpu)
  2936. };
  2937. } else {
  2938. model.buft_output = llama_default_buffer_type_cpu(true);
  2939. }
  2940. }
  2941. // count used buffer types
  2942. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2943. buft_layer_count[model.buft_input.buft]++;
  2944. buft_layer_count[model.buft_input.buft_matrix]++;
  2945. buft_layer_count[model.buft_output.buft]++;
  2946. buft_layer_count[model.buft_output.buft_matrix]++;
  2947. for (int64_t i = 0; i < n_layer; ++i) {
  2948. buft_layer_count[model.buft_layer[i].buft]++;
  2949. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  2950. }
  2951. // create one context per buffer type
  2952. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  2953. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2954. for (auto & it : buft_layer_count) {
  2955. struct ggml_init_params params = {
  2956. /*.mem_size =*/ ctx_size,
  2957. /*.mem_buffer =*/ NULL,
  2958. /*.no_alloc =*/ true,
  2959. };
  2960. ggml_context * ctx = ggml_init(params);
  2961. if (!ctx) {
  2962. throw std::runtime_error(format("failed to create context"));
  2963. }
  2964. ctx_map[it.first] = ctx;
  2965. model.ctxs.push_back(ctx);
  2966. }
  2967. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  2968. // create tensors for the weights
  2969. {
  2970. const int64_t n_embd = hparams.n_embd;
  2971. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  2972. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  2973. const int64_t n_embd_gqa = n_embd_v_gqa;
  2974. const int64_t n_vocab = hparams.n_vocab;
  2975. const int64_t n_ff = hparams.n_ff;
  2976. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  2977. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  2978. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  2979. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  2980. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  2981. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  2982. model.layers.resize(n_layer);
  2983. const auto tn = LLM_TN(model.arch);
  2984. switch (model.arch) {
  2985. case LLM_ARCH_LLAMA:
  2986. case LLM_ARCH_REFACT:
  2987. {
  2988. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2989. // output
  2990. {
  2991. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2992. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2993. }
  2994. for (int i = 0; i < n_layer; ++i) {
  2995. ggml_context * ctx_layer = ctx_for_layer(i);
  2996. ggml_context * ctx_split = ctx_for_layer_split(i);
  2997. auto & layer = model.layers[i];
  2998. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2999. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3000. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3001. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3002. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3003. // optional bias tensors
  3004. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3005. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3006. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3007. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3008. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3009. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3010. if (layer.ffn_gate_inp == nullptr) {
  3011. GGML_ASSERT(hparams.n_expert == 0);
  3012. GGML_ASSERT(hparams.n_expert_used == 0);
  3013. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3014. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3015. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3016. } else {
  3017. GGML_ASSERT(hparams.n_expert > 0);
  3018. GGML_ASSERT(hparams.n_expert_used > 0);
  3019. // MoE branch
  3020. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3021. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3022. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3023. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3024. }
  3025. }
  3026. }
  3027. } break;
  3028. case LLM_ARCH_BAICHUAN:
  3029. {
  3030. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3031. {
  3032. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3033. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3034. }
  3035. for (int i = 0; i < n_layer; ++i) {
  3036. ggml_context * ctx_layer = ctx_for_layer(i);
  3037. ggml_context * ctx_split = ctx_for_layer_split(i);
  3038. auto & layer = model.layers[i];
  3039. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3040. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3041. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3042. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3043. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3044. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3045. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3046. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3047. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3048. }
  3049. } break;
  3050. case LLM_ARCH_FALCON:
  3051. {
  3052. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3053. // output
  3054. {
  3055. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3056. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3057. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3058. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3059. } else {
  3060. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3061. ml.n_created--; // artificial tensor
  3062. }
  3063. }
  3064. for (int i = 0; i < n_layer; ++i) {
  3065. ggml_context * ctx_layer = ctx_for_layer(i);
  3066. ggml_context * ctx_split = ctx_for_layer_split(i);
  3067. auto & layer = model.layers[i];
  3068. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3069. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3070. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3071. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3072. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3073. }
  3074. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3075. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3076. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3077. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3078. }
  3079. } break;
  3080. case LLM_ARCH_STARCODER:
  3081. {
  3082. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3083. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3084. // output
  3085. {
  3086. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3087. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3088. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3089. }
  3090. for (int i = 0; i < n_layer; ++i) {
  3091. ggml_context * ctx_layer = ctx_for_layer(i);
  3092. ggml_context * ctx_split = ctx_for_layer_split(i);
  3093. auto & layer = model.layers[i];
  3094. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3095. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3096. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3097. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3098. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3099. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3100. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3101. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3102. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3103. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3104. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3105. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3106. }
  3107. } break;
  3108. case LLM_ARCH_PERSIMMON:
  3109. {
  3110. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3111. {
  3112. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3113. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3114. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3115. }
  3116. for (int i = 0; i < n_layer; ++i) {
  3117. ggml_context * ctx_layer = ctx_for_layer(i);
  3118. ggml_context * ctx_split = ctx_for_layer_split(i);
  3119. auto & layer = model.layers[i];
  3120. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3121. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3122. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3123. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3124. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3125. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3126. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3127. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3128. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3129. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3130. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3131. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3132. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3133. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3134. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3135. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3136. }
  3137. } break;
  3138. case LLM_ARCH_BLOOM:
  3139. {
  3140. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3141. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3142. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3143. // output
  3144. {
  3145. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3146. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3147. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3148. }
  3149. for (int i = 0; i < n_layer; ++i) {
  3150. ggml_context * ctx_layer = ctx_for_layer(i);
  3151. ggml_context * ctx_split = ctx_for_layer_split(i);
  3152. auto & layer = model.layers[i];
  3153. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3154. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3155. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3156. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3157. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3158. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3159. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3160. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3161. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3162. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3163. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3164. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3165. }
  3166. } break;
  3167. case LLM_ARCH_MPT:
  3168. {
  3169. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3170. // output
  3171. {
  3172. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3173. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3174. }
  3175. for (int i = 0; i < n_layer; ++i) {
  3176. ggml_context * ctx_layer = ctx_for_layer(i);
  3177. ggml_context * ctx_split = ctx_for_layer_split(i);
  3178. auto & layer = model.layers[i];
  3179. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3180. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3181. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3182. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3183. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3184. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3185. // AWQ ScaleActivation layer
  3186. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3187. }
  3188. } break;
  3189. case LLM_ARCH_STABLELM:
  3190. {
  3191. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3192. // output
  3193. {
  3194. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3195. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3196. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3197. }
  3198. for (int i = 0; i < n_layer; ++i) {
  3199. ggml_context * ctx_layer = ctx_for_layer(i);
  3200. ggml_context * ctx_split = ctx_for_layer_split(i);
  3201. auto & layer = model.layers[i];
  3202. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3203. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3204. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3205. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3206. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3207. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3208. // optional bias tensors, present in Stable LM 2 1.6B
  3209. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3210. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3211. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3212. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3213. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3214. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3215. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3216. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3217. }
  3218. } break;
  3219. case LLM_ARCH_QWEN:
  3220. {
  3221. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3222. // output
  3223. {
  3224. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3225. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3226. }
  3227. for (int i = 0; i < n_layer; ++i) {
  3228. ggml_context * ctx_layer = ctx_for_layer(i);
  3229. ggml_context * ctx_split = ctx_for_layer_split(i);
  3230. auto & layer = model.layers[i];
  3231. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3232. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3233. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3234. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3235. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3236. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3237. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3238. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3239. }
  3240. } break;
  3241. case LLM_ARCH_QWEN2:
  3242. {
  3243. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3244. // output
  3245. {
  3246. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3247. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3248. }
  3249. for (int i = 0; i < n_layer; ++i) {
  3250. ggml_context * ctx_layer = ctx_for_layer(i);
  3251. ggml_context * ctx_split = ctx_for_layer_split(i);
  3252. auto & layer = model.layers[i];
  3253. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3254. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3255. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3256. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3257. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3258. // optional bias tensors
  3259. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3260. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3261. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3262. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3263. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3264. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3265. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3266. }
  3267. } break;
  3268. case LLM_ARCH_PHI2:
  3269. {
  3270. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3271. // output
  3272. {
  3273. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3274. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3275. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3276. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3277. }
  3278. for (int i = 0; i < n_layer; ++i) {
  3279. ggml_context * ctx_layer = ctx_for_layer(i);
  3280. ggml_context * ctx_split = ctx_for_layer_split(i);
  3281. auto & layer = model.layers[i];
  3282. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3283. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3284. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3285. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3286. if (layer.wqkv == nullptr) {
  3287. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3288. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3289. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3290. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3291. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3292. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3293. }
  3294. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3295. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3296. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3297. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3298. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3299. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3300. }
  3301. } break;
  3302. case LLM_ARCH_PLAMO:
  3303. {
  3304. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3305. // output
  3306. {
  3307. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3308. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3309. }
  3310. for (int i = 0; i < n_layer; ++i) {
  3311. ggml_context * ctx_layer = ctx_for_layer(i);
  3312. ggml_context * ctx_split = ctx_for_layer_split(i);
  3313. auto & layer = model.layers[i];
  3314. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3315. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3316. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3317. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3318. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3319. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3320. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3321. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3322. }
  3323. } break;
  3324. case LLM_ARCH_GPT2:
  3325. {
  3326. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3327. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3328. // output
  3329. {
  3330. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3331. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3332. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3333. }
  3334. for (int i = 0; i < n_layer; ++i) {
  3335. ggml_context * ctx_layer = ctx_for_layer(i);
  3336. ggml_context * ctx_split = ctx_for_layer_split(i);
  3337. auto & layer = model.layers[i];
  3338. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3339. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3340. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3341. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3342. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3343. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3344. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3345. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3346. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3347. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3348. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3349. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3350. }
  3351. } break;
  3352. case LLM_ARCH_CODESHELL:
  3353. {
  3354. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3355. // output
  3356. {
  3357. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3358. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3359. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3360. }
  3361. for (int i = 0; i < n_layer; ++i) {
  3362. ggml_context * ctx_layer = ctx_for_layer(i);
  3363. ggml_context * ctx_split = ctx_for_layer_split(i);
  3364. auto & layer = model.layers[i];
  3365. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3366. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3367. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3368. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3369. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3370. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3371. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3372. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3373. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3374. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3375. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3376. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3377. }
  3378. } break;
  3379. case LLM_ARCH_ORION:
  3380. {
  3381. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3382. {
  3383. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3384. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3385. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3386. }
  3387. for (int i = 0; i < n_layer; ++i) {
  3388. ggml_context * ctx_layer = ctx_for_layer(i);
  3389. ggml_context * ctx_split = ctx_for_layer_split(i);
  3390. auto & layer = model.layers[i];
  3391. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3392. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3393. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3394. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3395. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3396. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3397. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3398. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3399. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3400. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3401. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3402. }
  3403. } break;
  3404. default:
  3405. throw std::runtime_error("unknown architecture");
  3406. }
  3407. }
  3408. ml.done_getting_tensors();
  3409. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3410. // create the backend buffers
  3411. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3412. for (auto & it : ctx_map) {
  3413. ggml_backend_buffer_type_t buft = it.first;
  3414. ggml_context * ctx = it.second;
  3415. ggml_backend_buffer_t buf = nullptr;
  3416. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3417. // this is important for metal with apple silicon: if the entire model could be mapped to a metal buffer, then we could just use metal for all layers
  3418. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3419. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3420. size_t first, last;
  3421. ml.get_mapping_range(&first, &last, ctx);
  3422. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3423. }
  3424. #ifdef GGML_USE_METAL
  3425. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3426. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3427. size_t first, last;
  3428. ml.get_mapping_range(&first, &last, ctx);
  3429. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3430. }
  3431. #endif
  3432. else {
  3433. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3434. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3435. model.mlock_bufs.emplace_back(new llama_mlock);
  3436. auto & mlock_buf = model.mlock_bufs.back();
  3437. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3438. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3439. }
  3440. }
  3441. if (buf == nullptr) {
  3442. throw std::runtime_error("failed to allocate buffer");
  3443. }
  3444. // indicate that this buffer contains weights
  3445. // this is used by ggml_backend_sched to improve op scheduling -> ops that use a weight are preferably scheduled to the backend that contains the weight
  3446. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3447. model.bufs.push_back(buf);
  3448. ctx_bufs.emplace_back(ctx, buf);
  3449. }
  3450. // print memory requirements
  3451. {
  3452. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3453. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3454. if (n_gpu_layers > (int) hparams.n_layer) {
  3455. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3456. }
  3457. const int max_backend_supported_layers = hparams.n_layer + 1;
  3458. const int max_offloadable_layers = hparams.n_layer + 1;
  3459. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3460. for (ggml_backend_buffer_t buf : model.bufs) {
  3461. LLAMA_LOG_INFO("%s: %10s buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  3462. }
  3463. }
  3464. // populate tensors_by_name
  3465. for (ggml_context * ctx : model.ctxs) {
  3466. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3467. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3468. }
  3469. }
  3470. // load tensor data
  3471. for (auto & it : ctx_bufs) {
  3472. ggml_context * ctx = it.first;
  3473. ggml_backend_buffer_t buf = it.second;
  3474. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3475. return false;
  3476. }
  3477. }
  3478. model.mapping = std::move(ml.mapping);
  3479. // loading time will be recalculate after the first eval, so
  3480. // we take page faults deferred by mmap() into consideration
  3481. model.t_load_us = ggml_time_us() - model.t_start_us;
  3482. return true;
  3483. }
  3484. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3485. static int llama_model_load(const std::string & fname, llama_model & model, const llama_model_params & params) {
  3486. try {
  3487. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3488. model.hparams.vocab_only = params.vocab_only;
  3489. llm_load_arch (ml, model);
  3490. llm_load_hparams(ml, model);
  3491. llm_load_vocab (ml, model);
  3492. llm_load_print_meta(ml, model);
  3493. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3494. throw std::runtime_error("vocab size mismatch");
  3495. }
  3496. if (params.vocab_only) {
  3497. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3498. return 0;
  3499. }
  3500. if (!llm_load_tensors(
  3501. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3502. params.progress_callback, params.progress_callback_user_data
  3503. )) {
  3504. return -2;
  3505. }
  3506. } catch (const std::exception & err) {
  3507. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3508. return -1;
  3509. }
  3510. return 0;
  3511. }
  3512. //
  3513. // llm_build
  3514. //
  3515. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3516. enum llm_rope_type {
  3517. LLM_ROPE,
  3518. LLM_ROPE_NEOX,
  3519. LLM_ROPE_GLM,
  3520. };
  3521. enum llm_ffn_op_type {
  3522. LLM_FFN_SILU,
  3523. LLM_FFN_GELU,
  3524. LLM_FFN_RELU,
  3525. LLM_FFN_RELU_SQR,
  3526. };
  3527. enum llm_ffn_gate_type {
  3528. LLM_FFN_SEQ,
  3529. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3530. };
  3531. enum llm_norm_type {
  3532. LLM_NORM,
  3533. LLM_NORM_RMS,
  3534. };
  3535. static struct ggml_tensor * llm_build_inp_embd(
  3536. struct ggml_context * ctx,
  3537. const llama_hparams & hparams,
  3538. const llama_batch & batch,
  3539. struct ggml_tensor * tok_embd,
  3540. struct ggml_tensor * inp_tokens,
  3541. struct ggml_tensor * inp_embd,
  3542. const llm_build_cb & cb) {
  3543. const int64_t n_embd = hparams.n_embd;
  3544. struct ggml_tensor * inpL;
  3545. if (batch.token) {
  3546. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3547. cb(inp_tokens, "inp_tokens", -1);
  3548. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  3549. } else {
  3550. #ifdef GGML_USE_MPI
  3551. GGML_ASSERT(false && "not implemented");
  3552. #endif
  3553. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  3554. }
  3555. return inpL;
  3556. }
  3557. // Persimmon: n_rot = n_embd_head_k/2
  3558. // Other: n_rot = n_embd_head_k
  3559. static void llm_build_k_shift(
  3560. struct ggml_context * ctx,
  3561. const llama_hparams & hparams,
  3562. const llama_cparams & cparams,
  3563. const llama_kv_cache & kv,
  3564. struct ggml_cgraph * graph,
  3565. struct ggml_tensor * K_shift,
  3566. llm_rope_type type,
  3567. int64_t n_ctx,
  3568. float freq_base,
  3569. float freq_scale,
  3570. const llm_build_cb & cb) {
  3571. const int64_t n_layer = hparams.n_layer;
  3572. const int64_t n_head_kv = hparams.n_head_kv;
  3573. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3574. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3575. const int32_t n_rot = hparams.n_rot;
  3576. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3577. const float ext_factor = cparams.yarn_ext_factor;
  3578. const float attn_factor = cparams.yarn_attn_factor;
  3579. const float beta_fast = cparams.yarn_beta_fast;
  3580. const float beta_slow = cparams.yarn_beta_slow;
  3581. int rope_type = 0;
  3582. switch (type) {
  3583. case LLM_ROPE: rope_type = 0; break;
  3584. case LLM_ROPE_NEOX: rope_type = 2; break;
  3585. case LLM_ROPE_GLM: rope_type = 4; break;
  3586. }
  3587. for (int il = 0; il < n_layer; ++il) {
  3588. struct ggml_tensor * tmp =
  3589. // we rotate only the first n_rot dimensions
  3590. ggml_rope_custom_inplace(ctx,
  3591. ggml_view_3d(ctx, kv.k_l[il],
  3592. n_embd_head_k, n_head_kv, n_ctx,
  3593. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3594. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3595. 0),
  3596. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3597. ext_factor, attn_factor, beta_fast, beta_slow);
  3598. cb(tmp, "K_shifted", il);
  3599. ggml_build_forward_expand(graph, tmp);
  3600. }
  3601. }
  3602. static void llm_build_kv_store(
  3603. struct ggml_context * ctx,
  3604. const llama_hparams & hparams,
  3605. const llama_kv_cache & kv,
  3606. struct ggml_cgraph * graph,
  3607. struct ggml_tensor * k_cur,
  3608. struct ggml_tensor * v_cur,
  3609. int64_t n_ctx,
  3610. int32_t n_tokens,
  3611. int32_t kv_head,
  3612. const llm_build_cb & cb,
  3613. int64_t il) {
  3614. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3615. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3616. // compute the transposed [n_tokens, n_embd] V matrix
  3617. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  3618. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3619. cb(v_cur_t, "v_cur_t", il);
  3620. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  3621. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  3622. cb(k_cache_view, "k_cache_view", il);
  3623. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  3624. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3625. (kv_head)*ggml_element_size(kv.v_l[il]));
  3626. cb(v_cache_view, "v_cache_view", il);
  3627. // important: storing RoPE-ed version of K in the KV cache!
  3628. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3629. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3630. }
  3631. static struct ggml_tensor * llm_build_norm(
  3632. struct ggml_context * ctx,
  3633. struct ggml_tensor * cur,
  3634. const llama_hparams & hparams,
  3635. struct ggml_tensor * mw,
  3636. struct ggml_tensor * mb,
  3637. llm_norm_type type,
  3638. const llm_build_cb & cb,
  3639. int il) {
  3640. switch (type) {
  3641. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3642. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3643. }
  3644. if (mw || mb) {
  3645. cb(cur, "norm", il);
  3646. }
  3647. if (mw) {
  3648. cur = ggml_mul(ctx, cur, mw);
  3649. if (mb) {
  3650. cb(cur, "norm_w", il);
  3651. }
  3652. }
  3653. if (mb) {
  3654. cur = ggml_add(ctx, cur, mb);
  3655. }
  3656. return cur;
  3657. }
  3658. static struct ggml_tensor * llm_build_ffn(
  3659. struct ggml_context * ctx,
  3660. struct ggml_tensor * cur,
  3661. struct ggml_tensor * up,
  3662. struct ggml_tensor * up_b,
  3663. struct ggml_tensor * gate,
  3664. struct ggml_tensor * gate_b,
  3665. struct ggml_tensor * down,
  3666. struct ggml_tensor * down_b,
  3667. struct ggml_tensor * act_scales,
  3668. llm_ffn_op_type type_op,
  3669. llm_ffn_gate_type type_gate,
  3670. const llm_build_cb & cb,
  3671. int il) {
  3672. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3673. cb(tmp, "ffn_up", il);
  3674. if (up_b) {
  3675. tmp = ggml_add(ctx, tmp, up_b);
  3676. cb(tmp, "ffn_up_b", il);
  3677. }
  3678. if (gate) {
  3679. switch (type_gate) {
  3680. case LLM_FFN_SEQ:
  3681. {
  3682. cur = ggml_mul_mat(ctx, gate, tmp);
  3683. cb(cur, "ffn_gate", il);
  3684. } break;
  3685. case LLM_FFN_PAR:
  3686. {
  3687. cur = ggml_mul_mat(ctx, gate, cur);
  3688. cb(cur, "ffn_gate", il);
  3689. } break;
  3690. }
  3691. if (gate_b) {
  3692. cur = ggml_add(ctx, cur, gate_b);
  3693. cb(cur, "ffn_gate_b", il);
  3694. }
  3695. } else {
  3696. cur = tmp;
  3697. }
  3698. switch (type_op) {
  3699. case LLM_FFN_SILU:
  3700. {
  3701. cur = ggml_silu(ctx, cur);
  3702. cb(cur, "ffn_silu", il);
  3703. } break;
  3704. case LLM_FFN_GELU:
  3705. {
  3706. cur = ggml_gelu(ctx, cur);
  3707. cb(cur, "ffn_gelu", il);
  3708. if (act_scales != NULL) {
  3709. cur = ggml_div(ctx, cur, act_scales);
  3710. cb(cur, "ffn_act", il);
  3711. }
  3712. } break;
  3713. case LLM_FFN_RELU:
  3714. {
  3715. cur = ggml_relu(ctx, cur);
  3716. cb(cur, "ffn_relu", il);
  3717. } break;
  3718. case LLM_FFN_RELU_SQR:
  3719. {
  3720. cur = ggml_relu(ctx, cur);
  3721. cb(cur, "ffn_relu", il);
  3722. cur = ggml_sqr(ctx, cur);
  3723. cb(cur, "ffn_sqr(relu)", il);
  3724. } break;
  3725. }
  3726. if (type_gate == LLM_FFN_PAR) {
  3727. cur = ggml_mul(ctx, cur, tmp);
  3728. cb(cur, "ffn_gate_par", il);
  3729. }
  3730. cur = ggml_mul_mat(ctx, down, cur);
  3731. if (down_b) {
  3732. cb(cur, "ffn_down", il);
  3733. }
  3734. if (down_b) {
  3735. cur = ggml_add(ctx, cur, down_b);
  3736. }
  3737. return cur;
  3738. }
  3739. // if max_alibi_bias > 0 then apply ALiBi
  3740. static struct ggml_tensor * llm_build_kqv(
  3741. struct ggml_context * ctx,
  3742. const llama_model & model,
  3743. const llama_hparams & hparams,
  3744. const llama_kv_cache & kv,
  3745. struct ggml_cgraph * graph,
  3746. struct ggml_tensor * wo,
  3747. struct ggml_tensor * wo_b,
  3748. struct ggml_tensor * q_cur,
  3749. struct ggml_tensor * kq_mask,
  3750. int64_t n_ctx,
  3751. int32_t n_tokens,
  3752. int32_t n_kv,
  3753. float max_alibi_bias,
  3754. float kq_scale,
  3755. const llm_build_cb & cb,
  3756. int il) {
  3757. const int64_t n_head = hparams.n_head;
  3758. const int64_t n_head_kv = hparams.n_head_kv;
  3759. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3760. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3761. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  3762. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3763. cb(q, "q", il);
  3764. struct ggml_tensor * k =
  3765. ggml_view_3d(ctx, kv.k_l[il],
  3766. n_embd_head_k, n_kv, n_head_kv,
  3767. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3768. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3769. 0);
  3770. cb(k, "k", il);
  3771. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3772. cb(kq, "kq", il);
  3773. if (model.arch == LLM_ARCH_PHI2) {
  3774. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  3775. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  3776. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  3777. }
  3778. if (max_alibi_bias > 0.0f) {
  3779. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  3780. kq = ggml_scale(ctx, kq, kq_scale);
  3781. cb(kq, "kq_scaled", il);
  3782. if (max_alibi_bias > 0.0f) {
  3783. // TODO: n_head or n_head_kv
  3784. // TODO: K-shift is likely not working
  3785. // TODO: change to ggml_add
  3786. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  3787. cb(kq, "kq_scaled_alibi", il);
  3788. }
  3789. kq = ggml_add(ctx, kq, kq_mask);
  3790. cb(kq, "kq_masked", il);
  3791. kq = ggml_soft_max(ctx, kq);
  3792. cb(kq, "kq_soft_max", il);
  3793. } else {
  3794. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale);
  3795. cb(kq, "kq_soft_max_ext", il);
  3796. }
  3797. // split cached v into n_head heads
  3798. struct ggml_tensor * v =
  3799. ggml_view_3d(ctx, kv.v_l[il],
  3800. n_kv, n_embd_head_v, n_head_kv,
  3801. ggml_element_size(kv.v_l[il])*n_ctx,
  3802. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  3803. 0);
  3804. cb(v, "v", il);
  3805. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3806. cb(kqv, "kqv", il);
  3807. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3808. cb(kqv_merged, "kqv_merged", il);
  3809. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  3810. cb(cur, "kqv_merged_cont", il);
  3811. ggml_build_forward_expand(graph, cur);
  3812. cur = ggml_mul_mat(ctx, wo, cur);
  3813. if (wo_b) {
  3814. cb(cur, "kqv_wo", il);
  3815. }
  3816. if (wo_b) {
  3817. cur = ggml_add(ctx, cur, wo_b);
  3818. }
  3819. return cur;
  3820. }
  3821. static struct ggml_tensor * llm_build_kv(
  3822. struct ggml_context * ctx,
  3823. const llama_model & model,
  3824. const llama_hparams & hparams,
  3825. const llama_kv_cache & kv,
  3826. struct ggml_cgraph * graph,
  3827. struct ggml_tensor * wo,
  3828. struct ggml_tensor * wo_b,
  3829. struct ggml_tensor * k_cur,
  3830. struct ggml_tensor * v_cur,
  3831. struct ggml_tensor * q_cur,
  3832. struct ggml_tensor * kq_mask,
  3833. int64_t n_ctx,
  3834. int32_t n_tokens,
  3835. int32_t kv_head,
  3836. int32_t n_kv,
  3837. float max_alibi_bias,
  3838. float kq_scale,
  3839. const llm_build_cb & cb,
  3840. int il) {
  3841. // these nodes are added to the graph together so that they are not reordered
  3842. // by doing so, the number of splits in the graph is reduced
  3843. ggml_build_forward_expand(graph, q_cur);
  3844. ggml_build_forward_expand(graph, k_cur);
  3845. ggml_build_forward_expand(graph, v_cur);
  3846. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  3847. struct ggml_tensor * cur;
  3848. cur = llm_build_kqv(ctx, model, hparams, kv, graph,
  3849. wo, wo_b,
  3850. q_cur, kq_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, kq_scale, cb, il);
  3851. cb(cur, "kqv_out", il);
  3852. return cur;
  3853. }
  3854. struct llm_build_context {
  3855. const llama_model & model;
  3856. const llama_context & lctx;
  3857. const llama_hparams & hparams;
  3858. const llama_cparams & cparams;
  3859. const llama_batch & batch;
  3860. const llama_kv_cache & kv_self;
  3861. const int64_t n_embd;
  3862. const int64_t n_layer;
  3863. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  3864. const int64_t n_head;
  3865. const int64_t n_head_kv;
  3866. const int64_t n_embd_head_k;
  3867. const int64_t n_embd_k_gqa;
  3868. const int64_t n_embd_head_v;
  3869. const int64_t n_embd_v_gqa;
  3870. const int64_t n_expert;
  3871. const int64_t n_expert_used;
  3872. const float freq_base;
  3873. const float freq_scale;
  3874. const float ext_factor;
  3875. const float attn_factor;
  3876. const float beta_fast;
  3877. const float beta_slow;
  3878. const float norm_eps;
  3879. const float norm_rms_eps;
  3880. const int32_t n_tokens;
  3881. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  3882. const int32_t kv_head; // index of where we store new KV data in the cache
  3883. const int32_t n_orig_ctx;
  3884. const bool do_rope_shift;
  3885. const llm_build_cb & cb;
  3886. std::vector<uint8_t> & buf_compute_meta;
  3887. struct ggml_context * ctx0 = nullptr;
  3888. // TODO: consider making the entire interface noexcept
  3889. llm_build_context(
  3890. llama_context & lctx,
  3891. const llama_batch & batch,
  3892. const llm_build_cb & cb,
  3893. bool worst_case) :
  3894. model (lctx.model),
  3895. lctx (lctx),
  3896. hparams (model.hparams),
  3897. cparams (lctx.cparams),
  3898. batch (batch),
  3899. kv_self (lctx.kv_self),
  3900. n_embd (hparams.n_embd),
  3901. n_layer (hparams.n_layer),
  3902. n_ctx (cparams.n_ctx),
  3903. n_head (hparams.n_head),
  3904. n_head_kv (hparams.n_head_kv),
  3905. n_embd_head_k (hparams.n_embd_head_k),
  3906. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  3907. n_embd_head_v (hparams.n_embd_head_v),
  3908. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  3909. n_expert (hparams.n_expert),
  3910. n_expert_used (hparams.n_expert_used),
  3911. freq_base (cparams.rope_freq_base),
  3912. freq_scale (cparams.rope_freq_scale),
  3913. ext_factor (cparams.yarn_ext_factor),
  3914. attn_factor (cparams.yarn_attn_factor),
  3915. beta_fast (cparams.yarn_beta_fast),
  3916. beta_slow (cparams.yarn_beta_slow),
  3917. norm_eps (hparams.f_norm_eps),
  3918. norm_rms_eps (hparams.f_norm_rms_eps),
  3919. n_tokens (batch.n_tokens),
  3920. n_kv (worst_case ? n_ctx : kv_self.n),
  3921. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  3922. n_orig_ctx (cparams.n_yarn_orig_ctx),
  3923. do_rope_shift (worst_case || kv_self.has_shift),
  3924. cb (cb),
  3925. buf_compute_meta (lctx.buf_compute_meta) {
  3926. // all initializations should be done in init()
  3927. }
  3928. void init() {
  3929. struct ggml_init_params params = {
  3930. /*.mem_size =*/ buf_compute_meta.size(),
  3931. /*.mem_buffer =*/ buf_compute_meta.data(),
  3932. /*.no_alloc =*/ true,
  3933. };
  3934. ctx0 = ggml_init(params);
  3935. }
  3936. void free() {
  3937. if (ctx0) {
  3938. ggml_free(ctx0);
  3939. ctx0 = nullptr;
  3940. }
  3941. }
  3942. struct ggml_cgraph * build_orion() {
  3943. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3944. const int64_t n_embd_head = hparams.n_embd_head_v;
  3945. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3946. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3947. struct ggml_tensor * cur;
  3948. struct ggml_tensor * inpL;
  3949. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  3950. cb(inpL, "inp_embd", -1);
  3951. // inp_pos - contains the positions
  3952. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  3953. cb(inp_pos, "inp_pos", -1);
  3954. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3955. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  3956. cb(KQ_mask, "KQ_mask", -1);
  3957. // shift the entire K-cache if needed
  3958. if (do_rope_shift) {
  3959. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  3960. }
  3961. for (int il = 0; il < n_layer; ++il) {
  3962. struct ggml_tensor * inpSA = inpL;
  3963. // norm
  3964. cur = llm_build_norm(ctx0, inpL, hparams,
  3965. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  3966. LLM_NORM, cb, il);
  3967. cb(cur, "attn_norm", il);
  3968. // self-attention
  3969. {
  3970. // compute Q and K and RoPE them
  3971. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3972. cb(Qcur, "Qcur", il);
  3973. // if (model.layers[il].bq) {
  3974. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3975. // cb(Qcur, "Qcur", il);
  3976. // }
  3977. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3978. cb(Kcur, "Kcur", il);
  3979. // if (model.layers[il].bk) {
  3980. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  3981. // cb(Kcur, "Kcur", il);
  3982. // }
  3983. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3984. cb(Vcur, "Vcur", il);
  3985. // if (model.layers[il].bv) {
  3986. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  3987. // cb(Vcur, "Vcur", il);
  3988. // }
  3989. Qcur = ggml_rope_custom(
  3990. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  3991. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  3992. ext_factor, attn_factor, beta_fast, beta_slow
  3993. );
  3994. cb(Qcur, "Qcur", il);
  3995. Kcur = ggml_rope_custom(
  3996. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  3997. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  3998. ext_factor, attn_factor, beta_fast, beta_slow
  3999. );
  4000. cb(Kcur, "Kcur", il);
  4001. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4002. model.layers[il].wo, NULL,
  4003. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4004. cb(cur, "kqv_out", il);
  4005. }
  4006. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4007. cb(ffn_inp, "ffn_inp", il);
  4008. // feed-forward network
  4009. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4010. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  4011. LLM_NORM, cb, il);
  4012. cb(cur, "ffn_norm", il);
  4013. cur = llm_build_ffn(ctx0, cur,
  4014. model.layers[il].ffn_up, NULL,
  4015. model.layers[il].ffn_gate, NULL,
  4016. model.layers[il].ffn_down, NULL,
  4017. NULL,
  4018. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4019. cb(cur, "ffn_out", il);
  4020. cur = ggml_add(ctx0, cur, ffn_inp);
  4021. cb(cur, "l_out", il);
  4022. // input for next layer
  4023. inpL = cur;
  4024. }
  4025. cur = inpL;
  4026. cur = llm_build_norm(ctx0, cur, hparams,
  4027. model.output_norm, model.output_norm_b,
  4028. LLM_NORM, cb, -1);
  4029. cb(cur, "result_norm", -1);
  4030. // lm_head
  4031. cur = ggml_mul_mat(ctx0, model.output, cur);
  4032. cb(cur, "result_output", -1);
  4033. ggml_build_forward_expand(gf, cur);
  4034. return gf;
  4035. }
  4036. struct ggml_cgraph * build_llama() {
  4037. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4038. const int64_t n_embd_head = hparams.n_embd_head_v;
  4039. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4040. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4041. struct ggml_tensor * cur;
  4042. struct ggml_tensor * inpL;
  4043. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4044. cb(inpL, "inp_embd", -1);
  4045. // inp_pos - contains the positions
  4046. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4047. cb(inp_pos, "inp_pos", -1);
  4048. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4049. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4050. cb(KQ_mask, "KQ_mask", -1);
  4051. // shift the entire K-cache if needed
  4052. if (do_rope_shift) {
  4053. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4054. }
  4055. for (int il = 0; il < n_layer; ++il) {
  4056. struct ggml_tensor * inpSA = inpL;
  4057. // norm
  4058. cur = llm_build_norm(ctx0, inpL, hparams,
  4059. model.layers[il].attn_norm, NULL,
  4060. LLM_NORM_RMS, cb, il);
  4061. cb(cur, "attn_norm", il);
  4062. // self-attention
  4063. {
  4064. // compute Q and K and RoPE them
  4065. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4066. cb(Qcur, "Qcur", il);
  4067. if (model.layers[il].bq) {
  4068. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4069. cb(Qcur, "Qcur", il);
  4070. }
  4071. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4072. cb(Kcur, "Kcur", il);
  4073. if (model.layers[il].bk) {
  4074. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4075. cb(Kcur, "Kcur", il);
  4076. }
  4077. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4078. cb(Vcur, "Vcur", il);
  4079. if (model.layers[il].bv) {
  4080. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4081. cb(Vcur, "Vcur", il);
  4082. }
  4083. Qcur = ggml_rope_custom(
  4084. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4085. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4086. ext_factor, attn_factor, beta_fast, beta_slow
  4087. );
  4088. cb(Qcur, "Qcur", il);
  4089. Kcur = ggml_rope_custom(
  4090. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4091. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4092. ext_factor, attn_factor, beta_fast, beta_slow
  4093. );
  4094. cb(Kcur, "Kcur", il);
  4095. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4096. model.layers[il].wo, model.layers[il].bo,
  4097. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4098. cb(cur, "kqv_out", il);
  4099. }
  4100. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4101. cb(ffn_inp, "ffn_inp", il);
  4102. // feed-forward network
  4103. if (model.layers[il].ffn_gate_inp == nullptr) {
  4104. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4105. model.layers[il].ffn_norm, NULL,
  4106. LLM_NORM_RMS, cb, il);
  4107. cb(cur, "ffn_norm", il);
  4108. cur = llm_build_ffn(ctx0, cur,
  4109. model.layers[il].ffn_up, NULL,
  4110. model.layers[il].ffn_gate, NULL,
  4111. model.layers[il].ffn_down, NULL,
  4112. NULL,
  4113. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4114. cb(cur, "ffn_out", il);
  4115. } else {
  4116. // MoE branch
  4117. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4118. model.layers[il].ffn_norm, NULL,
  4119. LLM_NORM_RMS, cb, il);
  4120. cb(cur, "ffn_norm", il);
  4121. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4122. cb(logits, "ffn_moe_logits", il);
  4123. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4124. cb(probs, "ffn_moe_probs", il);
  4125. // select experts
  4126. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4127. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4128. ggml_tensor * weights = ggml_get_rows(ctx0,
  4129. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4130. cb(weights, "ffn_moe_weights", il);
  4131. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4132. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4133. cb(weights_sum, "ffn_moe_weights_sum", il);
  4134. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4135. cb(weights, "ffn_moe_weights_norm", il);
  4136. // compute expert outputs
  4137. ggml_tensor * moe_out = nullptr;
  4138. for (int i = 0; i < n_expert_used; ++i) {
  4139. ggml_tensor * cur_expert;
  4140. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4141. cb(cur_up, "ffn_moe_up", il);
  4142. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4143. cb(cur_gate, "ffn_moe_gate", il);
  4144. cur_gate = ggml_silu(ctx0, cur_gate);
  4145. cb(cur_gate, "ffn_moe_silu", il);
  4146. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4147. cb(cur_expert, "ffn_moe_gate_par", il);
  4148. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4149. cb(cur_expert, "ffn_moe_down", il);
  4150. cur_expert = ggml_mul(ctx0, cur_expert,
  4151. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4152. cb(cur_expert, "ffn_moe_weighted", il);
  4153. if (i == 0) {
  4154. moe_out = cur_expert;
  4155. } else {
  4156. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4157. cb(moe_out, "ffn_moe_out", il);
  4158. }
  4159. }
  4160. cur = moe_out;
  4161. }
  4162. cur = ggml_add(ctx0, cur, ffn_inp);
  4163. cb(cur, "l_out", il);
  4164. // input for next layer
  4165. inpL = cur;
  4166. }
  4167. cur = inpL;
  4168. cur = llm_build_norm(ctx0, cur, hparams,
  4169. model.output_norm, NULL,
  4170. LLM_NORM_RMS, cb, -1);
  4171. cb(cur, "result_norm", -1);
  4172. // lm_head
  4173. cur = ggml_mul_mat(ctx0, model.output, cur);
  4174. cb(cur, "result_output", -1);
  4175. ggml_build_forward_expand(gf, cur);
  4176. return gf;
  4177. }
  4178. struct ggml_cgraph * build_baichuan() {
  4179. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4180. const int64_t n_embd_head = hparams.n_embd_head_v;
  4181. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4182. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4183. struct ggml_tensor * cur;
  4184. struct ggml_tensor * inpL;
  4185. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4186. cb(inpL, "inp_embd", -1);
  4187. // inp_pos - contains the positions
  4188. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4189. cb(inp_pos, "inp_pos", -1);
  4190. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4191. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4192. cb(KQ_mask, "KQ_mask", -1);
  4193. // shift the entire K-cache if needed
  4194. if (do_rope_shift) {
  4195. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4196. }
  4197. for (int il = 0; il < n_layer; ++il) {
  4198. struct ggml_tensor * inpSA = inpL;
  4199. cur = llm_build_norm(ctx0, inpL, hparams,
  4200. model.layers[il].attn_norm, NULL,
  4201. LLM_NORM_RMS, cb, il);
  4202. cb(cur, "attn_norm", il);
  4203. // self-attention
  4204. {
  4205. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4206. cb(Qcur, "Qcur", il);
  4207. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4208. cb(Kcur, "Kcur", il);
  4209. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4210. cb(Vcur, "Vcur", il);
  4211. switch (model.type) {
  4212. case MODEL_7B:
  4213. Qcur = ggml_rope_custom(
  4214. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4215. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4216. ext_factor, attn_factor, beta_fast, beta_slow
  4217. );
  4218. Kcur = ggml_rope_custom(
  4219. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4220. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4221. ext_factor, attn_factor, beta_fast, beta_slow
  4222. );
  4223. break;
  4224. case MODEL_13B:
  4225. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4226. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4227. break;
  4228. default:
  4229. GGML_ASSERT(false);
  4230. }
  4231. cb(Qcur, "Qcur", il);
  4232. cb(Kcur, "Kcur", il);
  4233. // apply ALiBi for 13B model
  4234. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  4235. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4236. model.layers[il].wo, NULL,
  4237. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4238. cb(cur, "kqv_out", il);
  4239. }
  4240. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4241. cb(ffn_inp, "ffn_inp", il);
  4242. // feed-forward network
  4243. {
  4244. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4245. model.layers[il].ffn_norm, NULL,
  4246. LLM_NORM_RMS, cb, il);
  4247. cb(cur, "ffn_norm", il);
  4248. cur = llm_build_ffn(ctx0, cur,
  4249. model.layers[il].ffn_up, NULL,
  4250. model.layers[il].ffn_gate, NULL,
  4251. model.layers[il].ffn_down, NULL,
  4252. NULL,
  4253. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4254. cb(cur, "ffn_out", il);
  4255. }
  4256. cur = ggml_add(ctx0, cur, ffn_inp);
  4257. cb(cur, "l_out", il);
  4258. // input for next layer
  4259. inpL = cur;
  4260. }
  4261. cur = inpL;
  4262. cur = llm_build_norm(ctx0, cur, hparams,
  4263. model.output_norm, NULL,
  4264. LLM_NORM_RMS, cb, -1);
  4265. cb(cur, "result_norm", -1);
  4266. // lm_head
  4267. cur = ggml_mul_mat(ctx0, model.output, cur);
  4268. cb(cur, "result_output", -1);
  4269. ggml_build_forward_expand(gf, cur);
  4270. return gf;
  4271. }
  4272. struct ggml_cgraph * build_falcon() {
  4273. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4274. const int64_t n_embd_head = hparams.n_embd_head_v;
  4275. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4276. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4277. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4278. struct ggml_tensor * cur;
  4279. struct ggml_tensor * inpL;
  4280. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4281. cb(inpL, "inp_embd", -1);
  4282. // inp_pos - contains the positions
  4283. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4284. cb(inp_pos, "inp_pos", -1);
  4285. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4286. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4287. cb(KQ_mask, "KQ_mask", -1);
  4288. // shift the entire K-cache if needed
  4289. if (do_rope_shift) {
  4290. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4291. }
  4292. for (int il = 0; il < n_layer; ++il) {
  4293. struct ggml_tensor * attn_norm;
  4294. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4295. model.layers[il].attn_norm,
  4296. model.layers[il].attn_norm_b,
  4297. LLM_NORM, cb, il);
  4298. cb(attn_norm, "attn_norm", il);
  4299. // self-attention
  4300. {
  4301. if (model.layers[il].attn_norm_2) {
  4302. // Falcon-40B
  4303. cur = llm_build_norm(ctx0, inpL, hparams,
  4304. model.layers[il].attn_norm_2,
  4305. model.layers[il].attn_norm_2_b,
  4306. LLM_NORM, cb, il);
  4307. cb(cur, "attn_norm_2", il);
  4308. } else {
  4309. cur = attn_norm;
  4310. }
  4311. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4312. cb(cur, "wqkv", il);
  4313. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4314. 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)));
  4315. 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)));
  4316. cb(Qcur, "Qcur", il);
  4317. cb(Kcur, "Kcur", il);
  4318. cb(Vcur, "Vcur", il);
  4319. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4320. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4321. // using mode = 2 for neox mode
  4322. Qcur = ggml_rope_custom(
  4323. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4324. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4325. );
  4326. cb(Qcur, "Qcur", il);
  4327. Kcur = ggml_rope_custom(
  4328. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4329. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4330. );
  4331. cb(Kcur, "Kcur", il);
  4332. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4333. model.layers[il].wo, NULL,
  4334. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4335. cb(cur, "kqv_out", il);
  4336. }
  4337. struct ggml_tensor * ffn_inp = cur;
  4338. // feed forward
  4339. {
  4340. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4341. model.layers[il].ffn_up, NULL,
  4342. NULL, NULL,
  4343. model.layers[il].ffn_down, NULL,
  4344. NULL,
  4345. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4346. cb(cur, "ffn_out", il);
  4347. }
  4348. cur = ggml_add(ctx0, cur, ffn_inp);
  4349. cb(cur, "l_out", il);
  4350. cur = ggml_add(ctx0, cur, inpL);
  4351. cb(cur, "l_out", il);
  4352. // input for next layer
  4353. inpL = cur;
  4354. }
  4355. cur = inpL;
  4356. // norm
  4357. cur = llm_build_norm(ctx0, cur, hparams,
  4358. model.output_norm,
  4359. model.output_norm_b,
  4360. LLM_NORM, cb, -1);
  4361. cb(cur, "result_norm", -1);
  4362. cur = ggml_mul_mat(ctx0, model.output, cur);
  4363. cb(cur, "result_output", -1);
  4364. ggml_build_forward_expand(gf, cur);
  4365. return gf;
  4366. }
  4367. struct ggml_cgraph * build_starcoder() {
  4368. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4369. const int64_t n_embd_head = hparams.n_embd_head_v;
  4370. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4371. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4372. struct ggml_tensor * cur;
  4373. struct ggml_tensor * pos;
  4374. struct ggml_tensor * inpL;
  4375. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4376. cb(inpL, "inp_embd", -1);
  4377. // inp_pos - contains the positions
  4378. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4379. cb(inp_pos, "inp_pos", -1);
  4380. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4381. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4382. cb(KQ_mask, "KQ_mask", -1);
  4383. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4384. cb(pos, "pos_embd", -1);
  4385. inpL = ggml_add(ctx0, inpL, pos);
  4386. cb(inpL, "inpL", -1);
  4387. for (int il = 0; il < n_layer; ++il) {
  4388. cur = llm_build_norm(ctx0, inpL, hparams,
  4389. model.layers[il].attn_norm,
  4390. model.layers[il].attn_norm_b,
  4391. LLM_NORM, cb, il);
  4392. cb(cur, "attn_norm", il);
  4393. // self-attention
  4394. {
  4395. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4396. cb(cur, "wqkv", il);
  4397. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4398. cb(cur, "bqkv", il);
  4399. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4400. 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)));
  4401. 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)));
  4402. cb(Qcur, "Qcur", il);
  4403. cb(Kcur, "Kcur", il);
  4404. cb(Vcur, "Vcur", il);
  4405. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4406. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4407. model.layers[il].wo, model.layers[il].bo,
  4408. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4409. cb(cur, "kqv_out", il);
  4410. }
  4411. // add the input
  4412. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4413. cb(ffn_inp, "ffn_inp", il);
  4414. // FF
  4415. {
  4416. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4417. model.layers[il].ffn_norm,
  4418. model.layers[il].ffn_norm_b,
  4419. LLM_NORM, cb, il);
  4420. cb(cur, "ffn_norm", il);
  4421. cur = llm_build_ffn(ctx0, cur,
  4422. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4423. NULL, NULL,
  4424. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4425. NULL,
  4426. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4427. cb(cur, "ffn_out", il);
  4428. }
  4429. inpL = ggml_add(ctx0, cur, ffn_inp);
  4430. cb(inpL, "l_out", il);
  4431. }
  4432. cur = llm_build_norm(ctx0, inpL, hparams,
  4433. model.output_norm,
  4434. model.output_norm_b,
  4435. LLM_NORM, cb, -1);
  4436. cb(cur, "result_norm", -1);
  4437. cur = ggml_mul_mat(ctx0, model.output, cur);
  4438. cb(cur, "result_output", -1);
  4439. ggml_build_forward_expand(gf, cur);
  4440. return gf;
  4441. }
  4442. struct ggml_cgraph * build_persimmon() {
  4443. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4444. const int64_t n_embd_head = hparams.n_embd_head_v;
  4445. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4446. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4447. struct ggml_tensor * cur;
  4448. struct ggml_tensor * inpL;
  4449. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4450. cb(inpL, "inp_embd", -1);
  4451. // inp_pos - contains the positions
  4452. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4453. cb(inp_pos, "inp_pos", -1);
  4454. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4455. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4456. cb(KQ_mask, "KQ_mask", -1);
  4457. if (do_rope_shift) {
  4458. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4459. }
  4460. for (int il = 0; il < n_layer; ++il) {
  4461. struct ggml_tensor * residual = inpL;
  4462. cur = llm_build_norm(ctx0, inpL, hparams,
  4463. model.layers[il].attn_norm,
  4464. model.layers[il].attn_norm_b,
  4465. LLM_NORM, cb, il);
  4466. cb(cur, "attn_norm", il);
  4467. // self attention
  4468. {
  4469. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4470. cb(cur, "wqkv", il);
  4471. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4472. cb(cur, "bqkv", il);
  4473. // split qkv
  4474. GGML_ASSERT(n_head_kv == n_head);
  4475. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4476. cb(tmpqkv, "tmpqkv", il);
  4477. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4478. cb(tmpqkv_perm, "tmpqkv", il);
  4479. struct ggml_tensor * tmpq = ggml_view_3d(
  4480. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4481. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4482. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4483. 0
  4484. );
  4485. cb(tmpq, "tmpq", il);
  4486. struct ggml_tensor * tmpk = ggml_view_3d(
  4487. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4488. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4489. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4490. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4491. );
  4492. cb(tmpk, "tmpk", il);
  4493. // Q/K Layernorm
  4494. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4495. model.layers[il].attn_q_norm,
  4496. model.layers[il].attn_q_norm_b,
  4497. LLM_NORM, cb, il);
  4498. cb(tmpq, "tmpq", il);
  4499. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4500. model.layers[il].attn_k_norm,
  4501. model.layers[il].attn_k_norm_b,
  4502. LLM_NORM, cb, il);
  4503. cb(tmpk, "tmpk", il);
  4504. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4505. struct ggml_tensor * qrot = ggml_view_3d(
  4506. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4507. ggml_element_size(tmpq) * n_embd_head,
  4508. ggml_element_size(tmpq) * n_embd_head * n_head,
  4509. 0
  4510. );
  4511. cb(qrot, "qrot", il);
  4512. struct ggml_tensor * krot = ggml_view_3d(
  4513. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4514. ggml_element_size(tmpk) * n_embd_head,
  4515. ggml_element_size(tmpk) * n_embd_head * n_head,
  4516. 0
  4517. );
  4518. cb(krot, "krot", il);
  4519. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4520. struct ggml_tensor * qpass = ggml_view_3d(
  4521. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4522. ggml_element_size(tmpq) * n_embd_head,
  4523. ggml_element_size(tmpq) * n_embd_head * n_head,
  4524. ggml_element_size(tmpq) * hparams.n_rot
  4525. );
  4526. cb(qpass, "qpass", il);
  4527. struct ggml_tensor * kpass = ggml_view_3d(
  4528. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4529. ggml_element_size(tmpk) * n_embd_head,
  4530. ggml_element_size(tmpk) * n_embd_head * n_head,
  4531. ggml_element_size(tmpk) * hparams.n_rot
  4532. );
  4533. cb(kpass, "kpass", il);
  4534. struct ggml_tensor * qrotated = ggml_rope_custom(
  4535. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4536. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4537. );
  4538. cb(qrotated, "qrotated", il);
  4539. struct ggml_tensor * krotated = ggml_rope_custom(
  4540. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4541. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4542. );
  4543. cb(krotated, "krotated", il);
  4544. // ggml currently only supports concatenation on dim=2
  4545. // so we need to permute qrot, qpass, concat, then permute back.
  4546. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4547. cb(qrotated, "qrotated", il);
  4548. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4549. cb(krotated, "krotated", il);
  4550. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4551. cb(qpass, "qpass", il);
  4552. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4553. cb(kpass, "kpass", il);
  4554. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4555. cb(Qcur, "Qcur", il);
  4556. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4557. cb(Kcur, "Kcur", il);
  4558. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4559. cb(Q, "Q", il);
  4560. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4561. cb(Kcur, "Kcur", il);
  4562. struct ggml_tensor * Vcur = ggml_view_3d(
  4563. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4564. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4565. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4566. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4567. );
  4568. cb(Vcur, "Vcur", il);
  4569. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4570. model.layers[il].wo, model.layers[il].bo,
  4571. Kcur, Vcur, Q, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4572. cb(cur, "kqv_out", il);
  4573. }
  4574. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4575. cb(ffn_inp, "ffn_inp", il);
  4576. // feed-forward network
  4577. {
  4578. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4579. model.layers[il].ffn_norm,
  4580. model.layers[il].ffn_norm_b,
  4581. LLM_NORM, cb, il);
  4582. cb(cur, "ffn_norm", il);
  4583. cur = llm_build_ffn(ctx0, cur,
  4584. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4585. NULL, NULL,
  4586. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4587. NULL,
  4588. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4589. cb(cur, "ffn_out", il);
  4590. }
  4591. cur = ggml_add(ctx0, cur, ffn_inp);
  4592. cb(cur, "l_out", il);
  4593. inpL = cur;
  4594. }
  4595. cur = inpL;
  4596. cur = llm_build_norm(ctx0, cur, hparams,
  4597. model.output_norm,
  4598. model.output_norm_b,
  4599. LLM_NORM, cb, -1);
  4600. cb(cur, "result_norm", -1);
  4601. cur = ggml_mul_mat(ctx0, model.output, cur);
  4602. cb(cur, "result_output", -1);
  4603. ggml_build_forward_expand(gf, cur);
  4604. return gf;
  4605. }
  4606. struct ggml_cgraph * build_refact() {
  4607. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4608. const int64_t n_embd_head = hparams.n_embd_head_v;
  4609. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4610. struct ggml_tensor * cur;
  4611. struct ggml_tensor * inpL;
  4612. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4613. cb(inpL, "inp_embd", -1);
  4614. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4615. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4616. cb(KQ_mask, "KQ_mask", -1);
  4617. for (int il = 0; il < n_layer; ++il) {
  4618. struct ggml_tensor * inpSA = inpL;
  4619. cur = llm_build_norm(ctx0, inpL, hparams,
  4620. model.layers[il].attn_norm, NULL,
  4621. LLM_NORM_RMS, cb, il);
  4622. cb(cur, "attn_norm", il);
  4623. // self-attention
  4624. {
  4625. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4626. cb(Qcur, "Qcur", il);
  4627. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4628. cb(Kcur, "Kcur", il);
  4629. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4630. cb(Vcur, "Vcur", il);
  4631. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4632. cb(Kcur, "Kcur", il);
  4633. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4634. cb(Qcur, "Qcur", il);
  4635. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4636. model.layers[il].wo, NULL,
  4637. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4638. cb(cur, "kqv_out", il);
  4639. }
  4640. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4641. cb(ffn_inp, "ffn_inp", il);
  4642. // feed-forward network
  4643. {
  4644. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4645. model.layers[il].ffn_norm, NULL,
  4646. LLM_NORM_RMS, cb, il);
  4647. cb(cur, "ffn_norm", il);
  4648. cur = llm_build_ffn(ctx0, cur,
  4649. model.layers[il].ffn_up, NULL,
  4650. model.layers[il].ffn_gate, NULL,
  4651. model.layers[il].ffn_down, NULL,
  4652. NULL,
  4653. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4654. cb(cur, "ffn_out", il);
  4655. }
  4656. cur = ggml_add(ctx0, cur, ffn_inp);
  4657. cb(cur, "l_out", il);
  4658. // input for next layer
  4659. inpL = cur;
  4660. }
  4661. cur = inpL;
  4662. cur = llm_build_norm(ctx0, cur, hparams,
  4663. model.output_norm, NULL,
  4664. LLM_NORM_RMS, cb, -1);
  4665. cb(cur, "result_norm", -1);
  4666. // lm_head
  4667. cur = ggml_mul_mat(ctx0, model.output, cur);
  4668. cb(cur, "result_output", -1);
  4669. ggml_build_forward_expand(gf, cur);
  4670. return gf;
  4671. }
  4672. struct ggml_cgraph * build_bloom() {
  4673. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4674. const int64_t n_embd_head = hparams.n_embd_head_v;
  4675. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4676. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4677. struct ggml_tensor * cur;
  4678. struct ggml_tensor * inpL;
  4679. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4680. cb(inpL, "inp_embd", -1);
  4681. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4682. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4683. cb(KQ_mask, "KQ_mask", -1);
  4684. inpL = llm_build_norm(ctx0, inpL, hparams,
  4685. model.tok_norm,
  4686. model.tok_norm_b,
  4687. LLM_NORM, cb, -1);
  4688. cb(inpL, "inp_norm", -1);
  4689. for (int il = 0; il < n_layer; ++il) {
  4690. cur = llm_build_norm(ctx0, inpL, hparams,
  4691. model.layers[il].attn_norm,
  4692. model.layers[il].attn_norm_b,
  4693. LLM_NORM, cb, il);
  4694. cb(cur, "attn_norm", il);
  4695. // self-attention
  4696. {
  4697. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4698. cb(cur, "wqkv", il);
  4699. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4700. cb(cur, "bqkv", il);
  4701. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4702. 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)));
  4703. 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)));
  4704. cb(Qcur, "Qcur", il);
  4705. cb(Kcur, "Kcur", il);
  4706. cb(Vcur, "Vcur", il);
  4707. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4708. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4709. model.layers[il].wo, model.layers[il].bo,
  4710. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4711. cb(cur, "kqv_out", il);
  4712. }
  4713. // Add the input
  4714. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4715. cb(ffn_inp, "ffn_inp", il);
  4716. // FF
  4717. {
  4718. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4719. model.layers[il].ffn_norm,
  4720. model.layers[il].ffn_norm_b,
  4721. LLM_NORM, cb, il);
  4722. cb(cur, "ffn_norm", il);
  4723. cur = llm_build_ffn(ctx0, cur,
  4724. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4725. NULL, NULL,
  4726. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4727. NULL,
  4728. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4729. cb(cur, "ffn_out", il);
  4730. }
  4731. inpL = ggml_add(ctx0, cur, ffn_inp);
  4732. cb(inpL, "l_out", il);
  4733. }
  4734. cur = llm_build_norm(ctx0, inpL, hparams,
  4735. model.output_norm,
  4736. model.output_norm_b,
  4737. LLM_NORM, cb, -1);
  4738. cb(cur, "result_norm", -1);
  4739. cur = ggml_mul_mat(ctx0, model.output, cur);
  4740. cb(cur, "result_output", -1);
  4741. ggml_build_forward_expand(gf, cur);
  4742. return gf;
  4743. }
  4744. struct ggml_cgraph * build_mpt() {
  4745. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4746. const int64_t n_embd_head = hparams.n_embd_head_v;
  4747. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4748. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4749. struct ggml_tensor * cur;
  4750. struct ggml_tensor * inpL;
  4751. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4752. cb(inpL, "inp_embd", -1);
  4753. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4754. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4755. cb(KQ_mask, "KQ_mask", -1);
  4756. for (int il = 0; il < n_layer; ++il) {
  4757. struct ggml_tensor * attn_norm;
  4758. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4759. model.layers[il].attn_norm,
  4760. NULL,
  4761. LLM_NORM, cb, il);
  4762. cb(attn_norm, "attn_norm", il);
  4763. // self-attention
  4764. {
  4765. cur = attn_norm;
  4766. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4767. cb(cur, "wqkv", il);
  4768. if (hparams.f_clamp_kqv > 0.0f) {
  4769. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4770. cb(cur, "wqkv_clamped", il);
  4771. }
  4772. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4773. 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)));
  4774. 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)));
  4775. cb(Qcur, "Qcur", il);
  4776. cb(Kcur, "Kcur", il);
  4777. cb(Vcur, "Vcur", il);
  4778. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4779. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4780. model.layers[il].wo, NULL,
  4781. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, hparams.f_max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4782. cb(cur, "kqv_out", il);
  4783. }
  4784. // Add the input
  4785. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4786. cb(ffn_inp, "ffn_inp", il);
  4787. // feed forward
  4788. {
  4789. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4790. model.layers[il].ffn_norm,
  4791. NULL,
  4792. LLM_NORM, cb, il);
  4793. cb(cur, "ffn_norm", il);
  4794. cur = llm_build_ffn(ctx0, cur,
  4795. model.layers[il].ffn_up, NULL,
  4796. NULL, NULL,
  4797. model.layers[il].ffn_down, NULL,
  4798. model.layers[il].ffn_act,
  4799. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4800. cb(cur, "ffn_out", il);
  4801. }
  4802. cur = ggml_add(ctx0, cur, ffn_inp);
  4803. cb(cur, "l_out", il);
  4804. // input for next layer
  4805. inpL = cur;
  4806. }
  4807. cur = inpL;
  4808. cur = llm_build_norm(ctx0, cur, hparams,
  4809. model.output_norm,
  4810. NULL,
  4811. LLM_NORM, cb, -1);
  4812. cb(cur, "result_norm", -1);
  4813. cur = ggml_mul_mat(ctx0, model.output, cur);
  4814. cb(cur, "result_output", -1);
  4815. ggml_build_forward_expand(gf, cur);
  4816. return gf;
  4817. }
  4818. struct ggml_cgraph * build_stablelm() {
  4819. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4820. const int64_t n_embd_head = hparams.n_embd_head_v;
  4821. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4822. struct ggml_tensor * cur;
  4823. struct ggml_tensor * inpL;
  4824. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4825. cb(inpL, "inp_embd", -1);
  4826. // inp_pos - contains the positions
  4827. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4828. cb(inp_pos, "inp_pos", -1);
  4829. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4830. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4831. cb(KQ_mask, "KQ_mask", -1);
  4832. // shift the entire K-cache if needed
  4833. if (do_rope_shift) {
  4834. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4835. }
  4836. for (int il = 0; il < n_layer; ++il) {
  4837. struct ggml_tensor * inpSA = inpL;
  4838. // norm
  4839. cur = llm_build_norm(ctx0, inpL, hparams,
  4840. model.layers[il].attn_norm,
  4841. model.layers[il].attn_norm_b,
  4842. LLM_NORM, cb, il);
  4843. cb(cur, "attn_norm", il);
  4844. // self-attention
  4845. {
  4846. // compute Q and K and RoPE them
  4847. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4848. cb(Qcur, "Qcur", il);
  4849. if (model.layers[il].bq) {
  4850. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4851. cb(Qcur, "Qcur", il);
  4852. }
  4853. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4854. cb(Kcur, "Kcur", il);
  4855. if (model.layers[il].bk) {
  4856. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4857. cb(Kcur, "Kcur", il);
  4858. }
  4859. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4860. cb(Vcur, "Vcur", il);
  4861. if (model.layers[il].bv) {
  4862. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4863. cb(Vcur, "Vcur", il);
  4864. }
  4865. Qcur = ggml_rope_custom(
  4866. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4867. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4868. ext_factor, attn_factor, beta_fast, beta_slow
  4869. );
  4870. cb(Qcur, "Qcur", il);
  4871. Kcur = ggml_rope_custom(
  4872. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4873. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4874. ext_factor, attn_factor, beta_fast, beta_slow
  4875. );
  4876. cb(Kcur, "Kcur", il);
  4877. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4878. model.layers[il].wo, NULL,
  4879. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4880. cb(cur, "kqv_out", il);
  4881. }
  4882. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4883. cb(ffn_inp, "ffn_inp", il);
  4884. // feed-forward network
  4885. {
  4886. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4887. model.layers[il].ffn_norm,
  4888. model.layers[il].ffn_norm_b,
  4889. LLM_NORM, cb, il);
  4890. cb(cur, "ffn_norm", il);
  4891. cur = llm_build_ffn(ctx0, cur,
  4892. model.layers[il].ffn_up, NULL,
  4893. model.layers[il].ffn_gate, NULL,
  4894. model.layers[il].ffn_down, NULL,
  4895. NULL,
  4896. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4897. cb(cur, "ffn_out", il);
  4898. }
  4899. cur = ggml_add(ctx0, cur, ffn_inp);
  4900. cb(cur, "l_out", il);
  4901. // input for next layer
  4902. inpL = cur;
  4903. }
  4904. cur = inpL;
  4905. cur = llm_build_norm(ctx0, cur, hparams,
  4906. model.output_norm,
  4907. model.output_norm_b,
  4908. LLM_NORM, cb, -1);
  4909. cb(cur, "result_norm", -1);
  4910. // lm_head
  4911. cur = ggml_mul_mat(ctx0, model.output, cur);
  4912. cb(cur, "result_output", -1);
  4913. ggml_build_forward_expand(gf, cur);
  4914. return gf;
  4915. }
  4916. struct ggml_cgraph * build_qwen() {
  4917. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4918. const int64_t n_embd_head = hparams.n_embd_head_v;
  4919. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4920. struct ggml_tensor * cur;
  4921. struct ggml_tensor * inpL;
  4922. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4923. cb(inpL, "inp_embd", -1);
  4924. // inp_pos - contains the positions
  4925. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4926. cb(inp_pos, "inp_pos", -1);
  4927. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4928. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4929. cb(KQ_mask, "KQ_mask", -1);
  4930. // shift the entire K-cache if needed
  4931. if (do_rope_shift) {
  4932. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4933. }
  4934. for (int il = 0; il < n_layer; ++il) {
  4935. struct ggml_tensor * inpSA = inpL;
  4936. cur = llm_build_norm(ctx0, inpL, hparams,
  4937. model.layers[il].attn_norm, NULL,
  4938. LLM_NORM_RMS, cb, il);
  4939. cb(cur, "attn_norm", il);
  4940. // self-attention
  4941. {
  4942. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4943. cb(cur, "wqkv", il);
  4944. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4945. cb(cur, "bqkv", il);
  4946. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4947. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4948. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  4949. cb(Qcur, "Qcur", il);
  4950. cb(Kcur, "Kcur", il);
  4951. cb(Vcur, "Vcur", il);
  4952. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4953. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4954. // using mode = 2 for neox mode
  4955. Qcur = ggml_rope_custom(
  4956. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4957. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4958. );
  4959. cb(Qcur, "Qcur", il);
  4960. Kcur = ggml_rope_custom(
  4961. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4962. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4963. );
  4964. cb(Kcur, "Kcur", il);
  4965. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4966. model.layers[il].wo, NULL,
  4967. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4968. cb(cur, "kqv_out", il);
  4969. }
  4970. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4971. cb(ffn_inp, "ffn_inp", il);
  4972. // feed-forward forward
  4973. {
  4974. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4975. model.layers[il].ffn_norm, NULL,
  4976. LLM_NORM_RMS, cb, il);
  4977. cb(cur, "ffn_norm", il);
  4978. cur = llm_build_ffn(ctx0, cur,
  4979. model.layers[il].ffn_up, NULL,
  4980. model.layers[il].ffn_gate, NULL,
  4981. model.layers[il].ffn_down, NULL,
  4982. NULL,
  4983. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4984. cb(cur, "ffn_out", il);
  4985. }
  4986. cur = ggml_add(ctx0, cur, ffn_inp);
  4987. cb(cur, "l_out", il);
  4988. // input for next layer
  4989. inpL = cur;
  4990. }
  4991. cur = inpL;
  4992. cur = llm_build_norm(ctx0, cur, hparams,
  4993. model.output_norm, NULL,
  4994. LLM_NORM_RMS, cb, -1);
  4995. cb(cur, "result_norm", -1);
  4996. // lm_head
  4997. cur = ggml_mul_mat(ctx0, model.output, cur);
  4998. cb(cur, "result_output", -1);
  4999. ggml_build_forward_expand(gf, cur);
  5000. return gf;
  5001. }
  5002. struct ggml_cgraph * build_qwen2() {
  5003. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5004. const int64_t n_embd_head = hparams.n_embd_head_v;
  5005. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5006. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5007. struct ggml_tensor * cur;
  5008. struct ggml_tensor * inpL;
  5009. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5010. cb(inpL, "inp_embd", -1);
  5011. // inp_pos - contains the positions
  5012. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5013. cb(inp_pos, "inp_pos", -1);
  5014. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5015. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5016. cb(KQ_mask, "KQ_mask", -1);
  5017. // shift the entire K-cache if needed
  5018. if (do_rope_shift) {
  5019. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5020. }
  5021. for (int il = 0; il < n_layer; ++il) {
  5022. struct ggml_tensor * inpSA = inpL;
  5023. // norm
  5024. cur = llm_build_norm(ctx0, inpL, hparams,
  5025. model.layers[il].attn_norm, NULL,
  5026. LLM_NORM_RMS, cb, il);
  5027. cb(cur, "attn_norm", il);
  5028. // self-attention
  5029. {
  5030. // compute Q and K and RoPE them
  5031. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5032. cb(Qcur, "Qcur", il);
  5033. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5034. cb(Qcur, "Qcur", il);
  5035. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5036. cb(Kcur, "Kcur", il);
  5037. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5038. cb(Kcur, "Kcur", il);
  5039. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5040. cb(Vcur, "Vcur", il);
  5041. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5042. cb(Vcur, "Vcur", il);
  5043. // these nodes are added to the graph together so that they are not reordered
  5044. // by doing so, the number of splits in the graph is reduced
  5045. ggml_build_forward_expand(gf, Qcur);
  5046. ggml_build_forward_expand(gf, Kcur);
  5047. ggml_build_forward_expand(gf, Vcur);
  5048. Qcur = ggml_rope_custom(
  5049. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5050. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5051. ext_factor, attn_factor, beta_fast, beta_slow
  5052. );
  5053. cb(Qcur, "Qcur", il);
  5054. Kcur = ggml_rope_custom(
  5055. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5056. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5057. ext_factor, attn_factor, beta_fast, beta_slow
  5058. );
  5059. cb(Kcur, "Kcur", il);
  5060. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5061. model.layers[il].wo, model.layers[il].bo,
  5062. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5063. cb(cur, "kqv_out", il);
  5064. }
  5065. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5066. cb(ffn_inp, "ffn_inp", il);
  5067. // feed-forward network
  5068. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5069. model.layers[il].ffn_norm, NULL,
  5070. LLM_NORM_RMS, cb, il);
  5071. cb(cur, "ffn_norm", il);
  5072. cur = llm_build_ffn(ctx0, cur,
  5073. model.layers[il].ffn_up, NULL,
  5074. model.layers[il].ffn_gate, NULL,
  5075. model.layers[il].ffn_down, NULL,
  5076. NULL,
  5077. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5078. cb(cur, "ffn_out", il);
  5079. cur = ggml_add(ctx0, cur, ffn_inp);
  5080. cb(cur, "l_out", il);
  5081. // input for next layer
  5082. inpL = cur;
  5083. }
  5084. cur = inpL;
  5085. cur = llm_build_norm(ctx0, cur, hparams,
  5086. model.output_norm, NULL,
  5087. LLM_NORM_RMS, cb, -1);
  5088. cb(cur, "result_norm", -1);
  5089. // lm_head
  5090. cur = ggml_mul_mat(ctx0, model.output, cur);
  5091. cb(cur, "result_output", -1);
  5092. ggml_build_forward_expand(gf, cur);
  5093. return gf;
  5094. }
  5095. struct ggml_cgraph * build_phi2() {
  5096. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5097. const int64_t n_embd_head = hparams.n_embd_head_v;
  5098. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5099. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5100. struct ggml_tensor * cur;
  5101. struct ggml_tensor * attn_norm_output;
  5102. struct ggml_tensor * ffn_output;
  5103. struct ggml_tensor * inpL;
  5104. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5105. cb(inpL, "inp_embd", -1);
  5106. // inp_pos - contains the positions
  5107. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5108. cb(inp_pos, "inp_pos", -1);
  5109. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5110. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5111. cb(KQ_mask, "KQ_mask", -1);
  5112. // shift the entire K-cache if needed
  5113. if (do_rope_shift) {
  5114. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5115. }
  5116. for (int il = 0; il < n_layer; ++il) {
  5117. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5118. model.layers[il].attn_norm,
  5119. model.layers[il].attn_norm_b,
  5120. LLM_NORM, cb, il);
  5121. cb(attn_norm_output, "attn_norm", il);
  5122. // self-attention
  5123. {
  5124. struct ggml_tensor * Qcur = nullptr;
  5125. struct ggml_tensor * Kcur = nullptr;
  5126. struct ggml_tensor * Vcur = nullptr;
  5127. if (model.layers[il].wqkv) {
  5128. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5129. cb(cur, "wqkv", il);
  5130. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5131. cb(cur, "bqkv", il);
  5132. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5133. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5134. 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)));
  5135. } else {
  5136. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5137. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5138. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5139. }
  5140. cb(Qcur, "Qcur", il);
  5141. cb(Kcur, "Kcur", il);
  5142. cb(Vcur, "Vcur", il);
  5143. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5144. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5145. Qcur = ggml_rope_custom(
  5146. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5147. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5148. );
  5149. cb(Qcur, "Qcur", il);
  5150. // with phi2, we scale the Q to avoid precision issues
  5151. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5152. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5153. cb(Qcur, "Qcur", il);
  5154. Kcur = ggml_rope_custom(
  5155. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5156. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5157. );
  5158. cb(Kcur, "Kcur", il);
  5159. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5160. model.layers[il].wo, model.layers[il].bo,
  5161. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f, cb, il);
  5162. cb(cur, "kqv_out", il);
  5163. }
  5164. // FF
  5165. {
  5166. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5167. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5168. NULL, NULL,
  5169. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5170. NULL,
  5171. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5172. cb(ffn_output, "ffn_out", il);
  5173. }
  5174. cur = ggml_add(ctx0, cur, ffn_output);
  5175. cb(cur, "l_out", il);
  5176. cur = ggml_add(ctx0, cur, inpL);
  5177. cb(cur, "l_out", il);
  5178. inpL = cur;
  5179. }
  5180. cur = llm_build_norm(ctx0, inpL, hparams,
  5181. model.output_norm,
  5182. model.output_norm_b,
  5183. LLM_NORM, cb, -1);
  5184. cb(cur, "result_norm", -1);
  5185. cur = ggml_mul_mat(ctx0, model.output, cur);
  5186. cb(cur, "result_output_no_bias", -1);
  5187. cur = ggml_add(ctx0, cur, model.output_b);
  5188. cb(cur, "result_output", -1);
  5189. ggml_build_forward_expand(gf, cur);
  5190. return gf;
  5191. }
  5192. struct ggml_cgraph * build_plamo() {
  5193. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5194. const int64_t n_embd_head = hparams.n_embd_head_v;
  5195. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5196. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5197. struct ggml_tensor * cur;
  5198. struct ggml_tensor * inpL;
  5199. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5200. cb(inpL, "inp_embd", -1);
  5201. // inp_pos - contains the positions
  5202. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5203. cb(inp_pos, "inp_pos", -1);
  5204. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5205. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5206. cb(KQ_mask, "KQ_mask", -1);
  5207. // shift the entire K-cache if needed
  5208. if (do_rope_shift) {
  5209. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5210. }
  5211. for (int il = 0; il < n_layer; ++il) {
  5212. // norm
  5213. cur = llm_build_norm(ctx0, inpL, hparams,
  5214. model.layers[il].attn_norm, NULL,
  5215. LLM_NORM_RMS, cb, il);
  5216. cb(cur, "attn_norm", il);
  5217. struct ggml_tensor * attention_norm = cur;
  5218. // self-attention
  5219. {
  5220. // compute Q and K and RoPE them
  5221. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5222. cb(Qcur, "Qcur", il);
  5223. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5224. cb(Kcur, "Kcur", il);
  5225. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5226. cb(Vcur, "Vcur", il);
  5227. Qcur = ggml_rope_custom(
  5228. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5229. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5230. ext_factor, attn_factor, beta_fast, beta_slow);
  5231. cb(Qcur, "Qcur", il);
  5232. Kcur = ggml_rope_custom(
  5233. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5234. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5235. ext_factor, attn_factor, beta_fast, beta_slow);
  5236. cb(Kcur, "Kcur", il);
  5237. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5238. model.layers[il].wo, NULL,
  5239. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5240. cb(cur, "kqv_out", il);
  5241. }
  5242. struct ggml_tensor * sa_out = cur;
  5243. cur = attention_norm;
  5244. // feed-forward network
  5245. {
  5246. cur = llm_build_ffn(ctx0, cur,
  5247. model.layers[il].ffn_up, NULL,
  5248. model.layers[il].ffn_gate, NULL,
  5249. model.layers[il].ffn_down, NULL,
  5250. NULL,
  5251. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5252. cb(cur, "ffn_out", il);
  5253. }
  5254. cur = ggml_add(ctx0, cur, sa_out);
  5255. cb(cur, "l_out", il);
  5256. cur = ggml_add(ctx0, cur, inpL);
  5257. cb(cur, "l_out", il);
  5258. // input for next layer
  5259. inpL = cur;
  5260. }
  5261. cur = inpL;
  5262. cur = llm_build_norm(ctx0, cur, hparams,
  5263. model.output_norm, NULL,
  5264. LLM_NORM_RMS, cb, -1);
  5265. cb(cur, "result_norm", -1);
  5266. // lm_head
  5267. cur = ggml_mul_mat(ctx0, model.output, cur);
  5268. cb(cur, "result_output", -1);
  5269. ggml_build_forward_expand(gf, cur);
  5270. return gf;
  5271. }
  5272. struct ggml_cgraph * build_gpt2() {
  5273. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5274. const int64_t n_embd_head = hparams.n_embd_head_v;
  5275. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5276. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5277. struct ggml_tensor * cur;
  5278. struct ggml_tensor * pos;
  5279. struct ggml_tensor * inpL;
  5280. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5281. cb(inpL, "inp_embd", -1);
  5282. // inp_pos - contains the positions
  5283. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5284. cb(inp_pos, "inp_pos", -1);
  5285. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5286. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5287. cb(KQ_mask, "KQ_mask", -1);
  5288. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5289. cb(pos, "pos_embd", -1);
  5290. inpL = ggml_add(ctx0, inpL, pos);
  5291. cb(inpL, "inpL", -1);
  5292. for (int il = 0; il < n_layer; ++il) {
  5293. cur = llm_build_norm(ctx0, inpL, hparams,
  5294. model.layers[il].attn_norm,
  5295. model.layers[il].attn_norm_b,
  5296. LLM_NORM, cb, il);
  5297. cb(cur, "attn_norm", il);
  5298. // self-attention
  5299. {
  5300. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5301. cb(cur, "wqkv", il);
  5302. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5303. cb(cur, "bqkv", il);
  5304. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5305. 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)));
  5306. 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)));
  5307. cb(Qcur, "Qcur", il);
  5308. cb(Kcur, "Kcur", il);
  5309. cb(Vcur, "Vcur", il);
  5310. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5311. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5312. model.layers[il].wo, model.layers[il].bo,
  5313. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5314. cb(cur, "kqv_out", il);
  5315. }
  5316. // add the input
  5317. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5318. cb(ffn_inp, "ffn_inp", il);
  5319. // FF
  5320. {
  5321. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5322. model.layers[il].ffn_norm,
  5323. model.layers[il].ffn_norm_b,
  5324. LLM_NORM, cb, il);
  5325. cb(cur, "ffn_norm", il);
  5326. cur = llm_build_ffn(ctx0, cur,
  5327. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5328. NULL, NULL,
  5329. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5330. NULL,
  5331. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5332. cb(cur, "ffn_out", il);
  5333. }
  5334. inpL = ggml_add(ctx0, cur, ffn_inp);
  5335. cb(inpL, "l_out", il);
  5336. }
  5337. cur = llm_build_norm(ctx0, inpL, hparams,
  5338. model.output_norm,
  5339. model.output_norm_b,
  5340. LLM_NORM, cb, -1);
  5341. cb(cur, "result_norm", -1);
  5342. cur = ggml_mul_mat(ctx0, model.output, cur);
  5343. cb(cur, "result_output", -1);
  5344. ggml_build_forward_expand(gf, cur);
  5345. return gf;
  5346. }
  5347. struct ggml_cgraph * build_codeshell() {
  5348. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5349. const int64_t n_embd_head = hparams.n_embd_head_v;
  5350. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5351. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5352. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5353. struct ggml_tensor * cur;
  5354. struct ggml_tensor * inpL;
  5355. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5356. cb(inpL, "inp_embd", -1);
  5357. // inp_pos - contains the positions
  5358. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5359. cb(inp_pos, "inp_pos", -1);
  5360. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5361. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5362. cb(KQ_mask, "KQ_mask", -1);
  5363. // shift the entire K-cache if needed
  5364. if (do_rope_shift) {
  5365. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5366. }
  5367. for (int il = 0; il < n_layer; ++il) {
  5368. cur = llm_build_norm(ctx0, inpL, hparams,
  5369. model.layers[il].attn_norm,
  5370. model.layers[il].attn_norm_b,
  5371. LLM_NORM, cb, il);
  5372. cb(cur, "attn_norm", il);
  5373. // self-attention
  5374. {
  5375. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5376. cb(cur, "wqkv", il);
  5377. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5378. cb(cur, "bqkv", il);
  5379. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5380. struct ggml_tensor * tmpk = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5381. 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)));
  5382. cb(tmpq, "tmpq", il);
  5383. cb(tmpk, "tmpk", il);
  5384. cb(Vcur, "Vcur", il);
  5385. struct ggml_tensor * Qcur = ggml_rope_custom(
  5386. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5387. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5388. ext_factor, attn_factor, beta_fast, beta_slow
  5389. );
  5390. cb(Qcur, "Qcur", il);
  5391. struct ggml_tensor * Kcur = ggml_rope_custom(
  5392. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5393. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5394. ext_factor, attn_factor, beta_fast, beta_slow
  5395. );
  5396. cb(Kcur, "Kcur", il);
  5397. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5398. model.layers[il].wo, model.layers[il].bo,
  5399. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5400. cb(cur, "kqv_out", il);
  5401. }
  5402. // add the input
  5403. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5404. cb(ffn_inp, "ffn_inp", il);
  5405. // FF
  5406. {
  5407. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5408. model.layers[il].ffn_norm,
  5409. model.layers[il].ffn_norm_b,
  5410. LLM_NORM, cb, il);
  5411. cb(cur, "ffn_norm", il);
  5412. cur = llm_build_ffn(ctx0, cur,
  5413. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5414. NULL, NULL,
  5415. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5416. NULL,
  5417. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5418. cb(cur, "ffn_out", il);
  5419. }
  5420. inpL = ggml_add(ctx0, cur, ffn_inp);
  5421. cb(inpL, "l_out", il);
  5422. }
  5423. cur = llm_build_norm(ctx0, inpL, hparams,
  5424. model.output_norm,
  5425. model.output_norm_b,
  5426. LLM_NORM, cb, -1);
  5427. cb(cur, "result_norm", -1);
  5428. cur = ggml_mul_mat(ctx0, model.output, cur);
  5429. cb(cur, "result_output", -1);
  5430. ggml_build_forward_expand(gf, cur);
  5431. return gf;
  5432. }
  5433. };
  5434. static struct ggml_cgraph * llama_build_graph(
  5435. llama_context & lctx,
  5436. const llama_batch & batch) {
  5437. const auto & model = lctx.model;
  5438. // check if we should build the worst-case graph (for memory measurement)
  5439. const bool worst_case = ggml_tallocr_is_measure(lctx.alloc);
  5440. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  5441. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  5442. if (il >= 0) {
  5443. ggml_format_name(cur, "%s-%d", name, il);
  5444. } else {
  5445. ggml_set_name(cur, name);
  5446. }
  5447. if (!lctx.cparams.offload_kqv) {
  5448. if (strcmp(name, "kqv_merged_cont") == 0) {
  5449. // all nodes between the KV store and the attention output are run on the CPU
  5450. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  5451. }
  5452. }
  5453. };
  5454. struct ggml_cgraph * result = NULL;
  5455. struct llm_build_context llm(lctx, batch, cb, worst_case);
  5456. //
  5457. // set input data
  5458. //
  5459. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5460. if (batch.token) {
  5461. const int64_t n_tokens = batch.n_tokens;
  5462. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  5463. }
  5464. if (batch.embd) {
  5465. const int64_t n_embd = llm.n_embd;
  5466. const int64_t n_tokens = batch.n_tokens;
  5467. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  5468. }
  5469. if (batch.pos) {
  5470. const int64_t n_tokens = batch.n_tokens;
  5471. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  5472. }
  5473. {
  5474. const int64_t n_kv = llm.n_kv;
  5475. const int64_t n_tokens = batch.n_tokens;
  5476. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  5477. float * data = (float *) lctx.inp_KQ_mask->data;
  5478. for (int h = 0; h < 1; ++h) {
  5479. for (int j = 0; j < n_tokens; ++j) {
  5480. const llama_pos pos = batch.pos[j];
  5481. const llama_seq_id seq_id = batch.seq_id[j][0];
  5482. for (int i = 0; i < n_kv; ++i) {
  5483. float f;
  5484. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  5485. f = -INFINITY;
  5486. } else {
  5487. f = 0;
  5488. }
  5489. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  5490. }
  5491. }
  5492. }
  5493. }
  5494. if (llm.do_rope_shift) {
  5495. const int64_t n_ctx = llm.n_ctx;
  5496. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  5497. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  5498. for (int i = 0; i < n_ctx; ++i) {
  5499. data[i] = lctx.kv_self.cells[i].delta;
  5500. }
  5501. }
  5502. }
  5503. llm.init();
  5504. switch (model.arch) {
  5505. case LLM_ARCH_LLAMA:
  5506. {
  5507. result = llm.build_llama();
  5508. } break;
  5509. case LLM_ARCH_BAICHUAN:
  5510. {
  5511. result = llm.build_baichuan();
  5512. } break;
  5513. case LLM_ARCH_FALCON:
  5514. {
  5515. result = llm.build_falcon();
  5516. } break;
  5517. case LLM_ARCH_STARCODER:
  5518. {
  5519. result = llm.build_starcoder();
  5520. } break;
  5521. case LLM_ARCH_PERSIMMON:
  5522. {
  5523. result = llm.build_persimmon();
  5524. } break;
  5525. case LLM_ARCH_REFACT:
  5526. {
  5527. result = llm.build_refact();
  5528. } break;
  5529. case LLM_ARCH_BLOOM:
  5530. {
  5531. result = llm.build_bloom();
  5532. } break;
  5533. case LLM_ARCH_MPT:
  5534. {
  5535. result = llm.build_mpt();
  5536. } break;
  5537. case LLM_ARCH_STABLELM:
  5538. {
  5539. result = llm.build_stablelm();
  5540. } break;
  5541. case LLM_ARCH_QWEN:
  5542. {
  5543. result = llm.build_qwen();
  5544. } break;
  5545. case LLM_ARCH_QWEN2:
  5546. {
  5547. result = llm.build_qwen2();
  5548. } break;
  5549. case LLM_ARCH_PHI2:
  5550. {
  5551. result = llm.build_phi2();
  5552. } break;
  5553. case LLM_ARCH_PLAMO:
  5554. {
  5555. result = llm.build_plamo();
  5556. } break;
  5557. case LLM_ARCH_GPT2:
  5558. {
  5559. result = llm.build_gpt2();
  5560. } break;
  5561. case LLM_ARCH_CODESHELL:
  5562. {
  5563. result = llm.build_codeshell();
  5564. } break;
  5565. case LLM_ARCH_ORION:
  5566. {
  5567. result = llm.build_orion();
  5568. } break;
  5569. default:
  5570. GGML_ASSERT(false);
  5571. }
  5572. llm.free();
  5573. return result;
  5574. }
  5575. // decode a batch of tokens by evaluating the transformer
  5576. //
  5577. // - lctx: llama context
  5578. // - batch: batch to evaluate
  5579. //
  5580. // return 0 on success
  5581. // return positive int on warning
  5582. // return negative int on error
  5583. //
  5584. static int llama_decode_internal(
  5585. llama_context & lctx,
  5586. llama_batch batch) {
  5587. const uint32_t n_tokens = batch.n_tokens;
  5588. if (n_tokens == 0) {
  5589. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  5590. return -1;
  5591. }
  5592. const auto & model = lctx.model;
  5593. const auto & hparams = model.hparams;
  5594. const auto & cparams = lctx.cparams;
  5595. const auto n_batch = cparams.n_batch;
  5596. GGML_ASSERT(n_tokens <= n_batch);
  5597. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  5598. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  5599. const int64_t t_start_us = ggml_time_us();
  5600. #ifdef GGML_USE_MPI
  5601. // TODO: needs fix after #3228
  5602. GGML_ASSERT(false && "not implemented");
  5603. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  5604. #endif
  5605. GGML_ASSERT(n_threads > 0);
  5606. auto & kv_self = lctx.kv_self;
  5607. const int64_t n_embd = hparams.n_embd;
  5608. const int64_t n_vocab = hparams.n_vocab;
  5609. // helpers for smoother batch API transition
  5610. // after deprecating the llama_eval calls, these will be removed
  5611. std::vector<llama_pos> pos;
  5612. std::vector<int32_t> n_seq_id;
  5613. std::vector<llama_seq_id *> seq_id_arr;
  5614. std::vector<std::vector<llama_seq_id>> seq_id;
  5615. if (batch.pos == nullptr) {
  5616. pos.resize(n_tokens);
  5617. for (uint32_t i = 0; i < n_tokens; i++) {
  5618. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  5619. }
  5620. batch.pos = pos.data();
  5621. }
  5622. if (batch.seq_id == nullptr) {
  5623. n_seq_id.resize(n_tokens);
  5624. seq_id.resize(n_tokens);
  5625. seq_id_arr.resize(n_tokens);
  5626. for (uint32_t i = 0; i < n_tokens; i++) {
  5627. n_seq_id[i] = 1;
  5628. seq_id[i].resize(1);
  5629. seq_id[i][0] = batch.all_seq_id;
  5630. seq_id_arr[i] = seq_id[i].data();
  5631. }
  5632. batch.n_seq_id = n_seq_id.data();
  5633. batch.seq_id = seq_id_arr.data();
  5634. }
  5635. // if we have enough unused cells before the current head ->
  5636. // better to start searching from the beginning of the cache, hoping to fill it
  5637. if (kv_self.head > kv_self.used + 2*n_tokens) {
  5638. kv_self.head = 0;
  5639. }
  5640. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  5641. return 1;
  5642. }
  5643. // a heuristic, to avoid attending the full cache if it is not yet utilized
  5644. // after enough generations, the benefit from this heuristic disappears
  5645. // if we start defragmenting the cache, the benefit from this will be more important
  5646. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  5647. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  5648. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  5649. ggml_backend_sched_reset(lctx.sched);
  5650. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  5651. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  5652. // the output is always the last tensor in the graph
  5653. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  5654. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  5655. // the embeddings could be the second to last tensor, or the third to last tensor
  5656. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  5657. if (strcmp(embeddings->name, "result_norm") != 0) {
  5658. embeddings = gf->nodes[gf->n_nodes - 3];
  5659. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  5660. }
  5661. // 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);
  5662. // for big prompts, if BLAS is enabled, it is better to use only one thread
  5663. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  5664. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  5665. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  5666. // with the BLAS calls. need a better solution
  5667. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  5668. n_threads = std::min(4, n_threads);
  5669. }
  5670. const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 1;
  5671. if ((ggml_cpu_has_cublas() || ggml_cpu_has_vulkan()) && fully_offloaded) {
  5672. n_threads = 1;
  5673. }
  5674. #ifdef GGML_USE_MPI
  5675. const int64_t n_layer = hparams.n_layer;
  5676. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  5677. #endif
  5678. #ifdef GGML_USE_METAL
  5679. if (ggml_backend_is_metal(lctx.backend_metal)) {
  5680. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  5681. }
  5682. #endif
  5683. if (lctx.backend_cpu != nullptr) {
  5684. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  5685. }
  5686. ggml_backend_sched_graph_compute(lctx.sched, gf);
  5687. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  5688. #ifdef GGML_USE_MPI
  5689. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  5690. #endif
  5691. // update the kv ring buffer
  5692. {
  5693. if (kv_self.has_shift) {
  5694. kv_self.has_shift = false;
  5695. for (uint32_t i = 0; i < kv_self.size; ++i) {
  5696. kv_self.cells[i].delta = 0;
  5697. }
  5698. }
  5699. kv_self.head += n_tokens;
  5700. // Ensure kv cache head points to a valid index.
  5701. if (kv_self.head >= kv_self.size) {
  5702. kv_self.head = 0;
  5703. }
  5704. }
  5705. #ifdef GGML_PERF
  5706. // print timing information per ggml operation (for debugging purposes)
  5707. // requires GGML_PERF to be defined
  5708. ggml_graph_print(gf);
  5709. #endif
  5710. // plot the computation graph in dot format (for debugging purposes)
  5711. //if (n_past%100 == 0) {
  5712. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  5713. //}
  5714. // extract logits
  5715. // TODO: do not compute and extract logits if only embeddings are needed
  5716. // need to update the graphs to skip "result_output"
  5717. {
  5718. auto & logits_out = lctx.logits;
  5719. #ifndef NDEBUG
  5720. auto & logits_valid = lctx.logits_valid;
  5721. logits_valid.clear();
  5722. logits_valid.resize(n_tokens);
  5723. logits_out.clear();
  5724. #endif
  5725. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  5726. GGML_ASSERT(res_backend != nullptr);
  5727. if (batch.logits) {
  5728. logits_out.resize(n_vocab * n_tokens);
  5729. for (uint32_t i = 0; i < n_tokens; i++) {
  5730. if (batch.logits[i] == 0) {
  5731. continue;
  5732. }
  5733. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  5734. #ifndef NDEBUG
  5735. logits_valid[i] = true;
  5736. #endif
  5737. }
  5738. } else if (lctx.logits_all) {
  5739. logits_out.resize(n_vocab * n_tokens);
  5740. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  5741. #ifndef NDEBUG
  5742. std::fill(logits_valid.begin(), logits_valid.end(), true);
  5743. #endif
  5744. } else {
  5745. logits_out.resize(n_vocab);
  5746. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  5747. #ifndef NDEBUG
  5748. logits_valid[0] = true;
  5749. #endif
  5750. }
  5751. ggml_backend_synchronize(res_backend);
  5752. }
  5753. // extract embeddings
  5754. if (!lctx.embedding.empty()) {
  5755. auto & embedding_out = lctx.embedding;
  5756. embedding_out.resize(n_embd);
  5757. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  5758. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), (n_embd*(n_tokens - 1))*sizeof(float), n_embd*sizeof(float));
  5759. ggml_backend_synchronize(embeddings_backend);
  5760. }
  5761. // measure the performance only for the single-token evals
  5762. if (n_tokens == 1) {
  5763. lctx.t_eval_us += ggml_time_us() - t_start_us;
  5764. lctx.n_eval++;
  5765. }
  5766. else if (n_tokens > 1) {
  5767. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  5768. lctx.n_p_eval += n_tokens;
  5769. }
  5770. // get a more accurate load time, upon first eval
  5771. // TODO: fix this
  5772. if (!lctx.has_evaluated_once) {
  5773. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  5774. lctx.has_evaluated_once = true;
  5775. }
  5776. return 0;
  5777. }
  5778. //
  5779. // tokenizer
  5780. //
  5781. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  5782. return vocab.type;
  5783. }
  5784. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  5785. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  5786. }
  5787. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  5788. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  5789. }
  5790. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  5791. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  5792. }
  5793. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  5794. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  5795. }
  5796. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  5797. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  5798. }
  5799. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  5800. GGML_ASSERT(llama_is_byte_token(vocab, id));
  5801. const auto& token_data = vocab.id_to_token.at(id);
  5802. switch (llama_vocab_get_type(vocab)) {
  5803. case LLAMA_VOCAB_TYPE_SPM: {
  5804. auto buf = token_data.text.substr(3, 2);
  5805. return strtol(buf.c_str(), NULL, 16);
  5806. }
  5807. case LLAMA_VOCAB_TYPE_BPE: {
  5808. GGML_ASSERT(false);
  5809. return unicode_to_bytes_bpe(token_data.text);
  5810. }
  5811. default:
  5812. GGML_ASSERT(false);
  5813. }
  5814. }
  5815. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  5816. static const char * hex = "0123456789ABCDEF";
  5817. switch (llama_vocab_get_type(vocab)) {
  5818. case LLAMA_VOCAB_TYPE_SPM: {
  5819. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  5820. return vocab.token_to_id.at(buf);
  5821. }
  5822. case LLAMA_VOCAB_TYPE_BPE: {
  5823. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  5824. }
  5825. default:
  5826. GGML_ASSERT(false);
  5827. }
  5828. }
  5829. static void llama_escape_whitespace(std::string & text) {
  5830. replace_all(text, " ", "\xe2\x96\x81");
  5831. }
  5832. static void llama_unescape_whitespace(std::string & word) {
  5833. replace_all(word, "\xe2\x96\x81", " ");
  5834. }
  5835. struct llm_symbol {
  5836. using index = int;
  5837. index prev;
  5838. index next;
  5839. const char * text;
  5840. size_t n;
  5841. };
  5842. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  5843. // SPM tokenizer
  5844. // original implementation:
  5845. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  5846. struct llm_bigram_spm {
  5847. struct comparator {
  5848. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  5849. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  5850. }
  5851. };
  5852. using queue_storage = std::vector<llm_bigram_spm>;
  5853. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  5854. llm_symbol::index left;
  5855. llm_symbol::index right;
  5856. float score;
  5857. size_t size;
  5858. };
  5859. struct llm_tokenizer_spm {
  5860. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  5861. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5862. // split string into utf8 chars
  5863. int index = 0;
  5864. size_t offs = 0;
  5865. while (offs < text.size()) {
  5866. llm_symbol sym;
  5867. size_t len = utf8_len(text[offs]);
  5868. sym.text = text.c_str() + offs;
  5869. sym.n = std::min(len, text.size() - offs);
  5870. offs += sym.n;
  5871. sym.prev = index - 1;
  5872. sym.next = offs == text.size() ? -1 : index + 1;
  5873. index++;
  5874. symbols.emplace_back(sym);
  5875. }
  5876. // seed the work queue with all possible 2-character tokens.
  5877. for (size_t i = 1; i < symbols.size(); ++i) {
  5878. try_add_bigram(i - 1, i);
  5879. }
  5880. // keep substituting the highest frequency pairs for as long as we can.
  5881. while (!work_queue.empty()) {
  5882. auto bigram = work_queue.top();
  5883. work_queue.pop();
  5884. auto & left_sym = symbols[bigram.left];
  5885. auto & right_sym = symbols[bigram.right];
  5886. // if one of the symbols already got merged, skip it.
  5887. if (left_sym.n == 0 || right_sym.n == 0 ||
  5888. left_sym.n + right_sym.n != bigram.size) {
  5889. continue;
  5890. }
  5891. // merge the right sym into the left one
  5892. left_sym.n += right_sym.n;
  5893. right_sym.n = 0;
  5894. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  5895. // remove the right sym from the chain
  5896. left_sym.next = right_sym.next;
  5897. if (right_sym.next >= 0) {
  5898. symbols[right_sym.next].prev = bigram.left;
  5899. }
  5900. // find more substitutions
  5901. try_add_bigram(left_sym.prev, bigram.left);
  5902. try_add_bigram(bigram.left, left_sym.next);
  5903. }
  5904. for (int i = 0; i != -1; i = symbols[i].next) {
  5905. auto & symbol = symbols[i];
  5906. resegment(symbol, output);
  5907. }
  5908. }
  5909. private:
  5910. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  5911. auto text = std::string(symbol.text, symbol.n);
  5912. auto token = vocab.token_to_id.find(text);
  5913. // Do we need to support is_unused?
  5914. if (token != vocab.token_to_id.end()) {
  5915. output.push_back((*token).second);
  5916. return;
  5917. }
  5918. const auto p = rev_merge.find(text);
  5919. if (p == rev_merge.end()) {
  5920. // output any symbols that did not form tokens as bytes.
  5921. for (int j = 0; j < (int)symbol.n; ++j) {
  5922. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  5923. output.push_back(token_id);
  5924. }
  5925. return;
  5926. }
  5927. resegment(symbols[p->second.first], output);
  5928. resegment(symbols[p->second.second], output);
  5929. }
  5930. void try_add_bigram(int left, int right) {
  5931. if (left == -1 || right == -1) {
  5932. return;
  5933. }
  5934. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  5935. auto token = vocab.token_to_id.find(text);
  5936. if (token == vocab.token_to_id.end()) {
  5937. return;
  5938. }
  5939. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  5940. return;
  5941. }
  5942. const auto & tok_data = vocab.id_to_token[(*token).second];
  5943. llm_bigram_spm bigram;
  5944. bigram.left = left;
  5945. bigram.right = right;
  5946. bigram.score = tok_data.score;
  5947. bigram.size = text.size();
  5948. work_queue.push(bigram);
  5949. // Do we need to support is_unused?
  5950. rev_merge[text] = std::make_pair(left, right);
  5951. }
  5952. const llama_vocab & vocab;
  5953. std::vector<llm_symbol> symbols;
  5954. llm_bigram_spm::queue work_queue;
  5955. std::map<std::string, std::pair<int, int>> rev_merge;
  5956. };
  5957. // BPE tokenizer
  5958. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  5959. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  5960. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  5961. struct llm_bigram_bpe {
  5962. struct comparator {
  5963. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  5964. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  5965. }
  5966. };
  5967. using queue_storage = std::vector<llm_bigram_bpe>;
  5968. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  5969. llm_symbol::index left;
  5970. llm_symbol::index right;
  5971. std::string text;
  5972. int rank;
  5973. size_t size;
  5974. };
  5975. struct llm_tokenizer_bpe {
  5976. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  5977. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5978. int final_prev_index = -1;
  5979. auto word_collection = bpe_gpt2_preprocess(text);
  5980. symbols_final.clear();
  5981. for (auto & word : word_collection) {
  5982. work_queue = llm_bigram_bpe::queue();
  5983. symbols.clear();
  5984. int index = 0;
  5985. size_t offset = 0;
  5986. while (offset < word.size()) {
  5987. llm_symbol sym;
  5988. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  5989. sym.text = word.c_str() + offset;
  5990. sym.n = char_len;
  5991. offset += sym.n;
  5992. sym.prev = index - 1;
  5993. sym.next = offset == word.size() ? -1 : index + 1;
  5994. index++;
  5995. symbols.emplace_back(sym);
  5996. }
  5997. for (size_t i = 1; i < symbols.size(); ++i) {
  5998. add_new_bigram(i - 1, i);
  5999. }
  6000. // build token(s)
  6001. while (!work_queue.empty()) {
  6002. auto bigram = work_queue.top();
  6003. work_queue.pop();
  6004. auto & left_symbol = symbols[bigram.left];
  6005. auto & right_symbol = symbols[bigram.right];
  6006. if (left_symbol.n == 0 || right_symbol.n == 0) {
  6007. continue;
  6008. }
  6009. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  6010. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  6011. if (left_token + right_token != bigram.text) {
  6012. continue; // Skip this bigram if it's outdated
  6013. }
  6014. // merge the right sym into the left one
  6015. left_symbol.n += right_symbol.n;
  6016. right_symbol.n = 0;
  6017. // remove the right sym from the chain
  6018. left_symbol.next = right_symbol.next;
  6019. if (right_symbol.next >= 0) {
  6020. symbols[right_symbol.next].prev = bigram.left;
  6021. }
  6022. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  6023. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  6024. }
  6025. // add the fnished tokens to the final list keeping correct order for next and prev
  6026. for (auto & sym : symbols) {
  6027. if (sym.n > 0) {
  6028. sym.prev = final_prev_index;
  6029. sym.next = -1;
  6030. if (final_prev_index != -1) {
  6031. symbols_final[final_prev_index].next = symbols_final.size();
  6032. }
  6033. symbols_final.emplace_back(sym);
  6034. final_prev_index = symbols_final.size() - 1;
  6035. }
  6036. }
  6037. }
  6038. symbols = symbols_final;
  6039. if (!symbols.empty()) {
  6040. for (int i = 0; i != -1; i = symbols[i].next) {
  6041. auto & symbol = symbols[i];
  6042. if (symbol.n == 0) {
  6043. continue;
  6044. }
  6045. const std::string str = std::string(symbol.text, symbol.n);
  6046. const auto token = vocab.token_to_id.find(str);
  6047. if (token == vocab.token_to_id.end()) {
  6048. for (auto j = str.begin(); j != str.end(); ++j) {
  6049. std::string byte_str(1, *j);
  6050. auto token_multibyte = vocab.token_to_id.find(byte_str);
  6051. if (token_multibyte == vocab.token_to_id.end()) {
  6052. throw std::runtime_error("ERROR: byte not found in vocab");
  6053. }
  6054. output.push_back((*token_multibyte).second);
  6055. }
  6056. } else {
  6057. output.push_back((*token).second);
  6058. }
  6059. }
  6060. }
  6061. }
  6062. private:
  6063. void add_new_bigram(int left, int right) {
  6064. if (left == -1 || right == -1) {
  6065. return;
  6066. }
  6067. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  6068. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  6069. int rank_found = -1;
  6070. rank_found = vocab.find_bpe_rank(left_token, right_token);
  6071. if (rank_found < 0) {
  6072. return;
  6073. }
  6074. llm_bigram_bpe bigram;
  6075. bigram.left = left;
  6076. bigram.right = right;
  6077. bigram.text = left_token + right_token;
  6078. bigram.size = left_token.size() + right_token.size();
  6079. bigram.rank = rank_found;
  6080. work_queue.push(bigram);
  6081. }
  6082. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  6083. std::vector<std::string> bpe_words;
  6084. std::vector<std::string> bpe_encoded_words;
  6085. std::string token = "";
  6086. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  6087. bool collecting_numeric = false;
  6088. bool collecting_letter = false;
  6089. bool collecting_special = false;
  6090. bool collecting_whitespace_lookahead = false;
  6091. bool collecting = false;
  6092. std::vector<std::string> text_utf;
  6093. text_utf.reserve(text.size());
  6094. bpe_words.reserve(text.size());
  6095. bpe_encoded_words.reserve(text.size());
  6096. auto cps = codepoints_from_utf8(text);
  6097. for (size_t i = 0; i < cps.size(); ++i)
  6098. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  6099. for (int i = 0; i < (int)text_utf.size(); i++) {
  6100. const std::string & utf_char = text_utf[i];
  6101. bool split_condition = false;
  6102. int bytes_remain = text_utf.size() - i;
  6103. // forward backward lookups
  6104. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  6105. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  6106. // handling contractions
  6107. if (!split_condition && bytes_remain >= 2) {
  6108. // 's|'t|'m|'d
  6109. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  6110. split_condition = true;
  6111. }
  6112. if (split_condition) {
  6113. if (token.size()) {
  6114. bpe_words.emplace_back(token); // push previous content as token
  6115. }
  6116. token = utf_char + utf_char_next;
  6117. bpe_words.emplace_back(token);
  6118. token = "";
  6119. i++;
  6120. continue;
  6121. }
  6122. }
  6123. if (!split_condition && bytes_remain >= 3) {
  6124. // 're|'ve|'ll
  6125. if (utf_char == "\'" && (
  6126. (utf_char_next == "r" && utf_char_next_next == "e") ||
  6127. (utf_char_next == "v" && utf_char_next_next == "e") ||
  6128. (utf_char_next == "l" && utf_char_next_next == "l"))
  6129. ) {
  6130. split_condition = true;
  6131. }
  6132. if (split_condition) {
  6133. // current token + next token can be defined
  6134. if (token.size()) {
  6135. bpe_words.emplace_back(token); // push previous content as token
  6136. }
  6137. token = utf_char + utf_char_next + utf_char_next_next;
  6138. bpe_words.emplace_back(token); // the contraction
  6139. token = "";
  6140. i += 2;
  6141. continue;
  6142. }
  6143. }
  6144. if (!split_condition && !collecting) {
  6145. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  6146. collecting_letter = true;
  6147. collecting = true;
  6148. }
  6149. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6150. collecting_numeric = true;
  6151. collecting = true;
  6152. }
  6153. else if (
  6154. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  6155. (!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)
  6156. ) {
  6157. collecting_special = true;
  6158. collecting = true;
  6159. }
  6160. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  6161. collecting_whitespace_lookahead = true;
  6162. collecting = true;
  6163. }
  6164. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  6165. split_condition = true;
  6166. }
  6167. }
  6168. else if (!split_condition && collecting) {
  6169. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  6170. split_condition = true;
  6171. }
  6172. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  6173. split_condition = true;
  6174. }
  6175. 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)) {
  6176. split_condition = true;
  6177. }
  6178. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6179. split_condition = true;
  6180. }
  6181. }
  6182. if (utf_char_next == "") {
  6183. split_condition = true; // final
  6184. token += utf_char;
  6185. }
  6186. if (split_condition) {
  6187. if (token.size()) {
  6188. bpe_words.emplace_back(token);
  6189. }
  6190. token = utf_char;
  6191. collecting = false;
  6192. collecting_letter = false;
  6193. collecting_numeric = false;
  6194. collecting_special = false;
  6195. collecting_whitespace_lookahead = false;
  6196. }
  6197. else {
  6198. token += utf_char;
  6199. }
  6200. }
  6201. for (std::string & word : bpe_words) {
  6202. std::string encoded_token = "";
  6203. for (char & c : word) {
  6204. encoded_token += bytes_to_unicode_bpe(c);
  6205. }
  6206. bpe_encoded_words.emplace_back(encoded_token);
  6207. }
  6208. return bpe_encoded_words;
  6209. }
  6210. const llama_vocab & vocab;
  6211. std::vector<llm_symbol> symbols;
  6212. std::vector<llm_symbol> symbols_final;
  6213. llm_bigram_bpe::queue work_queue;
  6214. };
  6215. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  6216. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  6217. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  6218. } FRAGMENT_BUFFER_VARIANT_TYPE;
  6219. struct fragment_buffer_variant{
  6220. fragment_buffer_variant(llama_vocab::id _token)
  6221. :
  6222. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  6223. token(_token),
  6224. raw_text(_dummy),
  6225. offset(0),
  6226. length(0){}
  6227. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  6228. :
  6229. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  6230. token((llama_vocab::id)-1),
  6231. raw_text(_raw_text),
  6232. offset(_offset),
  6233. length(_length){
  6234. GGML_ASSERT( _offset >= 0 );
  6235. GGML_ASSERT( _length >= 1 );
  6236. GGML_ASSERT( offset + length <= raw_text.length() );
  6237. }
  6238. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  6239. const llama_vocab::id token;
  6240. const std::string _dummy;
  6241. const std::string & raw_text;
  6242. const uint64_t offset;
  6243. const uint64_t length;
  6244. };
  6245. // #define PRETOKENIZERDEBUG
  6246. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  6247. {
  6248. // for each special token
  6249. for (const auto & st: vocab.special_tokens_cache) {
  6250. const auto & special_token = st.first;
  6251. const auto & special_id = st.second;
  6252. // for each text fragment
  6253. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  6254. while (it != buffer.end()) {
  6255. auto & fragment = (*it);
  6256. // if a fragment is text ( not yet processed )
  6257. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  6258. auto * raw_text = &(fragment.raw_text);
  6259. auto raw_text_base_offset = fragment.offset;
  6260. auto raw_text_base_length = fragment.length;
  6261. // loop over the text
  6262. while (true) {
  6263. // find the first occurrence of a given special token in this fragment
  6264. // passing offset argument only limit the "search area" but match coordinates
  6265. // are still relative to the source full raw_text
  6266. auto match = raw_text->find(special_token, raw_text_base_offset);
  6267. // no occurrences found, stop processing this fragment for a given special token
  6268. if (match == std::string::npos) break;
  6269. // check if match is within bounds of offset <-> length
  6270. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  6271. #ifdef PRETOKENIZERDEBUG
  6272. LLAMA_LOG_WARN("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());
  6273. #endif
  6274. auto source = std::distance(buffer.begin(), it);
  6275. // if match is further than base offset
  6276. // then we have some text to the left of it
  6277. if (match > raw_text_base_offset) {
  6278. // left
  6279. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  6280. const int64_t left_reminder_length = match - raw_text_base_offset;
  6281. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  6282. #ifdef PRETOKENIZERDEBUG
  6283. LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  6284. #endif
  6285. it++;
  6286. }
  6287. // special token
  6288. buffer.emplace_after(it, special_id);
  6289. it++;
  6290. // right
  6291. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  6292. const int64_t right_reminder_offset = match + special_token.length();
  6293. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  6294. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  6295. #ifdef PRETOKENIZERDEBUG
  6296. LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  6297. #endif
  6298. it++;
  6299. if (source == 0) {
  6300. buffer.erase_after(buffer.before_begin());
  6301. } else {
  6302. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6303. }
  6304. // repeat for the right side
  6305. raw_text_base_offset = right_reminder_offset;
  6306. raw_text_base_length = right_reminder_length;
  6307. #ifdef PRETOKENIZERDEBUG
  6308. LLAMA_LOG_WARN("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());
  6309. #endif
  6310. } else {
  6311. if (source == 0) {
  6312. buffer.erase_after(buffer.before_begin());
  6313. } else {
  6314. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6315. }
  6316. break;
  6317. }
  6318. }
  6319. }
  6320. it++;
  6321. }
  6322. }
  6323. }
  6324. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  6325. std::vector<llama_vocab::id> output;
  6326. // OG tokenizer behavior:
  6327. //
  6328. // tokenizer.encode('', add_bos=True) returns [1]
  6329. // tokenizer.encode('', add_bos=False) returns []
  6330. if (bos && vocab.special_bos_id != -1) {
  6331. output.push_back(vocab.special_bos_id);
  6332. }
  6333. if (raw_text.empty()) {
  6334. return output;
  6335. }
  6336. std::forward_list<fragment_buffer_variant> fragment_buffer;
  6337. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  6338. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  6339. switch (vocab.type) {
  6340. case LLAMA_VOCAB_TYPE_SPM:
  6341. {
  6342. for (const auto & fragment: fragment_buffer)
  6343. {
  6344. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6345. {
  6346. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  6347. // TODO: It's likely possible to get rid of this string copy entirely
  6348. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  6349. // and passing 'add space prefix' as bool argument
  6350. //
  6351. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6352. if (&fragment == &fragment_buffer.front()) {
  6353. raw_text = " " + raw_text; // prefix with space if the first token is not special
  6354. }
  6355. #ifdef PRETOKENIZERDEBUG
  6356. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6357. #endif
  6358. llm_tokenizer_spm tokenizer(vocab);
  6359. llama_escape_whitespace(raw_text);
  6360. tokenizer.tokenize(raw_text, output);
  6361. }
  6362. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6363. {
  6364. output.push_back(fragment.token);
  6365. }
  6366. }
  6367. } break;
  6368. case LLAMA_VOCAB_TYPE_BPE:
  6369. {
  6370. for (const auto & fragment: fragment_buffer)
  6371. {
  6372. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6373. {
  6374. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6375. #ifdef PRETOKENIZERDEBUG
  6376. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6377. #endif
  6378. llm_tokenizer_bpe tokenizer(vocab);
  6379. tokenizer.tokenize(raw_text, output);
  6380. }
  6381. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6382. {
  6383. output.push_back(fragment.token);
  6384. }
  6385. }
  6386. } break;
  6387. }
  6388. return output;
  6389. }
  6390. //
  6391. // grammar - internal
  6392. //
  6393. struct llama_partial_utf8 {
  6394. uint32_t value; // bit value so far (unshifted)
  6395. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  6396. };
  6397. struct llama_grammar {
  6398. const std::vector<std::vector<llama_grammar_element>> rules;
  6399. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6400. // buffer for partially generated UTF-8 sequence from accepted tokens
  6401. llama_partial_utf8 partial_utf8;
  6402. };
  6403. struct llama_grammar_candidate {
  6404. size_t index;
  6405. const uint32_t * code_points;
  6406. llama_partial_utf8 partial_utf8;
  6407. };
  6408. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  6409. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  6410. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  6411. const std::string & src,
  6412. llama_partial_utf8 partial_start) {
  6413. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  6414. const char * pos = src.c_str();
  6415. std::vector<uint32_t> code_points;
  6416. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  6417. code_points.reserve(src.size() + 1);
  6418. uint32_t value = partial_start.value;
  6419. int n_remain = partial_start.n_remain;
  6420. // continue previous decode, if applicable
  6421. while (*pos != 0 && n_remain > 0) {
  6422. uint8_t next_byte = static_cast<uint8_t>(*pos);
  6423. if ((next_byte >> 6) != 2) {
  6424. // invalid sequence, abort
  6425. code_points.push_back(0);
  6426. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  6427. }
  6428. value = (value << 6) + (next_byte & 0x3F);
  6429. ++pos;
  6430. --n_remain;
  6431. }
  6432. if (partial_start.n_remain > 0 && n_remain == 0) {
  6433. code_points.push_back(value);
  6434. }
  6435. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  6436. while (*pos != 0) {
  6437. uint8_t first_byte = static_cast<uint8_t>(*pos);
  6438. uint8_t highbits = first_byte >> 4;
  6439. n_remain = lookup[highbits] - 1;
  6440. if (n_remain < 0) {
  6441. // invalid sequence, abort
  6442. code_points.clear();
  6443. code_points.push_back(0);
  6444. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  6445. }
  6446. uint8_t mask = (1 << (7 - n_remain)) - 1;
  6447. value = first_byte & mask;
  6448. ++pos;
  6449. while (*pos != 0 && n_remain > 0) {
  6450. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  6451. ++pos;
  6452. --n_remain;
  6453. }
  6454. if (n_remain == 0) {
  6455. code_points.push_back(value);
  6456. }
  6457. }
  6458. code_points.push_back(0);
  6459. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  6460. }
  6461. // returns true iff pos points to the end of one of the definitions of a rule
  6462. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  6463. switch (pos->type) {
  6464. case LLAMA_GRETYPE_END: return true; // NOLINT
  6465. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  6466. default: return false;
  6467. }
  6468. }
  6469. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  6470. // asserts that pos is pointing to a char range element
  6471. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  6472. const llama_grammar_element * pos,
  6473. const uint32_t chr) {
  6474. bool found = false;
  6475. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6476. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  6477. do {
  6478. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6479. // inclusive range, e.g. [a-z]
  6480. found = found || (pos->value <= chr && chr <= pos[1].value);
  6481. pos += 2;
  6482. } else {
  6483. // exact char match, e.g. [a] or "a"
  6484. found = found || pos->value == chr;
  6485. pos += 1;
  6486. }
  6487. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6488. return std::make_pair(found == is_positive_char, pos);
  6489. }
  6490. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  6491. // range at pos (regular or inverse range)
  6492. // asserts that pos is pointing to a char range element
  6493. static bool llama_grammar_match_partial_char(
  6494. const llama_grammar_element * pos,
  6495. const llama_partial_utf8 partial_utf8) {
  6496. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6497. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  6498. uint32_t partial_value = partial_utf8.value;
  6499. int n_remain = partial_utf8.n_remain;
  6500. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  6501. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  6502. return false;
  6503. }
  6504. // range of possible code points this partial UTF-8 sequence could complete to
  6505. uint32_t low = partial_value << (n_remain * 6);
  6506. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  6507. if (low == 0) {
  6508. if (n_remain == 2) {
  6509. low = 1 << 11;
  6510. } else if (n_remain == 3) {
  6511. low = 1 << 16;
  6512. }
  6513. }
  6514. do {
  6515. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6516. // inclusive range, e.g. [a-z]
  6517. if (pos->value <= high && low <= pos[1].value) {
  6518. return is_positive_char;
  6519. }
  6520. pos += 2;
  6521. } else {
  6522. // exact char match, e.g. [a] or "a"
  6523. if (low <= pos->value && pos->value <= high) {
  6524. return is_positive_char;
  6525. }
  6526. pos += 1;
  6527. }
  6528. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6529. return !is_positive_char;
  6530. }
  6531. // transforms a grammar pushdown stack into N possible stacks, all ending
  6532. // at a character range (terminal element)
  6533. static void llama_grammar_advance_stack(
  6534. const std::vector<std::vector<llama_grammar_element>> & rules,
  6535. const std::vector<const llama_grammar_element *> & stack,
  6536. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  6537. if (stack.empty()) {
  6538. new_stacks.emplace_back(stack);
  6539. return;
  6540. }
  6541. const llama_grammar_element * pos = stack.back();
  6542. switch (pos->type) {
  6543. case LLAMA_GRETYPE_RULE_REF: {
  6544. const size_t rule_id = static_cast<size_t>(pos->value);
  6545. const llama_grammar_element * subpos = rules[rule_id].data();
  6546. do {
  6547. // init new stack without the top (pos)
  6548. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6549. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  6550. // if this rule ref is followed by another element, add that to stack
  6551. new_stack.push_back(pos + 1);
  6552. }
  6553. if (!llama_grammar_is_end_of_sequence(subpos)) {
  6554. // if alternate is nonempty, add to stack
  6555. new_stack.push_back(subpos);
  6556. }
  6557. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6558. while (!llama_grammar_is_end_of_sequence(subpos)) {
  6559. // scan to end of alternate def
  6560. subpos++;
  6561. }
  6562. if (subpos->type == LLAMA_GRETYPE_ALT) {
  6563. // there's another alternate def of this rule to process
  6564. subpos++;
  6565. } else {
  6566. break;
  6567. }
  6568. } while (true);
  6569. break;
  6570. }
  6571. case LLAMA_GRETYPE_CHAR:
  6572. case LLAMA_GRETYPE_CHAR_NOT:
  6573. new_stacks.emplace_back(stack);
  6574. break;
  6575. default:
  6576. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  6577. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  6578. // those
  6579. GGML_ASSERT(false);
  6580. }
  6581. }
  6582. // takes a set of possible pushdown stacks on a grammar, which are required to
  6583. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  6584. // produces the N possible stacks if the given char is accepted at those
  6585. // positions
  6586. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  6587. const std::vector<std::vector<llama_grammar_element>> & rules,
  6588. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6589. const uint32_t chr) {
  6590. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  6591. for (const auto & stack : stacks) {
  6592. if (stack.empty()) {
  6593. continue;
  6594. }
  6595. auto match = llama_grammar_match_char(stack.back(), chr);
  6596. if (match.first) {
  6597. const llama_grammar_element * pos = match.second;
  6598. // update top of stack to next element, if any
  6599. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6600. if (!llama_grammar_is_end_of_sequence(pos)) {
  6601. new_stack.push_back(pos);
  6602. }
  6603. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6604. }
  6605. }
  6606. return new_stacks;
  6607. }
  6608. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6609. const std::vector<std::vector<llama_grammar_element>> & rules,
  6610. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6611. const std::vector<llama_grammar_candidate> & candidates);
  6612. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  6613. const std::vector<std::vector<llama_grammar_element>> & rules,
  6614. const std::vector<const llama_grammar_element *> & stack,
  6615. const std::vector<llama_grammar_candidate> & candidates) {
  6616. std::vector<llama_grammar_candidate> rejects;
  6617. if (stack.empty()) {
  6618. for (const auto & tok : candidates) {
  6619. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  6620. rejects.push_back(tok);
  6621. }
  6622. }
  6623. return rejects;
  6624. }
  6625. const llama_grammar_element * stack_pos = stack.back();
  6626. std::vector<llama_grammar_candidate> next_candidates;
  6627. for (const auto & tok : candidates) {
  6628. if (*tok.code_points == 0) {
  6629. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  6630. // that cannot satisfy this position in grammar
  6631. if (tok.partial_utf8.n_remain != 0 &&
  6632. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  6633. rejects.push_back(tok);
  6634. }
  6635. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  6636. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  6637. } else {
  6638. rejects.push_back(tok);
  6639. }
  6640. }
  6641. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  6642. // update top of stack to next element, if any
  6643. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  6644. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  6645. stack_after.push_back(stack_pos_after);
  6646. }
  6647. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  6648. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  6649. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  6650. for (const auto & tok : next_rejects) {
  6651. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  6652. }
  6653. return rejects;
  6654. }
  6655. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6656. const std::vector<std::vector<llama_grammar_element>> & rules,
  6657. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6658. const std::vector<llama_grammar_candidate> & candidates) {
  6659. GGML_ASSERT(!stacks.empty()); // REVIEW
  6660. if (candidates.empty()) {
  6661. return std::vector<llama_grammar_candidate>();
  6662. }
  6663. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  6664. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  6665. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  6666. }
  6667. return rejects;
  6668. }
  6669. //
  6670. // grammar - external
  6671. //
  6672. struct llama_grammar * llama_grammar_init(
  6673. const llama_grammar_element ** rules,
  6674. size_t n_rules,
  6675. size_t start_rule_index) {
  6676. const llama_grammar_element * pos;
  6677. // copy rule definitions into vectors
  6678. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  6679. for (size_t i = 0; i < n_rules; i++) {
  6680. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  6681. vec_rules[i].push_back(*pos);
  6682. }
  6683. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  6684. }
  6685. // loop over alternates of start rule to build initial stacks
  6686. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6687. pos = rules[start_rule_index];
  6688. do {
  6689. std::vector<const llama_grammar_element *> stack;
  6690. if (!llama_grammar_is_end_of_sequence(pos)) {
  6691. // if alternate is nonempty, add to stack
  6692. stack.push_back(pos);
  6693. }
  6694. llama_grammar_advance_stack(vec_rules, stack, stacks);
  6695. while (!llama_grammar_is_end_of_sequence(pos)) {
  6696. // scan to end of alternate def
  6697. pos++;
  6698. }
  6699. if (pos->type == LLAMA_GRETYPE_ALT) {
  6700. // there's another alternate def of this rule to process
  6701. pos++;
  6702. } else {
  6703. break;
  6704. }
  6705. } while (true);
  6706. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  6707. }
  6708. void llama_grammar_free(struct llama_grammar * grammar) {
  6709. delete grammar;
  6710. }
  6711. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  6712. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  6713. // redirect elements in stacks to point to new rules
  6714. for (size_t is = 0; is < result->stacks.size(); is++) {
  6715. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  6716. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  6717. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  6718. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  6719. result->stacks[is][ie] = &result->rules[ir0][ir1];
  6720. }
  6721. }
  6722. }
  6723. }
  6724. }
  6725. return result;
  6726. }
  6727. //
  6728. // sampling
  6729. //
  6730. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  6731. if (seed == LLAMA_DEFAULT_SEED) {
  6732. seed = time(NULL);
  6733. }
  6734. ctx->rng.seed(seed);
  6735. }
  6736. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  6737. GGML_ASSERT(candidates->size > 0);
  6738. const int64_t t_start_sample_us = ggml_time_us();
  6739. // Sort the logits in descending order
  6740. if (!candidates->sorted) {
  6741. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6742. return a.logit > b.logit;
  6743. });
  6744. candidates->sorted = true;
  6745. }
  6746. float max_l = candidates->data[0].logit;
  6747. float cum_sum = 0.0f;
  6748. for (size_t i = 0; i < candidates->size; ++i) {
  6749. float p = expf(candidates->data[i].logit - max_l);
  6750. candidates->data[i].p = p;
  6751. cum_sum += p;
  6752. }
  6753. for (size_t i = 0; i < candidates->size; ++i) {
  6754. candidates->data[i].p /= cum_sum;
  6755. }
  6756. if (ctx) {
  6757. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6758. }
  6759. }
  6760. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  6761. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  6762. // if (k >= (int32_t)candidates->size) {
  6763. // return;
  6764. // }
  6765. const int64_t t_start_sample_us = ggml_time_us();
  6766. k = std::max(k, (int) min_keep);
  6767. k = std::min(k, (int) candidates->size);
  6768. // Sort scores in descending order
  6769. if (!candidates->sorted) {
  6770. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  6771. return a.logit > b.logit;
  6772. };
  6773. if (k <= 128) {
  6774. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  6775. } else {
  6776. constexpr int nbuckets = 128;
  6777. constexpr float bucket_low = -10.0f;
  6778. constexpr float bucket_high = 10.0f;
  6779. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  6780. constexpr float bucker_inter = -bucket_low * bucket_scale;
  6781. std::vector<int> bucket_idx(candidates->size);
  6782. std::vector<int> histo(nbuckets, 0);
  6783. for (int i = 0; i < (int)candidates->size; ++i) {
  6784. const float val = candidates->data[i].logit;
  6785. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  6786. ib = std::max(0, std::min(nbuckets-1, ib));
  6787. bucket_idx[i] = ib;
  6788. ++histo[ib];
  6789. }
  6790. int nhave = 0;
  6791. int ib = nbuckets - 1;
  6792. for ( ; ib >= 0; --ib) {
  6793. nhave += histo[ib];
  6794. if (nhave >= k) break;
  6795. }
  6796. std::vector<llama_token_data> tmp_tokens(nhave);
  6797. auto ptr = tmp_tokens.data();
  6798. std::vector<llama_token_data*> bucket_ptrs;
  6799. bucket_ptrs.reserve(nbuckets - ib);
  6800. for (int j = nbuckets - 1; j >= ib; --j) {
  6801. bucket_ptrs.push_back(ptr);
  6802. ptr += histo[j];
  6803. }
  6804. for (int i = 0; i < (int)candidates->size; ++i) {
  6805. int j = bucket_idx[i];
  6806. if (j >= ib) {
  6807. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  6808. }
  6809. }
  6810. ptr = tmp_tokens.data();
  6811. int ndone = 0;
  6812. for (int j = nbuckets-1; j > ib; --j) {
  6813. std::sort(ptr, ptr + histo[j], comp);
  6814. ptr += histo[j];
  6815. ndone += histo[j];
  6816. }
  6817. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  6818. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  6819. }
  6820. candidates->sorted = true;
  6821. }
  6822. candidates->size = k;
  6823. if (ctx) {
  6824. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6825. }
  6826. }
  6827. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6828. if (p >= 1.0f) {
  6829. return;
  6830. }
  6831. llama_sample_softmax(ctx, candidates);
  6832. const int64_t t_start_sample_us = ggml_time_us();
  6833. // Compute the cumulative probabilities
  6834. float cum_sum = 0.0f;
  6835. size_t last_idx = candidates->size;
  6836. for (size_t i = 0; i < candidates->size; ++i) {
  6837. cum_sum += candidates->data[i].p;
  6838. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  6839. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  6840. if (cum_sum >= p && i + 1 >= min_keep) {
  6841. last_idx = i + 1;
  6842. break;
  6843. }
  6844. }
  6845. // Resize the output vector to keep only the top-p tokens
  6846. candidates->size = last_idx;
  6847. if (ctx) {
  6848. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6849. }
  6850. }
  6851. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6852. if (p <= 0.0f || !candidates->size) {
  6853. return;
  6854. }
  6855. const int64_t t_start_sample_us = ggml_time_us();
  6856. bool min_p_applied = false;
  6857. // if the candidates aren't sorted, try the unsorted implementation first
  6858. if (!candidates->sorted) {
  6859. std::vector<llama_token_data> filtered_tokens;
  6860. float max_logit = -FLT_MAX;
  6861. for (size_t i = 0; i < candidates->size; ++i) {
  6862. max_logit = std::max(max_logit, candidates->data[i].logit);
  6863. }
  6864. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  6865. for (size_t i = 0; i < candidates->size; ++i) {
  6866. if (candidates->data[i].logit >= min_logit) {
  6867. filtered_tokens.push_back(candidates->data[i]);
  6868. }
  6869. }
  6870. // if we have enough values the operation was a success
  6871. if (filtered_tokens.size() >= min_keep) {
  6872. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  6873. candidates->size = filtered_tokens.size();
  6874. min_p_applied = true;
  6875. }
  6876. }
  6877. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  6878. if (!min_p_applied) {
  6879. // Sort the logits in descending order
  6880. if (!candidates->sorted) {
  6881. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6882. return a.logit > b.logit;
  6883. });
  6884. candidates->sorted = true;
  6885. }
  6886. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  6887. size_t i = 1; // first token always matches
  6888. for (; i < candidates->size; ++i) {
  6889. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  6890. break; // prob too small
  6891. }
  6892. }
  6893. // Resize the output vector to keep only the matching tokens
  6894. candidates->size = i;
  6895. }
  6896. if (ctx) {
  6897. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6898. }
  6899. }
  6900. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  6901. if (z >= 1.0f || candidates->size <= 2) {
  6902. return;
  6903. }
  6904. llama_sample_softmax(nullptr, candidates);
  6905. const int64_t t_start_sample_us = ggml_time_us();
  6906. // Compute the first and second derivatives
  6907. std::vector<float> first_derivatives(candidates->size - 1);
  6908. std::vector<float> second_derivatives(candidates->size - 2);
  6909. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  6910. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  6911. }
  6912. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6913. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  6914. }
  6915. // Calculate absolute value of second derivatives
  6916. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6917. second_derivatives[i] = std::abs(second_derivatives[i]);
  6918. }
  6919. // Normalize the second derivatives
  6920. {
  6921. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  6922. if (second_derivatives_sum > 1e-6f) {
  6923. for (float & value : second_derivatives) {
  6924. value /= second_derivatives_sum;
  6925. }
  6926. } else {
  6927. for (float & value : second_derivatives) {
  6928. value = 1.0f / second_derivatives.size();
  6929. }
  6930. }
  6931. }
  6932. float cum_sum = 0.0f;
  6933. size_t last_idx = candidates->size;
  6934. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6935. cum_sum += second_derivatives[i];
  6936. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  6937. if (cum_sum > z && i >= min_keep) {
  6938. last_idx = i;
  6939. break;
  6940. }
  6941. }
  6942. // Resize the output vector to keep only the tokens above the tail location
  6943. candidates->size = last_idx;
  6944. if (ctx) {
  6945. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6946. }
  6947. }
  6948. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6949. // Reference implementation:
  6950. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  6951. if (p >= 1.0f) {
  6952. return;
  6953. }
  6954. // Compute the softmax of logits and calculate entropy
  6955. llama_sample_softmax(nullptr, candidates);
  6956. const int64_t t_start_sample_us = ggml_time_us();
  6957. float entropy = 0.0f;
  6958. for (size_t i = 0; i < candidates->size; ++i) {
  6959. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  6960. }
  6961. // Compute the absolute difference between negative log probability and entropy for each candidate
  6962. std::vector<float> shifted_scores;
  6963. for (size_t i = 0; i < candidates->size; ++i) {
  6964. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  6965. shifted_scores.push_back(shifted_score);
  6966. }
  6967. // Sort tokens based on the shifted_scores and their corresponding indices
  6968. std::vector<size_t> indices(candidates->size);
  6969. std::iota(indices.begin(), indices.end(), 0);
  6970. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  6971. return shifted_scores[a] < shifted_scores[b];
  6972. });
  6973. // Compute the cumulative probabilities
  6974. float cum_sum = 0.0f;
  6975. size_t last_idx = indices.size();
  6976. for (size_t i = 0; i < indices.size(); ++i) {
  6977. size_t idx = indices[i];
  6978. cum_sum += candidates->data[idx].p;
  6979. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  6980. if (cum_sum > p && i >= min_keep - 1) {
  6981. last_idx = i + 1;
  6982. break;
  6983. }
  6984. }
  6985. // Resize the output vector to keep only the locally typical tokens
  6986. std::vector<llama_token_data> new_candidates;
  6987. for (size_t i = 0; i < last_idx; ++i) {
  6988. size_t idx = indices[i];
  6989. new_candidates.push_back(candidates->data[idx]);
  6990. }
  6991. // Replace the data in candidates with the new_candidates data
  6992. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  6993. candidates->size = new_candidates.size();
  6994. candidates->sorted = false;
  6995. if (ctx) {
  6996. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6997. }
  6998. }
  6999. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  7000. const int64_t t_start_sample_us = ggml_time_us();
  7001. // no need to do anything if there is only one (or zero) candidates
  7002. if(candidates_p->size <= 1) {
  7003. return;
  7004. }
  7005. // Calculate maximum possible entropy
  7006. float max_entropy = -logf(1.0f / candidates_p->size);
  7007. llama_sample_softmax(nullptr, candidates_p);
  7008. // Calculate entropy of the softmax probabilities
  7009. float entropy = 0.0f;
  7010. for (size_t i = 0; i < candidates_p->size; ++i) {
  7011. float prob = candidates_p->data[i].p;
  7012. if (prob > 0.0f) { // Ensure no log(0)
  7013. entropy -= prob * logf(prob);
  7014. }
  7015. }
  7016. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  7017. float normalized_entropy = entropy / max_entropy;
  7018. // Map the normalized entropy to the desired temperature range using the power function
  7019. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  7020. #ifdef DEBUG
  7021. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  7022. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  7023. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  7024. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  7025. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  7026. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  7027. #endif
  7028. // Apply the dynamically calculated temperature scaling
  7029. for (size_t i = 0; i < candidates_p->size; ++i) {
  7030. candidates_p->data[i].logit /= dyn_temp;
  7031. }
  7032. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  7033. double max_l_double = candidates_p->data[0].logit;
  7034. double cum_sum_double = 0.0;
  7035. for (size_t i = 0; i < candidates_p->size; ++i) {
  7036. double p = exp(candidates_p->data[i].logit - max_l_double);
  7037. candidates_p->data[i].p = p; // Store the scaled probability
  7038. cum_sum_double += p;
  7039. }
  7040. for (size_t i = 0; i < candidates_p->size; ++i) {
  7041. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  7042. }
  7043. #ifdef DEBUG
  7044. // Print the updated top 25 probabilities after temperature scaling
  7045. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  7046. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  7047. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  7048. }
  7049. #endif
  7050. if (ctx) {
  7051. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7052. }
  7053. }
  7054. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  7055. const int64_t t_start_sample_us = ggml_time_us();
  7056. for (size_t i = 0; i < candidates_p->size; ++i) {
  7057. candidates_p->data[i].logit /= temp;
  7058. }
  7059. if (ctx) {
  7060. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7061. }
  7062. }
  7063. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  7064. llama_sample_temp(ctx, candidates_p, temp);
  7065. }
  7066. void llama_sample_repetition_penalties(
  7067. struct llama_context * ctx,
  7068. llama_token_data_array * candidates,
  7069. const llama_token * last_tokens,
  7070. size_t penalty_last_n,
  7071. float penalty_repeat,
  7072. float penalty_freq,
  7073. float penalty_present) {
  7074. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  7075. return;
  7076. }
  7077. const int64_t t_start_sample_us = ggml_time_us();
  7078. // Create a frequency map to count occurrences of each token in last_tokens
  7079. std::unordered_map<llama_token, int> token_count;
  7080. for (size_t i = 0; i < penalty_last_n; ++i) {
  7081. token_count[last_tokens[i]]++;
  7082. }
  7083. // Apply frequency and presence penalties to the candidates
  7084. for (size_t i = 0; i < candidates->size; ++i) {
  7085. const auto token_iter = token_count.find(candidates->data[i].id);
  7086. if (token_iter == token_count.end()) {
  7087. continue;
  7088. }
  7089. const int count = token_iter->second;
  7090. // 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.
  7091. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  7092. if (candidates->data[i].logit <= 0) {
  7093. candidates->data[i].logit *= penalty_repeat;
  7094. } else {
  7095. candidates->data[i].logit /= penalty_repeat;
  7096. }
  7097. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  7098. }
  7099. candidates->sorted = false;
  7100. if (ctx) {
  7101. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7102. }
  7103. }
  7104. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  7105. GGML_ASSERT(ctx);
  7106. const int64_t t_start_sample_us = ggml_time_us();
  7107. bool allow_eos = false;
  7108. for (const auto & stack : grammar->stacks) {
  7109. if (stack.empty()) {
  7110. allow_eos = true;
  7111. break;
  7112. }
  7113. }
  7114. const llama_token eos = llama_token_eos(&ctx->model);
  7115. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  7116. candidates_decoded.reserve(candidates->size);
  7117. std::vector<llama_grammar_candidate> candidates_grammar;
  7118. candidates_grammar.reserve(candidates->size);
  7119. for (size_t i = 0; i < candidates->size; ++i) {
  7120. const llama_token id = candidates->data[i].id;
  7121. const std::string piece = llama_token_to_piece(ctx, id);
  7122. if (id == eos) {
  7123. if (!allow_eos) {
  7124. candidates->data[i].logit = -INFINITY;
  7125. }
  7126. } else if (piece.empty() || piece[0] == 0) {
  7127. candidates->data[i].logit = -INFINITY;
  7128. } else {
  7129. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  7130. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  7131. }
  7132. }
  7133. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  7134. for (const auto & reject : rejects) {
  7135. candidates->data[reject.index].logit = -INFINITY;
  7136. }
  7137. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7138. }
  7139. static void llama_log_softmax(float * array, size_t size) {
  7140. float max_l = *std::max_element(array, array + size);
  7141. float sum = 0.f;
  7142. for (size_t i = 0; i < size; ++i) {
  7143. float p = expf(array[i] - max_l);
  7144. sum += p;
  7145. array[i] = p;
  7146. }
  7147. for (size_t i = 0; i < size; ++i) {
  7148. array[i] = logf(array[i] / sum);
  7149. }
  7150. }
  7151. void llama_sample_apply_guidance(
  7152. struct llama_context * ctx,
  7153. float * logits,
  7154. float * logits_guidance,
  7155. float scale) {
  7156. GGML_ASSERT(ctx);
  7157. const auto t_start_sample_us = ggml_time_us();
  7158. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  7159. llama_log_softmax(logits, n_vocab);
  7160. llama_log_softmax(logits_guidance, n_vocab);
  7161. for (int i = 0; i < n_vocab; ++i) {
  7162. auto & l = logits[i];
  7163. const auto & g = logits_guidance[i];
  7164. l = scale * (l - g) + g;
  7165. }
  7166. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7167. }
  7168. void llama_sample_classifier_free_guidance(
  7169. struct llama_context * ctx,
  7170. llama_token_data_array * candidates,
  7171. struct llama_context * guidance_ctx,
  7172. float scale) {
  7173. GGML_ASSERT(ctx);
  7174. int64_t t_start_sample_us;
  7175. t_start_sample_us = ggml_time_us();
  7176. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  7177. GGML_ASSERT(n_vocab == candidates->size);
  7178. GGML_ASSERT(!candidates->sorted);
  7179. std::vector<float> logits_base(n_vocab);
  7180. for (size_t i = 0; i < n_vocab; ++i) {
  7181. logits_base[i] = candidates->data[i].logit;
  7182. }
  7183. float * logits_guidance = llama_get_logits(guidance_ctx);
  7184. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7185. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  7186. t_start_sample_us = ggml_time_us();
  7187. for (size_t i = 0; i < n_vocab; ++i) {
  7188. candidates->data[i].logit = logits_base[i];
  7189. }
  7190. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7191. }
  7192. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  7193. GGML_ASSERT(ctx);
  7194. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  7195. int64_t t_start_sample_us;
  7196. t_start_sample_us = ggml_time_us();
  7197. llama_sample_softmax(nullptr, candidates);
  7198. // Estimate s_hat using the most probable m tokens
  7199. float s_hat = 0.0;
  7200. float sum_ti_bi = 0.0;
  7201. float sum_ti_sq = 0.0;
  7202. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  7203. float t_i = logf(float(i + 2) / float(i + 1));
  7204. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  7205. sum_ti_bi += t_i * b_i;
  7206. sum_ti_sq += t_i * t_i;
  7207. }
  7208. s_hat = sum_ti_bi / sum_ti_sq;
  7209. // Compute k from the estimated s_hat and target surprise value
  7210. float epsilon_hat = s_hat - 1;
  7211. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  7212. // Sample the next word X using top-k sampling
  7213. llama_sample_top_k(nullptr, candidates, int(k), 1);
  7214. if (ctx) {
  7215. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7216. }
  7217. llama_token X = llama_sample_token(ctx, candidates);
  7218. t_start_sample_us = ggml_time_us();
  7219. // Compute error as the difference between observed surprise and target surprise value
  7220. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7221. return candidate.id == X;
  7222. }));
  7223. float observed_surprise = -log2f(candidates->data[X_idx].p);
  7224. float e = observed_surprise - tau;
  7225. // Update mu using the learning rate and error
  7226. *mu = *mu - eta * e;
  7227. if (ctx) {
  7228. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7229. }
  7230. return X;
  7231. }
  7232. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  7233. int64_t t_start_sample_us;
  7234. t_start_sample_us = ggml_time_us();
  7235. llama_sample_softmax(ctx, candidates);
  7236. // Truncate the words with surprise values greater than mu
  7237. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7238. return -log2f(candidate.p) > *mu;
  7239. }));
  7240. if (candidates->size == 0) {
  7241. candidates->size = 1;
  7242. }
  7243. if (ctx) {
  7244. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7245. }
  7246. // Normalize the probabilities of the remaining words
  7247. llama_sample_softmax(ctx, candidates);
  7248. // Sample the next word X from the remaining words
  7249. llama_token X = llama_sample_token(ctx, candidates);
  7250. t_start_sample_us = ggml_time_us();
  7251. // Compute error as the difference between observed surprise and target surprise value
  7252. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7253. return candidate.id == X;
  7254. }));
  7255. float observed_surprise = -log2f(candidates->data[X_idx].p);
  7256. float e = observed_surprise - tau;
  7257. // Update mu using the learning rate and error
  7258. *mu = *mu - eta * e;
  7259. if (ctx) {
  7260. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7261. }
  7262. return X;
  7263. }
  7264. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  7265. const int64_t t_start_sample_us = ggml_time_us();
  7266. // Find max element
  7267. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7268. return a.logit < b.logit;
  7269. });
  7270. llama_token result = max_iter->id;
  7271. if (ctx) {
  7272. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7273. ctx->n_sample++;
  7274. }
  7275. return result;
  7276. }
  7277. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  7278. GGML_ASSERT(ctx);
  7279. const int64_t t_start_sample_us = ggml_time_us();
  7280. llama_sample_softmax(nullptr, candidates);
  7281. std::vector<float> probs;
  7282. probs.reserve(candidates->size);
  7283. for (size_t i = 0; i < candidates->size; ++i) {
  7284. probs.push_back(candidates->data[i].p);
  7285. }
  7286. std::discrete_distribution<> dist(probs.begin(), probs.end());
  7287. auto & rng = ctx->rng;
  7288. int idx = dist(rng);
  7289. llama_token result = candidates->data[idx].id;
  7290. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7291. ctx->n_sample++;
  7292. return result;
  7293. }
  7294. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  7295. const int64_t t_start_sample_us = ggml_time_us();
  7296. if (token == llama_token_eos(&ctx->model)) {
  7297. for (const auto & stack : grammar->stacks) {
  7298. if (stack.empty()) {
  7299. return;
  7300. }
  7301. }
  7302. GGML_ASSERT(false);
  7303. }
  7304. const std::string piece = llama_token_to_piece(ctx, token);
  7305. // Note terminating 0 in decoded string
  7306. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  7307. const auto & code_points = decoded.first;
  7308. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  7309. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  7310. }
  7311. grammar->partial_utf8 = decoded.second;
  7312. GGML_ASSERT(!grammar->stacks.empty());
  7313. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7314. }
  7315. //
  7316. // Beam search
  7317. //
  7318. struct llama_beam {
  7319. std::vector<llama_token> tokens;
  7320. float p; // Cumulative beam probability (renormalized relative to all beams)
  7321. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  7322. // Sort beams by probability. In case of ties, prefer beams at eob.
  7323. bool operator<(const llama_beam & rhs) const {
  7324. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  7325. }
  7326. // Shift off first n tokens and discard them.
  7327. void shift_tokens(const size_t n) {
  7328. if (n) {
  7329. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  7330. tokens.resize(tokens.size() - n);
  7331. }
  7332. }
  7333. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  7334. };
  7335. // A struct for calculating logit-related info.
  7336. struct llama_logit_info {
  7337. const float * const logits;
  7338. const int n_vocab;
  7339. const float max_l;
  7340. const float normalizer;
  7341. struct sum_exp {
  7342. float max_l;
  7343. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  7344. };
  7345. llama_logit_info(llama_context * ctx)
  7346. : logits(llama_get_logits(ctx))
  7347. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  7348. , max_l(*std::max_element(logits, logits + n_vocab))
  7349. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  7350. { }
  7351. llama_token_data get_token_data(const llama_token token_id) const {
  7352. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  7353. return {token_id, logits[token_id], p};
  7354. }
  7355. // Return top k token_data by logit.
  7356. std::vector<llama_token_data> top_k(size_t k) {
  7357. std::vector<llama_token_data> min_heap; // min-heap by logit
  7358. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  7359. min_heap.reserve(k_min);
  7360. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  7361. min_heap.push_back(get_token_data(token_id));
  7362. }
  7363. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  7364. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  7365. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  7366. if (min_heap.front().logit < logits[token_id]) {
  7367. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  7368. min_heap.back().id = token_id;
  7369. min_heap.back().logit = logits[token_id];
  7370. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  7371. }
  7372. }
  7373. return min_heap;
  7374. }
  7375. float probability_from_logit(float logit) const {
  7376. return normalizer * std::exp(logit - max_l);
  7377. }
  7378. };
  7379. struct llama_beam_search_data {
  7380. llama_context * ctx;
  7381. size_t n_beams;
  7382. int n_past;
  7383. int n_predict;
  7384. std::vector<llama_beam> beams;
  7385. std::vector<llama_beam> next_beams;
  7386. // Re-calculated on each loop iteration
  7387. size_t common_prefix_length;
  7388. // Used to communicate to/from callback on beams state.
  7389. std::vector<llama_beam_view> beam_views;
  7390. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  7391. : ctx(ctx)
  7392. , n_beams(n_beams)
  7393. , n_past(n_past)
  7394. , n_predict(n_predict)
  7395. , beam_views(n_beams) {
  7396. beams.reserve(n_beams);
  7397. next_beams.reserve(n_beams);
  7398. }
  7399. // Collapse beams to a single beam given by index.
  7400. void collapse_beams(const size_t beam_idx) {
  7401. if (0u < beam_idx) {
  7402. std::swap(beams[0], beams[beam_idx]);
  7403. }
  7404. beams.resize(1);
  7405. }
  7406. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  7407. // The repetitive patterns below reflect the 2 stages of heaps:
  7408. // * Gather elements until the vector is full, then call std::make_heap() on it.
  7409. // * If the heap is full and a new element is found that should be included, pop the
  7410. // least element to the back(), replace it with the new, then push it into the heap.
  7411. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  7412. // Min-heaps use a greater-than comparator.
  7413. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  7414. if (beam.eob) {
  7415. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  7416. if (next_beams.size() < n_beams) {
  7417. next_beams.push_back(std::move(beam));
  7418. if (next_beams.size() == n_beams) {
  7419. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7420. }
  7421. } else if (next_beams.front().p < beam.p) {
  7422. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7423. next_beams.back() = std::move(beam);
  7424. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7425. }
  7426. } else {
  7427. // beam is not at end-of-sentence, so branch with next top_k tokens.
  7428. if (!beam.tokens.empty()) {
  7429. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  7430. }
  7431. llama_logit_info logit_info(ctx);
  7432. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  7433. size_t i=0;
  7434. if (next_beams.size() < n_beams) {
  7435. for (; next_beams.size() < n_beams ; ++i) {
  7436. llama_beam next_beam = beam;
  7437. next_beam.tokens.push_back(next_tokens[i].id);
  7438. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7439. next_beams.push_back(std::move(next_beam));
  7440. }
  7441. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7442. } else {
  7443. for (; next_beams.front().p == 0.0f ; ++i) {
  7444. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7445. next_beams.back() = beam;
  7446. next_beams.back().tokens.push_back(next_tokens[i].id);
  7447. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7448. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7449. }
  7450. }
  7451. for (; i < n_beams ; ++i) {
  7452. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  7453. if (next_beams.front().p < next_p) {
  7454. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7455. next_beams.back() = beam;
  7456. next_beams.back().tokens.push_back(next_tokens[i].id);
  7457. next_beams.back().p = next_p;
  7458. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7459. }
  7460. }
  7461. }
  7462. }
  7463. // Find common_prefix_length based on beams.
  7464. // Requires beams is not empty.
  7465. size_t find_common_prefix_length() {
  7466. size_t common_prefix_length = beams[0].tokens.size();
  7467. for (size_t i = 1 ; i < beams.size() ; ++i) {
  7468. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  7469. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  7470. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  7471. common_prefix_length = j;
  7472. break;
  7473. }
  7474. }
  7475. }
  7476. return common_prefix_length;
  7477. }
  7478. // Construct beams_state to send back to caller via the callback function.
  7479. // Side effect: set common_prefix_length = find_common_prefix_length();
  7480. llama_beams_state get_beams_state(const bool last_call) {
  7481. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7482. beam_views[i] = beams[i].view();
  7483. }
  7484. common_prefix_length = find_common_prefix_length();
  7485. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  7486. }
  7487. // Loop:
  7488. // * while i < n_predict, AND
  7489. // * any of the beams have not yet reached end-of-beam (eob), AND
  7490. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  7491. // (since all other beam probabilities can only decrease)
  7492. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  7493. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  7494. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  7495. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  7496. !beams[top_beam_index()].eob ; ++i) {
  7497. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  7498. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  7499. if (common_prefix_length) {
  7500. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  7501. n_past += common_prefix_length;
  7502. }
  7503. // Zero-out next_beam probabilities to place them last in following min-heap.
  7504. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  7505. for (llama_beam & beam : beams) {
  7506. beam.shift_tokens(common_prefix_length);
  7507. fill_next_beams_by_top_probabilities(beam);
  7508. }
  7509. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  7510. beams.swap(next_beams);
  7511. renormalize_beam_probabilities(beams);
  7512. }
  7513. collapse_beams(top_beam_index());
  7514. callback(callback_data, get_beams_state(true));
  7515. }
  7516. // As beams grow, the cumulative probabilities decrease.
  7517. // Renormalize them to avoid floating point underflow.
  7518. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  7519. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  7520. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  7521. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  7522. }
  7523. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  7524. size_t top_beam_index() {
  7525. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  7526. }
  7527. // Copy (p,eob) for each beam which may have been changed by the callback.
  7528. void update_beams_from_beam_views() {
  7529. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7530. beams[i].p = beam_views[i].p;
  7531. beams[i].eob = beam_views[i].eob;
  7532. }
  7533. }
  7534. };
  7535. void llama_beam_search(llama_context * ctx,
  7536. llama_beam_search_callback_fn_t callback, void * callback_data,
  7537. size_t n_beams, int n_past, int n_predict) {
  7538. assert(ctx);
  7539. const int64_t t_start_sample_us = ggml_time_us();
  7540. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  7541. beam_search_data.loop(callback, callback_data);
  7542. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7543. ctx->n_sample++;
  7544. }
  7545. //
  7546. // quantization
  7547. //
  7548. struct quantize_state_internal {
  7549. const llama_model & model;
  7550. const llama_model_quantize_params * params;
  7551. int n_attention_wv = 0;
  7552. int n_ffn_down = 0;
  7553. int n_ffn_gate = 0;
  7554. int n_ffn_up = 0;
  7555. int i_attention_wv = 0;
  7556. int i_ffn_down = 0;
  7557. int i_ffn_gate = 0;
  7558. int i_ffn_up = 0;
  7559. int n_k_quantized = 0;
  7560. int n_fallback = 0;
  7561. bool has_imatrix = false;
  7562. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  7563. : model(model)
  7564. , params(params)
  7565. {}
  7566. };
  7567. static void llama_convert_tensor_internal(
  7568. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  7569. const size_t nelements, const int nthread
  7570. ) {
  7571. if (output.size() < nelements) {
  7572. output.resize(nelements);
  7573. }
  7574. float * f32_output = (float *) output.data();
  7575. ggml_type_traits_t qtype;
  7576. if (ggml_is_quantized(tensor->type)) {
  7577. qtype = ggml_internal_get_type_traits(tensor->type);
  7578. if (qtype.to_float == NULL) {
  7579. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  7580. }
  7581. } else if (tensor->type != GGML_TYPE_F16) {
  7582. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  7583. }
  7584. if (nthread < 2) {
  7585. if (tensor->type == GGML_TYPE_F16) {
  7586. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  7587. } else if (ggml_is_quantized(tensor->type)) {
  7588. qtype.to_float(tensor->data, f32_output, nelements);
  7589. } else {
  7590. GGML_ASSERT(false); // unreachable
  7591. }
  7592. return;
  7593. }
  7594. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  7595. size_t block_size_bytes = ggml_type_size(tensor->type);
  7596. GGML_ASSERT(nelements % block_size == 0);
  7597. size_t nblocks = nelements / block_size;
  7598. size_t blocks_per_thread = nblocks / nthread;
  7599. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  7600. size_t in_buff_offs = 0;
  7601. size_t out_buff_offs = 0;
  7602. for (int tnum = 0; tnum < nthread; tnum++) {
  7603. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  7604. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  7605. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  7606. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  7607. if (typ == GGML_TYPE_F16) {
  7608. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  7609. } else {
  7610. qtype.to_float(inbuf, outbuf, nels);
  7611. }
  7612. };
  7613. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  7614. in_buff_offs += thr_block_bytes;
  7615. out_buff_offs += thr_elems;
  7616. }
  7617. for (auto & w : workers) { w.join(); }
  7618. workers.clear();
  7619. }
  7620. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  7621. const std::string name = ggml_get_name(tensor);
  7622. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7623. const llm_arch arch = qs.model.arch;
  7624. const auto tn = LLM_TN(arch);
  7625. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  7626. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  7627. };
  7628. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  7629. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  7630. if (n_expert > 1) {
  7631. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  7632. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  7633. // for getting the current layer as I initially thought, and we need to resort to parsing the
  7634. // tensor name.
  7635. n_layer /= n_expert;
  7636. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  7637. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  7638. }
  7639. if (i_layer < 0 || i_layer >= n_layer) {
  7640. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  7641. }
  7642. }
  7643. return std::make_pair(i_layer, n_layer);
  7644. };
  7645. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  7646. int nx = tensor->ne[0];
  7647. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  7648. new_type = GGML_TYPE_Q8_0;
  7649. }
  7650. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7651. new_type = GGML_TYPE_Q5_K;
  7652. }
  7653. else if (new_type != GGML_TYPE_Q8_0) {
  7654. new_type = GGML_TYPE_Q6_K;
  7655. }
  7656. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7657. if (name.find("attn_v.weight") != std::string::npos) {
  7658. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  7659. else new_type = GGML_TYPE_Q2_K;
  7660. ++qs.i_attention_wv;
  7661. }
  7662. else if (name.find("ffn_down") != std::string::npos) {
  7663. if (qs.i_ffn_down < qs.n_ffn_down/8) new_type = GGML_TYPE_Q2_K;
  7664. ++qs.i_ffn_down;
  7665. }
  7666. else if (name == "token_embd.weight") new_type = GGML_TYPE_Q2_K;
  7667. } else if (name.find("attn_v.weight") != std::string::npos) {
  7668. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  7669. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  7670. }
  7671. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  7672. new_type = GGML_TYPE_Q4_K;
  7673. }
  7674. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7675. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7676. }
  7677. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7678. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  7679. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  7680. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  7681. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  7682. (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;
  7683. if (qs.model.type == MODEL_70B) {
  7684. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  7685. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  7686. // nearly negligible increase in model size by quantizing this tensor with more bits:
  7687. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  7688. }
  7689. if (qs.model.hparams.n_expert == 8) {
  7690. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7691. // TODO: explore better strategies
  7692. new_type = GGML_TYPE_Q8_0;
  7693. }
  7694. ++qs.i_attention_wv;
  7695. } else if (name.find("attn_k.weight") != std::string::npos) {
  7696. if (qs.model.hparams.n_expert == 8) {
  7697. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7698. // TODO: explore better strategies
  7699. new_type = GGML_TYPE_Q8_0;
  7700. }
  7701. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7702. new_type = GGML_TYPE_Q2_K;
  7703. }
  7704. } else if (name.find("ffn_down") != std::string::npos) {
  7705. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  7706. int i_layer = info.first, n_layer = info.second;
  7707. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7708. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7709. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  7710. }
  7711. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7712. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  7713. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  7714. : GGML_TYPE_Q3_K;
  7715. }
  7716. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  7717. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  7718. }
  7719. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7720. if (arch == LLM_ARCH_FALCON) {
  7721. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  7722. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7723. } else {
  7724. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7725. }
  7726. }
  7727. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7728. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  7729. new_type = GGML_TYPE_Q5_K;
  7730. }
  7731. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  7732. && qs.has_imatrix && i_layer < n_layer/8) {
  7733. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  7734. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  7735. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  7736. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  7737. }
  7738. ++qs.i_ffn_down;
  7739. } else if (name.find("attn_output.weight") != std::string::npos) {
  7740. if (arch != LLM_ARCH_FALCON) {
  7741. if (qs.model.hparams.n_expert == 8) {
  7742. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS ||
  7743. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ||
  7744. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7745. new_type = GGML_TYPE_Q5_K;
  7746. }
  7747. } else {
  7748. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  7749. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  7750. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7751. }
  7752. } else {
  7753. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7754. }
  7755. }
  7756. else if (name.find("attn_qkv.weight") != std::string::npos) {
  7757. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7758. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  7759. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  7760. }
  7761. else if (name.find("ffn_gate") != std::string::npos) {
  7762. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  7763. int i_layer = info.first, n_layer = info.second;
  7764. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  7765. new_type = GGML_TYPE_Q2_K;
  7766. }
  7767. ++qs.i_ffn_gate;
  7768. }
  7769. else if (name.find("ffn_up") != std::string::npos) {
  7770. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  7771. int i_layer = info.first, n_layer = info.second;
  7772. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  7773. new_type = GGML_TYPE_Q2_K;
  7774. }
  7775. ++qs.i_ffn_up;
  7776. }
  7777. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7778. //}
  7779. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  7780. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  7781. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7782. //}
  7783. // This can be used to reduce the size of the Q5_K_S model.
  7784. // The associated PPL increase is fully in line with the size reduction
  7785. //else {
  7786. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  7787. //}
  7788. bool convert_incompatible_tensor = false;
  7789. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  7790. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  7791. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS) {
  7792. int nx = tensor->ne[0];
  7793. int ny = tensor->ne[1];
  7794. if (nx % QK_K != 0) {
  7795. 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));
  7796. convert_incompatible_tensor = true;
  7797. } else {
  7798. ++qs.n_k_quantized;
  7799. }
  7800. }
  7801. if (convert_incompatible_tensor) {
  7802. switch (new_type) {
  7803. case GGML_TYPE_IQ2_XXS:
  7804. case GGML_TYPE_IQ2_XS:
  7805. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  7806. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  7807. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  7808. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  7809. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  7810. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  7811. }
  7812. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  7813. ++qs.n_fallback;
  7814. }
  7815. return new_type;
  7816. }
  7817. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  7818. ggml_type quantized_type;
  7819. llama_ftype ftype = params->ftype;
  7820. switch (params->ftype) {
  7821. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  7822. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  7823. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  7824. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  7825. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  7826. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  7827. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  7828. // K-quants
  7829. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  7830. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  7831. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:
  7832. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  7833. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  7834. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  7835. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  7836. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  7837. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  7838. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  7839. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  7840. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:quantized_type = GGML_TYPE_IQ2_XXS; break;
  7841. case LLAMA_FTYPE_MOSTLY_IQ2_XS :quantized_type = GGML_TYPE_IQ2_XS; break;
  7842. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  7843. }
  7844. int nthread = params->nthread;
  7845. if (nthread <= 0) {
  7846. nthread = std::thread::hardware_concurrency();
  7847. }
  7848. // mmap consistently increases speed Linux, and also increases speed on Windows with
  7849. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  7850. #if defined(__linux__) || defined(_WIN32)
  7851. constexpr bool use_mmap = true;
  7852. #else
  7853. constexpr bool use_mmap = false;
  7854. #endif
  7855. llama_model_loader ml(fname_inp, use_mmap, NULL);
  7856. ml.init_mapping(false); // no prefetching?
  7857. llama_model model;
  7858. llm_load_arch(ml, model);
  7859. llm_load_hparams(ml, model);
  7860. struct quantize_state_internal qs(model, params);
  7861. if (params->only_copy) {
  7862. ftype = model.ftype;
  7863. }
  7864. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  7865. if (params->imatrix) {
  7866. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  7867. if (imatrix_data) {
  7868. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  7869. qs.has_imatrix = true;
  7870. }
  7871. }
  7872. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  7873. struct gguf_context * ctx_out = gguf_init_empty();
  7874. // copy the KV pairs from the input file
  7875. gguf_set_kv (ctx_out, ml.ctx_gguf);
  7876. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  7877. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  7878. for (int i = 0; i < ml.n_tensors; ++i) {
  7879. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7880. const std::string name = ggml_get_name(meta);
  7881. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7882. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  7883. ++qs.n_attention_wv;
  7884. }
  7885. else if (name.find("ffn_down") != std::string::npos) {
  7886. ++qs.n_ffn_down;
  7887. }
  7888. else if (name.find("ffn_gate") != std::string::npos) {
  7889. ++qs.n_ffn_gate;
  7890. }
  7891. else if (name.find("ffn_up") != std::string::npos) {
  7892. ++qs.n_ffn_up;
  7893. }
  7894. }
  7895. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  7896. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  7897. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  7898. }
  7899. size_t total_size_org = 0;
  7900. size_t total_size_new = 0;
  7901. std::vector<int64_t> hist_all(1 << 4, 0);
  7902. std::vector<std::thread> workers;
  7903. workers.reserve(nthread);
  7904. std::mutex mutex;
  7905. int idx = 0;
  7906. std::vector<no_init<uint8_t>> read_data;
  7907. std::vector<no_init<uint8_t>> work;
  7908. std::vector<no_init<float>> f32_conv_buf;
  7909. // populate the original tensors so we get an initial meta data
  7910. for (int i = 0; i < ml.n_tensors; ++i) {
  7911. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7912. gguf_add_tensor(ctx_out, meta);
  7913. }
  7914. std::ofstream fout(fname_out, std::ios::binary);
  7915. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  7916. const size_t meta_size = gguf_get_meta_size(ctx_out);
  7917. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  7918. // placeholder for the meta data
  7919. ::zeros(fout, meta_size);
  7920. for (int i = 0; i < ml.n_tensors; ++i) {
  7921. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  7922. const std::string name = ggml_get_name(tensor);
  7923. if (!ml.use_mmap) {
  7924. if (read_data.size() < ggml_nbytes(tensor)) {
  7925. read_data.resize(ggml_nbytes(tensor));
  7926. }
  7927. tensor->data = read_data.data();
  7928. }
  7929. ml.load_data_for(tensor);
  7930. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  7931. ++idx, ml.n_tensors,
  7932. ggml_get_name(tensor),
  7933. llama_format_tensor_shape(tensor).c_str(),
  7934. ggml_type_name(tensor->type));
  7935. // This used to be a regex, but <regex> has an extreme cost to compile times.
  7936. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  7937. // quantize only 2D tensors
  7938. quantize &= (ggml_n_dims(tensor) == 2);
  7939. quantize &= params->quantize_output_tensor || name != "output.weight";
  7940. quantize &= !params->only_copy;
  7941. // do not quantize expert gating tensors
  7942. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  7943. enum ggml_type new_type;
  7944. void * new_data;
  7945. size_t new_size;
  7946. if (quantize) {
  7947. new_type = quantized_type;
  7948. if (!params->pure) {
  7949. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  7950. }
  7951. // If we've decided to quantize to the same type the tensor is already
  7952. // in then there's nothing to do.
  7953. quantize = tensor->type != new_type;
  7954. }
  7955. if (!quantize) {
  7956. new_type = tensor->type;
  7957. new_data = tensor->data;
  7958. new_size = ggml_nbytes(tensor);
  7959. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  7960. } else {
  7961. const size_t nelements = ggml_nelements(tensor);
  7962. const float * imatrix = nullptr;
  7963. if (imatrix_data) {
  7964. auto it = imatrix_data->find(tensor->name);
  7965. if (it == imatrix_data->end()) {
  7966. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  7967. } else {
  7968. if (it->second.size() == (size_t)tensor->ne[0]) {
  7969. imatrix = it->second.data();
  7970. } else {
  7971. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  7972. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  7973. }
  7974. }
  7975. }
  7976. if ((new_type == GGML_TYPE_IQ2_XXS ||
  7977. new_type == GGML_TYPE_IQ2_XS ||
  7978. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  7979. LLAMA_LOG_ERROR("\n\n============================================================\n");
  7980. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  7981. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  7982. LLAMA_LOG_ERROR("============================================================\n\n");
  7983. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  7984. }
  7985. float * f32_data;
  7986. if (tensor->type == GGML_TYPE_F32) {
  7987. f32_data = (float *) tensor->data;
  7988. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  7989. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  7990. } else {
  7991. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  7992. f32_data = (float *) f32_conv_buf.data();
  7993. }
  7994. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  7995. fflush(stdout);
  7996. if (work.size() < nelements * 4) {
  7997. work.resize(nelements * 4); // upper bound on size
  7998. }
  7999. new_data = work.data();
  8000. std::array<int64_t, 1 << 4> hist_cur = {};
  8001. const int n_per_row = tensor->ne[0];
  8002. const int nrows = nelements / n_per_row;
  8003. static const int min_chunk_size = 32 * 512;
  8004. const int chunk_size = n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row);
  8005. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  8006. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  8007. if (nthread_use < 2) {
  8008. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  8009. } else {
  8010. int counter = 0;
  8011. new_size = 0;
  8012. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  8013. nrows, n_per_row, imatrix]() {
  8014. std::array<int64_t, 1 << 4> local_hist = {};
  8015. const int nrows_per_chunk = chunk_size / n_per_row;
  8016. size_t local_size = 0;
  8017. while (true) {
  8018. std::unique_lock<std::mutex> lock(mutex);
  8019. int first_row = counter; counter += nrows_per_chunk;
  8020. if (first_row >= nrows) {
  8021. if (local_size > 0) {
  8022. for (int j=0; j<int(local_hist.size()); ++j) {
  8023. hist_cur[j] += local_hist[j];
  8024. }
  8025. new_size += local_size;
  8026. }
  8027. break;
  8028. }
  8029. lock.unlock();
  8030. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  8031. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  8032. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  8033. }
  8034. };
  8035. for (int it = 0; it < nthread_use - 1; ++it) {
  8036. workers.emplace_back(compute);
  8037. }
  8038. compute();
  8039. for (auto & w : workers) { w.join(); }
  8040. workers.clear();
  8041. }
  8042. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  8043. int64_t tot_count = 0;
  8044. for (size_t i = 0; i < hist_cur.size(); i++) {
  8045. hist_all[i] += hist_cur[i];
  8046. tot_count += hist_cur[i];
  8047. }
  8048. if (tot_count > 0) {
  8049. LLAMA_LOG_INFO(" | hist: ");
  8050. for (size_t i = 0; i < hist_cur.size(); i++) {
  8051. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  8052. }
  8053. }
  8054. LLAMA_LOG_INFO("\n");
  8055. }
  8056. total_size_org += ggml_nbytes(tensor);
  8057. total_size_new += new_size;
  8058. // update the gguf meta data as we go
  8059. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  8060. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  8061. // write tensor data + padding
  8062. fout.write((const char *) new_data, new_size);
  8063. zeros(fout, GGML_PAD(new_size, align) - new_size);
  8064. }
  8065. // go back to beginning of file and write the updated meta data
  8066. {
  8067. fout.seekp(0);
  8068. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  8069. gguf_get_meta_data(ctx_out, data.data());
  8070. fout.write((const char *) data.data(), data.size());
  8071. }
  8072. fout.close();
  8073. gguf_free(ctx_out);
  8074. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  8075. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  8076. // print histogram for all tensors
  8077. {
  8078. int64_t sum_all = 0;
  8079. for (size_t i = 0; i < hist_all.size(); i++) {
  8080. sum_all += hist_all[i];
  8081. }
  8082. if (sum_all > 0) {
  8083. LLAMA_LOG_INFO("%s: hist: ", __func__);
  8084. for (size_t i = 0; i < hist_all.size(); i++) {
  8085. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  8086. }
  8087. LLAMA_LOG_INFO("\n");
  8088. }
  8089. }
  8090. if (qs.n_fallback > 0) {
  8091. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  8092. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  8093. }
  8094. }
  8095. static int llama_apply_lora_from_file_internal(
  8096. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  8097. ) {
  8098. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  8099. const int64_t t_start_lora_us = ggml_time_us();
  8100. llama_file fin(path_lora, "rb");
  8101. // verify magic and version
  8102. {
  8103. uint32_t magic = fin.read_u32();
  8104. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  8105. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  8106. return 1;
  8107. }
  8108. uint32_t format_version = fin.read_u32();
  8109. if (format_version != 1) {
  8110. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  8111. return 1;
  8112. }
  8113. }
  8114. int32_t lora_r = fin.read_u32();
  8115. int32_t lora_alpha = fin.read_u32();
  8116. float scaling = scale * (float)lora_alpha / (float)lora_r;
  8117. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  8118. // load base model
  8119. std::unique_ptr<llama_model_loader> ml;
  8120. if (path_base_model) {
  8121. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  8122. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  8123. ml->init_mapping(/*prefetch*/ false); // no prefetching
  8124. }
  8125. struct tensor_meta {
  8126. std::string name;
  8127. ggml_type type;
  8128. int32_t ne[2];
  8129. size_t offset;
  8130. };
  8131. std::map<std::string, tensor_meta> tensor_meta_map;
  8132. // load all tensor meta
  8133. while (true) {
  8134. if (fin.tell() == fin.size) {
  8135. // eof
  8136. break;
  8137. }
  8138. int32_t n_dims;
  8139. int32_t name_len;
  8140. int32_t ftype;
  8141. fin.read_raw(&n_dims, sizeof(n_dims));
  8142. fin.read_raw(&name_len, sizeof(name_len));
  8143. fin.read_raw(&ftype, sizeof(ftype));
  8144. if (n_dims != 1 && n_dims != 2) {
  8145. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  8146. return 1;
  8147. }
  8148. int32_t ne[2] = { 1, 1 };
  8149. for (int i = 0; i < n_dims; ++i) {
  8150. fin.read_raw(&ne[i], sizeof(ne[i]));
  8151. }
  8152. std::string name;
  8153. {
  8154. GGML_ASSERT(name_len < GGML_MAX_NAME);
  8155. char buf[GGML_MAX_NAME];
  8156. fin.read_raw(buf, name_len);
  8157. name = std::string(buf, name_len);
  8158. }
  8159. // check for lora suffix
  8160. std::string lora_suffix;
  8161. if (name.length() > 6) {
  8162. lora_suffix = name.substr(name.length() - 6);
  8163. }
  8164. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  8165. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  8166. return 1;
  8167. }
  8168. // tensor type
  8169. ggml_type wtype;
  8170. switch (ftype) {
  8171. case 0: wtype = GGML_TYPE_F32; break;
  8172. case 1: wtype = GGML_TYPE_F16; break;
  8173. default:
  8174. {
  8175. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  8176. __func__, ftype);
  8177. return false;
  8178. }
  8179. }
  8180. // data offset
  8181. size_t offset = fin.tell();
  8182. offset = (offset + 31) & -32;
  8183. // skip tensor data
  8184. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  8185. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  8186. }
  8187. bool warned = false;
  8188. int n_tensors = 0;
  8189. // apply
  8190. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  8191. if (backend_cpu == nullptr) {
  8192. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  8193. return 1;
  8194. }
  8195. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  8196. std::vector<no_init<uint8_t>> read_buf;
  8197. for (const auto & it : model.tensors_by_name) {
  8198. const std::string & base_name = it.first;
  8199. ggml_tensor * model_t = it.second;
  8200. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  8201. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  8202. continue;
  8203. }
  8204. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  8205. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  8206. ggml_init_params lora_init_params = {
  8207. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  8208. /* .mem_buffer */ nullptr,
  8209. /* .no_alloc */ true,
  8210. };
  8211. ggml_context * lora_ctx = ggml_init(lora_init_params);
  8212. if (lora_ctx == nullptr) {
  8213. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  8214. ggml_backend_free(backend_cpu);
  8215. return 1;
  8216. }
  8217. // create tensors
  8218. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  8219. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  8220. ggml_set_name(loraA, metaA.name.c_str());
  8221. ggml_set_name(loraB, metaB.name.c_str());
  8222. ggml_tensor * base_t;
  8223. if (ml) {
  8224. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  8225. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  8226. return 1;
  8227. }
  8228. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  8229. } else {
  8230. base_t = ggml_dup_tensor(lora_ctx, model_t);
  8231. }
  8232. ggml_set_name(base_t, base_name.c_str());
  8233. // allocate in backend buffer
  8234. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  8235. if (lora_buf == nullptr) {
  8236. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  8237. return 1;
  8238. }
  8239. // load tensor data
  8240. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  8241. read_buf.resize(ggml_nbytes(tensor));
  8242. fin.seek(tensor_meta.offset, SEEK_SET);
  8243. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  8244. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  8245. };
  8246. load_tensor(metaA, loraA);
  8247. load_tensor(metaB, loraB);
  8248. // load base model tensor data
  8249. if (ml) {
  8250. ml->load_data_for(base_t);
  8251. } else {
  8252. ggml_backend_tensor_copy(model_t, base_t);
  8253. }
  8254. if (ggml_is_quantized(base_t->type) && !warned) {
  8255. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  8256. "use a f16 or f32 base model with --lora-base\n", __func__);
  8257. warned = true;
  8258. }
  8259. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  8260. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  8261. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  8262. ggml_free(lora_ctx);
  8263. ggml_backend_buffer_free(lora_buf);
  8264. ggml_backend_free(backend_cpu);
  8265. return 1;
  8266. }
  8267. auto build_lora_graph = [&]() {
  8268. // w = w + BA*s
  8269. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  8270. ggml_set_name(BA, "BA");
  8271. if (scaling != 1.0f) {
  8272. BA = ggml_scale(lora_ctx, BA, scaling);
  8273. ggml_set_name(BA, "BA_scaled");
  8274. }
  8275. ggml_tensor * r;
  8276. r = ggml_add_inplace(lora_ctx, base_t, BA);
  8277. ggml_set_name(r, "r_add");
  8278. if (base_t->type != model_t->type) {
  8279. // convert the result to the model type
  8280. r = ggml_cast(lora_ctx, r, model_t->type);
  8281. ggml_set_name(r, "r_cast");
  8282. }
  8283. return r;
  8284. };
  8285. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  8286. ggml_tensor * r = build_lora_graph();
  8287. ggml_build_forward_expand(gf, r);
  8288. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  8289. if (graph_buf == nullptr) {
  8290. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  8291. ggml_free(lora_ctx);
  8292. ggml_backend_buffer_free(lora_buf);
  8293. ggml_backend_free(backend_cpu);
  8294. return 1;
  8295. }
  8296. ggml_backend_graph_compute(backend_cpu, gf);
  8297. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  8298. #if 0
  8299. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  8300. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  8301. // sched compute
  8302. ggml_build_forward_expand(gf, build_graph());
  8303. ggml_backend_sched_init_measure(sched, gf);
  8304. // create the graph again, since the previous one was destroyed by the measure
  8305. ggml_graph_clear(gf);
  8306. ggml_build_forward_expand(gf, build_graph());
  8307. ggml_backend_sched_graph_compute(sched, gf);
  8308. ggml_backend_sched_free(sched);
  8309. #endif
  8310. ggml_backend_buffer_free(lora_buf);
  8311. ggml_backend_buffer_free(graph_buf);
  8312. ggml_free(lora_ctx);
  8313. n_tensors++;
  8314. if (n_tensors % 4 == 0) {
  8315. LLAMA_LOG_INFO(".");
  8316. }
  8317. }
  8318. ggml_backend_free(backend_cpu);
  8319. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  8320. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  8321. return 0;
  8322. }
  8323. //
  8324. // interface implementation
  8325. //
  8326. struct llama_model_params llama_model_default_params() {
  8327. struct llama_model_params result = {
  8328. /*.n_gpu_layers =*/ 0,
  8329. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  8330. /*.main_gpu =*/ 0,
  8331. /*.tensor_split =*/ nullptr,
  8332. /*.progress_callback =*/ nullptr,
  8333. /*.progress_callback_user_data =*/ nullptr,
  8334. /*.kv_overrides =*/ nullptr,
  8335. /*.vocab_only =*/ false,
  8336. /*.use_mmap =*/ true,
  8337. /*.use_mlock =*/ false,
  8338. };
  8339. #ifdef GGML_USE_METAL
  8340. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  8341. result.n_gpu_layers = 999;
  8342. #endif
  8343. return result;
  8344. }
  8345. struct llama_context_params llama_context_default_params() {
  8346. struct llama_context_params result = {
  8347. /*.seed =*/ LLAMA_DEFAULT_SEED,
  8348. /*.n_ctx =*/ 512,
  8349. /*.n_batch =*/ 512,
  8350. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  8351. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  8352. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  8353. /*.rope_freq_base =*/ 0.0f,
  8354. /*.rope_freq_scale =*/ 0.0f,
  8355. /*.yarn_ext_factor =*/ -1.0f,
  8356. /*.yarn_attn_factor =*/ 1.0f,
  8357. /*.yarn_beta_fast =*/ 32.0f,
  8358. /*.yarn_beta_slow =*/ 1.0f,
  8359. /*.yarn_orig_ctx =*/ 0,
  8360. /*.cb_eval =*/ nullptr,
  8361. /*.cb_eval_user_data =*/ nullptr,
  8362. /*.type_k =*/ GGML_TYPE_F16,
  8363. /*.type_v =*/ GGML_TYPE_F16,
  8364. /*.mul_mat_q =*/ true,
  8365. /*.logits_all =*/ false,
  8366. /*.embedding =*/ false,
  8367. /*.offload_kqv =*/ true,
  8368. };
  8369. return result;
  8370. }
  8371. struct llama_model_quantize_params llama_model_quantize_default_params() {
  8372. struct llama_model_quantize_params result = {
  8373. /*.nthread =*/ 0,
  8374. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  8375. /*.allow_requantize =*/ false,
  8376. /*.quantize_output_tensor =*/ true,
  8377. /*.only_copy =*/ false,
  8378. /*.pure =*/ false,
  8379. /*.imatrix =*/ nullptr,
  8380. };
  8381. return result;
  8382. }
  8383. int32_t llama_max_devices(void) {
  8384. return LLAMA_MAX_DEVICES;
  8385. }
  8386. bool llama_mmap_supported(void) {
  8387. return llama_mmap::SUPPORTED;
  8388. }
  8389. bool llama_mlock_supported(void) {
  8390. return llama_mlock::SUPPORTED;
  8391. }
  8392. void llama_backend_init(bool numa) {
  8393. ggml_time_init();
  8394. // needed to initialize f16 tables
  8395. {
  8396. struct ggml_init_params params = { 0, NULL, false };
  8397. struct ggml_context * ctx = ggml_init(params);
  8398. ggml_free(ctx);
  8399. }
  8400. if (numa) {
  8401. ggml_numa_init();
  8402. }
  8403. #ifdef GGML_USE_MPI
  8404. ggml_mpi_backend_init();
  8405. #endif
  8406. }
  8407. void llama_backend_free(void) {
  8408. #ifdef GGML_USE_MPI
  8409. ggml_mpi_backend_free();
  8410. #endif
  8411. ggml_quantize_free();
  8412. }
  8413. int64_t llama_time_us(void) {
  8414. return ggml_time_us();
  8415. }
  8416. struct llama_model * llama_load_model_from_file(
  8417. const char * path_model,
  8418. struct llama_model_params params) {
  8419. ggml_time_init();
  8420. llama_model * model = new llama_model;
  8421. unsigned cur_percentage = 0;
  8422. if (params.progress_callback == NULL) {
  8423. params.progress_callback_user_data = &cur_percentage;
  8424. params.progress_callback = [](float progress, void * ctx) {
  8425. unsigned * cur_percentage_p = (unsigned *) ctx;
  8426. unsigned percentage = (unsigned) (100 * progress);
  8427. while (percentage > *cur_percentage_p) {
  8428. *cur_percentage_p = percentage;
  8429. LLAMA_LOG_INFO(".");
  8430. if (percentage >= 100) {
  8431. LLAMA_LOG_INFO("\n");
  8432. }
  8433. }
  8434. return true;
  8435. };
  8436. }
  8437. int status = llama_model_load(path_model, *model, params);
  8438. GGML_ASSERT(status <= 0);
  8439. if (status < 0) {
  8440. if (status == -1) {
  8441. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  8442. } else if (status == -2) {
  8443. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  8444. }
  8445. delete model;
  8446. return nullptr;
  8447. }
  8448. return model;
  8449. }
  8450. void llama_free_model(struct llama_model * model) {
  8451. delete model;
  8452. }
  8453. struct llama_context * llama_new_context_with_model(
  8454. struct llama_model * model,
  8455. struct llama_context_params params) {
  8456. if (!model) {
  8457. return nullptr;
  8458. }
  8459. llama_context * ctx = new llama_context(*model);
  8460. const auto & hparams = model->hparams;
  8461. auto & cparams = ctx->cparams;
  8462. cparams.n_batch = params.n_batch;
  8463. cparams.n_threads = params.n_threads;
  8464. cparams.n_threads_batch = params.n_threads_batch;
  8465. cparams.yarn_ext_factor = params.yarn_ext_factor;
  8466. cparams.yarn_attn_factor = params.yarn_attn_factor;
  8467. cparams.yarn_beta_fast = params.yarn_beta_fast;
  8468. cparams.yarn_beta_slow = params.yarn_beta_slow;
  8469. cparams.mul_mat_q = params.mul_mat_q;
  8470. cparams.offload_kqv = params.offload_kqv;
  8471. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  8472. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  8473. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  8474. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  8475. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  8476. hparams.n_ctx_train;
  8477. cparams.cb_eval = params.cb_eval;
  8478. cparams.cb_eval_user_data = params.cb_eval_user_data;
  8479. auto rope_scaling_type = params.rope_scaling_type;
  8480. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  8481. rope_scaling_type = hparams.rope_scaling_type_train;
  8482. }
  8483. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  8484. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  8485. }
  8486. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  8487. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  8488. }
  8489. if (params.seed == LLAMA_DEFAULT_SEED) {
  8490. params.seed = time(NULL);
  8491. }
  8492. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  8493. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  8494. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  8495. ctx->rng = std::mt19937(params.seed);
  8496. ctx->logits_all = params.logits_all;
  8497. const ggml_type type_k = params.type_k;
  8498. const ggml_type type_v = params.type_v;
  8499. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  8500. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  8501. if (!hparams.vocab_only) {
  8502. // initialize backends
  8503. #ifdef GGML_USE_METAL
  8504. if (model->n_gpu_layers > 0) {
  8505. ctx->backend_metal = ggml_backend_metal_init();
  8506. if (ctx->backend_metal == nullptr) {
  8507. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  8508. llama_free(ctx);
  8509. return nullptr;
  8510. }
  8511. ctx->backends.push_back(ctx->backend_metal);
  8512. }
  8513. #elif defined(GGML_USE_CUBLAS)
  8514. if (model->n_gpu_layers > 0) {
  8515. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  8516. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  8517. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  8518. if (backend == nullptr) {
  8519. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  8520. llama_free(ctx);
  8521. return nullptr;
  8522. }
  8523. ctx->backends.push_back(backend);
  8524. } else {
  8525. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  8526. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  8527. ggml_backend_t backend = ggml_backend_cuda_init(device);
  8528. if (backend == nullptr) {
  8529. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  8530. llama_free(ctx);
  8531. return nullptr;
  8532. }
  8533. ctx->backends.push_back(backend);
  8534. }
  8535. }
  8536. }
  8537. #elif defined(GGML_USE_VULKAN)
  8538. if (model->n_gpu_layers > 0) {
  8539. ggml_backend_t backend = ggml_backend_vk_init();
  8540. if (backend == nullptr) {
  8541. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  8542. llama_free(ctx);
  8543. return nullptr;
  8544. }
  8545. ctx->backends.push_back(backend);
  8546. }
  8547. #elif defined(GGML_USE_SYCL)
  8548. if (model->n_gpu_layers > 0) {
  8549. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  8550. if (backend == nullptr) {
  8551. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  8552. llama_free(ctx);
  8553. return nullptr;
  8554. }
  8555. ctx->backends.push_back(backend);
  8556. }
  8557. #endif
  8558. ctx->backend_cpu = ggml_backend_cpu_init();
  8559. if (ctx->backend_cpu == nullptr) {
  8560. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  8561. llama_free(ctx);
  8562. return nullptr;
  8563. }
  8564. ctx->backends.push_back(ctx->backend_cpu);
  8565. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  8566. cparams.n_ctx, cparams.offload_kqv)) {
  8567. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  8568. llama_free(ctx);
  8569. return nullptr;
  8570. }
  8571. {
  8572. size_t memory_size_k = 0;
  8573. size_t memory_size_v = 0;
  8574. for (auto & k : ctx->kv_self.k_l) {
  8575. memory_size_k += ggml_nbytes(k);
  8576. }
  8577. for (auto & v : ctx->kv_self.v_l) {
  8578. memory_size_v += ggml_nbytes(v);
  8579. }
  8580. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  8581. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  8582. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  8583. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  8584. }
  8585. // resized during inference, reserve maximum
  8586. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  8587. if (params.embedding){
  8588. ctx->embedding.resize(hparams.n_embd);
  8589. }
  8590. // graph inputs
  8591. {
  8592. ggml_init_params init_params = {
  8593. /* .mem_size */ ggml_tensor_overhead()*5,
  8594. /* .mem_buffer */ nullptr,
  8595. /* .no_alloc */ true,
  8596. };
  8597. ctx->ctx_input = ggml_init(init_params);
  8598. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  8599. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  8600. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  8601. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  8602. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  8603. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  8604. ggml_set_name(ctx->inp_embd, "inp_embd");
  8605. ggml_set_name(ctx->inp_pos, "inp_pos");
  8606. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  8607. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  8608. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  8609. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  8610. ggml_backend_buffer_name(ctx->buf_input),
  8611. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  8612. }
  8613. // scheduler and compute buffers
  8614. {
  8615. // buffer types used for the compute buffer of each backend
  8616. std::vector<ggml_backend_buffer_type_t> backend_buft;
  8617. for (auto * backend : ctx->backends) {
  8618. if (ggml_backend_is_cpu(backend)) {
  8619. // use host buffers for the CPU backend compute buffer
  8620. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  8621. } else {
  8622. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  8623. }
  8624. }
  8625. // buffer used to store the computation graph and the tensor meta data
  8626. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  8627. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  8628. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8629. // build worst-case graph
  8630. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  8631. int n_past = cparams.n_ctx - n_tokens;
  8632. 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
  8633. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  8634. // initialize scheduler with the worst-case graph
  8635. ggml_backend_sched_init_measure(ctx->sched, gf);
  8636. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8637. for (ggml_backend_t backend : ctx->backends) {
  8638. ggml_backend_buffer_t buf = ggml_backend_sched_get_buffer(ctx->sched, backend);
  8639. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  8640. ggml_backend_buffer_name(buf),
  8641. ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  8642. }
  8643. // note: the number of splits during measure is higher than during inference due to the kv shift
  8644. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  8645. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  8646. }
  8647. }
  8648. #ifdef GGML_USE_MPI
  8649. ctx->ctx_mpi = ggml_mpi_init();
  8650. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  8651. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  8652. // TODO: needs fix after #3228
  8653. GGML_ASSERT(false && "not implemented");
  8654. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  8655. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  8656. llama_backend_free();
  8657. exit(1);
  8658. }
  8659. #endif
  8660. return ctx;
  8661. }
  8662. void llama_free(struct llama_context * ctx) {
  8663. delete ctx;
  8664. }
  8665. const llama_model * llama_get_model(const struct llama_context * ctx) {
  8666. return &ctx->model;
  8667. }
  8668. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  8669. return ctx->cparams.n_ctx;
  8670. }
  8671. uint32_t llama_n_batch(const struct llama_context * ctx) {
  8672. return ctx->cparams.n_batch;
  8673. }
  8674. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  8675. return model->vocab.type;
  8676. }
  8677. int32_t llama_n_vocab(const struct llama_model * model) {
  8678. return model->vocab.id_to_token.size();
  8679. }
  8680. int32_t llama_n_ctx_train(const struct llama_model * model) {
  8681. return model->hparams.n_ctx_train;
  8682. }
  8683. int32_t llama_n_embd(const struct llama_model * model) {
  8684. return model->hparams.n_embd;
  8685. }
  8686. float llama_rope_freq_scale_train(const struct llama_model * model) {
  8687. return model->hparams.rope_freq_scale_train;
  8688. }
  8689. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  8690. const auto & it = model->gguf_kv.find(key);
  8691. if (it == model->gguf_kv.end()) {
  8692. if (buf_size > 0) {
  8693. buf[0] = '\0';
  8694. }
  8695. return -1;
  8696. }
  8697. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8698. }
  8699. int32_t llama_model_meta_count(const struct llama_model * model) {
  8700. return (int)model->gguf_kv.size();
  8701. }
  8702. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  8703. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8704. if (buf_size > 0) {
  8705. buf[0] = '\0';
  8706. }
  8707. return -1;
  8708. }
  8709. auto it = model->gguf_kv.begin();
  8710. std::advance(it, i);
  8711. return snprintf(buf, buf_size, "%s", it->first.c_str());
  8712. }
  8713. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  8714. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8715. if (buf_size > 0) {
  8716. buf[0] = '\0';
  8717. }
  8718. return -1;
  8719. }
  8720. auto it = model->gguf_kv.begin();
  8721. std::advance(it, i);
  8722. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8723. }
  8724. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  8725. return snprintf(buf, buf_size, "%s %s %s",
  8726. llama_model_arch_name(model->arch).c_str(),
  8727. llama_model_type_name(model->type),
  8728. llama_model_ftype_name(model->ftype).c_str());
  8729. }
  8730. uint64_t llama_model_size(const struct llama_model * model) {
  8731. uint64_t size = 0;
  8732. for (const auto & it : model->tensors_by_name) {
  8733. size += ggml_nbytes(it.second);
  8734. }
  8735. return size;
  8736. }
  8737. uint64_t llama_model_n_params(const struct llama_model * model) {
  8738. uint64_t nparams = 0;
  8739. for (const auto & it : model->tensors_by_name) {
  8740. nparams += ggml_nelements(it.second);
  8741. }
  8742. return nparams;
  8743. }
  8744. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  8745. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  8746. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  8747. return it.first == name;
  8748. });
  8749. if (it == model->tensors_by_name.end()) {
  8750. return nullptr;
  8751. }
  8752. return it->second;
  8753. }
  8754. uint32_t llama_model_quantize(
  8755. const char * fname_inp,
  8756. const char * fname_out,
  8757. const llama_model_quantize_params * params) {
  8758. try {
  8759. llama_model_quantize_internal(fname_inp, fname_out, params);
  8760. return 0;
  8761. } catch (const std::exception & err) {
  8762. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  8763. return 1;
  8764. }
  8765. }
  8766. int32_t llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  8767. try {
  8768. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  8769. } catch (const std::exception & err) {
  8770. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8771. return 1;
  8772. }
  8773. }
  8774. int32_t llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  8775. try {
  8776. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  8777. } catch (const std::exception & err) {
  8778. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8779. return 1;
  8780. }
  8781. }
  8782. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  8783. struct llama_kv_cache_view result = {
  8784. /*.n_cells = */ 0,
  8785. /*.n_max_seq = */ n_max_seq,
  8786. /*.token_count = */ 0,
  8787. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  8788. /*.max_contiguous = */ 0,
  8789. /*.max_contiguous_idx = */ -1,
  8790. /*.cells = */ nullptr,
  8791. /*.cells_sequences = */ nullptr,
  8792. };
  8793. return result;
  8794. }
  8795. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  8796. if (view->cells != nullptr) {
  8797. free(view->cells);
  8798. view->cells = nullptr;
  8799. }
  8800. if (view->cells_sequences != nullptr) {
  8801. free(view->cells_sequences);
  8802. view->cells_sequences = nullptr;
  8803. }
  8804. }
  8805. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  8806. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  8807. view->n_cells = int32_t(ctx->kv_self.size);
  8808. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  8809. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  8810. view->cells = (struct llama_kv_cache_view_cell *)p;
  8811. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  8812. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  8813. view->cells_sequences = (llama_seq_id *)p;
  8814. }
  8815. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  8816. llama_kv_cache_view_cell * c_curr = view->cells;
  8817. llama_seq_id * cs_curr = view->cells_sequences;
  8818. int32_t used_cells = 0;
  8819. int32_t token_count = 0;
  8820. int32_t curr_contig_idx = -1;
  8821. uint32_t max_contig = 0;
  8822. int32_t max_contig_idx = -1;
  8823. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  8824. const size_t curr_size = kv_cells[i].seq_id.size();
  8825. token_count += curr_size;
  8826. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  8827. if (curr_size > 0) {
  8828. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  8829. max_contig = i - curr_contig_idx;
  8830. max_contig_idx = curr_contig_idx;
  8831. }
  8832. curr_contig_idx = -1;
  8833. } else if (curr_contig_idx < 0) {
  8834. curr_contig_idx = i;
  8835. }
  8836. int seq_idx = 0;
  8837. for (const llama_seq_id it : kv_cells[i].seq_id) {
  8838. if (seq_idx >= view->n_max_seq) {
  8839. break;
  8840. }
  8841. cs_curr[seq_idx] = it;
  8842. seq_idx++;
  8843. }
  8844. if (seq_idx != 0) {
  8845. used_cells++;
  8846. }
  8847. for (; seq_idx < view->n_max_seq; seq_idx++) {
  8848. cs_curr[seq_idx] = -1;
  8849. }
  8850. }
  8851. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  8852. max_contig_idx = curr_contig_idx;
  8853. max_contig = kv_cells.size() - curr_contig_idx;
  8854. }
  8855. view->max_contiguous = max_contig;
  8856. view->max_contiguous_idx = max_contig_idx;
  8857. view->token_count = token_count;
  8858. view->used_cells = used_cells;
  8859. if (uint32_t(used_cells) != ctx->kv_self.used) {
  8860. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  8861. __func__, ctx->kv_self.used, used_cells);
  8862. }
  8863. }
  8864. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  8865. int result = 0;
  8866. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  8867. result += ctx->kv_self.cells[i].seq_id.size();
  8868. }
  8869. return result;
  8870. }
  8871. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  8872. return ctx->kv_self.used;
  8873. }
  8874. void llama_kv_cache_clear(struct llama_context * ctx) {
  8875. llama_kv_cache_clear(ctx->kv_self);
  8876. }
  8877. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  8878. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  8879. }
  8880. 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) {
  8881. if (seq_id_src == seq_id_dst) {
  8882. return;
  8883. }
  8884. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  8885. }
  8886. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  8887. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  8888. }
  8889. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  8890. if (delta == 0) {
  8891. return;
  8892. }
  8893. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  8894. }
  8895. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  8896. if (d == 1) {
  8897. return;
  8898. }
  8899. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  8900. }
  8901. // Returns the *maximum* size of the state
  8902. size_t llama_get_state_size(const struct llama_context * ctx) {
  8903. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  8904. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  8905. const size_t s_rng_size = sizeof(size_t);
  8906. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  8907. const size_t s_logits_size = sizeof(size_t);
  8908. // assume worst case for logits although only currently set ones are serialized
  8909. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  8910. const size_t s_embedding_size = sizeof(size_t);
  8911. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  8912. const size_t s_kv_size = sizeof(size_t);
  8913. const size_t s_kv_ntok = sizeof(int);
  8914. const size_t s_kv = ctx->kv_self.total_size();
  8915. const size_t s_total = (
  8916. + s_rng_size
  8917. + s_rng
  8918. + s_logits_size
  8919. + s_logits
  8920. + s_embedding_size
  8921. + s_embedding
  8922. + s_kv_size
  8923. + s_kv_ntok
  8924. + s_kv
  8925. );
  8926. return s_total;
  8927. }
  8928. // llama_context_data
  8929. struct llama_data_context {
  8930. virtual void write(const void * src, size_t size) = 0;
  8931. virtual size_t get_size_written() = 0;
  8932. virtual ~llama_data_context() = default;
  8933. };
  8934. struct llama_data_buffer_context : llama_data_context {
  8935. uint8_t * ptr;
  8936. size_t size_written = 0;
  8937. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  8938. void write(const void * src, size_t size) override {
  8939. memcpy(ptr, src, size);
  8940. ptr += size;
  8941. size_written += size;
  8942. }
  8943. size_t get_size_written() override {
  8944. return size_written;
  8945. }
  8946. };
  8947. struct llama_data_file_context : llama_data_context {
  8948. llama_file * file;
  8949. size_t size_written = 0;
  8950. llama_data_file_context(llama_file * f) : file(f) {}
  8951. void write(const void * src, size_t size) override {
  8952. file->write_raw(src, size);
  8953. size_written += size;
  8954. }
  8955. size_t get_size_written() override {
  8956. return size_written;
  8957. }
  8958. };
  8959. /** copy state data into either a buffer or file depending on the passed in context
  8960. *
  8961. * file context:
  8962. * llama_file file("/path", "wb");
  8963. * llama_data_file_context data_ctx(&file);
  8964. * llama_copy_state_data(ctx, &data_ctx);
  8965. *
  8966. * buffer context:
  8967. * std::vector<uint8_t> buf(max_size, 0);
  8968. * llama_data_buffer_context data_ctx(&buf.data());
  8969. * llama_copy_state_data(ctx, &data_ctx);
  8970. *
  8971. */
  8972. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  8973. // copy rng
  8974. {
  8975. std::ostringstream rng_ss;
  8976. rng_ss << ctx->rng;
  8977. const std::string & rng_str = rng_ss.str();
  8978. const size_t rng_size = rng_str.size();
  8979. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  8980. data_ctx->write(&rng_size, sizeof(rng_size));
  8981. data_ctx->write(rng_str.data(), rng_size);
  8982. }
  8983. // copy logits
  8984. {
  8985. const size_t logits_size = ctx->logits.size();
  8986. data_ctx->write(&logits_size, sizeof(logits_size));
  8987. if (logits_size) {
  8988. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  8989. }
  8990. }
  8991. // copy embeddings
  8992. {
  8993. const size_t embedding_size = ctx->embedding.size();
  8994. data_ctx->write(&embedding_size, sizeof(embedding_size));
  8995. if (embedding_size) {
  8996. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  8997. }
  8998. }
  8999. // copy kv cache
  9000. {
  9001. const auto & kv_self = ctx->kv_self;
  9002. const auto & hparams = ctx->model.hparams;
  9003. const auto & cparams = ctx->cparams;
  9004. const auto n_layer = hparams.n_layer;
  9005. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  9006. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  9007. const auto n_ctx = cparams.n_ctx;
  9008. const size_t kv_buf_size = kv_self.total_size();
  9009. const uint32_t kv_head = kv_self.head;
  9010. const uint32_t kv_size = kv_self.size;
  9011. const uint32_t kv_used = kv_self.used;
  9012. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  9013. data_ctx->write(&kv_head, sizeof(kv_head));
  9014. data_ctx->write(&kv_size, sizeof(kv_size));
  9015. data_ctx->write(&kv_used, sizeof(kv_used));
  9016. if (kv_buf_size) {
  9017. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  9018. std::vector<uint8_t> tmp_buf;
  9019. for (int il = 0; il < (int) n_layer; ++il) {
  9020. tmp_buf.resize(elt_size*n_embd_k_gqa*kv_head);
  9021. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  9022. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  9023. // v is not contiguous, copy row by row
  9024. tmp_buf.resize(elt_size*kv_head);
  9025. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  9026. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*elt_size*n_ctx, tmp_buf.size());
  9027. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  9028. }
  9029. }
  9030. }
  9031. for (uint32_t i = 0; i < kv_size; ++i) {
  9032. const auto & cell = kv_self.cells[i];
  9033. const llama_pos pos = cell.pos;
  9034. const size_t seq_id_size = cell.seq_id.size();
  9035. data_ctx->write(&pos, sizeof(pos));
  9036. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  9037. for (auto seq_id : cell.seq_id) {
  9038. data_ctx->write(&seq_id, sizeof(seq_id));
  9039. }
  9040. }
  9041. }
  9042. }
  9043. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  9044. llama_data_buffer_context data_ctx(dst);
  9045. llama_copy_state_data_internal(ctx, &data_ctx);
  9046. return data_ctx.get_size_written();
  9047. }
  9048. // Sets the state reading from the specified source address
  9049. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  9050. uint8_t * inp = src;
  9051. // set rng
  9052. {
  9053. size_t rng_size;
  9054. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  9055. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  9056. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  9057. std::istringstream rng_ss(rng_str);
  9058. rng_ss >> ctx->rng;
  9059. GGML_ASSERT(!rng_ss.fail());
  9060. }
  9061. // set logits
  9062. {
  9063. size_t logits_size;
  9064. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  9065. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  9066. if (logits_size) {
  9067. ctx->logits.resize(logits_size);
  9068. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  9069. inp += logits_size * sizeof(float);
  9070. }
  9071. }
  9072. // set embeddings
  9073. {
  9074. size_t embedding_size;
  9075. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  9076. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  9077. if (embedding_size) {
  9078. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  9079. inp += embedding_size * sizeof(float);
  9080. }
  9081. }
  9082. // set kv cache
  9083. {
  9084. const auto & kv_self = ctx->kv_self;
  9085. const auto & hparams = ctx->model.hparams;
  9086. const auto & cparams = ctx->cparams;
  9087. const int n_layer = hparams.n_layer;
  9088. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  9089. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  9090. const int n_ctx = cparams.n_ctx;
  9091. size_t kv_buf_size;
  9092. uint32_t kv_head;
  9093. uint32_t kv_size;
  9094. uint32_t kv_used;
  9095. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  9096. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  9097. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  9098. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  9099. if (kv_buf_size) {
  9100. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  9101. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  9102. for (int il = 0; il < (int) n_layer; ++il) {
  9103. size_t k_size = elt_size*n_embd_k_gqa*kv_head;
  9104. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  9105. inp += k_size;
  9106. // v is not contiguous, copy row by row
  9107. size_t v_row_size = elt_size*kv_head;
  9108. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  9109. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*elt_size*n_ctx, v_row_size);
  9110. inp += v_row_size;
  9111. }
  9112. }
  9113. }
  9114. ctx->kv_self.head = kv_head;
  9115. ctx->kv_self.size = kv_size;
  9116. ctx->kv_self.used = kv_used;
  9117. ctx->kv_self.cells.resize(kv_size);
  9118. for (uint32_t i = 0; i < kv_size; ++i) {
  9119. llama_pos pos;
  9120. size_t seq_id_size;
  9121. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  9122. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  9123. ctx->kv_self.cells[i].pos = pos;
  9124. llama_seq_id seq_id;
  9125. for (size_t j = 0; j < seq_id_size; ++j) {
  9126. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  9127. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  9128. }
  9129. }
  9130. }
  9131. const size_t nread = inp - src;
  9132. const size_t max_size = llama_get_state_size(ctx);
  9133. GGML_ASSERT(nread <= max_size);
  9134. return nread;
  9135. }
  9136. 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) {
  9137. llama_file file(path_session, "rb");
  9138. // sanity checks
  9139. {
  9140. const uint32_t magic = file.read_u32();
  9141. const uint32_t version = file.read_u32();
  9142. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  9143. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  9144. return false;
  9145. }
  9146. llama_hparams session_hparams;
  9147. file.read_raw(&session_hparams, sizeof(llama_hparams));
  9148. if (session_hparams != ctx->model.hparams) {
  9149. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  9150. return false;
  9151. }
  9152. }
  9153. // load the prompt
  9154. {
  9155. const uint32_t n_token_count = file.read_u32();
  9156. if (n_token_count > n_token_capacity) {
  9157. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  9158. return false;
  9159. }
  9160. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  9161. *n_token_count_out = n_token_count;
  9162. }
  9163. // restore the context state
  9164. {
  9165. const size_t n_state_size_cur = file.size - file.tell();
  9166. const size_t n_state_size_max = llama_get_state_size(ctx);
  9167. if (n_state_size_cur > n_state_size_max) {
  9168. 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);
  9169. return false;
  9170. }
  9171. std::vector<uint8_t> state_data(n_state_size_max);
  9172. file.read_raw(state_data.data(), n_state_size_cur);
  9173. llama_set_state_data(ctx, state_data.data());
  9174. }
  9175. return true;
  9176. }
  9177. 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) {
  9178. try {
  9179. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  9180. } catch (const std::exception & err) {
  9181. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  9182. return false;
  9183. }
  9184. }
  9185. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  9186. llama_file file(path_session, "wb");
  9187. file.write_u32(LLAMA_SESSION_MAGIC);
  9188. file.write_u32(LLAMA_SESSION_VERSION);
  9189. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  9190. // save the prompt
  9191. file.write_u32((uint32_t) n_token_count);
  9192. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  9193. // save the context state using stream saving
  9194. llama_data_file_context data_ctx(&file);
  9195. llama_copy_state_data_internal(ctx, &data_ctx);
  9196. return true;
  9197. }
  9198. int llama_eval(
  9199. struct llama_context * ctx,
  9200. llama_token * tokens,
  9201. int32_t n_tokens,
  9202. int32_t n_past) {
  9203. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  9204. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  9205. if (ret < 0) {
  9206. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9207. }
  9208. return ret;
  9209. }
  9210. int llama_eval_embd(
  9211. struct llama_context * ctx,
  9212. float * embd,
  9213. int32_t n_tokens,
  9214. int32_t n_past) {
  9215. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  9216. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  9217. const int ret = llama_decode_internal(*ctx, batch);
  9218. if (ret < 0) {
  9219. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9220. }
  9221. return ret;
  9222. }
  9223. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  9224. ctx->cparams.n_threads = n_threads;
  9225. ctx->cparams.n_threads_batch = n_threads_batch;
  9226. }
  9227. struct llama_batch llama_batch_get_one(
  9228. llama_token * tokens,
  9229. int32_t n_tokens,
  9230. llama_pos pos_0,
  9231. llama_seq_id seq_id) {
  9232. return {
  9233. /*n_tokens =*/ n_tokens,
  9234. /*tokens =*/ tokens,
  9235. /*embd =*/ nullptr,
  9236. /*pos =*/ nullptr,
  9237. /*n_seq_id =*/ nullptr,
  9238. /*seq_id =*/ nullptr,
  9239. /*logits =*/ nullptr,
  9240. /*all_pos_0 =*/ pos_0,
  9241. /*all_pos_1 =*/ 1,
  9242. /*all_seq_id =*/ seq_id,
  9243. };
  9244. }
  9245. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd, int32_t n_seq_max) {
  9246. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  9247. if (embd) {
  9248. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  9249. } else {
  9250. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  9251. }
  9252. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  9253. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens);
  9254. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * n_tokens);
  9255. for (int i = 0; i < n_tokens; ++i) {
  9256. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  9257. }
  9258. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  9259. return batch;
  9260. }
  9261. void llama_batch_free(struct llama_batch batch) {
  9262. if (batch.token) free(batch.token);
  9263. if (batch.embd) free(batch.embd);
  9264. if (batch.pos) free(batch.pos);
  9265. if (batch.n_seq_id) free(batch.n_seq_id);
  9266. if (batch.seq_id) {
  9267. for (int i = 0; i < batch.n_tokens; ++i) {
  9268. free(batch.seq_id[i]);
  9269. }
  9270. free(batch.seq_id);
  9271. }
  9272. if (batch.logits) free(batch.logits);
  9273. }
  9274. int32_t llama_decode(
  9275. struct llama_context * ctx,
  9276. struct llama_batch batch) {
  9277. const int ret = llama_decode_internal(*ctx, batch);
  9278. if (ret < 0) {
  9279. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9280. }
  9281. return ret;
  9282. }
  9283. float * llama_get_logits(struct llama_context * ctx) {
  9284. return ctx->logits.data();
  9285. }
  9286. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  9287. assert(ctx->logits_valid.at(i));
  9288. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  9289. }
  9290. float * llama_get_embeddings(struct llama_context * ctx) {
  9291. return ctx->embedding.data();
  9292. }
  9293. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  9294. return model->vocab.id_to_token[token].text.c_str();
  9295. }
  9296. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  9297. return model->vocab.id_to_token[token].score;
  9298. }
  9299. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  9300. return model->vocab.id_to_token[token].type;
  9301. }
  9302. llama_token llama_token_bos(const struct llama_model * model) {
  9303. return model->vocab.special_bos_id;
  9304. }
  9305. llama_token llama_token_eos(const struct llama_model * model) {
  9306. return model->vocab.special_eos_id;
  9307. }
  9308. llama_token llama_token_nl(const struct llama_model * model) {
  9309. return model->vocab.linefeed_id;
  9310. }
  9311. int32_t llama_add_bos_token(const struct llama_model * model) {
  9312. return model->vocab.special_add_bos;
  9313. }
  9314. int32_t llama_add_eos_token(const struct llama_model * model) {
  9315. return model->vocab.special_add_eos;
  9316. }
  9317. llama_token llama_token_prefix(const struct llama_model * model) {
  9318. return model->vocab.special_prefix_id;
  9319. }
  9320. llama_token llama_token_middle(const struct llama_model * model) {
  9321. return model->vocab.special_middle_id;
  9322. }
  9323. llama_token llama_token_suffix(const struct llama_model * model) {
  9324. return model->vocab.special_suffix_id;
  9325. }
  9326. llama_token llama_token_eot(const struct llama_model * model) {
  9327. return model->vocab.special_eot_id;
  9328. }
  9329. int32_t llama_tokenize(
  9330. const struct llama_model * model,
  9331. const char * text,
  9332. int32_t text_len,
  9333. llama_token * tokens,
  9334. int32_t n_max_tokens,
  9335. bool add_bos,
  9336. bool special) {
  9337. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  9338. if (n_max_tokens < (int) res.size()) {
  9339. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  9340. return -((int) res.size());
  9341. }
  9342. for (size_t i = 0; i < res.size(); i++) {
  9343. tokens[i] = res[i];
  9344. }
  9345. return res.size();
  9346. }
  9347. static std::string llama_decode_text(const std::string & text) {
  9348. std::string decoded_text;
  9349. auto unicode_sequences = codepoints_from_utf8(text);
  9350. for (auto& unicode_sequence : unicode_sequences) {
  9351. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  9352. }
  9353. return decoded_text;
  9354. }
  9355. // does not write null-terminator to buf
  9356. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  9357. if (0 <= token && token < llama_n_vocab(model)) {
  9358. switch (llama_vocab_get_type(model->vocab)) {
  9359. case LLAMA_VOCAB_TYPE_SPM: {
  9360. // NOTE: we accept all unsupported token types,
  9361. // suppressing them like CONTROL tokens.
  9362. if (llama_is_normal_token(model->vocab, token)) {
  9363. std::string result = model->vocab.id_to_token[token].text;
  9364. llama_unescape_whitespace(result);
  9365. if (length < (int) result.length()) {
  9366. return -(int) result.length();
  9367. }
  9368. memcpy(buf, result.c_str(), result.length());
  9369. return result.length();
  9370. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9371. std::string result = model->vocab.id_to_token[token].text;
  9372. if (length < (int) result.length()) {
  9373. return -result.length();
  9374. }
  9375. memcpy(buf, result.c_str(), result.length());
  9376. return result.length();
  9377. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  9378. if (length < 3) {
  9379. return -3;
  9380. }
  9381. memcpy(buf, "\xe2\x96\x85", 3);
  9382. return 3;
  9383. } else if (llama_is_control_token(model->vocab, token)) {
  9384. ;
  9385. } else if (llama_is_byte_token(model->vocab, token)) {
  9386. if (length < 1) {
  9387. return -1;
  9388. }
  9389. buf[0] = llama_token_to_byte(model->vocab, token);
  9390. return 1;
  9391. }
  9392. break;
  9393. }
  9394. case LLAMA_VOCAB_TYPE_BPE: {
  9395. // NOTE: we accept all unsupported token types,
  9396. // suppressing them like CONTROL tokens.
  9397. if (llama_is_normal_token(model->vocab, token)) {
  9398. std::string result = model->vocab.id_to_token[token].text;
  9399. result = llama_decode_text(result);
  9400. if (length < (int) result.length()) {
  9401. return -(int) result.length();
  9402. }
  9403. memcpy(buf, result.c_str(), result.length());
  9404. return result.length();
  9405. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9406. std::string result = model->vocab.id_to_token[token].text;
  9407. if (length < (int) result.length()) {
  9408. return -result.length();
  9409. }
  9410. memcpy(buf, result.c_str(), result.length());
  9411. return result.length();
  9412. } else if (llama_is_control_token(model->vocab, token)) {
  9413. ;
  9414. }
  9415. break;
  9416. }
  9417. default:
  9418. GGML_ASSERT(false);
  9419. }
  9420. }
  9421. return 0;
  9422. }
  9423. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  9424. struct llama_timings result = {
  9425. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  9426. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  9427. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  9428. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  9429. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  9430. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  9431. /*.n_sample =*/ std::max(1, ctx->n_sample),
  9432. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  9433. /*.n_eval =*/ std::max(1, ctx->n_eval),
  9434. };
  9435. return result;
  9436. }
  9437. void llama_print_timings(struct llama_context * ctx) {
  9438. const llama_timings timings = llama_get_timings(ctx);
  9439. LLAMA_LOG_INFO("\n");
  9440. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  9441. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9442. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  9443. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  9444. __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);
  9445. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9446. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  9447. LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (timings.t_end_ms - timings.t_start_ms), (timings.n_p_eval + timings.n_eval));
  9448. }
  9449. void llama_reset_timings(struct llama_context * ctx) {
  9450. ctx->t_start_us = ggml_time_us();
  9451. ctx->t_sample_us = ctx->n_sample = 0;
  9452. ctx->t_eval_us = ctx->n_eval = 0;
  9453. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  9454. }
  9455. const char * llama_print_system_info(void) {
  9456. static std::string s;
  9457. s = "";
  9458. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  9459. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  9460. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  9461. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  9462. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  9463. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  9464. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  9465. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  9466. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  9467. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  9468. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  9469. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  9470. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  9471. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  9472. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  9473. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  9474. return s.c_str();
  9475. }
  9476. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  9477. fprintf(stream, "\n");
  9478. fprintf(stream, "###########\n");
  9479. fprintf(stream, "# Timings #\n");
  9480. fprintf(stream, "###########\n");
  9481. fprintf(stream, "\n");
  9482. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  9483. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  9484. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  9485. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  9486. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  9487. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  9488. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  9489. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  9490. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  9491. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  9492. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  9493. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  9494. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  9495. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  9496. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  9497. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  9498. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  9499. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  9500. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  9501. }
  9502. // For internal test use
  9503. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  9504. struct llama_context * ctx
  9505. ) {
  9506. return ctx->model.tensors_by_name;
  9507. }
  9508. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  9509. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  9510. g_state.log_callback_user_data = user_data;
  9511. #ifdef GGML_USE_METAL
  9512. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  9513. #endif
  9514. }
  9515. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  9516. va_list args_copy;
  9517. va_copy(args_copy, args);
  9518. char buffer[128];
  9519. int len = vsnprintf(buffer, 128, format, args);
  9520. if (len < 128) {
  9521. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  9522. } else {
  9523. char* buffer2 = new char[len+1];
  9524. vsnprintf(buffer2, len+1, format, args_copy);
  9525. buffer2[len] = 0;
  9526. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  9527. delete[] buffer2;
  9528. }
  9529. va_end(args_copy);
  9530. }
  9531. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  9532. va_list args;
  9533. va_start(args, format);
  9534. llama_log_internal_v(level, format, args);
  9535. va_end(args);
  9536. }
  9537. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  9538. (void) level;
  9539. (void) user_data;
  9540. fputs(text, stderr);
  9541. fflush(stderr);
  9542. }