llama.cpp 523 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469
  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. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.h"
  23. #endif
  24. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #include <io.h>
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cfloat>
  55. #include <cinttypes>
  56. #include <climits>
  57. #include <cmath>
  58. #include <cstdarg>
  59. #include <cstddef>
  60. #include <cstdint>
  61. #include <cstdio>
  62. #include <cstring>
  63. #include <ctime>
  64. #include <cwctype>
  65. #include <forward_list>
  66. #include <fstream>
  67. #include <functional>
  68. #include <initializer_list>
  69. #include <locale>
  70. #include <map>
  71. #include <memory>
  72. #include <mutex>
  73. #include <numeric>
  74. #include <queue>
  75. #include <random>
  76. #include <regex>
  77. #include <set>
  78. #include <sstream>
  79. #include <thread>
  80. #include <type_traits>
  81. #include <unordered_map>
  82. #if defined(_MSC_VER)
  83. #pragma warning(disable: 4244 4267) // possible loss of data
  84. #endif
  85. #ifdef __GNUC__
  86. #ifdef __MINGW32__
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  88. #else
  89. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  90. #endif
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...)
  93. #endif
  94. #define LLAMA_MAX_NODES 8192
  95. #define LLAMA_MAX_EXPERTS 8
  96. //
  97. // logging
  98. //
  99. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  100. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  101. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  102. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  103. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  104. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  105. //
  106. // helpers
  107. //
  108. static size_t utf8_len(char src) {
  109. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  110. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  111. return lookup[highbits];
  112. }
  113. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  114. std::string result;
  115. for (size_t pos = 0; ; pos += search.length()) {
  116. auto new_pos = s.find(search, pos);
  117. if (new_pos == std::string::npos) {
  118. result += s.substr(pos, s.size() - pos);
  119. break;
  120. }
  121. result += s.substr(pos, new_pos - pos) + replace;
  122. pos = new_pos;
  123. }
  124. s = std::move(result);
  125. }
  126. static bool is_float_close(float a, float b, float abs_tol) {
  127. // Check for non-negative tolerance
  128. if (abs_tol < 0.0) {
  129. throw std::invalid_argument("Tolerance must be non-negative");
  130. }
  131. // Exact equality check
  132. if (a == b) {
  133. return true;
  134. }
  135. // Check for infinities
  136. if (std::isinf(a) || std::isinf(b)) {
  137. return false;
  138. }
  139. // Regular comparison using the provided absolute tolerance
  140. return std::fabs(b - a) <= abs_tol;
  141. }
  142. static void zeros(std::ofstream & file, size_t n) {
  143. char zero = 0;
  144. for (size_t i = 0; i < n; ++i) {
  145. file.write(&zero, 1);
  146. }
  147. }
  148. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  149. static std::string format(const char * fmt, ...) {
  150. va_list ap;
  151. va_list ap2;
  152. va_start(ap, fmt);
  153. va_copy(ap2, ap);
  154. int size = vsnprintf(NULL, 0, fmt, ap);
  155. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  156. std::vector<char> buf(size + 1);
  157. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  158. GGML_ASSERT(size2 == size);
  159. va_end(ap2);
  160. va_end(ap);
  161. return std::string(buf.data(), size);
  162. }
  163. //
  164. // gguf constants (sync with gguf.py)
  165. //
  166. enum llm_arch {
  167. LLM_ARCH_LLAMA,
  168. LLM_ARCH_FALCON,
  169. LLM_ARCH_BAICHUAN,
  170. LLM_ARCH_GPT2,
  171. LLM_ARCH_GPTJ,
  172. LLM_ARCH_GPTNEOX,
  173. LLM_ARCH_MPT,
  174. LLM_ARCH_STARCODER,
  175. LLM_ARCH_PERSIMMON,
  176. LLM_ARCH_REFACT,
  177. LLM_ARCH_BERT,
  178. LLM_ARCH_NOMIC_BERT,
  179. LLM_ARCH_BLOOM,
  180. LLM_ARCH_STABLELM,
  181. LLM_ARCH_QWEN,
  182. LLM_ARCH_QWEN2,
  183. LLM_ARCH_PHI2,
  184. LLM_ARCH_PLAMO,
  185. LLM_ARCH_CODESHELL,
  186. LLM_ARCH_ORION,
  187. LLM_ARCH_INTERNLM2,
  188. LLM_ARCH_MINICPM,
  189. LLM_ARCH_GEMMA,
  190. LLM_ARCH_STARCODER2,
  191. LLM_ARCH_UNKNOWN,
  192. };
  193. static std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  194. { LLM_ARCH_LLAMA, "llama" },
  195. { LLM_ARCH_FALCON, "falcon" },
  196. { LLM_ARCH_GPT2, "gpt2" },
  197. { LLM_ARCH_GPTJ, "gptj" },
  198. { LLM_ARCH_GPTNEOX, "gptneox" },
  199. { LLM_ARCH_MPT, "mpt" },
  200. { LLM_ARCH_BAICHUAN, "baichuan" },
  201. { LLM_ARCH_STARCODER, "starcoder" },
  202. { LLM_ARCH_PERSIMMON, "persimmon" },
  203. { LLM_ARCH_REFACT, "refact" },
  204. { LLM_ARCH_BERT, "bert" },
  205. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  206. { LLM_ARCH_BLOOM, "bloom" },
  207. { LLM_ARCH_STABLELM, "stablelm" },
  208. { LLM_ARCH_QWEN, "qwen" },
  209. { LLM_ARCH_QWEN2, "qwen2" },
  210. { LLM_ARCH_PHI2, "phi2" },
  211. { LLM_ARCH_PLAMO, "plamo" },
  212. { LLM_ARCH_CODESHELL, "codeshell" },
  213. { LLM_ARCH_ORION, "orion" },
  214. { LLM_ARCH_INTERNLM2, "internlm2" },
  215. { LLM_ARCH_MINICPM, "minicpm" },
  216. { LLM_ARCH_GEMMA, "gemma" },
  217. { LLM_ARCH_STARCODER2, "starcoder2" },
  218. };
  219. enum llm_kv {
  220. LLM_KV_GENERAL_ARCHITECTURE,
  221. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  222. LLM_KV_GENERAL_ALIGNMENT,
  223. LLM_KV_GENERAL_NAME,
  224. LLM_KV_GENERAL_AUTHOR,
  225. LLM_KV_GENERAL_URL,
  226. LLM_KV_GENERAL_DESCRIPTION,
  227. LLM_KV_GENERAL_LICENSE,
  228. LLM_KV_GENERAL_SOURCE_URL,
  229. LLM_KV_GENERAL_SOURCE_HF_REPO,
  230. LLM_KV_CONTEXT_LENGTH,
  231. LLM_KV_EMBEDDING_LENGTH,
  232. LLM_KV_BLOCK_COUNT,
  233. LLM_KV_FEED_FORWARD_LENGTH,
  234. LLM_KV_USE_PARALLEL_RESIDUAL,
  235. LLM_KV_TENSOR_DATA_LAYOUT,
  236. LLM_KV_EXPERT_COUNT,
  237. LLM_KV_EXPERT_USED_COUNT,
  238. LLM_KV_POOLING_TYPE,
  239. LLM_KV_ATTENTION_HEAD_COUNT,
  240. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  241. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  242. LLM_KV_ATTENTION_CLAMP_KQV,
  243. LLM_KV_ATTENTION_KEY_LENGTH,
  244. LLM_KV_ATTENTION_VALUE_LENGTH,
  245. LLM_KV_ATTENTION_LAYERNORM_EPS,
  246. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  247. LLM_KV_ATTENTION_CAUSAL,
  248. LLM_KV_ROPE_DIMENSION_COUNT,
  249. LLM_KV_ROPE_FREQ_BASE,
  250. LLM_KV_ROPE_SCALE_LINEAR,
  251. LLM_KV_ROPE_SCALING_TYPE,
  252. LLM_KV_ROPE_SCALING_FACTOR,
  253. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  254. LLM_KV_ROPE_SCALING_FINETUNED,
  255. LLM_KV_TOKENIZER_MODEL,
  256. LLM_KV_TOKENIZER_LIST,
  257. LLM_KV_TOKENIZER_TOKEN_TYPE,
  258. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  259. LLM_KV_TOKENIZER_SCORES,
  260. LLM_KV_TOKENIZER_MERGES,
  261. LLM_KV_TOKENIZER_BOS_ID,
  262. LLM_KV_TOKENIZER_EOS_ID,
  263. LLM_KV_TOKENIZER_UNK_ID,
  264. LLM_KV_TOKENIZER_SEP_ID,
  265. LLM_KV_TOKENIZER_PAD_ID,
  266. LLM_KV_TOKENIZER_ADD_BOS,
  267. LLM_KV_TOKENIZER_ADD_EOS,
  268. LLM_KV_TOKENIZER_ADD_PREFIX,
  269. LLM_KV_TOKENIZER_HF_JSON,
  270. LLM_KV_TOKENIZER_RWKV,
  271. };
  272. static std::map<llm_kv, const char *> LLM_KV_NAMES = {
  273. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  274. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  275. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  276. { LLM_KV_GENERAL_NAME, "general.name" },
  277. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  278. { LLM_KV_GENERAL_URL, "general.url" },
  279. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  280. { LLM_KV_GENERAL_LICENSE, "general.license" },
  281. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  282. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  283. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  284. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  285. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  286. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  287. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  288. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  289. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  290. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  291. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  292. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  293. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  294. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  295. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  296. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  297. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  298. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  299. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  300. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  301. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  302. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  303. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  304. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  305. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  306. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  307. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  308. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  309. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  310. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  311. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  312. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  313. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  314. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  315. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  316. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  317. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  318. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  319. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  320. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  321. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  322. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  323. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  324. };
  325. struct LLM_KV {
  326. LLM_KV(llm_arch arch) : arch(arch) {}
  327. llm_arch arch;
  328. std::string operator()(llm_kv kv) const {
  329. return ::format(LLM_KV_NAMES[kv], LLM_ARCH_NAMES[arch]);
  330. }
  331. };
  332. enum llm_tensor {
  333. LLM_TENSOR_TOKEN_EMBD,
  334. LLM_TENSOR_TOKEN_EMBD_NORM,
  335. LLM_TENSOR_TOKEN_TYPES,
  336. LLM_TENSOR_POS_EMBD,
  337. LLM_TENSOR_OUTPUT,
  338. LLM_TENSOR_OUTPUT_NORM,
  339. LLM_TENSOR_ROPE_FREQS,
  340. LLM_TENSOR_ATTN_Q,
  341. LLM_TENSOR_ATTN_K,
  342. LLM_TENSOR_ATTN_V,
  343. LLM_TENSOR_ATTN_QKV,
  344. LLM_TENSOR_ATTN_OUT,
  345. LLM_TENSOR_ATTN_NORM,
  346. LLM_TENSOR_ATTN_NORM_2,
  347. LLM_TENSOR_ATTN_OUT_NORM,
  348. LLM_TENSOR_ATTN_ROT_EMBD,
  349. LLM_TENSOR_FFN_GATE_INP,
  350. LLM_TENSOR_FFN_NORM,
  351. LLM_TENSOR_FFN_GATE,
  352. LLM_TENSOR_FFN_DOWN,
  353. LLM_TENSOR_FFN_UP,
  354. LLM_TENSOR_FFN_ACT,
  355. LLM_TENSOR_FFN_DOWN_EXP,
  356. LLM_TENSOR_FFN_GATE_EXP,
  357. LLM_TENSOR_FFN_UP_EXP,
  358. LLM_TENSOR_ATTN_Q_NORM,
  359. LLM_TENSOR_ATTN_K_NORM,
  360. LLM_TENSOR_LAYER_OUT_NORM,
  361. };
  362. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  363. {
  364. LLM_ARCH_LLAMA,
  365. {
  366. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  367. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  368. { LLM_TENSOR_OUTPUT, "output" },
  369. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  370. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  371. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  372. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  373. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  374. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  375. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  376. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  377. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  378. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  379. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  380. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  381. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  382. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  383. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  384. },
  385. },
  386. {
  387. LLM_ARCH_BAICHUAN,
  388. {
  389. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  390. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  391. { LLM_TENSOR_OUTPUT, "output" },
  392. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  393. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  394. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  395. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  396. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  397. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  398. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  399. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  400. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  401. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  402. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  403. },
  404. },
  405. {
  406. LLM_ARCH_FALCON,
  407. {
  408. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  409. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  410. { LLM_TENSOR_OUTPUT, "output" },
  411. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  412. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  413. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  414. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  415. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  416. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  417. },
  418. },
  419. {
  420. LLM_ARCH_GPT2,
  421. {
  422. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  423. { LLM_TENSOR_POS_EMBD, "position_embd" },
  424. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  425. { LLM_TENSOR_OUTPUT, "output" },
  426. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  427. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  428. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  429. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  430. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  431. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  432. },
  433. },
  434. {
  435. LLM_ARCH_GPTJ,
  436. {
  437. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  438. },
  439. },
  440. {
  441. LLM_ARCH_GPTNEOX,
  442. {
  443. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  444. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  445. { LLM_TENSOR_OUTPUT, "output" },
  446. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  447. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  448. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  449. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  450. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  451. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  452. },
  453. },
  454. {
  455. LLM_ARCH_PERSIMMON,
  456. {
  457. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  458. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  459. { LLM_TENSOR_OUTPUT, "output"},
  460. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  461. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  462. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  463. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  464. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  465. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  466. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  467. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  468. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  469. },
  470. },
  471. {
  472. LLM_ARCH_MPT,
  473. {
  474. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  475. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  476. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  477. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  478. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  479. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  480. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  481. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  482. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  483. },
  484. },
  485. {
  486. LLM_ARCH_STARCODER,
  487. {
  488. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  489. { LLM_TENSOR_POS_EMBD, "position_embd" },
  490. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  491. { LLM_TENSOR_OUTPUT, "output" },
  492. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  493. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  494. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  495. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  496. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  497. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  498. },
  499. },
  500. {
  501. LLM_ARCH_REFACT,
  502. {
  503. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  504. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  505. { LLM_TENSOR_OUTPUT, "output" },
  506. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  507. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  508. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  509. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  510. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  511. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  512. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  513. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  514. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  515. },
  516. },
  517. {
  518. LLM_ARCH_BERT,
  519. {
  520. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  521. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  522. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  523. { LLM_TENSOR_POS_EMBD, "position_embd" },
  524. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  525. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  526. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  527. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  528. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  529. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  530. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  531. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  532. },
  533. },
  534. {
  535. LLM_ARCH_NOMIC_BERT,
  536. {
  537. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  538. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  539. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  540. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  541. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  542. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  543. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  544. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  545. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  546. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  547. },
  548. },
  549. {
  550. LLM_ARCH_BLOOM,
  551. {
  552. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  553. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  554. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  555. { LLM_TENSOR_OUTPUT, "output" },
  556. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  557. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  558. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  559. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  560. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  561. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  562. },
  563. },
  564. {
  565. LLM_ARCH_STABLELM,
  566. {
  567. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  568. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  569. { LLM_TENSOR_OUTPUT, "output" },
  570. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  571. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  572. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  573. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  574. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  575. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  576. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  577. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  578. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  579. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  580. },
  581. },
  582. {
  583. LLM_ARCH_QWEN,
  584. {
  585. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  586. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  587. { LLM_TENSOR_OUTPUT, "output" },
  588. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  589. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  590. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  591. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  592. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  593. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  594. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  595. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  596. },
  597. },
  598. {
  599. LLM_ARCH_QWEN2,
  600. {
  601. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  602. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  603. { LLM_TENSOR_OUTPUT, "output" },
  604. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  605. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  606. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  607. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  608. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  609. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  610. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  611. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  612. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  613. },
  614. },
  615. {
  616. LLM_ARCH_PHI2,
  617. {
  618. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  619. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  620. { LLM_TENSOR_OUTPUT, "output" },
  621. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  622. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  623. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  624. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  625. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  626. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  627. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  628. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  629. },
  630. },
  631. {
  632. LLM_ARCH_PLAMO,
  633. {
  634. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  635. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  636. { LLM_TENSOR_OUTPUT, "output" },
  637. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  638. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  639. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  640. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  641. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  642. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  643. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  644. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  645. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  646. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  647. },
  648. },
  649. {
  650. LLM_ARCH_CODESHELL,
  651. {
  652. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  653. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  654. { LLM_TENSOR_OUTPUT, "output" },
  655. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  656. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  657. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  658. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  659. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  660. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  661. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  662. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  663. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  664. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  665. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  666. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  667. },
  668. },
  669. {
  670. LLM_ARCH_ORION,
  671. {
  672. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  673. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  674. { LLM_TENSOR_OUTPUT, "output" },
  675. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  676. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  677. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  678. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  679. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  680. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  681. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  682. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  683. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  684. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  685. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  686. },
  687. },
  688. {
  689. LLM_ARCH_INTERNLM2,
  690. {
  691. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  692. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  693. { LLM_TENSOR_OUTPUT, "output" },
  694. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  695. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  696. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  697. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  698. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  699. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  700. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  701. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  702. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  703. },
  704. },
  705. {
  706. LLM_ARCH_MINICPM,
  707. {
  708. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  709. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  710. { LLM_TENSOR_OUTPUT, "output" },
  711. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  712. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  713. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  714. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  715. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  716. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  717. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  718. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  719. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  720. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  721. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  722. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  723. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  724. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  725. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  726. },
  727. },
  728. {
  729. LLM_ARCH_GEMMA,
  730. {
  731. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  732. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  733. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  734. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  735. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  736. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  737. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  738. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  739. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  740. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  741. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  742. },
  743. },
  744. {
  745. LLM_ARCH_STARCODER2,
  746. {
  747. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  748. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  749. { LLM_TENSOR_OUTPUT, "output" },
  750. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  751. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  752. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  753. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  754. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  755. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  756. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  757. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  758. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  759. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  760. },
  761. },
  762. {
  763. LLM_ARCH_UNKNOWN,
  764. {
  765. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  766. },
  767. },
  768. };
  769. static llm_arch llm_arch_from_string(const std::string & name) {
  770. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  771. if (kv.second == name) {
  772. return kv.first;
  773. }
  774. }
  775. return LLM_ARCH_UNKNOWN;
  776. }
  777. // helper to handle gguf constants
  778. // usage:
  779. //
  780. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  781. //
  782. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  783. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  784. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  785. //
  786. struct LLM_TN {
  787. LLM_TN(llm_arch arch) : arch(arch) {}
  788. llm_arch arch;
  789. std::string operator()(llm_tensor tensor) const {
  790. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  791. return "__missing__";
  792. }
  793. return LLM_TENSOR_NAMES[arch].at(tensor);
  794. }
  795. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  796. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  797. return "__missing__";
  798. }
  799. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  800. }
  801. std::string operator()(llm_tensor tensor, int bid) const {
  802. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  803. return "__missing__";
  804. }
  805. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  806. }
  807. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  808. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  809. return "__missing__";
  810. }
  811. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  812. }
  813. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  814. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  815. return "__missing__";
  816. }
  817. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  818. }
  819. };
  820. //
  821. // gguf helpers
  822. //
  823. static std::map<int32_t, const char *> LLAMA_ROPE_SCALING_TYPES = {
  824. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  825. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  826. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  827. };
  828. static int32_t llama_rope_scaling_type_from_string(const std::string & name) {
  829. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  830. if (kv.second == name) {
  831. return kv.first;
  832. }
  833. }
  834. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  835. }
  836. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  837. switch (type) {
  838. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  839. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  840. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  841. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  842. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  843. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  844. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  845. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  846. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  847. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  848. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  849. default: return format("unknown type %d", type);
  850. }
  851. }
  852. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  853. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  854. switch (type) {
  855. case GGUF_TYPE_STRING:
  856. return gguf_get_val_str(ctx_gguf, i);
  857. case GGUF_TYPE_ARRAY:
  858. {
  859. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  860. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  861. const void * data = gguf_get_arr_data(ctx_gguf, i);
  862. std::stringstream ss;
  863. ss << "[";
  864. for (int j = 0; j < arr_n; j++) {
  865. if (arr_type == GGUF_TYPE_STRING) {
  866. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  867. // escape quotes
  868. replace_all(val, "\\", "\\\\");
  869. replace_all(val, "\"", "\\\"");
  870. ss << '"' << val << '"';
  871. } else if (arr_type == GGUF_TYPE_ARRAY) {
  872. ss << "???";
  873. } else {
  874. ss << gguf_data_to_str(arr_type, data, j);
  875. }
  876. if (j < arr_n - 1) {
  877. ss << ", ";
  878. }
  879. }
  880. ss << "]";
  881. return ss.str();
  882. }
  883. default:
  884. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  885. }
  886. }
  887. //
  888. // ggml helpers
  889. //
  890. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  891. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  892. if (plan.work_size > 0) {
  893. buf.resize(plan.work_size);
  894. plan.work_data = buf.data();
  895. }
  896. ggml_graph_compute(graph, &plan);
  897. }
  898. //
  899. // llama helpers
  900. //
  901. #if defined(_WIN32)
  902. static std::string llama_format_win_err(DWORD err) {
  903. LPSTR buf;
  904. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  905. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  906. if (!size) {
  907. return "FormatMessageA failed";
  908. }
  909. std::string ret(buf, size);
  910. LocalFree(buf);
  911. return ret;
  912. }
  913. #endif
  914. template <typename T>
  915. struct no_init {
  916. T value;
  917. no_init() { /* do nothing */ }
  918. };
  919. struct llama_file {
  920. // use FILE * so we don't have to re-open the file to mmap
  921. FILE * fp;
  922. size_t size;
  923. llama_file(const char * fname, const char * mode) {
  924. fp = std::fopen(fname, mode);
  925. if (fp == NULL) {
  926. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  927. }
  928. seek(0, SEEK_END);
  929. size = tell();
  930. seek(0, SEEK_SET);
  931. }
  932. size_t tell() const {
  933. #ifdef _WIN32
  934. __int64 ret = _ftelli64(fp);
  935. #else
  936. long ret = std::ftell(fp);
  937. #endif
  938. GGML_ASSERT(ret != -1); // this really shouldn't fail
  939. return (size_t) ret;
  940. }
  941. void seek(size_t offset, int whence) const {
  942. #ifdef _WIN32
  943. int ret = _fseeki64(fp, (__int64) offset, whence);
  944. #else
  945. int ret = std::fseek(fp, (long) offset, whence);
  946. #endif
  947. GGML_ASSERT(ret == 0); // same
  948. }
  949. void read_raw(void * ptr, size_t len) const {
  950. if (len == 0) {
  951. return;
  952. }
  953. errno = 0;
  954. std::size_t ret = std::fread(ptr, len, 1, fp);
  955. if (ferror(fp)) {
  956. throw std::runtime_error(format("read error: %s", strerror(errno)));
  957. }
  958. if (ret != 1) {
  959. throw std::runtime_error("unexpectedly reached end of file");
  960. }
  961. }
  962. uint32_t read_u32() const {
  963. uint32_t ret;
  964. read_raw(&ret, sizeof(ret));
  965. return ret;
  966. }
  967. void write_raw(const void * ptr, size_t len) const {
  968. if (len == 0) {
  969. return;
  970. }
  971. errno = 0;
  972. size_t ret = std::fwrite(ptr, len, 1, fp);
  973. if (ret != 1) {
  974. throw std::runtime_error(format("write error: %s", strerror(errno)));
  975. }
  976. }
  977. void write_u32(std::uint32_t val) const {
  978. write_raw(&val, sizeof(val));
  979. }
  980. ~llama_file() {
  981. if (fp) {
  982. std::fclose(fp);
  983. }
  984. }
  985. };
  986. struct llama_mmap {
  987. void * addr;
  988. size_t size;
  989. llama_mmap(const llama_mmap &) = delete;
  990. #ifdef _POSIX_MAPPED_FILES
  991. static constexpr bool SUPPORTED = true;
  992. // list of mapped fragments (first_offset, last_offset)
  993. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  994. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  995. size = file->size;
  996. int fd = fileno(file->fp);
  997. int flags = MAP_SHARED;
  998. // prefetch/readahead impairs performance on NUMA systems
  999. if (numa) { prefetch = 0; }
  1000. #ifdef __linux__
  1001. // advise the kernel to read the file sequentially (increases readahead)
  1002. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1003. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1004. strerror(errno));
  1005. }
  1006. if (prefetch) { flags |= MAP_POPULATE; }
  1007. #endif
  1008. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1009. if (addr == MAP_FAILED) { // NOLINT
  1010. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1011. }
  1012. if (prefetch > 0) {
  1013. // advise the kernel to preload the mapped memory
  1014. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1015. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1016. strerror(errno));
  1017. }
  1018. }
  1019. if (numa) {
  1020. // advise the kernel not to use readahead
  1021. // (because the next page might not belong on the same node)
  1022. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1023. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1024. strerror(errno));
  1025. }
  1026. }
  1027. // initialize list of mapped_fragments
  1028. mapped_fragments.emplace_back(0, file->size);
  1029. }
  1030. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1031. // align first to the next page
  1032. size_t offset_in_page = *first & (page_size - 1);
  1033. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1034. *first += offset_to_page;
  1035. // align last to the previous page
  1036. *last = *last & ~(page_size - 1);
  1037. if (*last <= *first) {
  1038. *last = *first;
  1039. }
  1040. }
  1041. // partially unmap the file in the range [first, last)
  1042. void unmap_fragment(size_t first, size_t last) {
  1043. // note: this function must not be called multiple times with overlapping ranges
  1044. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1045. int page_size = sysconf(_SC_PAGESIZE);
  1046. align_range(&first, &last, page_size);
  1047. size_t len = last - first;
  1048. if (len == 0) {
  1049. return;
  1050. }
  1051. GGML_ASSERT(first % page_size == 0);
  1052. GGML_ASSERT(last % page_size == 0);
  1053. GGML_ASSERT(last > first);
  1054. void * next_page_start = (uint8_t *) addr + first;
  1055. // unmap the range
  1056. if (munmap(next_page_start, len)) {
  1057. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1058. }
  1059. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1060. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1061. for (const auto & frag : mapped_fragments) {
  1062. if (frag.first < first && frag.second > last) {
  1063. // the range is in the middle of the fragment, split it
  1064. new_mapped_fragments.emplace_back(frag.first, first);
  1065. new_mapped_fragments.emplace_back(last, frag.second);
  1066. } else if (frag.first < first && frag.second > first) {
  1067. // the range starts in the middle of the fragment
  1068. new_mapped_fragments.emplace_back(frag.first, first);
  1069. } else if (frag.first < last && frag.second > last) {
  1070. // the range ends in the middle of the fragment
  1071. new_mapped_fragments.emplace_back(last, frag.second);
  1072. } else if (frag.first >= first && frag.second <= last) {
  1073. // the range covers the entire fragment
  1074. } else {
  1075. // the range is outside the fragment
  1076. new_mapped_fragments.push_back(frag);
  1077. }
  1078. }
  1079. mapped_fragments = std::move(new_mapped_fragments);
  1080. }
  1081. ~llama_mmap() {
  1082. for (const auto & frag : mapped_fragments) {
  1083. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1084. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1085. }
  1086. }
  1087. }
  1088. #elif defined(_WIN32)
  1089. static constexpr bool SUPPORTED = true;
  1090. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1091. GGML_UNUSED(numa);
  1092. size = file->size;
  1093. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1094. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1095. if (hMapping == NULL) {
  1096. DWORD error = GetLastError();
  1097. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1098. }
  1099. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1100. DWORD error = GetLastError();
  1101. CloseHandle(hMapping);
  1102. if (addr == NULL) {
  1103. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1104. }
  1105. if (prefetch > 0) {
  1106. #if _WIN32_WINNT >= 0x602
  1107. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1108. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1109. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1110. // may fail on pre-Windows 8 systems
  1111. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1112. if (pPrefetchVirtualMemory) {
  1113. // advise the kernel to preload the mapped memory
  1114. WIN32_MEMORY_RANGE_ENTRY range;
  1115. range.VirtualAddress = addr;
  1116. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1117. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1118. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1119. llama_format_win_err(GetLastError()).c_str());
  1120. }
  1121. }
  1122. #else
  1123. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1124. #endif
  1125. }
  1126. }
  1127. void unmap_fragment(size_t first, size_t last) {
  1128. // not supported
  1129. GGML_UNUSED(first);
  1130. GGML_UNUSED(last);
  1131. }
  1132. ~llama_mmap() {
  1133. if (!UnmapViewOfFile(addr)) {
  1134. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1135. llama_format_win_err(GetLastError()).c_str());
  1136. }
  1137. }
  1138. #else
  1139. static constexpr bool SUPPORTED = false;
  1140. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1141. GGML_UNUSED(file);
  1142. GGML_UNUSED(prefetch);
  1143. GGML_UNUSED(numa);
  1144. throw std::runtime_error("mmap not supported");
  1145. }
  1146. void unmap_fragment(size_t first, size_t last) {
  1147. GGML_UNUSED(first);
  1148. GGML_UNUSED(last);
  1149. throw std::runtime_error("mmap not supported");
  1150. }
  1151. #endif
  1152. };
  1153. // Represents some region of memory being locked using mlock or VirtualLock;
  1154. // will automatically unlock on destruction.
  1155. struct llama_mlock {
  1156. void * addr = NULL;
  1157. size_t size = 0;
  1158. bool failed_already = false;
  1159. llama_mlock() {}
  1160. llama_mlock(const llama_mlock &) = delete;
  1161. ~llama_mlock() {
  1162. if (size) {
  1163. raw_unlock(addr, size);
  1164. }
  1165. }
  1166. void init(void * ptr) {
  1167. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1168. addr = ptr;
  1169. }
  1170. void grow_to(size_t target_size) {
  1171. GGML_ASSERT(addr);
  1172. if (failed_already) {
  1173. return;
  1174. }
  1175. size_t granularity = lock_granularity();
  1176. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1177. if (target_size > size) {
  1178. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1179. size = target_size;
  1180. } else {
  1181. failed_already = true;
  1182. }
  1183. }
  1184. }
  1185. #ifdef _POSIX_MEMLOCK_RANGE
  1186. static constexpr bool SUPPORTED = true;
  1187. static size_t lock_granularity() {
  1188. return (size_t) sysconf(_SC_PAGESIZE);
  1189. }
  1190. #ifdef __APPLE__
  1191. #define MLOCK_SUGGESTION \
  1192. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1193. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1194. #else
  1195. #define MLOCK_SUGGESTION \
  1196. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1197. #endif
  1198. bool raw_lock(const void * addr, size_t size) const {
  1199. if (!mlock(addr, size)) {
  1200. return true;
  1201. }
  1202. char* errmsg = std::strerror(errno);
  1203. bool suggest = (errno == ENOMEM);
  1204. // Check if the resource limit is fine after all
  1205. struct rlimit lock_limit;
  1206. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1207. suggest = false;
  1208. }
  1209. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1210. suggest = false;
  1211. }
  1212. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1213. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1214. return false;
  1215. }
  1216. #undef MLOCK_SUGGESTION
  1217. static void raw_unlock(void * addr, size_t size) {
  1218. if (munlock(addr, size)) {
  1219. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1220. }
  1221. }
  1222. #elif defined(_WIN32)
  1223. static constexpr bool SUPPORTED = true;
  1224. static size_t lock_granularity() {
  1225. SYSTEM_INFO si;
  1226. GetSystemInfo(&si);
  1227. return (size_t) si.dwPageSize;
  1228. }
  1229. bool raw_lock(void * ptr, size_t len) const {
  1230. for (int tries = 1; ; tries++) {
  1231. if (VirtualLock(ptr, len)) {
  1232. return true;
  1233. }
  1234. if (tries == 2) {
  1235. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1236. len, size, llama_format_win_err(GetLastError()).c_str());
  1237. return false;
  1238. }
  1239. // It failed but this was only the first try; increase the working
  1240. // set size and try again.
  1241. SIZE_T min_ws_size, max_ws_size;
  1242. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1243. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1244. llama_format_win_err(GetLastError()).c_str());
  1245. return false;
  1246. }
  1247. // Per MSDN: "The maximum number of pages that a process can lock
  1248. // is equal to the number of pages in its minimum working set minus
  1249. // a small overhead."
  1250. // Hopefully a megabyte is enough overhead:
  1251. size_t increment = len + 1048576;
  1252. // The minimum must be <= the maximum, so we need to increase both:
  1253. min_ws_size += increment;
  1254. max_ws_size += increment;
  1255. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1256. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1257. llama_format_win_err(GetLastError()).c_str());
  1258. return false;
  1259. }
  1260. }
  1261. }
  1262. static void raw_unlock(void * ptr, size_t len) {
  1263. if (!VirtualUnlock(ptr, len)) {
  1264. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1265. llama_format_win_err(GetLastError()).c_str());
  1266. }
  1267. }
  1268. #else
  1269. static constexpr bool SUPPORTED = false;
  1270. static size_t lock_granularity() {
  1271. return (size_t) 65536;
  1272. }
  1273. bool raw_lock(const void * addr, size_t len) const {
  1274. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1275. return false;
  1276. }
  1277. static void raw_unlock(const void * addr, size_t len) {}
  1278. #endif
  1279. };
  1280. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1281. std::vector<char> result(8, 0);
  1282. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1283. if (n_tokens < 0) {
  1284. result.resize(-n_tokens);
  1285. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1286. GGML_ASSERT(check == -n_tokens);
  1287. }
  1288. else {
  1289. result.resize(n_tokens);
  1290. }
  1291. return std::string(result.data(), result.size());
  1292. }
  1293. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1294. ggml_backend_buffer_type_t buft = nullptr;
  1295. #if defined(GGML_USE_CUBLAS)
  1296. // host buffers should only be used when data is expected to be copied to/from the GPU
  1297. if (host_buffer) {
  1298. buft = ggml_backend_cuda_host_buffer_type();
  1299. }
  1300. #elif defined(GGML_USE_SYCL)
  1301. buft = ggml_backend_sycl_host_buffer_type();
  1302. #elif defined(GGML_USE_CPU_HBM)
  1303. buft = ggml_backend_cpu_hbm_buffer_type();
  1304. #elif defined(GGML_USE_VULKAN)
  1305. if (host_buffer) {
  1306. buft = ggml_backend_vk_host_buffer_type();
  1307. }
  1308. #endif
  1309. if (buft == nullptr) {
  1310. buft = ggml_backend_cpu_buffer_type();
  1311. }
  1312. return buft;
  1313. GGML_UNUSED(host_buffer);
  1314. }
  1315. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1316. ggml_backend_buffer_type_t buft = nullptr;
  1317. #ifdef GGML_USE_METAL
  1318. buft = ggml_backend_metal_buffer_type();
  1319. #elif defined(GGML_USE_CUBLAS)
  1320. buft = ggml_backend_cuda_buffer_type(gpu);
  1321. #elif defined(GGML_USE_VULKAN)
  1322. buft = ggml_backend_vk_buffer_type(gpu);
  1323. #elif defined(GGML_USE_SYCL)
  1324. buft = ggml_backend_sycl_buffer_type(gpu);
  1325. #elif defined(GGML_USE_CLBLAST)
  1326. buft = ggml_backend_opencl_buffer_type();
  1327. #elif defined(GGML_USE_KOMPUTE)
  1328. buft = ggml_backend_kompute_buffer_type(gpu);
  1329. if (buft == nullptr) {
  1330. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1331. }
  1332. #endif
  1333. if (buft == nullptr) {
  1334. buft = llama_default_buffer_type_cpu(true);
  1335. }
  1336. return buft;
  1337. GGML_UNUSED(gpu);
  1338. }
  1339. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1340. ggml_backend_buffer_type_t buft = nullptr;
  1341. #ifdef GGML_USE_CUBLAS
  1342. if (ggml_backend_cuda_get_device_count() > 1) {
  1343. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1344. }
  1345. #endif
  1346. if (buft == nullptr) {
  1347. buft = llama_default_buffer_type_offload(fallback_gpu);
  1348. }
  1349. return buft;
  1350. GGML_UNUSED(tensor_split);
  1351. }
  1352. static size_t llama_get_device_count() {
  1353. #if defined(GGML_USE_CUBLAS)
  1354. return ggml_backend_cuda_get_device_count();
  1355. #elif defined(GGML_USE_VULKAN)
  1356. return ggml_backend_vk_get_device_count();
  1357. #else
  1358. return 1;
  1359. #endif
  1360. }
  1361. static size_t llama_get_device_memory(int device) {
  1362. #if defined(GGML_USE_CUBLAS)
  1363. size_t total;
  1364. size_t free;
  1365. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1366. return free;
  1367. #elif defined(GGML_USE_VULKAN)
  1368. size_t total;
  1369. size_t free;
  1370. ggml_backend_vk_get_device_memory(device, &total, &free);
  1371. return free;
  1372. #else
  1373. return 1;
  1374. GGML_UNUSED(device);
  1375. #endif
  1376. }
  1377. //
  1378. // globals
  1379. //
  1380. struct llama_state {
  1381. llama_state() {
  1382. #ifdef GGML_USE_METAL
  1383. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1384. #endif
  1385. }
  1386. // We save the log callback globally
  1387. ggml_log_callback log_callback = llama_log_callback_default;
  1388. void * log_callback_user_data = nullptr;
  1389. };
  1390. static llama_state g_state;
  1391. // available llama models
  1392. enum e_model {
  1393. MODEL_UNKNOWN,
  1394. MODEL_17M,
  1395. MODEL_22M,
  1396. MODEL_33M,
  1397. MODEL_109M,
  1398. MODEL_137M,
  1399. MODEL_335M,
  1400. MODEL_0_5B,
  1401. MODEL_1B,
  1402. MODEL_2B,
  1403. MODEL_3B,
  1404. MODEL_4B,
  1405. MODEL_7B,
  1406. MODEL_8B,
  1407. MODEL_13B,
  1408. MODEL_14B,
  1409. MODEL_15B,
  1410. MODEL_20B,
  1411. MODEL_30B,
  1412. MODEL_34B,
  1413. MODEL_40B,
  1414. MODEL_65B,
  1415. MODEL_70B,
  1416. MODEL_SMALL,
  1417. MODEL_MEDIUM,
  1418. MODEL_LARGE,
  1419. MODEL_XL,
  1420. };
  1421. static const size_t kiB = 1024;
  1422. static const size_t MiB = 1024*kiB;
  1423. static const size_t GiB = 1024*MiB;
  1424. struct llama_hparams {
  1425. bool vocab_only;
  1426. bool rope_finetuned;
  1427. uint32_t n_vocab;
  1428. uint32_t n_ctx_train; // context size the model was trained on
  1429. uint32_t n_embd;
  1430. uint32_t n_head;
  1431. uint32_t n_head_kv;
  1432. uint32_t n_layer;
  1433. uint32_t n_rot;
  1434. 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
  1435. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1436. uint32_t n_ff;
  1437. uint32_t n_expert = 0;
  1438. uint32_t n_expert_used = 0;
  1439. uint32_t n_vocab_type = 0; // for BERT-style token types
  1440. float f_norm_eps;
  1441. float f_norm_rms_eps;
  1442. float rope_freq_base_train;
  1443. float rope_freq_scale_train;
  1444. uint32_t n_yarn_orig_ctx;
  1445. int32_t rope_scaling_type_train;
  1446. float f_clamp_kqv = 0.0f;
  1447. float f_max_alibi_bias = 0.0f;
  1448. bool causal_attn = true;
  1449. bool need_kq_pos = false;
  1450. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1451. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1452. bool operator!=(const llama_hparams & other) const {
  1453. if (this->vocab_only != other.vocab_only) return true;
  1454. if (this->n_vocab != other.n_vocab) return true;
  1455. if (this->n_ctx_train != other.n_ctx_train) return true;
  1456. if (this->n_embd != other.n_embd) return true;
  1457. if (this->n_head != other.n_head) return true;
  1458. if (this->n_head_kv != other.n_head_kv) return true;
  1459. if (this->n_layer != other.n_layer) return true;
  1460. if (this->n_rot != other.n_rot) return true;
  1461. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1462. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1463. if (this->n_ff != other.n_ff) return true;
  1464. if (this->n_expert != other.n_expert) return true;
  1465. if (this->n_expert_used != other.n_expert_used) return true;
  1466. if (this->rope_finetuned != other.rope_finetuned) return true;
  1467. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1468. const float EPSILON = 1e-9f;
  1469. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1470. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1471. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1472. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1473. return false;
  1474. }
  1475. uint32_t n_gqa() const {
  1476. return n_head/n_head_kv;
  1477. }
  1478. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1479. return n_embd_head_k * n_head_kv;
  1480. }
  1481. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1482. return n_embd_head_v * n_head_kv;
  1483. }
  1484. };
  1485. struct llama_cparams {
  1486. uint32_t n_ctx; // context size used during inference
  1487. uint32_t n_batch;
  1488. uint32_t n_threads; // number of threads to use for generation
  1489. uint32_t n_threads_batch; // number of threads to use for batch processing
  1490. float rope_freq_base;
  1491. float rope_freq_scale;
  1492. uint32_t n_yarn_orig_ctx;
  1493. // These hyperparameters are not exposed in GGUF, because all
  1494. // existing YaRN models use the same values for them.
  1495. float yarn_ext_factor;
  1496. float yarn_attn_factor;
  1497. float yarn_beta_fast;
  1498. float yarn_beta_slow;
  1499. float defrag_thold;
  1500. bool offload_kqv;
  1501. bool do_pooling;
  1502. ggml_backend_sched_eval_callback cb_eval;
  1503. void * cb_eval_user_data;
  1504. };
  1505. struct llama_layer {
  1506. // normalization
  1507. struct ggml_tensor * attn_norm;
  1508. struct ggml_tensor * attn_norm_b;
  1509. struct ggml_tensor * attn_norm_2;
  1510. struct ggml_tensor * attn_norm_2_b;
  1511. struct ggml_tensor * attn_q_norm;
  1512. struct ggml_tensor * attn_q_norm_b;
  1513. struct ggml_tensor * attn_k_norm;
  1514. struct ggml_tensor * attn_k_norm_b;
  1515. struct ggml_tensor * attn_out_norm;
  1516. struct ggml_tensor * attn_out_norm_b;
  1517. // attention
  1518. struct ggml_tensor * wq;
  1519. struct ggml_tensor * wk;
  1520. struct ggml_tensor * wv;
  1521. struct ggml_tensor * wo;
  1522. struct ggml_tensor * wqkv;
  1523. // attention bias
  1524. struct ggml_tensor * bq;
  1525. struct ggml_tensor * bk;
  1526. struct ggml_tensor * bv;
  1527. struct ggml_tensor * bo;
  1528. struct ggml_tensor * bqkv;
  1529. // normalization
  1530. struct ggml_tensor * ffn_norm;
  1531. struct ggml_tensor * ffn_norm_b;
  1532. struct ggml_tensor * layer_out_norm;
  1533. struct ggml_tensor * layer_out_norm_b;
  1534. // ff
  1535. struct ggml_tensor * ffn_gate; // w1
  1536. struct ggml_tensor * ffn_down; // w2
  1537. struct ggml_tensor * ffn_up; // w3
  1538. // ff MoE
  1539. struct ggml_tensor * ffn_gate_inp;
  1540. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1541. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1542. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1543. // ff bias
  1544. struct ggml_tensor * ffn_down_b; // b2
  1545. struct ggml_tensor * ffn_up_b; // b3
  1546. struct ggml_tensor * ffn_act;
  1547. };
  1548. struct llama_kv_cell {
  1549. llama_pos pos = -1;
  1550. llama_pos delta = 0;
  1551. std::set<llama_seq_id> seq_id;
  1552. bool has_seq_id(const llama_seq_id & id) const {
  1553. return seq_id.find(id) != seq_id.end();
  1554. }
  1555. bool is_empty() const {
  1556. return seq_id.empty();
  1557. }
  1558. bool is_same_seq(const llama_kv_cell & other) const {
  1559. return seq_id == other.seq_id;
  1560. }
  1561. };
  1562. // ring-buffer of cached KV data
  1563. struct llama_kv_cache {
  1564. bool has_shift = false;
  1565. bool do_defrag = false;
  1566. // Note: The value of head isn't only used to optimize searching
  1567. // for a free KV slot. llama_decode_internal also uses it, so it
  1568. // cannot be freely changed after a slot has been allocated.
  1569. uint32_t head = 0;
  1570. uint32_t size = 0;
  1571. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1572. // computed before each graph build
  1573. uint32_t n = 0;
  1574. ggml_type type_k = GGML_TYPE_F16;
  1575. ggml_type type_v = GGML_TYPE_F16;
  1576. std::vector<llama_kv_cell> cells;
  1577. std::vector<struct ggml_tensor *> k_l; // per layer
  1578. std::vector<struct ggml_tensor *> v_l;
  1579. std::vector<struct ggml_context *> ctxs;
  1580. std::vector<ggml_backend_buffer_t> bufs;
  1581. size_t total_size() const {
  1582. size_t size = 0;
  1583. for (ggml_backend_buffer_t buf : bufs) {
  1584. size += ggml_backend_buffer_get_size(buf);
  1585. }
  1586. return size;
  1587. }
  1588. ~llama_kv_cache() {
  1589. for (struct ggml_context * ctx : ctxs) {
  1590. ggml_free(ctx);
  1591. }
  1592. for (ggml_backend_buffer_t buf : bufs) {
  1593. ggml_backend_buffer_free(buf);
  1594. }
  1595. }
  1596. };
  1597. struct llama_vocab {
  1598. using id = int32_t;
  1599. using token = std::string;
  1600. using ttype = llama_token_type;
  1601. struct token_data {
  1602. token text;
  1603. float score;
  1604. ttype type;
  1605. };
  1606. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1607. std::unordered_map<token, id> token_to_id;
  1608. std::vector<token_data> id_to_token;
  1609. std::unordered_map<token, id> special_tokens_cache;
  1610. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1611. // default LLaMA special tokens
  1612. id special_bos_id = 1;
  1613. id special_eos_id = 2;
  1614. id special_unk_id = 0;
  1615. id special_sep_id = -1;
  1616. id special_pad_id = -1;
  1617. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1618. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1619. id linefeed_id = 13;
  1620. id special_prefix_id = 32007;
  1621. id special_middle_id = 32009;
  1622. id special_suffix_id = 32008;
  1623. id special_eot_id = 32010;
  1624. bool add_space_prefix = true;
  1625. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1626. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1627. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1628. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1629. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1630. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1631. if (it == bpe_ranks.end()) {
  1632. return -1;
  1633. }
  1634. return it->second;
  1635. }
  1636. };
  1637. struct llama_model {
  1638. e_model type = MODEL_UNKNOWN;
  1639. llm_arch arch = LLM_ARCH_UNKNOWN;
  1640. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1641. std::string name = "n/a";
  1642. llama_hparams hparams = {};
  1643. llama_vocab vocab;
  1644. struct ggml_tensor * tok_embd;
  1645. struct ggml_tensor * type_embd;
  1646. struct ggml_tensor * pos_embd;
  1647. struct ggml_tensor * tok_norm;
  1648. struct ggml_tensor * tok_norm_b;
  1649. struct ggml_tensor * output_norm;
  1650. struct ggml_tensor * output_norm_b;
  1651. struct ggml_tensor * output;
  1652. struct ggml_tensor * output_b;
  1653. std::vector<llama_layer> layers;
  1654. llama_split_mode split_mode;
  1655. int main_gpu;
  1656. int n_gpu_layers;
  1657. // gguf metadata
  1658. std::unordered_map<std::string, std::string> gguf_kv;
  1659. // layer -> buffer type mapping
  1660. struct layer_buft {
  1661. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1662. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1663. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1664. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1665. ggml_backend_buffer_type_t buft; // everything else
  1666. };
  1667. layer_buft buft_input;
  1668. layer_buft buft_output;
  1669. std::vector<layer_buft> buft_layer;
  1670. // contexts where the model tensors metadata is stored
  1671. std::vector<struct ggml_context *> ctxs;
  1672. // the model memory buffers for the tensor data
  1673. std::vector<ggml_backend_buffer_t> bufs;
  1674. // model memory mapped file
  1675. std::unique_ptr<llama_mmap> mapping;
  1676. // objects representing data potentially being locked in memory
  1677. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1678. llama_mlock mlock_mmap;
  1679. // for quantize-stats only
  1680. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1681. int64_t t_load_us = 0;
  1682. int64_t t_start_us = 0;
  1683. ~llama_model() {
  1684. for (struct ggml_context * ctx : ctxs) {
  1685. ggml_free(ctx);
  1686. }
  1687. for (ggml_backend_buffer_t buf : bufs) {
  1688. ggml_backend_buffer_free(buf);
  1689. }
  1690. }
  1691. };
  1692. struct llama_context {
  1693. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1694. ~llama_context() {
  1695. ggml_backend_sched_free(sched);
  1696. for (ggml_backend_t backend : backends) {
  1697. ggml_backend_free(backend);
  1698. }
  1699. #ifdef GGML_USE_VULKAN
  1700. ggml_vk_free_cpu_assist();
  1701. #endif
  1702. ggml_backend_buffer_free(buf_input);
  1703. ggml_free(ctx_input);
  1704. }
  1705. llama_cparams cparams;
  1706. std::vector<ggml_backend_t> backends;
  1707. #ifdef GGML_USE_METAL
  1708. ggml_backend_t backend_metal = nullptr;
  1709. #endif
  1710. ggml_backend_t backend_cpu = nullptr;
  1711. const llama_model & model;
  1712. // key + value cache for the self attention
  1713. struct llama_kv_cache kv_self;
  1714. std::mt19937 rng;
  1715. bool has_evaluated_once = false;
  1716. int64_t t_start_us;
  1717. int64_t t_load_us;
  1718. int64_t t_sample_us = 0;
  1719. int64_t t_p_eval_us = 0;
  1720. int64_t t_eval_us = 0;
  1721. int32_t n_sample = 0; // number of tokens sampled
  1722. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1723. int32_t n_eval = 0; // number of eval calls
  1724. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1725. std::vector<float> logits;
  1726. #ifndef NDEBUG
  1727. // guard against access to unset logits
  1728. std::vector<bool> logits_valid;
  1729. #endif
  1730. bool logits_all = false;
  1731. // input embedding (1-dimensional array: [n_embd])
  1732. std::vector<float> embedding;
  1733. // memory buffers used to evaluate the model
  1734. std::vector<uint8_t> buf_compute_meta;
  1735. ggml_backend_sched_t sched = nullptr;
  1736. // input tensors
  1737. ggml_backend_buffer_t buf_input = nullptr;
  1738. ggml_context * ctx_input = nullptr;
  1739. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1740. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1741. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1742. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1743. struct ggml_tensor * inp_KQ_pos; // F32 [n_ctx]
  1744. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1745. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1746. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1747. #ifdef GGML_USE_MPI
  1748. ggml_mpi_context * ctx_mpi = NULL;
  1749. #endif
  1750. };
  1751. //
  1752. // kv cache helpers
  1753. //
  1754. static bool llama_kv_cache_init(
  1755. struct llama_kv_cache & cache,
  1756. const llama_model & model,
  1757. ggml_type type_k,
  1758. ggml_type type_v,
  1759. uint32_t n_ctx,
  1760. bool offload) {
  1761. const struct llama_hparams & hparams = model.hparams;
  1762. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1763. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1764. const int64_t n_layer = hparams.n_layer;
  1765. cache.has_shift = false;
  1766. cache.head = 0;
  1767. cache.size = n_ctx;
  1768. cache.used = 0;
  1769. cache.type_k = type_k;
  1770. cache.type_v = type_v;
  1771. cache.cells.clear();
  1772. cache.cells.resize(n_ctx);
  1773. #ifdef GGML_USE_CLBLAST
  1774. offload = false;
  1775. #endif
  1776. // count used buffer types
  1777. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1778. if (offload) {
  1779. for (int64_t i = 0; i < n_layer; ++i) {
  1780. buft_layer_count[model.buft_layer[i].buft]++;
  1781. }
  1782. } else {
  1783. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1784. }
  1785. // create a context for each buffer type
  1786. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1787. for (auto & it : buft_layer_count) {
  1788. int n_layers = it.second;
  1789. struct ggml_init_params params = {
  1790. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1791. /*.mem_buffer =*/ NULL,
  1792. /*.no_alloc =*/ true,
  1793. };
  1794. ggml_context * ctx = ggml_init(params);
  1795. if (!ctx) {
  1796. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1797. return false;
  1798. }
  1799. ctx_map[it.first] = ctx;
  1800. cache.ctxs.push_back(ctx);
  1801. }
  1802. cache.k_l.reserve(n_layer);
  1803. cache.v_l.reserve(n_layer);
  1804. for (int i = 0; i < (int) n_layer; i++) {
  1805. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1806. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*n_ctx);
  1807. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*n_ctx);
  1808. ggml_format_name(k, "cache_k_l%d", i);
  1809. ggml_format_name(v, "cache_v_l%d", i);
  1810. cache.k_l.push_back(k);
  1811. cache.v_l.push_back(v);
  1812. }
  1813. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1814. for (auto it : ctx_map) {
  1815. ggml_backend_buffer_type_t buft = it.first;
  1816. ggml_context * ctx = it.second;
  1817. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1818. if (!buf) {
  1819. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1820. return false;
  1821. }
  1822. ggml_backend_buffer_clear(buf, 0);
  1823. 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);
  1824. cache.bufs.push_back(buf);
  1825. }
  1826. return true;
  1827. }
  1828. // find an empty slot of size "n_tokens" in the cache
  1829. // updates the cache head
  1830. // Note: On success, it's important that cache.head points
  1831. // to the first cell of the slot.
  1832. static bool llama_kv_cache_find_slot(
  1833. struct llama_kv_cache & cache,
  1834. const struct llama_batch & batch) {
  1835. const uint32_t n_ctx = cache.size;
  1836. const uint32_t n_tokens = batch.n_tokens;
  1837. if (n_tokens > n_ctx) {
  1838. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1839. return false;
  1840. }
  1841. uint32_t n_tested = 0;
  1842. while (true) {
  1843. if (cache.head + n_tokens > n_ctx) {
  1844. n_tested += n_ctx - cache.head;
  1845. cache.head = 0;
  1846. continue;
  1847. }
  1848. bool found = true;
  1849. for (uint32_t i = 0; i < n_tokens; i++) {
  1850. if (cache.cells[cache.head + i].pos >= 0) {
  1851. found = false;
  1852. cache.head += i + 1;
  1853. n_tested += i + 1;
  1854. break;
  1855. }
  1856. }
  1857. if (found) {
  1858. break;
  1859. }
  1860. if (n_tested >= n_ctx) {
  1861. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1862. return false;
  1863. }
  1864. }
  1865. for (uint32_t i = 0; i < n_tokens; i++) {
  1866. cache.cells[cache.head + i].pos = batch.pos[i];
  1867. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1868. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1869. }
  1870. }
  1871. cache.used += n_tokens;
  1872. return true;
  1873. }
  1874. // find how many cells are currently in use
  1875. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1876. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1877. if (cache.cells[i].pos >= 0 && !cache.cells[i].is_empty()) {
  1878. return i + 1;
  1879. }
  1880. }
  1881. return 0;
  1882. }
  1883. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1884. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1885. cache.cells[i].pos = -1;
  1886. cache.cells[i].seq_id.clear();
  1887. }
  1888. cache.head = 0;
  1889. cache.used = 0;
  1890. }
  1891. static void llama_kv_cache_seq_rm(
  1892. struct llama_kv_cache & cache,
  1893. llama_seq_id seq_id,
  1894. llama_pos p0,
  1895. llama_pos p1) {
  1896. uint32_t new_head = cache.size;
  1897. if (p0 < 0) p0 = 0;
  1898. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1899. for (uint32_t i = 0; i < cache.size; ++i) {
  1900. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1901. if (seq_id < 0) {
  1902. cache.cells[i].seq_id.clear();
  1903. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1904. cache.cells[i].seq_id.erase(seq_id);
  1905. } else {
  1906. continue;
  1907. }
  1908. if (cache.cells[i].is_empty()) {
  1909. // keep count of the number of used cells
  1910. if (cache.cells[i].pos >= 0) cache.used--;
  1911. cache.cells[i].pos = -1;
  1912. if (new_head == cache.size) new_head = i;
  1913. }
  1914. }
  1915. }
  1916. // If we freed up a slot, set head to it so searching can start there.
  1917. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1918. }
  1919. static void llama_kv_cache_seq_cp(
  1920. struct llama_kv_cache & cache,
  1921. llama_seq_id seq_id_src,
  1922. llama_seq_id seq_id_dst,
  1923. llama_pos p0,
  1924. llama_pos p1) {
  1925. if (p0 < 0) p0 = 0;
  1926. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1927. cache.head = 0;
  1928. for (uint32_t i = 0; i < cache.size; ++i) {
  1929. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1930. cache.cells[i].seq_id.insert(seq_id_dst);
  1931. }
  1932. }
  1933. }
  1934. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1935. uint32_t new_head = cache.size;
  1936. for (uint32_t i = 0; i < cache.size; ++i) {
  1937. if (!cache.cells[i].has_seq_id(seq_id)) {
  1938. if (cache.cells[i].pos >= 0) cache.used--;
  1939. cache.cells[i].pos = -1;
  1940. cache.cells[i].seq_id.clear();
  1941. if (new_head == cache.size) new_head = i;
  1942. } else {
  1943. cache.cells[i].seq_id.clear();
  1944. cache.cells[i].seq_id.insert(seq_id);
  1945. }
  1946. }
  1947. // If we freed up a slot, set head to it so searching can start there.
  1948. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1949. }
  1950. static void llama_kv_cache_seq_add(
  1951. struct llama_kv_cache & cache,
  1952. llama_seq_id seq_id,
  1953. llama_pos p0,
  1954. llama_pos p1,
  1955. llama_pos delta) {
  1956. uint32_t new_head = cache.size;
  1957. if (p0 < 0) p0 = 0;
  1958. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1959. for (uint32_t i = 0; i < cache.size; ++i) {
  1960. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1961. cache.has_shift = true;
  1962. cache.cells[i].pos += delta;
  1963. cache.cells[i].delta += delta;
  1964. if (cache.cells[i].pos < 0) {
  1965. if (!cache.cells[i].is_empty()) {
  1966. cache.used--;
  1967. }
  1968. cache.cells[i].pos = -1;
  1969. cache.cells[i].seq_id.clear();
  1970. if (new_head == cache.size) {
  1971. new_head = i;
  1972. }
  1973. }
  1974. }
  1975. }
  1976. // If we freed up a slot, set head to it so searching can start there.
  1977. // Otherwise we just start the next search from the beginning.
  1978. cache.head = new_head != cache.size ? new_head : 0;
  1979. }
  1980. static void llama_kv_cache_seq_div(
  1981. struct llama_kv_cache & cache,
  1982. llama_seq_id seq_id,
  1983. llama_pos p0,
  1984. llama_pos p1,
  1985. int d) {
  1986. if (p0 < 0) p0 = 0;
  1987. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1988. for (uint32_t i = 0; i < cache.size; ++i) {
  1989. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1990. cache.has_shift = true;
  1991. {
  1992. llama_pos p_old = cache.cells[i].pos;
  1993. cache.cells[i].pos /= d;
  1994. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1995. }
  1996. }
  1997. }
  1998. }
  1999. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2000. llama_pos result = 0;
  2001. for (uint32_t i = 0; i < cache.size; ++i) {
  2002. if (cache.cells[i].has_seq_id(seq_id)) {
  2003. result = std::max(result, cache.cells[i].pos);
  2004. }
  2005. }
  2006. return result;
  2007. }
  2008. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2009. cache.do_defrag = true;
  2010. }
  2011. //
  2012. // model loading and saving
  2013. //
  2014. enum llama_fver {
  2015. GGUF_FILE_VERSION_V1 = 1,
  2016. GGUF_FILE_VERSION_V2 = 2,
  2017. GGUF_FILE_VERSION_V3 = 3,
  2018. };
  2019. static const char * llama_file_version_name(llama_fver version) {
  2020. switch (version) {
  2021. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2022. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2023. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2024. }
  2025. return "unknown";
  2026. }
  2027. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2028. char buf[256];
  2029. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2030. for (size_t i = 1; i < ne.size(); i++) {
  2031. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2032. }
  2033. return buf;
  2034. }
  2035. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2036. char buf[256];
  2037. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2038. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2039. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2040. }
  2041. return buf;
  2042. }
  2043. namespace GGUFMeta {
  2044. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2045. struct GKV_Base_Type {
  2046. static constexpr gguf_type gt = gt_;
  2047. static T getter(const gguf_context * ctx, const int kid) {
  2048. return gfun(ctx, kid);
  2049. }
  2050. };
  2051. template<typename T> struct GKV_Base;
  2052. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2053. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2054. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2055. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2056. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2057. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2058. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2059. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2060. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2061. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2062. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2063. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2064. template<> struct GKV_Base<std::string> {
  2065. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2066. static std::string getter(const gguf_context * ctx, const int kid) {
  2067. return gguf_get_val_str(ctx, kid);
  2068. }
  2069. };
  2070. struct ArrayInfo {
  2071. const gguf_type gt;
  2072. const size_t length;
  2073. const void * data;
  2074. };
  2075. template<> struct GKV_Base<ArrayInfo> {
  2076. public:
  2077. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2078. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2079. return ArrayInfo {
  2080. gguf_get_arr_type(ctx, k),
  2081. size_t(gguf_get_arr_n(ctx, k)),
  2082. gguf_get_arr_data(ctx, k),
  2083. };
  2084. }
  2085. };
  2086. template<typename T>
  2087. class GKV : public GKV_Base<T> {
  2088. GKV() = delete;
  2089. public:
  2090. static T get_kv(const gguf_context * ctx, const int k) {
  2091. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2092. if (kt != GKV::gt) {
  2093. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2094. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2095. }
  2096. return GKV::getter(ctx, k);
  2097. }
  2098. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2099. switch (ty) {
  2100. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2101. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2102. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2103. }
  2104. return "unknown";
  2105. }
  2106. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2107. if (!ovrd) { return false; }
  2108. if (ovrd->tag == expected_type) {
  2109. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2110. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2111. switch (ovrd->tag) {
  2112. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2113. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2114. } break;
  2115. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2116. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2117. } break;
  2118. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2119. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2120. } break;
  2121. default:
  2122. // Shouldn't be possible to end up here, but just in case...
  2123. throw std::runtime_error(
  2124. format("Unsupported attempt to override %s type for metadata key %s\n",
  2125. override_type_to_str(ovrd->tag), ovrd->key));
  2126. }
  2127. return true;
  2128. }
  2129. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2130. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2131. return false;
  2132. }
  2133. template<typename OT>
  2134. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2135. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2136. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2137. target = ovrd->bool_value;
  2138. return true;
  2139. }
  2140. return false;
  2141. }
  2142. template<typename OT>
  2143. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2144. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2145. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2146. target = ovrd->int_value;
  2147. return true;
  2148. }
  2149. return false;
  2150. }
  2151. template<typename OT>
  2152. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2153. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2154. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2155. target = ovrd->float_value;
  2156. return true;
  2157. }
  2158. return false;
  2159. }
  2160. template<typename OT>
  2161. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2162. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2163. (void)target;
  2164. (void)ovrd;
  2165. if (!ovrd) { return false; }
  2166. // Currently, we should never end up here so it would be a bug if we do.
  2167. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2168. ovrd ? ovrd->key : "NULL"));
  2169. }
  2170. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2171. if (try_override<T>(target, ovrd)) {
  2172. return true;
  2173. }
  2174. if (k < 0) { return false; }
  2175. target = get_kv(ctx, k);
  2176. return true;
  2177. }
  2178. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2179. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2180. }
  2181. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2182. return set(ctx, key.c_str(), target, ovrd);
  2183. }
  2184. };
  2185. }
  2186. struct llama_model_loader {
  2187. int n_kv = 0;
  2188. int n_tensors = 0;
  2189. int n_created = 0;
  2190. int64_t n_elements = 0;
  2191. size_t n_bytes = 0;
  2192. bool use_mmap = false;
  2193. llama_file file;
  2194. llama_ftype ftype;
  2195. llama_fver fver;
  2196. std::unique_ptr<llama_mmap> mapping;
  2197. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2198. struct gguf_context * ctx_gguf = NULL;
  2199. struct ggml_context * ctx_meta = NULL;
  2200. std::string arch_name;
  2201. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2202. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2203. int trace = 0;
  2204. if (getenv("LLAMA_TRACE")) {
  2205. trace = atoi(getenv("LLAMA_TRACE"));
  2206. }
  2207. struct gguf_init_params params = {
  2208. /*.no_alloc = */ true,
  2209. /*.ctx = */ &ctx_meta,
  2210. };
  2211. if (param_overrides_p != nullptr) {
  2212. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2213. kv_overrides.insert({std::string(p->key), *p});
  2214. }
  2215. }
  2216. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2217. if (!ctx_gguf) {
  2218. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2219. }
  2220. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2221. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2222. n_kv = gguf_get_n_kv(ctx_gguf);
  2223. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2224. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2225. for (int i = 0; i < n_tensors; i++) {
  2226. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2227. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2228. n_elements += ggml_nelements(t);
  2229. n_bytes += ggml_nbytes(t);
  2230. }
  2231. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2232. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2233. // determine file type based on the number of tensors for each quantization and print meta data
  2234. // TODO: make optional
  2235. {
  2236. std::map<enum ggml_type, uint32_t> n_type;
  2237. uint32_t n_type_max = 0;
  2238. enum ggml_type type_max = GGML_TYPE_F32;
  2239. for (int i = 0; i < n_tensors; i++) {
  2240. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2241. n_type[type]++;
  2242. if (n_type_max < n_type[type]) {
  2243. n_type_max = n_type[type];
  2244. type_max = type;
  2245. }
  2246. if (trace > 0) {
  2247. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2248. 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());
  2249. }
  2250. }
  2251. switch (type_max) {
  2252. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2253. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2254. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2255. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2256. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2257. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2258. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2259. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2260. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2261. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2262. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2263. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2264. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2265. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2266. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2267. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2268. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2269. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2270. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2271. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2272. default:
  2273. {
  2274. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2275. ftype = LLAMA_FTYPE_ALL_F32;
  2276. } break;
  2277. }
  2278. // this is a way to mark that we have "guessed" the file type
  2279. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2280. {
  2281. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2282. if (kid >= 0) {
  2283. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2284. }
  2285. }
  2286. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2287. for (int i = 0; i < n_kv; i++) {
  2288. const char * name = gguf_get_key(ctx_gguf, i);
  2289. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2290. const std::string type_name =
  2291. type == GGUF_TYPE_ARRAY
  2292. ? 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))
  2293. : gguf_type_name(type);
  2294. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2295. const size_t MAX_VALUE_LEN = 40;
  2296. if (value.size() > MAX_VALUE_LEN) {
  2297. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2298. }
  2299. replace_all(value, "\n", "\\n");
  2300. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2301. }
  2302. // print type counts
  2303. for (auto & kv : n_type) {
  2304. if (kv.second == 0) {
  2305. continue;
  2306. }
  2307. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2308. }
  2309. }
  2310. if (!llama_mmap::SUPPORTED) {
  2311. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2312. use_mmap = false;
  2313. }
  2314. this->use_mmap = use_mmap;
  2315. }
  2316. ~llama_model_loader() {
  2317. if (ctx_gguf) {
  2318. gguf_free(ctx_gguf);
  2319. }
  2320. if (ctx_meta) {
  2321. ggml_free(ctx_meta);
  2322. }
  2323. }
  2324. template<typename T>
  2325. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2326. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2327. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2328. if (kid < 0) {
  2329. if (required) {
  2330. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2331. }
  2332. return false;
  2333. }
  2334. struct GGUFMeta::ArrayInfo arr_info =
  2335. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2336. result = arr_info.length;
  2337. return true;
  2338. }
  2339. template<typename T>
  2340. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2341. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2342. return get_arr_n(llm_kv(kid), result, required);
  2343. }
  2344. template<typename T>
  2345. bool get_key(const std::string & key, T & result, const bool required = true) {
  2346. auto it = kv_overrides.find(key);
  2347. const struct llama_model_kv_override * override =
  2348. it != kv_overrides.end() ? &it->second : nullptr;
  2349. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2350. if (required && !found) {
  2351. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2352. }
  2353. return found;
  2354. }
  2355. template<typename T>
  2356. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2357. return get_key(llm_kv(kid), result, required);
  2358. }
  2359. std::string get_arch_name() const {
  2360. return arch_name;
  2361. }
  2362. enum llm_arch get_arch() const {
  2363. return llm_kv.arch;
  2364. }
  2365. const char * get_tensor_name(int i) const {
  2366. return gguf_get_tensor_name(ctx_gguf, i);
  2367. }
  2368. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2369. return ggml_get_tensor(ctx_meta, name);
  2370. }
  2371. struct ggml_tensor * get_tensor_meta(int i) const {
  2372. return get_tensor_meta(get_tensor_name(i));
  2373. }
  2374. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2375. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2376. ggml_set_name(tensor, ggml_get_name(meta));
  2377. n_created++;
  2378. return tensor;
  2379. }
  2380. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2381. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2382. if (cur == NULL) {
  2383. if (!required) {
  2384. return NULL;
  2385. }
  2386. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2387. }
  2388. {
  2389. bool is_ok = true;
  2390. for (size_t i = 0; i < ne.size(); ++i) {
  2391. if (ne[i] != cur->ne[i]) {
  2392. is_ok = false;
  2393. break;
  2394. }
  2395. }
  2396. if (!is_ok) {
  2397. throw std::runtime_error(
  2398. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2399. __func__, name.c_str(),
  2400. llama_format_tensor_shape(ne).c_str(),
  2401. llama_format_tensor_shape(cur).c_str()));
  2402. }
  2403. }
  2404. return create_tensor_for(ctx, cur);
  2405. }
  2406. void done_getting_tensors() const {
  2407. if (n_created != n_tensors) {
  2408. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2409. }
  2410. }
  2411. size_t file_offset(const char * name) const {
  2412. const int idx = gguf_find_tensor(ctx_gguf, name);
  2413. if (idx < 0) {
  2414. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2415. }
  2416. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2417. }
  2418. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2419. // prefetch the whole file - all the data is needed anyway
  2420. if (use_mmap) {
  2421. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2422. }
  2423. // compute the total size of all tensors for progress reporting
  2424. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2425. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2426. size_data += ggml_nbytes(cur);
  2427. }
  2428. if (use_mmap && mapping) {
  2429. if (lmlock) {
  2430. lmlock->init(mapping->addr);
  2431. }
  2432. mmap_used_first = mapping->size;
  2433. }
  2434. }
  2435. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2436. GGML_ASSERT(mapping);
  2437. *first = mapping->size;
  2438. *last = 0;
  2439. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2440. const size_t offs = file_offset(ggml_get_name(tensor));
  2441. *first = std::min(*first, offs);
  2442. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2443. }
  2444. }
  2445. // for backwards compatibility, does not support ggml-backend
  2446. void load_data_for(struct ggml_tensor * cur) const {
  2447. const size_t offs = file_offset(ggml_get_name(cur));
  2448. if (use_mmap && mapping) {
  2449. if (cur->data == nullptr) {
  2450. cur->data = (uint8_t *)mapping->addr + offs;
  2451. } else {
  2452. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2453. }
  2454. } else {
  2455. GGML_ASSERT(cur->data != nullptr);
  2456. file.seek(offs, SEEK_SET);
  2457. file.read_raw(cur->data, ggml_nbytes(cur));
  2458. }
  2459. }
  2460. size_t size_done = 0;
  2461. size_t size_data = 0;
  2462. size_t mmap_used_first = -1;
  2463. size_t mmap_used_last = 0;
  2464. // Returns false if cancelled by progress_callback
  2465. 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) {
  2466. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2467. std::vector<no_init<uint8_t>> read_buf;
  2468. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2469. if (progress_callback) {
  2470. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2471. return false;
  2472. }
  2473. }
  2474. const size_t offs = file_offset(ggml_get_name(cur));
  2475. if (use_mmap && mapping) {
  2476. if (buf_mmap && cur->data == nullptr) {
  2477. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2478. if (lmlock) {
  2479. lmlock->grow_to(offs + ggml_nbytes(cur));
  2480. }
  2481. mmap_used_first = std::min(mmap_used_first, offs);
  2482. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2483. } else {
  2484. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2485. }
  2486. } else {
  2487. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2488. file.seek(offs, SEEK_SET);
  2489. file.read_raw(cur->data, ggml_nbytes(cur));
  2490. } else {
  2491. read_buf.resize(ggml_nbytes(cur));
  2492. file.seek(offs, SEEK_SET);
  2493. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2494. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2495. }
  2496. }
  2497. size_done += ggml_nbytes(cur);
  2498. }
  2499. // check if this is the last call and do final cleanup
  2500. if (size_done >= size_data) {
  2501. // unmap offloaded tensors and metadata
  2502. if (use_mmap && mapping) {
  2503. mapping->unmap_fragment(0, mmap_used_first);
  2504. if (mmap_used_last != 0) {
  2505. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2506. }
  2507. }
  2508. if (progress_callback) {
  2509. // Even though the model is done loading, we still honor
  2510. // cancellation since we need to free allocations.
  2511. return progress_callback(1.0f, progress_callback_user_data);
  2512. }
  2513. }
  2514. return true;
  2515. }
  2516. };
  2517. template<>
  2518. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2519. uint32_t tmp;
  2520. const bool found = get_key(kid, tmp, required);
  2521. result = (enum llama_pooling_type) tmp;
  2522. return found;
  2523. }
  2524. //
  2525. // load LLaMA models
  2526. //
  2527. static const char * llama_model_arch_name(llm_arch arch) {
  2528. auto it = LLM_ARCH_NAMES.find(arch);
  2529. if (it == LLM_ARCH_NAMES.end()) {
  2530. return "unknown";
  2531. }
  2532. return it->second;
  2533. }
  2534. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2535. if (ftype & LLAMA_FTYPE_GUESSED) {
  2536. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2537. }
  2538. switch (ftype) {
  2539. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2540. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2541. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2542. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2543. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2544. return "Q4_1, some F16";
  2545. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2546. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2547. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2548. // K-quants
  2549. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2550. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2551. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2552. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2553. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2554. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2555. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2556. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2557. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2558. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2559. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2560. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2561. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2562. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2563. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2564. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2565. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2566. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2567. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2568. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2569. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2570. default: return "unknown, may not work";
  2571. }
  2572. }
  2573. static const char * llama_model_type_name(e_model type) {
  2574. switch (type) {
  2575. case MODEL_22M: return "22M";
  2576. case MODEL_33M: return "33M";
  2577. case MODEL_109M: return "109M";
  2578. case MODEL_137M: return "137M";
  2579. case MODEL_0_5B: return "0.5B";
  2580. case MODEL_1B: return "1B";
  2581. case MODEL_2B: return "2B";
  2582. case MODEL_3B: return "3B";
  2583. case MODEL_7B: return "7B";
  2584. case MODEL_8B: return "8B";
  2585. case MODEL_13B: return "13B";
  2586. case MODEL_14B: return "14B";
  2587. case MODEL_15B: return "15B";
  2588. case MODEL_20B: return "20B";
  2589. case MODEL_30B: return "30B";
  2590. case MODEL_34B: return "34B";
  2591. case MODEL_40B: return "40B";
  2592. case MODEL_65B: return "65B";
  2593. case MODEL_70B: return "70B";
  2594. case MODEL_SMALL: return "0.1B";
  2595. case MODEL_MEDIUM: return "0.4B";
  2596. case MODEL_LARGE: return "0.8B";
  2597. case MODEL_XL: return "1.5B";
  2598. default: return "?B";
  2599. }
  2600. }
  2601. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2602. switch (type) {
  2603. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2604. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2605. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2606. default: return "unknown";
  2607. }
  2608. }
  2609. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2610. model.arch = ml.get_arch();
  2611. if (model.arch == LLM_ARCH_UNKNOWN) {
  2612. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2613. }
  2614. }
  2615. static void llm_load_hparams(
  2616. llama_model_loader & ml,
  2617. llama_model & model) {
  2618. auto & hparams = model.hparams;
  2619. const gguf_context * ctx = ml.ctx_gguf;
  2620. // get metadata as string
  2621. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2622. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2623. if (type == GGUF_TYPE_ARRAY) {
  2624. continue;
  2625. }
  2626. const char * name = gguf_get_key(ctx, i);
  2627. const std::string value = gguf_kv_to_str(ctx, i);
  2628. model.gguf_kv.emplace(name, value);
  2629. }
  2630. // get general kv
  2631. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2632. // get hparams kv
  2633. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2634. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2635. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2636. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2637. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2638. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2639. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2640. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2641. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2642. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2643. if (hparams.n_expert > 0) {
  2644. GGML_ASSERT(hparams.n_expert_used > 0);
  2645. } else {
  2646. GGML_ASSERT(hparams.n_expert_used == 0);
  2647. }
  2648. // n_head_kv is optional, default to n_head
  2649. hparams.n_head_kv = hparams.n_head;
  2650. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2651. bool rope_finetuned = false;
  2652. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2653. hparams.rope_finetuned = rope_finetuned;
  2654. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2655. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2656. // rope_freq_base (optional)
  2657. hparams.rope_freq_base_train = 10000.0f;
  2658. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2659. std::string rope_scaling("linear");
  2660. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2661. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2662. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  2663. // rope_freq_scale (inverse of the kv) is optional
  2664. float ropescale = 0.0f;
  2665. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2666. // try the old key name
  2667. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2668. }
  2669. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2670. // sanity check for n_rot (optional)
  2671. {
  2672. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2673. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2674. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2675. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2676. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2677. }
  2678. }
  2679. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2680. // gpt-j n_rot = rotary_dim
  2681. }
  2682. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2683. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2684. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2685. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2686. // arch-specific KVs
  2687. switch (model.arch) {
  2688. case LLM_ARCH_LLAMA:
  2689. {
  2690. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2691. switch (hparams.n_layer) {
  2692. case 22: model.type = e_model::MODEL_1B; break;
  2693. case 26: model.type = e_model::MODEL_3B; break;
  2694. case 32: model.type = e_model::MODEL_7B; break;
  2695. case 40: model.type = e_model::MODEL_13B; break;
  2696. case 48: model.type = e_model::MODEL_34B; break;
  2697. case 60: model.type = e_model::MODEL_30B; break;
  2698. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2699. default: model.type = e_model::MODEL_UNKNOWN;
  2700. }
  2701. } break;
  2702. case LLM_ARCH_MINICPM:
  2703. {
  2704. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2705. switch (hparams.n_layer) {
  2706. case 40: model.type = e_model::MODEL_2B; break;
  2707. default: model.type = e_model::MODEL_UNKNOWN;
  2708. }
  2709. } break;
  2710. case LLM_ARCH_FALCON:
  2711. {
  2712. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2713. switch (hparams.n_layer) {
  2714. case 32: model.type = e_model::MODEL_7B; break;
  2715. case 60: model.type = e_model::MODEL_40B; break;
  2716. default: model.type = e_model::MODEL_UNKNOWN;
  2717. }
  2718. } break;
  2719. case LLM_ARCH_BAICHUAN:
  2720. {
  2721. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2722. switch (hparams.n_layer) {
  2723. case 32: model.type = e_model::MODEL_7B; break;
  2724. case 40: model.type = e_model::MODEL_13B; break;
  2725. default: model.type = e_model::MODEL_UNKNOWN;
  2726. }
  2727. if (model.type == e_model::MODEL_13B) {
  2728. // TODO: become GGUF KV parameter
  2729. hparams.f_max_alibi_bias = 8.0f;
  2730. }
  2731. } break;
  2732. case LLM_ARCH_STARCODER:
  2733. {
  2734. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2735. switch (hparams.n_layer) {
  2736. case 24: model.type = e_model::MODEL_1B; break;
  2737. case 36: model.type = e_model::MODEL_3B; break;
  2738. case 42: model.type = e_model::MODEL_7B; break;
  2739. case 40: model.type = e_model::MODEL_15B; break;
  2740. default: model.type = e_model::MODEL_UNKNOWN;
  2741. }
  2742. } break;
  2743. case LLM_ARCH_PERSIMMON:
  2744. {
  2745. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2746. switch (hparams.n_layer) {
  2747. case 36: model.type = e_model::MODEL_8B; break;
  2748. default: model.type = e_model::MODEL_UNKNOWN;
  2749. }
  2750. } break;
  2751. case LLM_ARCH_REFACT:
  2752. {
  2753. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2754. switch (hparams.n_layer) {
  2755. case 32: model.type = e_model::MODEL_1B; break;
  2756. default: model.type = e_model::MODEL_UNKNOWN;
  2757. }
  2758. // TODO: become GGUF KV parameter
  2759. hparams.f_max_alibi_bias = 8.0f;
  2760. } break;
  2761. case LLM_ARCH_BERT:
  2762. {
  2763. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2764. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2765. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2766. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2767. switch (hparams.n_layer) {
  2768. case 3:
  2769. model.type = e_model::MODEL_17M; break; // bge-micro
  2770. case 6:
  2771. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2772. case 12:
  2773. switch (hparams.n_embd) {
  2774. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2775. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2776. } break;
  2777. case 24:
  2778. model.type = e_model::MODEL_335M; break; // bge-large
  2779. }
  2780. } break;
  2781. case LLM_ARCH_NOMIC_BERT:
  2782. {
  2783. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2784. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2785. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2786. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2787. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  2788. model.type = e_model::MODEL_137M;
  2789. }
  2790. } break;
  2791. case LLM_ARCH_BLOOM:
  2792. {
  2793. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2794. switch (hparams.n_layer) {
  2795. case 24: model.type = e_model::MODEL_1B; break;
  2796. case 30:
  2797. switch (hparams.n_embd) {
  2798. case 2560: model.type = e_model::MODEL_3B; break;
  2799. case 4096: model.type = e_model::MODEL_7B; break;
  2800. } break;
  2801. }
  2802. // TODO: become GGUF KV parameter
  2803. hparams.f_max_alibi_bias = 8.0f;
  2804. } break;
  2805. case LLM_ARCH_MPT:
  2806. {
  2807. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2808. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2809. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2810. switch (hparams.n_layer) {
  2811. case 32: model.type = e_model::MODEL_7B; break;
  2812. case 48: model.type = e_model::MODEL_30B; break;
  2813. default: model.type = e_model::MODEL_UNKNOWN;
  2814. }
  2815. } break;
  2816. case LLM_ARCH_STABLELM:
  2817. {
  2818. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2819. switch (hparams.n_layer) {
  2820. case 24: model.type = e_model::MODEL_1B; break;
  2821. case 32: model.type = e_model::MODEL_3B; break;
  2822. default: model.type = e_model::MODEL_UNKNOWN;
  2823. }
  2824. } break;
  2825. case LLM_ARCH_QWEN:
  2826. {
  2827. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2828. switch (hparams.n_layer) {
  2829. case 32: model.type = e_model::MODEL_7B; break;
  2830. case 40: model.type = e_model::MODEL_13B; break;
  2831. default: model.type = e_model::MODEL_UNKNOWN;
  2832. }
  2833. } break;
  2834. case LLM_ARCH_QWEN2:
  2835. {
  2836. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2837. switch (hparams.n_layer) {
  2838. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2839. case 32: model.type = e_model::MODEL_7B; break;
  2840. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2841. case 80: model.type = e_model::MODEL_70B; break;
  2842. default: model.type = e_model::MODEL_UNKNOWN;
  2843. }
  2844. } break;
  2845. case LLM_ARCH_PHI2:
  2846. {
  2847. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2848. switch (hparams.n_layer) {
  2849. case 24: model.type = e_model::MODEL_1B; break;
  2850. case 32: model.type = e_model::MODEL_3B; break;
  2851. default: model.type = e_model::MODEL_UNKNOWN;
  2852. }
  2853. } break;
  2854. case LLM_ARCH_PLAMO:
  2855. {
  2856. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2857. switch (hparams.n_layer) {
  2858. case 40: model.type = e_model::MODEL_13B; break;
  2859. default: model.type = e_model::MODEL_UNKNOWN;
  2860. }
  2861. } break;
  2862. case LLM_ARCH_GPT2:
  2863. {
  2864. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2865. switch (hparams.n_layer) {
  2866. case 12: model.type = e_model::MODEL_SMALL; break;
  2867. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2868. case 36: model.type = e_model::MODEL_LARGE; break;
  2869. case 48: model.type = e_model::MODEL_XL; break;
  2870. default: model.type = e_model::MODEL_UNKNOWN;
  2871. }
  2872. } break;
  2873. case LLM_ARCH_CODESHELL:
  2874. {
  2875. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2876. switch (hparams.n_layer) {
  2877. case 42: model.type = e_model::MODEL_SMALL; break;
  2878. default: model.type = e_model::MODEL_UNKNOWN;
  2879. }
  2880. } break;
  2881. case LLM_ARCH_ORION:
  2882. {
  2883. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2884. switch (hparams.n_layer) {
  2885. case 40: model.type = e_model::MODEL_14B; break;
  2886. default: model.type = e_model::MODEL_UNKNOWN;
  2887. }
  2888. } break;
  2889. case LLM_ARCH_INTERNLM2:
  2890. {
  2891. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2892. switch (hparams.n_layer) {
  2893. case 32: model.type = e_model::MODEL_7B; break;
  2894. case 48: model.type = e_model::MODEL_20B; break;
  2895. default: model.type = e_model::MODEL_UNKNOWN;
  2896. }
  2897. } break;
  2898. case LLM_ARCH_GEMMA:
  2899. {
  2900. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2901. switch (hparams.n_layer) {
  2902. case 18: model.type = e_model::MODEL_2B; break;
  2903. case 28: model.type = e_model::MODEL_7B; break;
  2904. default: model.type = e_model::MODEL_UNKNOWN;
  2905. }
  2906. } break;
  2907. case LLM_ARCH_STARCODER2:
  2908. {
  2909. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2910. switch (hparams.n_layer) {
  2911. case 30: model.type = e_model::MODEL_3B; break;
  2912. case 32: model.type = e_model::MODEL_7B; break;
  2913. case 40: model.type = e_model::MODEL_15B; break;
  2914. default: model.type = e_model::MODEL_UNKNOWN;
  2915. }
  2916. } break;
  2917. default: (void)0;
  2918. }
  2919. model.ftype = ml.ftype;
  2920. if (hparams.f_max_alibi_bias > 0.0f) {
  2921. hparams.need_kq_pos = true;
  2922. }
  2923. hparams.rope_type = llama_rope_type(&model);
  2924. }
  2925. // TODO: This should probably be in llama.h
  2926. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2927. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2928. static void llm_load_vocab(
  2929. llama_model_loader & ml,
  2930. llama_model & model) {
  2931. auto & vocab = model.vocab;
  2932. struct gguf_context * ctx = ml.ctx_gguf;
  2933. const auto kv = LLM_KV(model.arch);
  2934. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2935. if (token_idx == -1) {
  2936. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2937. }
  2938. const float * scores = nullptr;
  2939. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2940. if (score_idx != -1) {
  2941. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2942. }
  2943. const int * toktypes = nullptr;
  2944. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2945. if (toktype_idx != -1) {
  2946. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2947. }
  2948. // determine vocab type
  2949. {
  2950. std::string tokenizer_name;
  2951. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2952. if (tokenizer_name == "llama") {
  2953. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2954. // default special tokens
  2955. vocab.special_bos_id = 1;
  2956. vocab.special_eos_id = 2;
  2957. vocab.special_unk_id = 0;
  2958. vocab.special_sep_id = -1;
  2959. vocab.special_pad_id = -1;
  2960. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2961. if (add_space_prefix_keyidx != -1) {
  2962. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2963. } // The default value of add_space_prefix is true.
  2964. } else if (tokenizer_name == "gpt2") {
  2965. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2966. // read bpe merges and populate bpe ranks
  2967. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2968. if (merges_keyidx == -1) {
  2969. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2970. }
  2971. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2972. for (int i = 0; i < n_merges; i++) {
  2973. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2974. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2975. std::string first;
  2976. std::string second;
  2977. const size_t pos = word.find(' ', 1);
  2978. if (pos != std::string::npos) {
  2979. first = word.substr(0, pos);
  2980. second = word.substr(pos + 1);
  2981. }
  2982. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2983. }
  2984. // default special tokens
  2985. vocab.special_bos_id = 11;
  2986. vocab.special_eos_id = 11;
  2987. vocab.special_unk_id = -1;
  2988. vocab.special_sep_id = -1;
  2989. vocab.special_pad_id = -1;
  2990. } else if (tokenizer_name == "bert") {
  2991. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  2992. // default special tokens
  2993. vocab.special_bos_id = 101;
  2994. vocab.special_eos_id = 102;
  2995. vocab.special_unk_id = 100;
  2996. vocab.special_sep_id = -1;
  2997. vocab.special_pad_id = -1;
  2998. vocab.add_space_prefix = false;
  2999. } else {
  3000. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3001. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3002. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3003. }
  3004. }
  3005. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3006. vocab.id_to_token.resize(n_vocab);
  3007. for (uint32_t i = 0; i < n_vocab; i++) {
  3008. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3009. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  3010. vocab.token_to_id[word] = i;
  3011. auto & token_data = vocab.id_to_token[i];
  3012. token_data.text = std::move(word);
  3013. token_data.score = scores ? scores[i] : 0.0f;
  3014. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3015. }
  3016. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3017. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3018. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3019. try {
  3020. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3021. } catch (const std::exception & e) {
  3022. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3023. vocab.linefeed_id = vocab.special_pad_id;
  3024. }
  3025. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3026. vocab.linefeed_id = vocab.special_pad_id;
  3027. } else {
  3028. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  3029. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3030. vocab.linefeed_id = ids[0];
  3031. }
  3032. // special tokens
  3033. {
  3034. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3035. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3036. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3037. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3038. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3039. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3040. };
  3041. for (const auto & it : special_token_types) {
  3042. const std::string & key = kv(std::get<0>(it));
  3043. int32_t & id = std::get<1>(it);
  3044. uint32_t new_id;
  3045. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3046. continue;
  3047. }
  3048. if (new_id >= vocab.id_to_token.size()) {
  3049. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3050. __func__, key.c_str(), new_id, id);
  3051. } else {
  3052. id = new_id;
  3053. }
  3054. }
  3055. // Handle add_bos_token and add_eos_token
  3056. {
  3057. bool temp = true;
  3058. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3059. vocab.special_add_bos = int(temp);
  3060. }
  3061. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3062. vocab.special_add_eos = int(temp);
  3063. }
  3064. }
  3065. }
  3066. // build special tokens cache
  3067. {
  3068. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3069. // and will always be correctly labeled in 'added_tokens.json' etc.
  3070. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3071. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3072. // are special tokens.
  3073. // From testing, this appears to correlate 1:1 with special tokens.
  3074. //
  3075. // Counting special tokens and verifying in only one direction
  3076. // is sufficient to detect difference in those two sets.
  3077. //
  3078. uint32_t special_tokens_count_by_type = 0;
  3079. uint32_t special_tokens_count_from_verification = 0;
  3080. bool special_tokens_definition_mismatch = false;
  3081. for (const auto & t : vocab.token_to_id) {
  3082. const auto & token = t.first;
  3083. const auto & id = t.second;
  3084. // Count all non-normal tokens in the vocab while iterating
  3085. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3086. special_tokens_count_by_type++;
  3087. }
  3088. // Skip single character tokens
  3089. if (token.length() > 1) {
  3090. bool is_tokenizable = false;
  3091. // Split token string representation in two, in all possible ways
  3092. // and check if both halves can be matched to a valid token
  3093. for (unsigned i = 1; i < token.length();) {
  3094. const auto left = token.substr(0, i);
  3095. const auto right = token.substr(i);
  3096. // check if we didnt partition in the middle of a utf sequence
  3097. auto utf = utf8_len(left.at(left.length() - 1));
  3098. if (utf == 1) {
  3099. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3100. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3101. is_tokenizable = true;
  3102. break;
  3103. }
  3104. i++;
  3105. } else {
  3106. // skip over the rest of multibyte utf sequence
  3107. i += utf - 1;
  3108. }
  3109. }
  3110. if (!is_tokenizable) {
  3111. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3112. // it's faster to re-filter them here, since there are way less candidates now
  3113. // Calculate a total "utf" length of a token string representation
  3114. size_t utf8_str_len = 0;
  3115. for (unsigned i = 0; i < token.length();) {
  3116. utf8_str_len++;
  3117. i += utf8_len(token.at(i));
  3118. }
  3119. // And skip the ones which are one character
  3120. if (utf8_str_len > 1) {
  3121. // At this point what we have left are special tokens only
  3122. vocab.special_tokens_cache[token] = id;
  3123. // Count manually found special tokens
  3124. special_tokens_count_from_verification++;
  3125. // If this manually found special token is not marked as such, flag a mismatch
  3126. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3127. special_tokens_definition_mismatch = true;
  3128. }
  3129. }
  3130. }
  3131. }
  3132. }
  3133. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3134. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3135. __func__,
  3136. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3137. special_tokens_count_by_type, vocab.id_to_token.size()
  3138. );
  3139. } else {
  3140. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3141. __func__,
  3142. special_tokens_count_from_verification, vocab.id_to_token.size()
  3143. );
  3144. }
  3145. }
  3146. }
  3147. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3148. const auto & hparams = model.hparams;
  3149. const auto & vocab = model.vocab;
  3150. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3151. // hparams
  3152. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3153. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3154. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3155. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3156. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3157. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3158. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3159. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3160. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3161. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3162. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3163. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3164. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3165. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3166. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3167. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3168. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3169. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3170. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3171. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3172. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3173. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3174. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3175. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3176. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3177. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3178. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3179. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3180. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3181. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3182. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3183. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3184. if (ml.n_elements >= 1e12) {
  3185. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3186. } else if (ml.n_elements >= 1e9) {
  3187. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3188. } else if (ml.n_elements >= 1e6) {
  3189. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3190. } else {
  3191. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3192. }
  3193. if (ml.n_bytes < GiB) {
  3194. 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);
  3195. } else {
  3196. 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);
  3197. }
  3198. // general kv
  3199. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3200. // special tokens
  3201. 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() ); }
  3202. 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() ); }
  3203. 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() ); }
  3204. 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() ); }
  3205. 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() ); }
  3206. 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() ); }
  3207. }
  3208. // Returns false if cancelled by progress_callback
  3209. static bool llm_load_tensors(
  3210. llama_model_loader & ml,
  3211. llama_model & model,
  3212. int n_gpu_layers,
  3213. enum llama_split_mode split_mode,
  3214. int main_gpu,
  3215. const float * tensor_split,
  3216. bool use_mlock,
  3217. llama_progress_callback progress_callback,
  3218. void * progress_callback_user_data) {
  3219. model.t_start_us = ggml_time_us();
  3220. auto & hparams = model.hparams;
  3221. model.split_mode = split_mode;
  3222. model.main_gpu = main_gpu;
  3223. model.n_gpu_layers = n_gpu_layers;
  3224. const int64_t n_layer = hparams.n_layer;
  3225. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3226. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3227. model.buft_input = llama_default_buffer_type_cpu(true);
  3228. model.buft_layer.resize(n_layer);
  3229. // assign cpu layers
  3230. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3231. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3232. }
  3233. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3234. // calculate the split points
  3235. int device_count = llama_get_device_count();
  3236. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3237. std::vector<float> splits(device_count);
  3238. if (all_zero) {
  3239. // default split, by free memory
  3240. for (int i = 0; i < device_count; ++i) {
  3241. splits[i] = llama_get_device_memory(i);
  3242. }
  3243. } else {
  3244. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3245. }
  3246. // sum and normalize the splits to get the split points
  3247. float split_sum = 0.0f;
  3248. for (int i = 0; i < device_count; ++i) {
  3249. split_sum += splits[i];
  3250. splits[i] = split_sum;
  3251. }
  3252. for (int i = 0; i < device_count; ++i) {
  3253. splits[i] /= split_sum;
  3254. }
  3255. // assign the repeating layers to the devices according to the splits
  3256. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3257. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3258. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3259. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3260. }
  3261. // assign the output layer
  3262. if (n_gpu_layers > n_layer) {
  3263. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3264. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3265. } else {
  3266. model.buft_output = llama_default_buffer_type_cpu(true);
  3267. }
  3268. } else {
  3269. ggml_backend_buffer_type_t split_buft;
  3270. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3271. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3272. } else {
  3273. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3274. split_buft = llama_default_buffer_type_offload(main_gpu);
  3275. }
  3276. // assign the repeating layers
  3277. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3278. model.buft_layer[i] = {
  3279. split_buft,
  3280. llama_default_buffer_type_offload(main_gpu)
  3281. };
  3282. }
  3283. // assign the output layer
  3284. if (n_gpu_layers > n_layer) {
  3285. model.buft_output = {
  3286. split_buft,
  3287. llama_default_buffer_type_offload(main_gpu)
  3288. };
  3289. } else {
  3290. model.buft_output = llama_default_buffer_type_cpu(true);
  3291. }
  3292. }
  3293. // count used buffer types
  3294. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3295. buft_layer_count[model.buft_input.buft]++;
  3296. buft_layer_count[model.buft_input.buft_matrix]++;
  3297. buft_layer_count[model.buft_output.buft]++;
  3298. buft_layer_count[model.buft_output.buft_matrix]++;
  3299. for (int64_t i = 0; i < n_layer; ++i) {
  3300. buft_layer_count[model.buft_layer[i].buft]++;
  3301. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3302. }
  3303. // create one context per buffer type
  3304. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3305. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3306. for (auto & it : buft_layer_count) {
  3307. struct ggml_init_params params = {
  3308. /*.mem_size =*/ ctx_size,
  3309. /*.mem_buffer =*/ NULL,
  3310. /*.no_alloc =*/ true,
  3311. };
  3312. ggml_context * ctx = ggml_init(params);
  3313. if (!ctx) {
  3314. throw std::runtime_error(format("failed to create context"));
  3315. }
  3316. ctx_map[it.first] = ctx;
  3317. model.ctxs.push_back(ctx);
  3318. }
  3319. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3320. // create tensors for the weights
  3321. {
  3322. const int64_t n_embd = hparams.n_embd;
  3323. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3324. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3325. const int64_t n_embd_gqa = n_embd_v_gqa;
  3326. const int64_t n_vocab = hparams.n_vocab;
  3327. const int64_t n_vocab_type = hparams.n_vocab_type;
  3328. const int64_t n_ff = hparams.n_ff;
  3329. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3330. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3331. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3332. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3333. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3334. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3335. model.layers.resize(n_layer);
  3336. const auto tn = LLM_TN(model.arch);
  3337. switch (model.arch) {
  3338. case LLM_ARCH_LLAMA:
  3339. case LLM_ARCH_REFACT:
  3340. case LLM_ARCH_MINICPM:
  3341. {
  3342. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3343. // output
  3344. {
  3345. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3346. if (model.arch != LLM_ARCH_MINICPM){
  3347. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3348. }
  3349. }
  3350. for (int i = 0; i < n_layer; ++i) {
  3351. ggml_context * ctx_layer = ctx_for_layer(i);
  3352. ggml_context * ctx_split = ctx_for_layer_split(i);
  3353. auto & layer = model.layers[i];
  3354. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3355. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3356. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3357. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3358. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3359. // optional bias tensors
  3360. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3361. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3362. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3363. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3364. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3365. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3366. if (layer.ffn_gate_inp == nullptr) {
  3367. GGML_ASSERT(hparams.n_expert == 0);
  3368. GGML_ASSERT(hparams.n_expert_used == 0);
  3369. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3370. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3371. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3372. } else {
  3373. GGML_ASSERT(hparams.n_expert > 0);
  3374. GGML_ASSERT(hparams.n_expert_used > 0);
  3375. // MoE branch
  3376. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3377. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3378. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3379. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3380. }
  3381. }
  3382. }
  3383. } break;
  3384. case LLM_ARCH_BAICHUAN:
  3385. {
  3386. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3387. {
  3388. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3389. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3390. }
  3391. for (int i = 0; i < n_layer; ++i) {
  3392. ggml_context * ctx_layer = ctx_for_layer(i);
  3393. ggml_context * ctx_split = ctx_for_layer_split(i);
  3394. auto & layer = model.layers[i];
  3395. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3396. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3397. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3398. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3399. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3400. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3401. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3402. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3403. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3404. }
  3405. } break;
  3406. case LLM_ARCH_FALCON:
  3407. {
  3408. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3409. // output
  3410. {
  3411. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3412. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3413. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3414. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3415. } else {
  3416. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3417. ml.n_created--; // artificial tensor
  3418. ml.size_data += ggml_nbytes(model.output);
  3419. }
  3420. }
  3421. for (int i = 0; i < n_layer; ++i) {
  3422. ggml_context * ctx_layer = ctx_for_layer(i);
  3423. ggml_context * ctx_split = ctx_for_layer_split(i);
  3424. auto & layer = model.layers[i];
  3425. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3426. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3427. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3428. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3429. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3430. }
  3431. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3432. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3433. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3434. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3435. }
  3436. } break;
  3437. case LLM_ARCH_STARCODER:
  3438. {
  3439. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3440. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3441. // output
  3442. {
  3443. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3444. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3445. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3446. }
  3447. for (int i = 0; i < n_layer; ++i) {
  3448. ggml_context * ctx_layer = ctx_for_layer(i);
  3449. ggml_context * ctx_split = ctx_for_layer_split(i);
  3450. auto & layer = model.layers[i];
  3451. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3452. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3453. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3454. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3455. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3456. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3457. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3458. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3459. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3460. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3461. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3462. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3463. }
  3464. } break;
  3465. case LLM_ARCH_PERSIMMON:
  3466. {
  3467. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3468. {
  3469. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3470. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3471. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3472. }
  3473. for (int i = 0; i < n_layer; ++i) {
  3474. ggml_context * ctx_layer = ctx_for_layer(i);
  3475. ggml_context * ctx_split = ctx_for_layer_split(i);
  3476. auto & layer = model.layers[i];
  3477. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3478. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3479. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3480. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3481. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3482. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3483. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3484. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3485. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3486. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3487. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3488. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3489. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3490. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3491. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3492. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3493. }
  3494. } break;
  3495. case LLM_ARCH_BERT:
  3496. case LLM_ARCH_NOMIC_BERT:
  3497. {
  3498. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3499. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3500. if (model.arch == LLM_ARCH_BERT) {
  3501. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3502. }
  3503. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3504. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3505. for (int i = 0; i < n_layer; ++i) {
  3506. ggml_context * ctx_layer = ctx_for_layer(i);
  3507. ggml_context * ctx_split = ctx_for_layer_split(i);
  3508. auto & layer = model.layers[i];
  3509. if (model.arch == LLM_ARCH_BERT) {
  3510. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3511. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3512. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3513. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3514. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3515. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3516. } else {
  3517. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3518. }
  3519. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3520. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3521. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3522. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3523. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3524. if (model.arch == LLM_ARCH_BERT) {
  3525. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3526. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3527. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3528. } else {
  3529. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3530. }
  3531. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3532. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3533. }
  3534. } break;
  3535. case LLM_ARCH_BLOOM:
  3536. {
  3537. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3538. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3539. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3540. // output
  3541. {
  3542. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3543. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3544. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3545. }
  3546. for (int i = 0; i < n_layer; ++i) {
  3547. ggml_context * ctx_layer = ctx_for_layer(i);
  3548. ggml_context * ctx_split = ctx_for_layer_split(i);
  3549. auto & layer = model.layers[i];
  3550. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3551. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3552. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3553. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3554. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3555. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3556. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3557. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3558. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3559. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3560. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3561. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3562. }
  3563. } break;
  3564. case LLM_ARCH_MPT:
  3565. {
  3566. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3567. // output
  3568. {
  3569. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3570. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  3571. // same as tok_embd, duplicated to allow offloading
  3572. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3573. ml.n_created--; // artificial tensor
  3574. ml.size_data += ggml_nbytes(model.output);
  3575. }
  3576. for (int i = 0; i < n_layer; ++i) {
  3577. ggml_context * ctx_layer = ctx_for_layer(i);
  3578. ggml_context * ctx_split = ctx_for_layer_split(i);
  3579. auto & layer = model.layers[i];
  3580. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3581. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  3582. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3583. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3584. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3585. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3586. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3587. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  3588. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3589. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  3590. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3591. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  3592. // AWQ ScaleActivation layer
  3593. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3594. }
  3595. } break;
  3596. case LLM_ARCH_STABLELM:
  3597. {
  3598. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3599. // output
  3600. {
  3601. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3602. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3603. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3604. }
  3605. for (int i = 0; i < n_layer; ++i) {
  3606. ggml_context * ctx_layer = ctx_for_layer(i);
  3607. ggml_context * ctx_split = ctx_for_layer_split(i);
  3608. auto & layer = model.layers[i];
  3609. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3610. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3611. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3612. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3613. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3614. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3615. // optional bias tensors, present in Stable LM 2 1.6B
  3616. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3617. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3618. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3619. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3620. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3621. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3622. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3623. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3624. }
  3625. } break;
  3626. case LLM_ARCH_QWEN:
  3627. {
  3628. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3629. // output
  3630. {
  3631. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3632. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3633. }
  3634. for (int i = 0; i < n_layer; ++i) {
  3635. ggml_context * ctx_layer = ctx_for_layer(i);
  3636. ggml_context * ctx_split = ctx_for_layer_split(i);
  3637. auto & layer = model.layers[i];
  3638. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3639. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3640. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3641. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3642. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3643. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3644. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3645. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3646. }
  3647. } break;
  3648. case LLM_ARCH_QWEN2:
  3649. {
  3650. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3651. // output
  3652. {
  3653. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3654. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3655. }
  3656. for (int i = 0; i < n_layer; ++i) {
  3657. ggml_context * ctx_layer = ctx_for_layer(i);
  3658. ggml_context * ctx_split = ctx_for_layer_split(i);
  3659. auto & layer = model.layers[i];
  3660. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3661. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3662. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3663. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3664. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3665. // optional bias tensors
  3666. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3667. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3668. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3669. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3670. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3671. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3672. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3673. }
  3674. } break;
  3675. case LLM_ARCH_PHI2:
  3676. {
  3677. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3678. // output
  3679. {
  3680. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3681. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3682. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3683. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3684. }
  3685. for (int i = 0; i < n_layer; ++i) {
  3686. ggml_context * ctx_layer = ctx_for_layer(i);
  3687. ggml_context * ctx_split = ctx_for_layer_split(i);
  3688. auto & layer = model.layers[i];
  3689. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3690. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3691. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3692. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3693. if (layer.wqkv == nullptr) {
  3694. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3695. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3696. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3697. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3698. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3699. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3700. }
  3701. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3702. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3703. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3704. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3705. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3706. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3707. }
  3708. } break;
  3709. case LLM_ARCH_PLAMO:
  3710. {
  3711. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3712. // output
  3713. {
  3714. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3715. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3716. }
  3717. for (int i = 0; i < n_layer; ++i) {
  3718. ggml_context * ctx_layer = ctx_for_layer(i);
  3719. ggml_context * ctx_split = ctx_for_layer_split(i);
  3720. auto & layer = model.layers[i];
  3721. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3722. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3723. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3724. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3725. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3726. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3727. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3728. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3729. }
  3730. } break;
  3731. case LLM_ARCH_GPT2:
  3732. {
  3733. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3734. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3735. // output
  3736. {
  3737. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3738. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3739. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3740. }
  3741. for (int i = 0; i < n_layer; ++i) {
  3742. ggml_context * ctx_layer = ctx_for_layer(i);
  3743. ggml_context * ctx_split = ctx_for_layer_split(i);
  3744. auto & layer = model.layers[i];
  3745. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3746. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3747. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3748. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3749. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3750. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3751. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3752. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3753. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3754. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3755. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3756. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3757. }
  3758. } break;
  3759. case LLM_ARCH_CODESHELL:
  3760. {
  3761. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3762. // output
  3763. {
  3764. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3765. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3766. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3767. }
  3768. for (int i = 0; i < n_layer; ++i) {
  3769. ggml_context * ctx_layer = ctx_for_layer(i);
  3770. ggml_context * ctx_split = ctx_for_layer_split(i);
  3771. auto & layer = model.layers[i];
  3772. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3773. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3774. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3775. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3776. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3777. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3778. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3779. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3780. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3781. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3782. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3783. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3784. }
  3785. } break;
  3786. case LLM_ARCH_ORION:
  3787. {
  3788. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3789. {
  3790. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3791. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3792. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3793. }
  3794. for (int i = 0; i < n_layer; ++i) {
  3795. ggml_context * ctx_layer = ctx_for_layer(i);
  3796. ggml_context * ctx_split = ctx_for_layer_split(i);
  3797. auto & layer = model.layers[i];
  3798. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3799. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3800. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3801. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3802. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3803. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3804. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3805. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3806. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3807. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3808. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3809. }
  3810. } break;
  3811. case LLM_ARCH_INTERNLM2:
  3812. {
  3813. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3814. // output
  3815. {
  3816. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3817. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3818. }
  3819. for (int i = 0; i < n_layer; ++i) {
  3820. ggml_context * ctx_layer = ctx_for_layer(i);
  3821. ggml_context * ctx_split = ctx_for_layer_split(i);
  3822. auto & layer = model.layers[i];
  3823. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3824. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3825. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3826. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3827. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3828. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3829. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3830. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3831. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3832. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3833. }
  3834. } break;
  3835. case LLM_ARCH_GEMMA:
  3836. {
  3837. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3838. // output
  3839. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3840. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // same as tok_embd, duplicated to allow offloading
  3841. ml.n_created--; // artificial tensor
  3842. ml.size_data += ggml_nbytes(model.output);
  3843. const int64_t n_ff = hparams.n_ff;
  3844. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3845. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3846. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3847. for (uint32_t i = 0; i < n_layer; ++i) {
  3848. ggml_context * ctx_layer = ctx_for_layer(i);
  3849. ggml_context * ctx_split = ctx_for_layer_split(i);
  3850. auto & layer = model.layers[i];
  3851. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3852. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  3853. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  3854. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  3855. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  3856. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3857. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3858. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3859. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3860. }
  3861. } break;
  3862. case LLM_ARCH_STARCODER2:
  3863. {
  3864. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3865. // output
  3866. {
  3867. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3868. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3869. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3870. // if output is NULL, init from the input tok embed
  3871. if (model.output == NULL) {
  3872. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3873. ml.n_created--; // artificial tensor
  3874. ml.size_data += ggml_nbytes(model.output);
  3875. }
  3876. }
  3877. for (int i = 0; i < n_layer; ++i) {
  3878. ggml_context * ctx_layer = ctx_for_layer(i);
  3879. ggml_context * ctx_split = ctx_for_layer_split(i);
  3880. auto & layer = model.layers[i];
  3881. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3882. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3883. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3884. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3885. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3886. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3887. // optional bias tensors
  3888. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3889. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3890. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3891. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3892. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3893. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3894. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3895. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3896. // optional bias tensors
  3897. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3898. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  3899. }
  3900. } break;
  3901. default:
  3902. throw std::runtime_error("unknown architecture");
  3903. }
  3904. }
  3905. ml.done_getting_tensors();
  3906. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3907. // create the backend buffers
  3908. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3909. for (auto & it : ctx_map) {
  3910. ggml_backend_buffer_type_t buft = it.first;
  3911. ggml_context * ctx = it.second;
  3912. ggml_backend_buffer_t buf = nullptr;
  3913. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3914. // 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
  3915. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3916. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3917. size_t first, last;
  3918. ml.get_mapping_range(&first, &last, ctx);
  3919. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3920. }
  3921. #ifdef GGML_USE_METAL
  3922. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3923. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3924. size_t first, last;
  3925. ml.get_mapping_range(&first, &last, ctx);
  3926. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3927. }
  3928. #endif
  3929. else {
  3930. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3931. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3932. model.mlock_bufs.emplace_back(new llama_mlock);
  3933. auto & mlock_buf = model.mlock_bufs.back();
  3934. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3935. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3936. }
  3937. }
  3938. if (buf == nullptr) {
  3939. throw std::runtime_error("failed to allocate buffer");
  3940. }
  3941. // indicate that this buffer contains weights
  3942. // 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
  3943. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3944. model.bufs.push_back(buf);
  3945. ctx_bufs.emplace_back(ctx, buf);
  3946. }
  3947. if (llama_supports_gpu_offload()) {
  3948. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3949. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3950. if (n_gpu_layers > (int) hparams.n_layer) {
  3951. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3952. }
  3953. const int max_backend_supported_layers = hparams.n_layer + 1;
  3954. const int max_offloadable_layers = hparams.n_layer + 1;
  3955. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3956. }
  3957. // print memory requirements
  3958. for (ggml_backend_buffer_t buf : model.bufs) {
  3959. 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);
  3960. }
  3961. // populate tensors_by_name
  3962. for (ggml_context * ctx : model.ctxs) {
  3963. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3964. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3965. }
  3966. }
  3967. // load tensor data
  3968. for (auto & it : ctx_bufs) {
  3969. ggml_context * ctx = it.first;
  3970. ggml_backend_buffer_t buf = it.second;
  3971. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3972. return false;
  3973. }
  3974. }
  3975. model.mapping = std::move(ml.mapping);
  3976. // loading time will be recalculate after the first eval, so
  3977. // we take page faults deferred by mmap() into consideration
  3978. model.t_load_us = ggml_time_us() - model.t_start_us;
  3979. return true;
  3980. }
  3981. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3982. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  3983. try {
  3984. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3985. model.hparams.vocab_only = params.vocab_only;
  3986. try {
  3987. llm_load_arch(ml, model);
  3988. } catch(const std::exception & e) {
  3989. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  3990. }
  3991. try {
  3992. llm_load_hparams(ml, model);
  3993. } catch(const std::exception & e) {
  3994. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  3995. }
  3996. try {
  3997. llm_load_vocab(ml, model);
  3998. } catch(const std::exception & e) {
  3999. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4000. }
  4001. llm_load_print_meta(ml, model);
  4002. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4003. throw std::runtime_error("vocab size mismatch");
  4004. }
  4005. if (params.vocab_only) {
  4006. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4007. return 0;
  4008. }
  4009. #ifdef GGML_USE_KOMPUTE
  4010. if (params.n_gpu_layers > 0 && (
  4011. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4012. || !(
  4013. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4014. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4015. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4016. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4017. )
  4018. )) {
  4019. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4020. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4021. params.n_gpu_layers = 0;
  4022. }
  4023. #endif
  4024. if (!llm_load_tensors(
  4025. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4026. params.progress_callback, params.progress_callback_user_data
  4027. )) {
  4028. return -2;
  4029. }
  4030. } catch (const std::exception & err) {
  4031. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4032. return -1;
  4033. }
  4034. return 0;
  4035. }
  4036. //
  4037. // llm_build
  4038. //
  4039. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4040. enum llm_ffn_op_type {
  4041. LLM_FFN_SILU,
  4042. LLM_FFN_GELU,
  4043. LLM_FFN_RELU,
  4044. LLM_FFN_RELU_SQR,
  4045. };
  4046. enum llm_ffn_gate_type {
  4047. LLM_FFN_SEQ,
  4048. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4049. };
  4050. enum llm_norm_type {
  4051. LLM_NORM,
  4052. LLM_NORM_RMS,
  4053. };
  4054. static struct ggml_tensor * llm_build_inp_embd(
  4055. struct ggml_context * ctx,
  4056. const llama_hparams & hparams,
  4057. const llama_batch & batch,
  4058. struct ggml_tensor * tok_embd,
  4059. struct ggml_tensor * inp_tokens,
  4060. struct ggml_tensor * inp_embd,
  4061. const llm_build_cb & cb) {
  4062. const int64_t n_embd = hparams.n_embd;
  4063. struct ggml_tensor * inpL;
  4064. if (batch.token) {
  4065. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  4066. cb(inp_tokens, "inp_tokens", -1);
  4067. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  4068. } else {
  4069. #ifdef GGML_USE_MPI
  4070. GGML_ASSERT(false && "not implemented");
  4071. #endif
  4072. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  4073. }
  4074. return inpL;
  4075. }
  4076. static void llm_build_kv_store(
  4077. struct ggml_context * ctx,
  4078. const llama_hparams & hparams,
  4079. const llama_kv_cache & kv,
  4080. struct ggml_cgraph * graph,
  4081. struct ggml_tensor * k_cur,
  4082. struct ggml_tensor * v_cur,
  4083. int64_t n_ctx,
  4084. int32_t n_tokens,
  4085. int32_t kv_head,
  4086. const llm_build_cb & cb,
  4087. int64_t il) {
  4088. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4089. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4090. // compute the transposed [n_tokens, n_embd] V matrix
  4091. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4092. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4093. cb(v_cur_t, "v_cur_t", il);
  4094. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4095. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4096. cb(k_cache_view, "k_cache_view", il);
  4097. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4098. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4099. (kv_head)*ggml_element_size(kv.v_l[il]));
  4100. cb(v_cache_view, "v_cache_view", il);
  4101. // important: storing RoPE-ed version of K in the KV cache!
  4102. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4103. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4104. }
  4105. static struct ggml_tensor * llm_build_norm(
  4106. struct ggml_context * ctx,
  4107. struct ggml_tensor * cur,
  4108. const llama_hparams & hparams,
  4109. struct ggml_tensor * mw,
  4110. struct ggml_tensor * mb,
  4111. llm_norm_type type,
  4112. const llm_build_cb & cb,
  4113. int il) {
  4114. switch (type) {
  4115. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4116. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4117. }
  4118. if (mw || mb) {
  4119. cb(cur, "norm", il);
  4120. }
  4121. if (mw) {
  4122. cur = ggml_mul(ctx, cur, mw);
  4123. if (mb) {
  4124. cb(cur, "norm_w", il);
  4125. }
  4126. }
  4127. if (mb) {
  4128. cur = ggml_add(ctx, cur, mb);
  4129. }
  4130. return cur;
  4131. }
  4132. static struct ggml_tensor * llm_build_ffn(
  4133. struct ggml_context * ctx,
  4134. struct ggml_tensor * cur,
  4135. struct ggml_tensor * up,
  4136. struct ggml_tensor * up_b,
  4137. struct ggml_tensor * gate,
  4138. struct ggml_tensor * gate_b,
  4139. struct ggml_tensor * down,
  4140. struct ggml_tensor * down_b,
  4141. struct ggml_tensor * act_scales,
  4142. llm_ffn_op_type type_op,
  4143. llm_ffn_gate_type type_gate,
  4144. const llm_build_cb & cb,
  4145. int il) {
  4146. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4147. cb(tmp, "ffn_up", il);
  4148. if (up_b) {
  4149. tmp = ggml_add(ctx, tmp, up_b);
  4150. cb(tmp, "ffn_up_b", il);
  4151. }
  4152. if (gate) {
  4153. switch (type_gate) {
  4154. case LLM_FFN_SEQ:
  4155. {
  4156. cur = ggml_mul_mat(ctx, gate, tmp);
  4157. cb(cur, "ffn_gate", il);
  4158. } break;
  4159. case LLM_FFN_PAR:
  4160. {
  4161. cur = ggml_mul_mat(ctx, gate, cur);
  4162. cb(cur, "ffn_gate", il);
  4163. } break;
  4164. }
  4165. if (gate_b) {
  4166. cur = ggml_add(ctx, cur, gate_b);
  4167. cb(cur, "ffn_gate_b", il);
  4168. }
  4169. } else {
  4170. cur = tmp;
  4171. }
  4172. switch (type_op) {
  4173. case LLM_FFN_SILU:
  4174. {
  4175. cur = ggml_silu(ctx, cur);
  4176. cb(cur, "ffn_silu", il);
  4177. } break;
  4178. case LLM_FFN_GELU:
  4179. {
  4180. cur = ggml_gelu(ctx, cur);
  4181. cb(cur, "ffn_gelu", il);
  4182. if (act_scales != NULL) {
  4183. cur = ggml_div(ctx, cur, act_scales);
  4184. cb(cur, "ffn_act", il);
  4185. }
  4186. } break;
  4187. case LLM_FFN_RELU:
  4188. {
  4189. cur = ggml_relu(ctx, cur);
  4190. cb(cur, "ffn_relu", il);
  4191. } break;
  4192. case LLM_FFN_RELU_SQR:
  4193. {
  4194. cur = ggml_relu(ctx, cur);
  4195. cb(cur, "ffn_relu", il);
  4196. cur = ggml_sqr(ctx, cur);
  4197. cb(cur, "ffn_sqr(relu)", il);
  4198. } break;
  4199. }
  4200. if (type_gate == LLM_FFN_PAR) {
  4201. cur = ggml_mul(ctx, cur, tmp);
  4202. cb(cur, "ffn_gate_par", il);
  4203. }
  4204. cur = ggml_mul_mat(ctx, down, cur);
  4205. if (down_b) {
  4206. cb(cur, "ffn_down", il);
  4207. }
  4208. if (down_b) {
  4209. cur = ggml_add(ctx, cur, down_b);
  4210. }
  4211. return cur;
  4212. }
  4213. // if max_alibi_bias > 0 then apply ALiBi
  4214. static struct ggml_tensor * llm_build_kqv(
  4215. struct ggml_context * ctx,
  4216. const llama_model & model,
  4217. const llama_hparams & hparams,
  4218. const llama_kv_cache & kv,
  4219. struct ggml_cgraph * graph,
  4220. struct ggml_tensor * wo,
  4221. struct ggml_tensor * wo_b,
  4222. struct ggml_tensor * q_cur,
  4223. struct ggml_tensor * kq_mask,
  4224. struct ggml_tensor * kq_pos,
  4225. int64_t n_ctx,
  4226. int32_t n_tokens,
  4227. int32_t n_kv,
  4228. float kq_scale,
  4229. const llm_build_cb & cb,
  4230. int il) {
  4231. const int64_t n_head = hparams.n_head;
  4232. const int64_t n_head_kv = hparams.n_head_kv;
  4233. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4234. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4235. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4236. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4237. cb(q, "q", il);
  4238. struct ggml_tensor * k =
  4239. ggml_view_3d(ctx, kv.k_l[il],
  4240. n_embd_head_k, n_kv, n_head_kv,
  4241. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4242. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4243. 0);
  4244. cb(k, "k", il);
  4245. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4246. cb(kq, "kq", il);
  4247. if (model.arch == LLM_ARCH_PHI2) {
  4248. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4249. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4250. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4251. }
  4252. #if defined(GGML_USE_VULKAN) || defined(GGML_USE_KOMPUTE)
  4253. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Vulkan, and Kompute")
  4254. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4255. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4256. if (hparams.f_max_alibi_bias > 0.0f) {
  4257. kq = ggml_scale(ctx, kq, kq_scale);
  4258. cb(kq, "kq_scaled", il);
  4259. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4260. cb(kq, "kq_scaled_alibi", il);
  4261. kq = ggml_add(ctx, kq, kq_mask);
  4262. cb(kq, "kq_masked", il);
  4263. kq = ggml_soft_max(ctx, kq);
  4264. cb(kq, "kq_soft_max", il);
  4265. } else
  4266. #endif
  4267. {
  4268. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4269. cb(kq, "kq_soft_max_ext", il);
  4270. }
  4271. // split cached v into n_head heads
  4272. struct ggml_tensor * v =
  4273. ggml_view_3d(ctx, kv.v_l[il],
  4274. n_kv, n_embd_head_v, n_head_kv,
  4275. ggml_element_size(kv.v_l[il])*n_ctx,
  4276. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4277. 0);
  4278. cb(v, "v", il);
  4279. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4280. cb(kqv, "kqv", il);
  4281. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4282. cb(kqv_merged, "kqv_merged", il);
  4283. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4284. cb(cur, "kqv_merged_cont", il);
  4285. ggml_build_forward_expand(graph, cur);
  4286. cur = ggml_mul_mat(ctx, wo, cur);
  4287. if (wo_b) {
  4288. cb(cur, "kqv_wo", il);
  4289. }
  4290. if (wo_b) {
  4291. cur = ggml_add(ctx, cur, wo_b);
  4292. }
  4293. return cur;
  4294. }
  4295. static struct ggml_tensor * llm_build_kv(
  4296. struct ggml_context * ctx,
  4297. const llama_model & model,
  4298. const llama_hparams & hparams,
  4299. const llama_kv_cache & kv,
  4300. struct ggml_cgraph * graph,
  4301. struct ggml_tensor * wo,
  4302. struct ggml_tensor * wo_b,
  4303. struct ggml_tensor * k_cur,
  4304. struct ggml_tensor * v_cur,
  4305. struct ggml_tensor * q_cur,
  4306. struct ggml_tensor * kq_mask,
  4307. struct ggml_tensor * kq_pos,
  4308. int64_t n_ctx,
  4309. int32_t n_tokens,
  4310. int32_t kv_head,
  4311. int32_t n_kv,
  4312. float kq_scale,
  4313. const llm_build_cb & cb,
  4314. int il) {
  4315. // these nodes are added to the graph together so that they are not reordered
  4316. // by doing so, the number of splits in the graph is reduced
  4317. ggml_build_forward_expand(graph, q_cur);
  4318. ggml_build_forward_expand(graph, k_cur);
  4319. ggml_build_forward_expand(graph, v_cur);
  4320. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4321. struct ggml_tensor * cur;
  4322. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4323. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4324. cb(cur, "kqv_out", il);
  4325. return cur;
  4326. }
  4327. struct llm_build_context {
  4328. const llama_model & model;
  4329. const llama_context & lctx;
  4330. const llama_hparams & hparams;
  4331. const llama_cparams & cparams;
  4332. const llama_batch & batch;
  4333. const llama_kv_cache & kv_self;
  4334. const int64_t n_embd;
  4335. const int64_t n_layer;
  4336. const int64_t n_rot;
  4337. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4338. const int64_t n_head;
  4339. const int64_t n_head_kv;
  4340. const int64_t n_embd_head_k;
  4341. const int64_t n_embd_k_gqa;
  4342. const int64_t n_embd_head_v;
  4343. const int64_t n_embd_v_gqa;
  4344. const int64_t n_expert;
  4345. const int64_t n_expert_used;
  4346. const float freq_base;
  4347. const float freq_scale;
  4348. const float ext_factor;
  4349. const float attn_factor;
  4350. const float beta_fast;
  4351. const float beta_slow;
  4352. const float norm_eps;
  4353. const float norm_rms_eps;
  4354. const int32_t n_tokens;
  4355. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4356. const int32_t kv_head; // index of where we store new KV data in the cache
  4357. const int32_t n_orig_ctx;
  4358. const enum llama_pooling_type pooling_type;
  4359. const enum llama_rope_type rope_type;
  4360. const llm_build_cb & cb;
  4361. std::vector<uint8_t> & buf_compute_meta;
  4362. struct ggml_context * ctx0 = nullptr;
  4363. // TODO: consider making the entire interface noexcept
  4364. llm_build_context(
  4365. llama_context & lctx,
  4366. const llama_batch & batch,
  4367. const llm_build_cb & cb,
  4368. bool worst_case) :
  4369. model (lctx.model),
  4370. lctx (lctx),
  4371. hparams (model.hparams),
  4372. cparams (lctx.cparams),
  4373. batch (batch),
  4374. kv_self (lctx.kv_self),
  4375. n_embd (hparams.n_embd),
  4376. n_layer (hparams.n_layer),
  4377. n_rot (hparams.n_rot),
  4378. n_ctx (cparams.n_ctx),
  4379. n_head (hparams.n_head),
  4380. n_head_kv (hparams.n_head_kv),
  4381. n_embd_head_k (hparams.n_embd_head_k),
  4382. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4383. n_embd_head_v (hparams.n_embd_head_v),
  4384. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4385. n_expert (hparams.n_expert),
  4386. n_expert_used (hparams.n_expert_used),
  4387. freq_base (cparams.rope_freq_base),
  4388. freq_scale (cparams.rope_freq_scale),
  4389. ext_factor (cparams.yarn_ext_factor),
  4390. attn_factor (cparams.yarn_attn_factor),
  4391. beta_fast (cparams.yarn_beta_fast),
  4392. beta_slow (cparams.yarn_beta_slow),
  4393. norm_eps (hparams.f_norm_eps),
  4394. norm_rms_eps (hparams.f_norm_rms_eps),
  4395. n_tokens (batch.n_tokens),
  4396. n_kv (worst_case ? n_ctx : kv_self.n),
  4397. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4398. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4399. pooling_type (cparams.do_pooling ? hparams.pooling_type : LLAMA_POOLING_TYPE_NONE),
  4400. rope_type (hparams.rope_type),
  4401. cb (cb),
  4402. buf_compute_meta (lctx.buf_compute_meta) {
  4403. // all initializations should be done in init()
  4404. }
  4405. void init() {
  4406. struct ggml_init_params params = {
  4407. /*.mem_size =*/ buf_compute_meta.size(),
  4408. /*.mem_buffer =*/ buf_compute_meta.data(),
  4409. /*.no_alloc =*/ true,
  4410. };
  4411. ctx0 = ggml_init(params);
  4412. }
  4413. void free() {
  4414. if (ctx0) {
  4415. ggml_free(ctx0);
  4416. ctx0 = nullptr;
  4417. }
  4418. }
  4419. struct ggml_cgraph * build_k_shift() {
  4420. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4421. for (int il = 0; il < n_layer; ++il) {
  4422. struct ggml_tensor * tmp =
  4423. // we rotate only the first n_rot dimensions
  4424. ggml_rope_custom_inplace(ctx0,
  4425. ggml_view_3d(ctx0, kv_self.k_l[il],
  4426. n_embd_head_k, n_head_kv, n_ctx,
  4427. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  4428. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4429. 0),
  4430. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4431. ext_factor, attn_factor, beta_fast, beta_slow);
  4432. cb(tmp, "K_shifted", il);
  4433. ggml_build_forward_expand(gf, tmp);
  4434. }
  4435. return gf;
  4436. }
  4437. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  4438. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4439. for (uint32_t i = 0; i < ids.size(); ++i) {
  4440. const uint32_t id = ids[i];
  4441. if (i == id || id == ids.size()) {
  4442. continue;
  4443. }
  4444. uint32_t nm = 1;
  4445. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  4446. nm++;
  4447. }
  4448. for (int il = 0; il < n_layer; ++il) {
  4449. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  4450. n_embd_k_gqa, nm,
  4451. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4452. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  4453. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  4454. n_embd_k_gqa, nm,
  4455. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4456. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  4457. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  4458. nm, n_embd_v_gqa,
  4459. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4460. ggml_row_size(kv_self.v_l[il]->type, i));
  4461. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  4462. nm, n_embd_v_gqa,
  4463. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4464. ggml_row_size(kv_self.v_l[il]->type, id));
  4465. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  4466. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  4467. }
  4468. i += nm - 1;
  4469. }
  4470. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  4471. return gf;
  4472. }
  4473. struct ggml_cgraph * build_llama() {
  4474. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4475. const int64_t n_embd_head = hparams.n_embd_head_v;
  4476. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4477. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4478. struct ggml_tensor * cur;
  4479. struct ggml_tensor * inpL;
  4480. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4481. cb(inpL, "inp_embd", -1);
  4482. // inp_pos - contains the positions
  4483. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4484. cb(inp_pos, "inp_pos", -1);
  4485. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4486. 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);
  4487. cb(KQ_mask, "KQ_mask", -1);
  4488. for (int il = 0; il < n_layer; ++il) {
  4489. struct ggml_tensor * inpSA = inpL;
  4490. // norm
  4491. cur = llm_build_norm(ctx0, inpL, hparams,
  4492. model.layers[il].attn_norm, NULL,
  4493. LLM_NORM_RMS, cb, il);
  4494. cb(cur, "attn_norm", il);
  4495. // self-attention
  4496. {
  4497. // compute Q and K and RoPE them
  4498. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4499. cb(Qcur, "Qcur", il);
  4500. if (model.layers[il].bq) {
  4501. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4502. cb(Qcur, "Qcur", il);
  4503. }
  4504. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4505. cb(Kcur, "Kcur", il);
  4506. if (model.layers[il].bk) {
  4507. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4508. cb(Kcur, "Kcur", il);
  4509. }
  4510. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4511. cb(Vcur, "Vcur", il);
  4512. if (model.layers[il].bv) {
  4513. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4514. cb(Vcur, "Vcur", il);
  4515. }
  4516. Qcur = ggml_rope_custom(
  4517. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4518. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4519. ext_factor, attn_factor, beta_fast, beta_slow
  4520. );
  4521. cb(Qcur, "Qcur", il);
  4522. Kcur = ggml_rope_custom(
  4523. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4524. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4525. ext_factor, attn_factor, beta_fast, beta_slow
  4526. );
  4527. cb(Kcur, "Kcur", il);
  4528. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4529. model.layers[il].wo, model.layers[il].bo,
  4530. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4531. cb(cur, "kqv_out", il);
  4532. }
  4533. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4534. cb(ffn_inp, "ffn_inp", il);
  4535. // feed-forward network
  4536. if (model.layers[il].ffn_gate_inp == nullptr) {
  4537. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4538. model.layers[il].ffn_norm, NULL,
  4539. LLM_NORM_RMS, cb, il);
  4540. cb(cur, "ffn_norm", il);
  4541. cur = llm_build_ffn(ctx0, cur,
  4542. model.layers[il].ffn_up, NULL,
  4543. model.layers[il].ffn_gate, NULL,
  4544. model.layers[il].ffn_down, NULL,
  4545. NULL,
  4546. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4547. cb(cur, "ffn_out", il);
  4548. } else {
  4549. // MoE branch
  4550. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4551. model.layers[il].ffn_norm, NULL,
  4552. LLM_NORM_RMS, cb, il);
  4553. cb(cur, "ffn_norm", il);
  4554. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4555. cb(logits, "ffn_moe_logits", il);
  4556. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4557. cb(probs, "ffn_moe_probs", il);
  4558. // select experts
  4559. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4560. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4561. ggml_tensor * weights = ggml_get_rows(ctx0,
  4562. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4563. cb(weights, "ffn_moe_weights", il);
  4564. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4565. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4566. cb(weights_sum, "ffn_moe_weights_sum", il);
  4567. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4568. cb(weights, "ffn_moe_weights_norm", il);
  4569. // compute expert outputs
  4570. ggml_tensor * moe_out = nullptr;
  4571. for (int i = 0; i < n_expert_used; ++i) {
  4572. ggml_tensor * cur_expert;
  4573. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4574. cb(cur_up, "ffn_moe_up", il);
  4575. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4576. cb(cur_gate, "ffn_moe_gate", il);
  4577. cur_gate = ggml_silu(ctx0, cur_gate);
  4578. cb(cur_gate, "ffn_moe_silu", il);
  4579. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4580. cb(cur_expert, "ffn_moe_gate_par", il);
  4581. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4582. cb(cur_expert, "ffn_moe_down", il);
  4583. cur_expert = ggml_mul(ctx0, cur_expert,
  4584. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4585. cb(cur_expert, "ffn_moe_weighted", il);
  4586. if (i == 0) {
  4587. moe_out = cur_expert;
  4588. } else {
  4589. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4590. cb(moe_out, "ffn_moe_out", il);
  4591. }
  4592. }
  4593. cur = moe_out;
  4594. }
  4595. cur = ggml_add(ctx0, cur, ffn_inp);
  4596. cb(cur, "l_out", il);
  4597. // input for next layer
  4598. inpL = cur;
  4599. }
  4600. cur = inpL;
  4601. cur = llm_build_norm(ctx0, cur, hparams,
  4602. model.output_norm, NULL,
  4603. LLM_NORM_RMS, cb, -1);
  4604. cb(cur, "result_norm", -1);
  4605. // lm_head
  4606. cur = ggml_mul_mat(ctx0, model.output, cur);
  4607. cb(cur, "result_output", -1);
  4608. ggml_build_forward_expand(gf, cur);
  4609. return gf;
  4610. }
  4611. struct ggml_cgraph * build_baichuan() {
  4612. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4613. const int64_t n_embd_head = hparams.n_embd_head_v;
  4614. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4615. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4616. struct ggml_tensor * cur;
  4617. struct ggml_tensor * inpL;
  4618. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4619. cb(inpL, "inp_embd", -1);
  4620. // inp_pos - contains the positions
  4621. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4622. cb(inp_pos, "inp_pos", -1);
  4623. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4624. 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);
  4625. cb(KQ_mask, "KQ_mask", -1);
  4626. // positions of the tokens in the KV cache
  4627. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4628. cb(KQ_pos, "KQ_pos", -1);
  4629. for (int il = 0; il < n_layer; ++il) {
  4630. struct ggml_tensor * inpSA = inpL;
  4631. cur = llm_build_norm(ctx0, inpL, hparams,
  4632. model.layers[il].attn_norm, NULL,
  4633. LLM_NORM_RMS, cb, il);
  4634. cb(cur, "attn_norm", il);
  4635. // self-attention
  4636. {
  4637. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4638. cb(Qcur, "Qcur", il);
  4639. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4640. cb(Kcur, "Kcur", il);
  4641. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4642. cb(Vcur, "Vcur", il);
  4643. switch (model.type) {
  4644. case MODEL_7B:
  4645. Qcur = ggml_rope_custom(
  4646. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4647. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4648. ext_factor, attn_factor, beta_fast, beta_slow
  4649. );
  4650. Kcur = ggml_rope_custom(
  4651. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4652. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4653. ext_factor, attn_factor, beta_fast, beta_slow
  4654. );
  4655. break;
  4656. case MODEL_13B:
  4657. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4658. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4659. break;
  4660. default:
  4661. GGML_ASSERT(false);
  4662. }
  4663. cb(Qcur, "Qcur", il);
  4664. cb(Kcur, "Kcur", il);
  4665. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4666. model.layers[il].wo, NULL,
  4667. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4668. cb(cur, "kqv_out", il);
  4669. }
  4670. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4671. cb(ffn_inp, "ffn_inp", il);
  4672. // feed-forward network
  4673. {
  4674. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4675. model.layers[il].ffn_norm, NULL,
  4676. LLM_NORM_RMS, cb, il);
  4677. cb(cur, "ffn_norm", il);
  4678. cur = llm_build_ffn(ctx0, cur,
  4679. model.layers[il].ffn_up, NULL,
  4680. model.layers[il].ffn_gate, NULL,
  4681. model.layers[il].ffn_down, NULL,
  4682. NULL,
  4683. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4684. cb(cur, "ffn_out", il);
  4685. }
  4686. cur = ggml_add(ctx0, cur, ffn_inp);
  4687. cb(cur, "l_out", il);
  4688. // input for next layer
  4689. inpL = cur;
  4690. }
  4691. cur = inpL;
  4692. cur = llm_build_norm(ctx0, cur, hparams,
  4693. model.output_norm, NULL,
  4694. LLM_NORM_RMS, cb, -1);
  4695. cb(cur, "result_norm", -1);
  4696. // lm_head
  4697. cur = ggml_mul_mat(ctx0, model.output, cur);
  4698. cb(cur, "result_output", -1);
  4699. ggml_build_forward_expand(gf, cur);
  4700. return gf;
  4701. }
  4702. struct ggml_cgraph * build_falcon() {
  4703. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4704. const int64_t n_embd_head = hparams.n_embd_head_v;
  4705. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4706. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4707. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4708. struct ggml_tensor * cur;
  4709. struct ggml_tensor * inpL;
  4710. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4711. cb(inpL, "inp_embd", -1);
  4712. // inp_pos - contains the positions
  4713. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4714. cb(inp_pos, "inp_pos", -1);
  4715. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4716. 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);
  4717. cb(KQ_mask, "KQ_mask", -1);
  4718. for (int il = 0; il < n_layer; ++il) {
  4719. struct ggml_tensor * attn_norm;
  4720. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4721. model.layers[il].attn_norm,
  4722. model.layers[il].attn_norm_b,
  4723. LLM_NORM, cb, il);
  4724. cb(attn_norm, "attn_norm", il);
  4725. // self-attention
  4726. {
  4727. if (model.layers[il].attn_norm_2) {
  4728. // Falcon-40B
  4729. cur = llm_build_norm(ctx0, inpL, hparams,
  4730. model.layers[il].attn_norm_2,
  4731. model.layers[il].attn_norm_2_b,
  4732. LLM_NORM, cb, il);
  4733. cb(cur, "attn_norm_2", il);
  4734. } else {
  4735. cur = attn_norm;
  4736. }
  4737. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4738. cb(cur, "wqkv", il);
  4739. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4740. 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)));
  4741. 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)));
  4742. cb(Qcur, "Qcur", il);
  4743. cb(Kcur, "Kcur", il);
  4744. cb(Vcur, "Vcur", il);
  4745. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4746. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4747. // using mode = 2 for neox mode
  4748. Qcur = ggml_rope_custom(
  4749. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4750. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4751. );
  4752. cb(Qcur, "Qcur", il);
  4753. Kcur = ggml_rope_custom(
  4754. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4755. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4756. );
  4757. cb(Kcur, "Kcur", il);
  4758. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4759. model.layers[il].wo, NULL,
  4760. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4761. cb(cur, "kqv_out", il);
  4762. }
  4763. struct ggml_tensor * ffn_inp = cur;
  4764. // feed forward
  4765. {
  4766. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4767. model.layers[il].ffn_up, NULL,
  4768. NULL, NULL,
  4769. model.layers[il].ffn_down, NULL,
  4770. NULL,
  4771. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4772. cb(cur, "ffn_out", il);
  4773. }
  4774. cur = ggml_add(ctx0, cur, ffn_inp);
  4775. cb(cur, "l_out", il);
  4776. cur = ggml_add(ctx0, cur, inpL);
  4777. cb(cur, "l_out", il);
  4778. // input for next layer
  4779. inpL = cur;
  4780. }
  4781. cur = inpL;
  4782. // norm
  4783. cur = llm_build_norm(ctx0, cur, hparams,
  4784. model.output_norm,
  4785. model.output_norm_b,
  4786. LLM_NORM, cb, -1);
  4787. cb(cur, "result_norm", -1);
  4788. cur = ggml_mul_mat(ctx0, model.output, cur);
  4789. cb(cur, "result_output", -1);
  4790. ggml_build_forward_expand(gf, cur);
  4791. return gf;
  4792. }
  4793. struct ggml_cgraph * build_starcoder() {
  4794. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4795. const int64_t n_embd_head = hparams.n_embd_head_v;
  4796. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4797. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4798. struct ggml_tensor * cur;
  4799. struct ggml_tensor * pos;
  4800. struct ggml_tensor * inpL;
  4801. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4802. cb(inpL, "inp_embd", -1);
  4803. // inp_pos - contains the positions
  4804. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4805. cb(inp_pos, "inp_pos", -1);
  4806. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4807. 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);
  4808. cb(KQ_mask, "KQ_mask", -1);
  4809. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4810. cb(pos, "pos_embd", -1);
  4811. inpL = ggml_add(ctx0, inpL, pos);
  4812. cb(inpL, "inpL", -1);
  4813. for (int il = 0; il < n_layer; ++il) {
  4814. cur = llm_build_norm(ctx0, inpL, hparams,
  4815. model.layers[il].attn_norm,
  4816. model.layers[il].attn_norm_b,
  4817. LLM_NORM, cb, il);
  4818. cb(cur, "attn_norm", il);
  4819. // self-attention
  4820. {
  4821. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4822. cb(cur, "wqkv", il);
  4823. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4824. cb(cur, "bqkv", il);
  4825. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4826. 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)));
  4827. 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)));
  4828. cb(Qcur, "Qcur", il);
  4829. cb(Kcur, "Kcur", il);
  4830. cb(Vcur, "Vcur", il);
  4831. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4832. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4833. model.layers[il].wo, model.layers[il].bo,
  4834. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4835. cb(cur, "kqv_out", il);
  4836. }
  4837. // add the input
  4838. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4839. cb(ffn_inp, "ffn_inp", il);
  4840. // FF
  4841. {
  4842. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4843. model.layers[il].ffn_norm,
  4844. model.layers[il].ffn_norm_b,
  4845. LLM_NORM, cb, il);
  4846. cb(cur, "ffn_norm", il);
  4847. cur = llm_build_ffn(ctx0, cur,
  4848. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4849. NULL, NULL,
  4850. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4851. NULL,
  4852. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4853. cb(cur, "ffn_out", il);
  4854. }
  4855. inpL = ggml_add(ctx0, cur, ffn_inp);
  4856. cb(inpL, "l_out", il);
  4857. }
  4858. cur = llm_build_norm(ctx0, inpL, hparams,
  4859. model.output_norm,
  4860. model.output_norm_b,
  4861. LLM_NORM, cb, -1);
  4862. cb(cur, "result_norm", -1);
  4863. cur = ggml_mul_mat(ctx0, model.output, cur);
  4864. cb(cur, "result_output", -1);
  4865. ggml_build_forward_expand(gf, cur);
  4866. return gf;
  4867. }
  4868. struct ggml_cgraph * build_persimmon() {
  4869. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4870. const int64_t n_embd_head = hparams.n_embd_head_v;
  4871. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4872. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4873. struct ggml_tensor * cur;
  4874. struct ggml_tensor * inpL;
  4875. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4876. cb(inpL, "inp_embd", -1);
  4877. // inp_pos - contains the positions
  4878. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4879. cb(inp_pos, "inp_pos", -1);
  4880. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4881. 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);
  4882. cb(KQ_mask, "KQ_mask", -1);
  4883. for (int il = 0; il < n_layer; ++il) {
  4884. struct ggml_tensor * residual = inpL;
  4885. cur = llm_build_norm(ctx0, inpL, hparams,
  4886. model.layers[il].attn_norm,
  4887. model.layers[il].attn_norm_b,
  4888. LLM_NORM, cb, il);
  4889. cb(cur, "attn_norm", il);
  4890. // self attention
  4891. {
  4892. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4893. cb(cur, "wqkv", il);
  4894. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4895. cb(cur, "bqkv", il);
  4896. // split qkv
  4897. GGML_ASSERT(n_head_kv == n_head);
  4898. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4899. cb(tmpqkv, "tmpqkv", il);
  4900. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4901. cb(tmpqkv_perm, "tmpqkv", il);
  4902. struct ggml_tensor * tmpq = ggml_view_3d(
  4903. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4904. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4905. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4906. 0
  4907. );
  4908. cb(tmpq, "tmpq", il);
  4909. struct ggml_tensor * tmpk = ggml_view_3d(
  4910. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4911. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4912. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4913. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4914. );
  4915. cb(tmpk, "tmpk", il);
  4916. // Q/K Layernorm
  4917. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4918. model.layers[il].attn_q_norm,
  4919. model.layers[il].attn_q_norm_b,
  4920. LLM_NORM, cb, il);
  4921. cb(tmpq, "tmpq", il);
  4922. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4923. model.layers[il].attn_k_norm,
  4924. model.layers[il].attn_k_norm_b,
  4925. LLM_NORM, cb, il);
  4926. cb(tmpk, "tmpk", il);
  4927. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4928. struct ggml_tensor * qrot = ggml_view_3d(
  4929. ctx0, tmpq, n_rot, n_head, n_tokens,
  4930. ggml_element_size(tmpq) * n_embd_head,
  4931. ggml_element_size(tmpq) * n_embd_head * n_head,
  4932. 0
  4933. );
  4934. cb(qrot, "qrot", il);
  4935. struct ggml_tensor * krot = ggml_view_3d(
  4936. ctx0, tmpk, n_rot, n_head, n_tokens,
  4937. ggml_element_size(tmpk) * n_embd_head,
  4938. ggml_element_size(tmpk) * n_embd_head * n_head,
  4939. 0
  4940. );
  4941. cb(krot, "krot", il);
  4942. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4943. struct ggml_tensor * qpass = ggml_view_3d(
  4944. ctx0, tmpq, n_rot, n_head, n_tokens,
  4945. ggml_element_size(tmpq) * n_embd_head,
  4946. ggml_element_size(tmpq) * n_embd_head * n_head,
  4947. ggml_element_size(tmpq) * n_rot
  4948. );
  4949. cb(qpass, "qpass", il);
  4950. struct ggml_tensor * kpass = ggml_view_3d(
  4951. ctx0, tmpk, n_rot, n_head, n_tokens,
  4952. ggml_element_size(tmpk) * n_embd_head,
  4953. ggml_element_size(tmpk) * n_embd_head * n_head,
  4954. ggml_element_size(tmpk) * n_rot
  4955. );
  4956. cb(kpass, "kpass", il);
  4957. struct ggml_tensor * qrotated = ggml_rope_custom(
  4958. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4959. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4960. );
  4961. cb(qrotated, "qrotated", il);
  4962. struct ggml_tensor * krotated = ggml_rope_custom(
  4963. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4964. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4965. );
  4966. cb(krotated, "krotated", il);
  4967. // ggml currently only supports concatenation on dim=2
  4968. // so we need to permute qrot, qpass, concat, then permute back.
  4969. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4970. cb(qrotated, "qrotated", il);
  4971. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4972. cb(krotated, "krotated", il);
  4973. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4974. cb(qpass, "qpass", il);
  4975. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4976. cb(kpass, "kpass", il);
  4977. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4978. cb(Qcur, "Qcur", il);
  4979. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4980. cb(Kcur, "Kcur", il);
  4981. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4982. cb(Q, "Q", il);
  4983. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4984. cb(Kcur, "Kcur", il);
  4985. struct ggml_tensor * Vcur = ggml_view_3d(
  4986. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4987. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4988. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4989. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4990. );
  4991. cb(Vcur, "Vcur", il);
  4992. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4993. model.layers[il].wo, model.layers[il].bo,
  4994. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4995. cb(cur, "kqv_out", il);
  4996. }
  4997. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4998. cb(ffn_inp, "ffn_inp", il);
  4999. // feed-forward network
  5000. {
  5001. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5002. model.layers[il].ffn_norm,
  5003. model.layers[il].ffn_norm_b,
  5004. LLM_NORM, cb, il);
  5005. cb(cur, "ffn_norm", il);
  5006. cur = llm_build_ffn(ctx0, cur,
  5007. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5008. NULL, NULL,
  5009. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5010. NULL,
  5011. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  5012. cb(cur, "ffn_out", il);
  5013. }
  5014. cur = ggml_add(ctx0, cur, ffn_inp);
  5015. cb(cur, "l_out", il);
  5016. inpL = cur;
  5017. }
  5018. cur = inpL;
  5019. cur = llm_build_norm(ctx0, cur, hparams,
  5020. model.output_norm,
  5021. model.output_norm_b,
  5022. LLM_NORM, cb, -1);
  5023. cb(cur, "result_norm", -1);
  5024. cur = ggml_mul_mat(ctx0, model.output, cur);
  5025. cb(cur, "result_output", -1);
  5026. ggml_build_forward_expand(gf, cur);
  5027. return gf;
  5028. }
  5029. struct ggml_cgraph * build_refact() {
  5030. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5031. const int64_t n_embd_head = hparams.n_embd_head_v;
  5032. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5033. struct ggml_tensor * cur;
  5034. struct ggml_tensor * inpL;
  5035. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5036. cb(inpL, "inp_embd", -1);
  5037. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5038. 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);
  5039. cb(KQ_mask, "KQ_mask", -1);
  5040. // positions of the tokens in the KV cache
  5041. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5042. cb(KQ_pos, "KQ_pos", -1);
  5043. for (int il = 0; il < n_layer; ++il) {
  5044. struct ggml_tensor * inpSA = inpL;
  5045. cur = llm_build_norm(ctx0, inpL, hparams,
  5046. model.layers[il].attn_norm, NULL,
  5047. LLM_NORM_RMS, cb, il);
  5048. cb(cur, "attn_norm", il);
  5049. // self-attention
  5050. {
  5051. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5052. cb(Qcur, "Qcur", il);
  5053. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5054. cb(Kcur, "Kcur", il);
  5055. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5056. cb(Vcur, "Vcur", il);
  5057. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5058. cb(Kcur, "Kcur", il);
  5059. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5060. cb(Qcur, "Qcur", il);
  5061. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5062. model.layers[il].wo, NULL,
  5063. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5064. cb(cur, "kqv_out", il);
  5065. }
  5066. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5067. cb(ffn_inp, "ffn_inp", il);
  5068. // feed-forward network
  5069. {
  5070. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5071. model.layers[il].ffn_norm, NULL,
  5072. LLM_NORM_RMS, cb, il);
  5073. cb(cur, "ffn_norm", il);
  5074. cur = llm_build_ffn(ctx0, cur,
  5075. model.layers[il].ffn_up, NULL,
  5076. model.layers[il].ffn_gate, NULL,
  5077. model.layers[il].ffn_down, NULL,
  5078. NULL,
  5079. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5080. cb(cur, "ffn_out", il);
  5081. }
  5082. cur = ggml_add(ctx0, cur, ffn_inp);
  5083. cb(cur, "l_out", il);
  5084. // input for next layer
  5085. inpL = cur;
  5086. }
  5087. cur = inpL;
  5088. cur = llm_build_norm(ctx0, cur, hparams,
  5089. model.output_norm, NULL,
  5090. LLM_NORM_RMS, cb, -1);
  5091. cb(cur, "result_norm", -1);
  5092. // lm_head
  5093. cur = ggml_mul_mat(ctx0, model.output, cur);
  5094. cb(cur, "result_output", -1);
  5095. ggml_build_forward_expand(gf, cur);
  5096. return gf;
  5097. }
  5098. struct ggml_cgraph * build_bert() {
  5099. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5100. const int64_t n_embd_head = hparams.n_embd_head_v;
  5101. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5102. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5103. struct ggml_tensor * cur;
  5104. struct ggml_tensor * inpL;
  5105. // get input vectors with right size
  5106. const size_t stride1 = n_tokens * ggml_type_size(lctx.inp_tokens->type);
  5107. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5108. struct ggml_tensor * inp_mean = ggml_view_2d(ctx0, lctx.inp_mean, n_tokens, n_tokens, stride1, 0);
  5109. struct ggml_tensor * inp_cls = ggml_view_1d(ctx0, lctx.inp_cls, n_tokens, 0);
  5110. // construct input embeddings (token, type, position)
  5111. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5112. // token types are hardcoded to zero ("Sentence A")
  5113. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5114. inpL = ggml_add(ctx0, inpL, type_row0);
  5115. if (model.arch == LLM_ARCH_BERT) {
  5116. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5117. }
  5118. cb(inpL, "inp_embd", -1);
  5119. // embed layer norm
  5120. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5121. cb(inpL, "inp_norm", -1);
  5122. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5123. 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);
  5124. cb(KQ_mask, "KQ_mask", -1); // [n_kv, n_tokens]
  5125. // iterate layers
  5126. for (int il = 0; il < n_layer; ++il) {
  5127. struct ggml_tensor * cur = inpL;
  5128. // self-attention
  5129. if (model.arch == LLM_ARCH_BERT) {
  5130. struct ggml_tensor * Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5131. cb(Qcur, "Qcur", il);
  5132. struct ggml_tensor * Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5133. cb(Kcur, "Kcur", il);
  5134. struct ggml_tensor * Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5135. cb(Vcur, "Vcur", il);
  5136. // seems like we just need to do this for Q?
  5137. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5138. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5139. model.layers[il].wo, model.layers[il].bo,
  5140. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5141. cb(cur, "kqv_out", il);
  5142. } else {
  5143. // compute Q and K and RoPE them
  5144. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5145. cb(cur, "wqkv", il);
  5146. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5147. 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)));
  5148. 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)));
  5149. cb(Qcur, "Qcur", il);
  5150. cb(Kcur, "Kcur", il);
  5151. cb(Vcur, "Vcur", il);
  5152. Qcur = ggml_rope_custom(
  5153. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5154. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5155. ext_factor, attn_factor, beta_fast, beta_slow
  5156. );
  5157. cb(Qcur, "Qcur", il);
  5158. Kcur = ggml_rope_custom(
  5159. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5160. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5161. ext_factor, attn_factor, beta_fast, beta_slow
  5162. );
  5163. cb(Kcur, "Kcur", il);
  5164. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5165. model.layers[il].wo, model.layers[il].bo,
  5166. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5167. cb(cur, "kqv_out", il);
  5168. }
  5169. // re-add the layer input
  5170. cur = ggml_add(ctx0, cur, inpL);
  5171. // attention layer norm
  5172. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5173. struct ggml_tensor * ffn_inp = cur;
  5174. cb(ffn_inp, "ffn_inp", il);
  5175. // feed-forward network
  5176. if (model.arch == LLM_ARCH_BERT) {
  5177. cur = llm_build_ffn(ctx0, cur,
  5178. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5179. NULL, NULL,
  5180. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5181. NULL,
  5182. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5183. } else {
  5184. cur = llm_build_ffn(ctx0, cur,
  5185. model.layers[il].ffn_up, NULL,
  5186. model.layers[il].ffn_gate, NULL,
  5187. model.layers[il].ffn_down, NULL,
  5188. NULL,
  5189. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5190. }
  5191. cb(cur, "ffn_out", il);
  5192. // attentions bypass the intermediate layer
  5193. cur = ggml_add(ctx0, cur, ffn_inp);
  5194. // output layer norm
  5195. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5196. // input for next layer
  5197. inpL = cur;
  5198. }
  5199. // final output
  5200. cur = inpL;
  5201. // pooling layer
  5202. if (pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  5203. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5204. } else if (pooling_type == LLAMA_POOLING_TYPE_CLS) {
  5205. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5206. } else {
  5207. GGML_ASSERT(pooling_type == LLAMA_POOLING_TYPE_NONE && "Invalid pooling type");
  5208. }
  5209. cb(cur, "result_embd", -1);
  5210. ggml_build_forward_expand(gf, cur);
  5211. return gf;
  5212. }
  5213. struct ggml_cgraph * build_bloom() {
  5214. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5215. const int64_t n_embd_head = hparams.n_embd_head_v;
  5216. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5217. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5218. struct ggml_tensor * cur;
  5219. struct ggml_tensor * inpL;
  5220. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5221. cb(inpL, "inp_embd", -1);
  5222. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5223. 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);
  5224. cb(KQ_mask, "KQ_mask", -1);
  5225. // positions of the tokens in the KV cache
  5226. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5227. cb(KQ_pos, "KQ_pos", -1);
  5228. inpL = llm_build_norm(ctx0, inpL, hparams,
  5229. model.tok_norm,
  5230. model.tok_norm_b,
  5231. LLM_NORM, cb, -1);
  5232. cb(inpL, "inp_norm", -1);
  5233. for (int il = 0; il < n_layer; ++il) {
  5234. cur = llm_build_norm(ctx0, inpL, hparams,
  5235. model.layers[il].attn_norm,
  5236. model.layers[il].attn_norm_b,
  5237. LLM_NORM, cb, il);
  5238. cb(cur, "attn_norm", il);
  5239. // self-attention
  5240. {
  5241. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5242. cb(cur, "wqkv", il);
  5243. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5244. cb(cur, "bqkv", il);
  5245. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5246. 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)));
  5247. 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)));
  5248. cb(Qcur, "Qcur", il);
  5249. cb(Kcur, "Kcur", il);
  5250. cb(Vcur, "Vcur", il);
  5251. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5252. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5253. model.layers[il].wo, model.layers[il].bo,
  5254. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5255. cb(cur, "kqv_out", il);
  5256. }
  5257. // Add the input
  5258. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5259. cb(ffn_inp, "ffn_inp", il);
  5260. // FF
  5261. {
  5262. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5263. model.layers[il].ffn_norm,
  5264. model.layers[il].ffn_norm_b,
  5265. LLM_NORM, cb, il);
  5266. cb(cur, "ffn_norm", il);
  5267. cur = llm_build_ffn(ctx0, cur,
  5268. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5269. NULL, NULL,
  5270. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5271. NULL,
  5272. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5273. cb(cur, "ffn_out", il);
  5274. }
  5275. inpL = ggml_add(ctx0, cur, ffn_inp);
  5276. cb(inpL, "l_out", il);
  5277. }
  5278. cur = llm_build_norm(ctx0, inpL, hparams,
  5279. model.output_norm,
  5280. model.output_norm_b,
  5281. LLM_NORM, cb, -1);
  5282. cb(cur, "result_norm", -1);
  5283. cur = ggml_mul_mat(ctx0, model.output, cur);
  5284. cb(cur, "result_output", -1);
  5285. ggml_build_forward_expand(gf, cur);
  5286. return gf;
  5287. }
  5288. struct ggml_cgraph * build_mpt() {
  5289. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5290. const int64_t n_embd_head = hparams.n_embd_head_v;
  5291. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5292. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5293. struct ggml_tensor * cur;
  5294. struct ggml_tensor * inpL;
  5295. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5296. cb(inpL, "inp_embd", -1);
  5297. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5298. 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);
  5299. cb(KQ_mask, "KQ_mask", -1);
  5300. // positions of the tokens in the KV cache
  5301. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5302. cb(KQ_pos, "KQ_pos", -1);
  5303. for (int il = 0; il < n_layer; ++il) {
  5304. struct ggml_tensor * attn_norm;
  5305. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5306. model.layers[il].attn_norm,
  5307. model.layers[il].attn_norm_b,
  5308. LLM_NORM, cb, il);
  5309. cb(attn_norm, "attn_norm", il);
  5310. // self-attention
  5311. {
  5312. cur = attn_norm;
  5313. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5314. cb(cur, "wqkv", il);
  5315. if (model.layers[il].bqkv){
  5316. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5317. cb(cur, "bqkv", il);
  5318. }
  5319. if (hparams.f_clamp_kqv > 0.0f) {
  5320. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5321. cb(cur, "wqkv_clamped", il);
  5322. }
  5323. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5324. 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)));
  5325. 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)));
  5326. cb(Qcur, "Qcur", il);
  5327. cb(Kcur, "Kcur", il);
  5328. cb(Vcur, "Vcur", il);
  5329. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5330. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5331. model.layers[il].wo, model.layers[il].bo,
  5332. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5333. cb(cur, "kqv_out", il);
  5334. }
  5335. // Add the input
  5336. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5337. cb(ffn_inp, "ffn_inp", il);
  5338. // feed forward
  5339. {
  5340. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5341. model.layers[il].ffn_norm,
  5342. model.layers[il].ffn_norm_b,
  5343. LLM_NORM, cb, il);
  5344. cb(cur, "ffn_norm", il);
  5345. cur = llm_build_ffn(ctx0, cur,
  5346. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5347. NULL, NULL,
  5348. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5349. model.layers[il].ffn_act,
  5350. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5351. cb(cur, "ffn_out", il);
  5352. }
  5353. cur = ggml_add(ctx0, cur, ffn_inp);
  5354. cb(cur, "l_out", il);
  5355. // input for next layer
  5356. inpL = cur;
  5357. }
  5358. cur = inpL;
  5359. cur = llm_build_norm(ctx0, cur, hparams,
  5360. model.output_norm,
  5361. model.output_norm_b,
  5362. LLM_NORM, cb, -1);
  5363. cb(cur, "result_norm", -1);
  5364. cur = ggml_mul_mat(ctx0, model.output, cur);
  5365. cb(cur, "result_output", -1);
  5366. ggml_build_forward_expand(gf, cur);
  5367. return gf;
  5368. }
  5369. struct ggml_cgraph * build_stablelm() {
  5370. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5371. const int64_t n_embd_head = hparams.n_embd_head_v;
  5372. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5373. struct ggml_tensor * cur;
  5374. struct ggml_tensor * inpL;
  5375. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5376. cb(inpL, "inp_embd", -1);
  5377. // inp_pos - contains the positions
  5378. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5379. cb(inp_pos, "inp_pos", -1);
  5380. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5381. 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);
  5382. cb(KQ_mask, "KQ_mask", -1);
  5383. for (int il = 0; il < n_layer; ++il) {
  5384. struct ggml_tensor * inpSA = inpL;
  5385. // norm
  5386. cur = llm_build_norm(ctx0, inpL, hparams,
  5387. model.layers[il].attn_norm,
  5388. model.layers[il].attn_norm_b,
  5389. LLM_NORM, cb, il);
  5390. cb(cur, "attn_norm", il);
  5391. // self-attention
  5392. {
  5393. // compute Q and K and RoPE them
  5394. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5395. cb(Qcur, "Qcur", il);
  5396. if (model.layers[il].bq) {
  5397. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5398. cb(Qcur, "Qcur", il);
  5399. }
  5400. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5401. cb(Kcur, "Kcur", il);
  5402. if (model.layers[il].bk) {
  5403. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5404. cb(Kcur, "Kcur", il);
  5405. }
  5406. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5407. cb(Vcur, "Vcur", il);
  5408. if (model.layers[il].bv) {
  5409. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5410. cb(Vcur, "Vcur", il);
  5411. }
  5412. Qcur = ggml_rope_custom(
  5413. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5414. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5415. ext_factor, attn_factor, beta_fast, beta_slow
  5416. );
  5417. cb(Qcur, "Qcur", il);
  5418. Kcur = ggml_rope_custom(
  5419. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5420. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5421. ext_factor, attn_factor, beta_fast, beta_slow
  5422. );
  5423. cb(Kcur, "Kcur", il);
  5424. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5425. model.layers[il].wo, NULL,
  5426. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5427. cb(cur, "kqv_out", il);
  5428. }
  5429. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5430. cb(ffn_inp, "ffn_inp", il);
  5431. // feed-forward network
  5432. {
  5433. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5434. model.layers[il].ffn_norm,
  5435. model.layers[il].ffn_norm_b,
  5436. LLM_NORM, cb, il);
  5437. cb(cur, "ffn_norm", il);
  5438. cur = llm_build_ffn(ctx0, cur,
  5439. model.layers[il].ffn_up, NULL,
  5440. model.layers[il].ffn_gate, NULL,
  5441. model.layers[il].ffn_down, NULL,
  5442. NULL,
  5443. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5444. cb(cur, "ffn_out", il);
  5445. }
  5446. cur = ggml_add(ctx0, cur, ffn_inp);
  5447. cb(cur, "l_out", il);
  5448. // input for next layer
  5449. inpL = cur;
  5450. }
  5451. cur = inpL;
  5452. cur = llm_build_norm(ctx0, cur, hparams,
  5453. model.output_norm,
  5454. model.output_norm_b,
  5455. LLM_NORM, cb, -1);
  5456. cb(cur, "result_norm", -1);
  5457. // lm_head
  5458. cur = ggml_mul_mat(ctx0, model.output, cur);
  5459. cb(cur, "result_output", -1);
  5460. ggml_build_forward_expand(gf, cur);
  5461. return gf;
  5462. }
  5463. struct ggml_cgraph * build_qwen() {
  5464. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5465. const int64_t n_embd_head = hparams.n_embd_head_v;
  5466. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5467. struct ggml_tensor * cur;
  5468. struct ggml_tensor * inpL;
  5469. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5470. cb(inpL, "inp_embd", -1);
  5471. // inp_pos - contains the positions
  5472. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5473. cb(inp_pos, "inp_pos", -1);
  5474. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5475. 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);
  5476. cb(KQ_mask, "KQ_mask", -1);
  5477. for (int il = 0; il < n_layer; ++il) {
  5478. struct ggml_tensor * inpSA = inpL;
  5479. cur = llm_build_norm(ctx0, inpL, hparams,
  5480. model.layers[il].attn_norm, NULL,
  5481. LLM_NORM_RMS, cb, il);
  5482. cb(cur, "attn_norm", il);
  5483. // self-attention
  5484. {
  5485. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5486. cb(cur, "wqkv", il);
  5487. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5488. cb(cur, "bqkv", il);
  5489. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5490. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5491. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5492. cb(Qcur, "Qcur", il);
  5493. cb(Kcur, "Kcur", il);
  5494. cb(Vcur, "Vcur", il);
  5495. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5496. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5497. // using mode = 2 for neox mode
  5498. Qcur = ggml_rope_custom(
  5499. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5500. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5501. );
  5502. cb(Qcur, "Qcur", il);
  5503. Kcur = ggml_rope_custom(
  5504. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5505. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5506. );
  5507. cb(Kcur, "Kcur", il);
  5508. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5509. model.layers[il].wo, NULL,
  5510. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5511. cb(cur, "kqv_out", il);
  5512. }
  5513. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5514. cb(ffn_inp, "ffn_inp", il);
  5515. // feed-forward forward
  5516. {
  5517. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5518. model.layers[il].ffn_norm, NULL,
  5519. LLM_NORM_RMS, cb, il);
  5520. cb(cur, "ffn_norm", il);
  5521. cur = llm_build_ffn(ctx0, cur,
  5522. model.layers[il].ffn_up, NULL,
  5523. model.layers[il].ffn_gate, NULL,
  5524. model.layers[il].ffn_down, NULL,
  5525. NULL,
  5526. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5527. cb(cur, "ffn_out", il);
  5528. }
  5529. cur = ggml_add(ctx0, cur, ffn_inp);
  5530. cb(cur, "l_out", il);
  5531. // input for next layer
  5532. inpL = cur;
  5533. }
  5534. cur = inpL;
  5535. cur = llm_build_norm(ctx0, cur, hparams,
  5536. model.output_norm, NULL,
  5537. LLM_NORM_RMS, cb, -1);
  5538. cb(cur, "result_norm", -1);
  5539. // lm_head
  5540. cur = ggml_mul_mat(ctx0, model.output, cur);
  5541. cb(cur, "result_output", -1);
  5542. ggml_build_forward_expand(gf, cur);
  5543. return gf;
  5544. }
  5545. struct ggml_cgraph * build_qwen2() {
  5546. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5547. const int64_t n_embd_head = hparams.n_embd_head_v;
  5548. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5549. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5550. struct ggml_tensor * cur;
  5551. struct ggml_tensor * inpL;
  5552. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5553. cb(inpL, "inp_embd", -1);
  5554. // inp_pos - contains the positions
  5555. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5556. cb(inp_pos, "inp_pos", -1);
  5557. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5558. 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);
  5559. cb(KQ_mask, "KQ_mask", -1);
  5560. for (int il = 0; il < n_layer; ++il) {
  5561. struct ggml_tensor * inpSA = inpL;
  5562. // norm
  5563. cur = llm_build_norm(ctx0, inpL, hparams,
  5564. model.layers[il].attn_norm, NULL,
  5565. LLM_NORM_RMS, cb, il);
  5566. cb(cur, "attn_norm", il);
  5567. // self-attention
  5568. {
  5569. // compute Q and K and RoPE them
  5570. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5571. cb(Qcur, "Qcur", il);
  5572. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5573. cb(Qcur, "Qcur", il);
  5574. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5575. cb(Kcur, "Kcur", il);
  5576. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5577. cb(Kcur, "Kcur", il);
  5578. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5579. cb(Vcur, "Vcur", il);
  5580. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5581. cb(Vcur, "Vcur", il);
  5582. // these nodes are added to the graph together so that they are not reordered
  5583. // by doing so, the number of splits in the graph is reduced
  5584. ggml_build_forward_expand(gf, Qcur);
  5585. ggml_build_forward_expand(gf, Kcur);
  5586. ggml_build_forward_expand(gf, Vcur);
  5587. Qcur = ggml_rope_custom(
  5588. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5589. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5590. ext_factor, attn_factor, beta_fast, beta_slow
  5591. );
  5592. cb(Qcur, "Qcur", il);
  5593. Kcur = ggml_rope_custom(
  5594. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5595. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5596. ext_factor, attn_factor, beta_fast, beta_slow
  5597. );
  5598. cb(Kcur, "Kcur", il);
  5599. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5600. model.layers[il].wo, model.layers[il].bo,
  5601. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5602. cb(cur, "kqv_out", il);
  5603. }
  5604. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5605. cb(ffn_inp, "ffn_inp", il);
  5606. // feed-forward network
  5607. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5608. model.layers[il].ffn_norm, NULL,
  5609. LLM_NORM_RMS, cb, il);
  5610. cb(cur, "ffn_norm", il);
  5611. cur = llm_build_ffn(ctx0, cur,
  5612. model.layers[il].ffn_up, NULL,
  5613. model.layers[il].ffn_gate, NULL,
  5614. model.layers[il].ffn_down, NULL,
  5615. NULL,
  5616. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5617. cb(cur, "ffn_out", il);
  5618. cur = ggml_add(ctx0, cur, ffn_inp);
  5619. cb(cur, "l_out", il);
  5620. // input for next layer
  5621. inpL = cur;
  5622. }
  5623. cur = inpL;
  5624. cur = llm_build_norm(ctx0, cur, hparams,
  5625. model.output_norm, NULL,
  5626. LLM_NORM_RMS, cb, -1);
  5627. cb(cur, "result_norm", -1);
  5628. // lm_head
  5629. cur = ggml_mul_mat(ctx0, model.output, cur);
  5630. cb(cur, "result_output", -1);
  5631. ggml_build_forward_expand(gf, cur);
  5632. return gf;
  5633. }
  5634. struct ggml_cgraph * build_phi2() {
  5635. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5636. const int64_t n_embd_head = hparams.n_embd_head_v;
  5637. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5638. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5639. struct ggml_tensor * cur;
  5640. struct ggml_tensor * attn_norm_output;
  5641. struct ggml_tensor * ffn_output;
  5642. struct ggml_tensor * inpL;
  5643. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5644. cb(inpL, "inp_embd", -1);
  5645. // inp_pos - contains the positions
  5646. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5647. cb(inp_pos, "inp_pos", -1);
  5648. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5649. 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);
  5650. cb(KQ_mask, "KQ_mask", -1);
  5651. for (int il = 0; il < n_layer; ++il) {
  5652. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5653. model.layers[il].attn_norm,
  5654. model.layers[il].attn_norm_b,
  5655. LLM_NORM, cb, il);
  5656. cb(attn_norm_output, "attn_norm", il);
  5657. // self-attention
  5658. {
  5659. struct ggml_tensor * Qcur = nullptr;
  5660. struct ggml_tensor * Kcur = nullptr;
  5661. struct ggml_tensor * Vcur = nullptr;
  5662. if (model.layers[il].wqkv) {
  5663. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5664. cb(cur, "wqkv", il);
  5665. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5666. cb(cur, "bqkv", il);
  5667. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5668. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5669. 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)));
  5670. } else {
  5671. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5672. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5673. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5674. }
  5675. cb(Qcur, "Qcur", il);
  5676. cb(Kcur, "Kcur", il);
  5677. cb(Vcur, "Vcur", il);
  5678. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5679. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5680. Qcur = ggml_rope_custom(
  5681. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5682. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5683. );
  5684. cb(Qcur, "Qcur", il);
  5685. // with phi2, we scale the Q to avoid precision issues
  5686. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5687. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5688. cb(Qcur, "Qcur", il);
  5689. Kcur = ggml_rope_custom(
  5690. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5691. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5692. );
  5693. cb(Kcur, "Kcur", il);
  5694. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5695. model.layers[il].wo, model.layers[il].bo,
  5696. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5697. cb(cur, "kqv_out", il);
  5698. }
  5699. // FF
  5700. {
  5701. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5702. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5703. NULL, NULL,
  5704. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5705. NULL,
  5706. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5707. cb(ffn_output, "ffn_out", il);
  5708. }
  5709. cur = ggml_add(ctx0, cur, ffn_output);
  5710. cb(cur, "l_out", il);
  5711. cur = ggml_add(ctx0, cur, inpL);
  5712. cb(cur, "l_out", il);
  5713. inpL = cur;
  5714. }
  5715. cur = llm_build_norm(ctx0, inpL, hparams,
  5716. model.output_norm,
  5717. model.output_norm_b,
  5718. LLM_NORM, cb, -1);
  5719. cb(cur, "result_norm", -1);
  5720. cur = ggml_mul_mat(ctx0, model.output, cur);
  5721. cb(cur, "result_output_no_bias", -1);
  5722. cur = ggml_add(ctx0, cur, model.output_b);
  5723. cb(cur, "result_output", -1);
  5724. ggml_build_forward_expand(gf, cur);
  5725. return gf;
  5726. }
  5727. struct ggml_cgraph * build_plamo() {
  5728. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5729. const int64_t n_embd_head = hparams.n_embd_head_v;
  5730. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5731. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5732. struct ggml_tensor * cur;
  5733. struct ggml_tensor * inpL;
  5734. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5735. cb(inpL, "inp_embd", -1);
  5736. // inp_pos - contains the positions
  5737. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5738. cb(inp_pos, "inp_pos", -1);
  5739. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5740. 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);
  5741. cb(KQ_mask, "KQ_mask", -1);
  5742. for (int il = 0; il < n_layer; ++il) {
  5743. // norm
  5744. cur = llm_build_norm(ctx0, inpL, hparams,
  5745. model.layers[il].attn_norm, NULL,
  5746. LLM_NORM_RMS, cb, il);
  5747. cb(cur, "attn_norm", il);
  5748. struct ggml_tensor * attention_norm = cur;
  5749. // self-attention
  5750. {
  5751. // compute Q and K and RoPE them
  5752. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5753. cb(Qcur, "Qcur", il);
  5754. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5755. cb(Kcur, "Kcur", il);
  5756. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5757. cb(Vcur, "Vcur", il);
  5758. Qcur = ggml_rope_custom(
  5759. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  5760. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5761. ext_factor, attn_factor, beta_fast, beta_slow);
  5762. cb(Qcur, "Qcur", il);
  5763. Kcur = ggml_rope_custom(
  5764. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  5765. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5766. ext_factor, attn_factor, beta_fast, beta_slow);
  5767. cb(Kcur, "Kcur", il);
  5768. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5769. model.layers[il].wo, NULL,
  5770. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5771. cb(cur, "kqv_out", il);
  5772. }
  5773. struct ggml_tensor * sa_out = cur;
  5774. cur = attention_norm;
  5775. // feed-forward network
  5776. {
  5777. cur = llm_build_ffn(ctx0, cur,
  5778. model.layers[il].ffn_up, NULL,
  5779. model.layers[il].ffn_gate, NULL,
  5780. model.layers[il].ffn_down, NULL,
  5781. NULL,
  5782. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5783. cb(cur, "ffn_out", il);
  5784. }
  5785. cur = ggml_add(ctx0, cur, sa_out);
  5786. cb(cur, "l_out", il);
  5787. cur = ggml_add(ctx0, cur, inpL);
  5788. cb(cur, "l_out", il);
  5789. // input for next layer
  5790. inpL = cur;
  5791. }
  5792. cur = inpL;
  5793. cur = llm_build_norm(ctx0, cur, hparams,
  5794. model.output_norm, NULL,
  5795. LLM_NORM_RMS, cb, -1);
  5796. cb(cur, "result_norm", -1);
  5797. // lm_head
  5798. cur = ggml_mul_mat(ctx0, model.output, cur);
  5799. cb(cur, "result_output", -1);
  5800. ggml_build_forward_expand(gf, cur);
  5801. return gf;
  5802. }
  5803. struct ggml_cgraph * build_gpt2() {
  5804. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5805. const int64_t n_embd_head = hparams.n_embd_head_v;
  5806. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5807. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5808. struct ggml_tensor * cur;
  5809. struct ggml_tensor * pos;
  5810. struct ggml_tensor * inpL;
  5811. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5812. cb(inpL, "inp_embd", -1);
  5813. // inp_pos - contains the positions
  5814. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5815. cb(inp_pos, "inp_pos", -1);
  5816. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5817. 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);
  5818. cb(KQ_mask, "KQ_mask", -1);
  5819. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5820. cb(pos, "pos_embd", -1);
  5821. inpL = ggml_add(ctx0, inpL, pos);
  5822. cb(inpL, "inpL", -1);
  5823. for (int il = 0; il < n_layer; ++il) {
  5824. cur = llm_build_norm(ctx0, inpL, hparams,
  5825. model.layers[il].attn_norm,
  5826. model.layers[il].attn_norm_b,
  5827. LLM_NORM, cb, il);
  5828. cb(cur, "attn_norm", il);
  5829. // self-attention
  5830. {
  5831. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5832. cb(cur, "wqkv", il);
  5833. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5834. cb(cur, "bqkv", il);
  5835. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5836. 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)));
  5837. 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)));
  5838. cb(Qcur, "Qcur", il);
  5839. cb(Kcur, "Kcur", il);
  5840. cb(Vcur, "Vcur", il);
  5841. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5842. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5843. model.layers[il].wo, model.layers[il].bo,
  5844. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5845. cb(cur, "kqv_out", il);
  5846. }
  5847. // add the input
  5848. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5849. cb(ffn_inp, "ffn_inp", il);
  5850. // FF
  5851. {
  5852. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5853. model.layers[il].ffn_norm,
  5854. model.layers[il].ffn_norm_b,
  5855. LLM_NORM, cb, il);
  5856. cb(cur, "ffn_norm", il);
  5857. cur = llm_build_ffn(ctx0, cur,
  5858. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5859. NULL, NULL,
  5860. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5861. NULL,
  5862. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5863. cb(cur, "ffn_out", il);
  5864. }
  5865. inpL = ggml_add(ctx0, cur, ffn_inp);
  5866. cb(inpL, "l_out", il);
  5867. }
  5868. cur = llm_build_norm(ctx0, inpL, hparams,
  5869. model.output_norm,
  5870. model.output_norm_b,
  5871. LLM_NORM, cb, -1);
  5872. cb(cur, "result_norm", -1);
  5873. cur = ggml_mul_mat(ctx0, model.output, cur);
  5874. cb(cur, "result_output", -1);
  5875. ggml_build_forward_expand(gf, cur);
  5876. return gf;
  5877. }
  5878. struct ggml_cgraph * build_codeshell() {
  5879. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5880. const int64_t n_embd_head = hparams.n_embd_head_v;
  5881. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5882. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5883. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5884. struct ggml_tensor * cur;
  5885. struct ggml_tensor * inpL;
  5886. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5887. cb(inpL, "inp_embd", -1);
  5888. // inp_pos - contains the positions
  5889. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5890. cb(inp_pos, "inp_pos", -1);
  5891. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5892. 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);
  5893. cb(KQ_mask, "KQ_mask", -1);
  5894. for (int il = 0; il < n_layer; ++il) {
  5895. cur = llm_build_norm(ctx0, inpL, hparams,
  5896. model.layers[il].attn_norm,
  5897. model.layers[il].attn_norm_b,
  5898. LLM_NORM, cb, il);
  5899. cb(cur, "attn_norm", il);
  5900. // self-attention
  5901. {
  5902. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5903. cb(cur, "wqkv", il);
  5904. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5905. cb(cur, "bqkv", il);
  5906. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5907. 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)));
  5908. 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)));
  5909. cb(tmpq, "tmpq", il);
  5910. cb(tmpk, "tmpk", il);
  5911. cb(Vcur, "Vcur", il);
  5912. struct ggml_tensor * Qcur = ggml_rope_custom(
  5913. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5914. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5915. ext_factor, attn_factor, beta_fast, beta_slow
  5916. );
  5917. cb(Qcur, "Qcur", il);
  5918. struct ggml_tensor * Kcur = ggml_rope_custom(
  5919. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5920. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5921. ext_factor, attn_factor, beta_fast, beta_slow
  5922. );
  5923. cb(Kcur, "Kcur", il);
  5924. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5925. model.layers[il].wo, model.layers[il].bo,
  5926. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5927. cb(cur, "kqv_out", il);
  5928. }
  5929. // add the input
  5930. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5931. cb(ffn_inp, "ffn_inp", il);
  5932. // FF
  5933. {
  5934. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5935. model.layers[il].ffn_norm,
  5936. model.layers[il].ffn_norm_b,
  5937. LLM_NORM, cb, il);
  5938. cb(cur, "ffn_norm", il);
  5939. cur = llm_build_ffn(ctx0, cur,
  5940. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5941. NULL, NULL,
  5942. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5943. NULL,
  5944. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5945. cb(cur, "ffn_out", il);
  5946. }
  5947. inpL = ggml_add(ctx0, cur, ffn_inp);
  5948. cb(inpL, "l_out", il);
  5949. }
  5950. cur = llm_build_norm(ctx0, inpL, hparams,
  5951. model.output_norm,
  5952. model.output_norm_b,
  5953. LLM_NORM, cb, -1);
  5954. cb(cur, "result_norm", -1);
  5955. cur = ggml_mul_mat(ctx0, model.output, cur);
  5956. cb(cur, "result_output", -1);
  5957. ggml_build_forward_expand(gf, cur);
  5958. return gf;
  5959. }
  5960. struct ggml_cgraph * build_orion() {
  5961. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5962. const int64_t n_embd_head = hparams.n_embd_head_v;
  5963. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5964. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5965. struct ggml_tensor * cur;
  5966. struct ggml_tensor * inpL;
  5967. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5968. cb(inpL, "inp_embd", -1);
  5969. // inp_pos - contains the positions
  5970. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5971. cb(inp_pos, "inp_pos", -1);
  5972. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5973. 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);
  5974. cb(KQ_mask, "KQ_mask", -1);
  5975. for (int il = 0; il < n_layer; ++il) {
  5976. struct ggml_tensor * inpSA = inpL;
  5977. // norm
  5978. cur = llm_build_norm(ctx0, inpL, hparams,
  5979. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  5980. LLM_NORM, cb, il);
  5981. cb(cur, "attn_norm", il);
  5982. // self-attention
  5983. {
  5984. // compute Q and K and RoPE them
  5985. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5986. cb(Qcur, "Qcur", il);
  5987. // if (model.layers[il].bq) {
  5988. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5989. // cb(Qcur, "Qcur", il);
  5990. // }
  5991. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5992. cb(Kcur, "Kcur", il);
  5993. // if (model.layers[il].bk) {
  5994. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5995. // cb(Kcur, "Kcur", il);
  5996. // }
  5997. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5998. cb(Vcur, "Vcur", il);
  5999. // if (model.layers[il].bv) {
  6000. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6001. // cb(Vcur, "Vcur", il);
  6002. // }
  6003. Qcur = ggml_rope_custom(
  6004. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6005. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6006. ext_factor, attn_factor, beta_fast, beta_slow
  6007. );
  6008. cb(Qcur, "Qcur", il);
  6009. Kcur = ggml_rope_custom(
  6010. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6011. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6012. ext_factor, attn_factor, beta_fast, beta_slow
  6013. );
  6014. cb(Kcur, "Kcur", il);
  6015. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6016. model.layers[il].wo, NULL,
  6017. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6018. cb(cur, "kqv_out", il);
  6019. }
  6020. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6021. cb(ffn_inp, "ffn_inp", il);
  6022. // feed-forward network
  6023. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6024. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6025. LLM_NORM, cb, il);
  6026. cb(cur, "ffn_norm", il);
  6027. cur = llm_build_ffn(ctx0, cur,
  6028. model.layers[il].ffn_up, NULL,
  6029. model.layers[il].ffn_gate, NULL,
  6030. model.layers[il].ffn_down, NULL,
  6031. NULL,
  6032. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6033. cb(cur, "ffn_out", il);
  6034. cur = ggml_add(ctx0, cur, ffn_inp);
  6035. cb(cur, "l_out", il);
  6036. // input for next layer
  6037. inpL = cur;
  6038. }
  6039. cur = inpL;
  6040. cur = llm_build_norm(ctx0, cur, hparams,
  6041. model.output_norm, model.output_norm_b,
  6042. LLM_NORM, cb, -1);
  6043. cb(cur, "result_norm", -1);
  6044. // lm_head
  6045. cur = ggml_mul_mat(ctx0, model.output, cur);
  6046. cb(cur, "result_output", -1);
  6047. ggml_build_forward_expand(gf, cur);
  6048. return gf;
  6049. }
  6050. struct ggml_cgraph * build_internlm2() {
  6051. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6052. const int64_t n_embd_head = hparams.n_embd_head_v;
  6053. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6054. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6055. struct ggml_tensor * cur;
  6056. struct ggml_tensor * inpL;
  6057. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6058. cb(inpL, "inp_embd", -1);
  6059. // inp_pos - contains the positions
  6060. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6061. cb(inp_pos, "inp_pos", -1);
  6062. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6063. 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);
  6064. cb(KQ_mask, "KQ_mask", -1);
  6065. for (int il = 0; il < n_layer; ++il) {
  6066. struct ggml_tensor * inpSA = inpL;
  6067. // norm
  6068. cur = llm_build_norm(ctx0, inpL, hparams,
  6069. model.layers[il].attn_norm, NULL,
  6070. LLM_NORM_RMS, cb, il);
  6071. cb(cur, "attn_norm", il);
  6072. // self-attention
  6073. {
  6074. // compute Q and K and RoPE them
  6075. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6076. cb(Qcur, "Qcur", il);
  6077. if (model.layers[il].bq) {
  6078. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6079. cb(Qcur, "Qcur", il);
  6080. }
  6081. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6082. cb(Kcur, "Kcur", il);
  6083. if (model.layers[il].bk) {
  6084. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6085. cb(Kcur, "Kcur", il);
  6086. }
  6087. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6088. cb(Vcur, "Vcur", il);
  6089. if (model.layers[il].bv) {
  6090. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6091. cb(Vcur, "Vcur", il);
  6092. }
  6093. Qcur = ggml_rope_custom(
  6094. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6095. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6096. ext_factor, attn_factor, beta_fast, beta_slow
  6097. );
  6098. cb(Qcur, "Qcur", il);
  6099. Kcur = ggml_rope_custom(
  6100. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6101. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6102. ext_factor, attn_factor, beta_fast, beta_slow
  6103. );
  6104. cb(Kcur, "Kcur", il);
  6105. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6106. model.layers[il].wo, model.layers[il].bo,
  6107. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6108. cb(cur, "kqv_out", il);
  6109. }
  6110. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6111. cb(ffn_inp, "ffn_inp", il);
  6112. // feed-forward network
  6113. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6114. model.layers[il].ffn_norm, NULL,
  6115. LLM_NORM_RMS, cb, il);
  6116. cb(cur, "ffn_norm", il);
  6117. cur = llm_build_ffn(ctx0, cur,
  6118. model.layers[il].ffn_up, NULL,
  6119. model.layers[il].ffn_gate, NULL,
  6120. model.layers[il].ffn_down, NULL,
  6121. NULL,
  6122. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6123. cb(cur, "ffn_out", il);
  6124. cur = ggml_add(ctx0, cur, ffn_inp);
  6125. cb(cur, "l_out", il);
  6126. // input for next layer
  6127. inpL = cur;
  6128. }
  6129. cur = inpL;
  6130. cur = llm_build_norm(ctx0, cur, hparams,
  6131. model.output_norm, NULL,
  6132. LLM_NORM_RMS, cb, -1);
  6133. cb(cur, "result_norm", -1);
  6134. // lm_head
  6135. cur = ggml_mul_mat(ctx0, model.output, cur);
  6136. cb(cur, "result_output", -1);
  6137. ggml_build_forward_expand(gf, cur);
  6138. return gf;
  6139. }
  6140. // ref: https://arxiv.org/abs/2203.03466
  6141. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6142. // based on the original build_llama() function
  6143. struct ggml_cgraph * build_minicpm() {
  6144. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6145. const int64_t n_embd_head = hparams.n_embd_head_v;
  6146. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6147. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6148. const int64_t n_embd = hparams.n_embd;
  6149. //TODO: if the model varies, these parameters need to be read from the model
  6150. const int64_t n_embd_base = 256;
  6151. const float scale_embd = 12.0f;
  6152. const float scale_depth = 1.4f;
  6153. struct ggml_tensor * cur;
  6154. struct ggml_tensor * inpL;
  6155. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6156. cb(inpL, "inp_embd", -1);
  6157. // scale the input embeddings
  6158. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6159. cb(inpL, "inp_scaled", -1);
  6160. // inp_pos - contains the positions
  6161. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6162. cb(inp_pos, "inp_pos", -1);
  6163. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6164. 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);
  6165. cb(KQ_mask, "KQ_mask", -1);
  6166. for (int il = 0; il < n_layer; ++il) {
  6167. struct ggml_tensor * inpSA = inpL;
  6168. // norm
  6169. cur = llm_build_norm(ctx0, inpL, hparams,
  6170. model.layers[il].attn_norm, NULL,
  6171. LLM_NORM_RMS, cb, il);
  6172. cb(cur, "attn_norm", il);
  6173. // self-attention
  6174. {
  6175. // compute Q and K and RoPE them
  6176. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6177. cb(Qcur, "Qcur", il);
  6178. if (model.layers[il].bq) {
  6179. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6180. cb(Qcur, "Qcur", il);
  6181. }
  6182. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6183. cb(Kcur, "Kcur", il);
  6184. if (model.layers[il].bk) {
  6185. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6186. cb(Kcur, "Kcur", il);
  6187. }
  6188. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6189. cb(Vcur, "Vcur", il);
  6190. if (model.layers[il].bv) {
  6191. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6192. cb(Vcur, "Vcur", il);
  6193. }
  6194. Qcur = ggml_rope_custom(
  6195. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6196. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6197. ext_factor, attn_factor, beta_fast, beta_slow
  6198. );
  6199. cb(Qcur, "Qcur", il);
  6200. Kcur = ggml_rope_custom(
  6201. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6202. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6203. ext_factor, attn_factor, beta_fast, beta_slow
  6204. );
  6205. cb(Kcur, "Kcur", il);
  6206. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6207. model.layers[il].wo, model.layers[il].bo,
  6208. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6209. cb(cur, "kqv_out", il);
  6210. }
  6211. // scale_res - scale the hidden states for residual connection
  6212. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6213. cur = ggml_scale(ctx0, cur, scale_res);
  6214. cb(cur, "hidden_scaled", -1);
  6215. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6216. cb(ffn_inp, "ffn_inp", il);
  6217. // feed-forward network
  6218. {
  6219. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6220. model.layers[il].ffn_norm, NULL,
  6221. LLM_NORM_RMS, cb, il);
  6222. cb(cur, "ffn_norm", il);
  6223. cur = llm_build_ffn(ctx0, cur,
  6224. model.layers[il].ffn_up, NULL,
  6225. model.layers[il].ffn_gate, NULL,
  6226. model.layers[il].ffn_down, NULL,
  6227. NULL,
  6228. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6229. cb(cur, "ffn_out", il);
  6230. }
  6231. // scale the hidden states for residual connection
  6232. cur = ggml_scale(ctx0, cur, scale_res);
  6233. cb(cur, "hidden_scaled_ffn", -1);
  6234. cur = ggml_add(ctx0, cur, ffn_inp);
  6235. cb(cur, "l_out", il);
  6236. // input for next layer
  6237. inpL = cur;
  6238. }
  6239. cur = inpL;
  6240. cur = llm_build_norm(ctx0, cur, hparams,
  6241. model.output_norm, NULL,
  6242. LLM_NORM_RMS, cb, -1);
  6243. cb(cur, "result_norm", -1);
  6244. // lm_head scaling
  6245. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6246. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6247. cb(cur, "lmhead_scaling", -1);
  6248. // lm_head
  6249. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6250. cb(cur, "result_output", -1);
  6251. ggml_build_forward_expand(gf, cur);
  6252. return gf;
  6253. }
  6254. struct ggml_cgraph * build_gemma() {
  6255. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6256. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6257. struct ggml_tensor * cur;
  6258. struct ggml_tensor * inpL;
  6259. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6260. cb(inpL, "inp_embd", -1);
  6261. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6262. cb(inpL, "inp_scaled", -1);
  6263. // inp_pos - contains the positions
  6264. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6265. cb(inp_pos, "inp_pos", -1);
  6266. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6267. 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);
  6268. cb(KQ_mask, "KQ_mask", -1);
  6269. for (int il = 0; il < n_layer; ++il) {
  6270. // norm
  6271. cur = llm_build_norm(ctx0, inpL, hparams,
  6272. model.layers[il].attn_norm, NULL,
  6273. LLM_NORM_RMS, cb, il);
  6274. cb(cur, "attn_norm", il);
  6275. // self-attention
  6276. {
  6277. // compute Q and K and RoPE them
  6278. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6279. cb(Qcur, "Qcur", il);
  6280. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6281. cb(Kcur, "Kcur", il);
  6282. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6283. cb(Vcur, "Vcur", il);
  6284. Qcur = ggml_rope_custom(
  6285. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6286. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6287. ext_factor, attn_factor, beta_fast, beta_slow);
  6288. cb(Qcur, "Qcur", il);
  6289. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6290. cb(Qcur, "Qcur_scaled", il);
  6291. Kcur = ggml_rope_custom(
  6292. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6293. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6294. ext_factor, attn_factor, beta_fast, beta_slow);
  6295. cb(Kcur, "Kcur", il);
  6296. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6297. model.layers[il].wo, NULL,
  6298. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6299. cb(cur, "kqv_out", il);
  6300. }
  6301. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6302. cb(sa_out, "sa_out", il);
  6303. cur = llm_build_norm(ctx0, sa_out, hparams,
  6304. model.layers[il].ffn_norm, NULL,
  6305. LLM_NORM_RMS, cb, il);
  6306. cb(cur, "ffn_norm", il);
  6307. // feed-forward network
  6308. {
  6309. cur = llm_build_ffn(ctx0, cur,
  6310. model.layers[il].ffn_up, NULL,
  6311. model.layers[il].ffn_gate, NULL,
  6312. model.layers[il].ffn_down, NULL,
  6313. NULL,
  6314. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6315. cb(cur, "ffn_out", il);
  6316. }
  6317. cur = ggml_add(ctx0, cur, sa_out);
  6318. cb(cur, "l_out", il);
  6319. // input for next layer
  6320. inpL = cur;
  6321. }
  6322. cur = inpL;
  6323. cur = llm_build_norm(ctx0, cur, hparams,
  6324. model.output_norm, NULL,
  6325. LLM_NORM_RMS, cb, -1);
  6326. cb(cur, "result_norm", -1);
  6327. // lm_head
  6328. cur = ggml_mul_mat(ctx0, model.output, cur);
  6329. cb(cur, "result_output", -1);
  6330. ggml_build_forward_expand(gf, cur);
  6331. return gf;
  6332. }
  6333. struct ggml_cgraph * build_starcoder2() {
  6334. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6335. const int64_t n_embd_head = hparams.n_embd_head_v;
  6336. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6337. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6338. struct ggml_tensor * cur;
  6339. struct ggml_tensor * inpL;
  6340. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6341. cb(inpL, "inp_embd", -1);
  6342. // inp_pos - contains the positions
  6343. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6344. cb(inp_pos, "inp_pos", -1);
  6345. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6346. 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);
  6347. cb(KQ_mask, "KQ_mask", -1);
  6348. for (int il = 0; il < n_layer; ++il) {
  6349. struct ggml_tensor * inpSA = inpL;
  6350. // norm
  6351. cur = llm_build_norm(ctx0, inpL, hparams,
  6352. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6353. LLM_NORM, cb, il);
  6354. cb(cur, "attn_norm", il);
  6355. // self-attention
  6356. {
  6357. // compute Q and K and RoPE them
  6358. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6359. cb(Qcur, "Qcur", il);
  6360. if (model.layers[il].bq) {
  6361. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6362. cb(Qcur, "Qcur", il);
  6363. }
  6364. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6365. cb(Kcur, "Kcur", il);
  6366. if (model.layers[il].bk) {
  6367. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6368. cb(Kcur, "Kcur", il);
  6369. }
  6370. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6371. cb(Vcur, "Vcur", il);
  6372. if (model.layers[il].bv) {
  6373. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6374. cb(Vcur, "Vcur", il);
  6375. }
  6376. Qcur = ggml_rope_custom(
  6377. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6378. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6379. ext_factor, attn_factor, beta_fast, beta_slow
  6380. );
  6381. cb(Qcur, "Qcur", il);
  6382. Kcur = ggml_rope_custom(
  6383. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6384. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6385. ext_factor, attn_factor, beta_fast, beta_slow
  6386. );
  6387. cb(Kcur, "Kcur", il);
  6388. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6389. model.layers[il].wo, model.layers[il].bo,
  6390. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6391. cb(cur, "kqv_out", il);
  6392. }
  6393. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6394. cb(ffn_inp, "ffn_inp", il);
  6395. // feed-forward network
  6396. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6397. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6398. LLM_NORM, cb, il);
  6399. cb(cur, "ffn_norm", il);
  6400. cur = llm_build_ffn(ctx0, cur,
  6401. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6402. NULL, NULL,
  6403. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6404. NULL,
  6405. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6406. cb(cur, "ffn_out", il);
  6407. cur = ggml_add(ctx0, cur, ffn_inp);
  6408. cb(cur, "l_out", il);
  6409. // input for next layer
  6410. inpL = cur;
  6411. }
  6412. cur = inpL;
  6413. cur = llm_build_norm(ctx0, cur, hparams,
  6414. model.output_norm, model.output_norm_b,
  6415. LLM_NORM, cb, -1);
  6416. cb(cur, "result_norm", -1);
  6417. // lm_head
  6418. cur = ggml_mul_mat(ctx0, model.output, cur);
  6419. cb(cur, "result_output", -1);
  6420. ggml_build_forward_expand(gf, cur);
  6421. return gf;
  6422. }
  6423. };
  6424. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  6425. llama_batch dummy;
  6426. dummy.n_tokens = 0;
  6427. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6428. struct llm_build_context llm(lctx, dummy, cb, false);
  6429. llm.init();
  6430. struct ggml_cgraph * result = llm.build_defrag(ids);
  6431. llm.free();
  6432. return result;
  6433. }
  6434. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  6435. llama_batch dummy;
  6436. dummy.n_tokens = 0;
  6437. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6438. struct llm_build_context llm(lctx, dummy, cb, false);
  6439. llm.init();
  6440. struct ggml_cgraph * result = llm.build_k_shift();
  6441. llm.free();
  6442. return result;
  6443. }
  6444. static struct ggml_cgraph * llama_build_graph(
  6445. llama_context & lctx,
  6446. const llama_batch & batch,
  6447. bool worst_case) {
  6448. const auto & model = lctx.model;
  6449. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6450. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6451. if (il >= 0) {
  6452. ggml_format_name(cur, "%s-%d", name, il);
  6453. } else {
  6454. ggml_set_name(cur, name);
  6455. }
  6456. if (!lctx.cparams.offload_kqv) {
  6457. if (strcmp(name, "kqv_merged_cont") == 0) {
  6458. // all nodes between the KV store and the attention output are run on the CPU
  6459. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  6460. }
  6461. }
  6462. };
  6463. struct ggml_cgraph * result = NULL;
  6464. struct llm_build_context llm(lctx, batch, cb, worst_case);
  6465. llm.init();
  6466. switch (model.arch) {
  6467. case LLM_ARCH_LLAMA:
  6468. {
  6469. result = llm.build_llama();
  6470. } break;
  6471. case LLM_ARCH_BAICHUAN:
  6472. {
  6473. result = llm.build_baichuan();
  6474. } break;
  6475. case LLM_ARCH_FALCON:
  6476. {
  6477. result = llm.build_falcon();
  6478. } break;
  6479. case LLM_ARCH_STARCODER:
  6480. {
  6481. result = llm.build_starcoder();
  6482. } break;
  6483. case LLM_ARCH_PERSIMMON:
  6484. {
  6485. result = llm.build_persimmon();
  6486. } break;
  6487. case LLM_ARCH_REFACT:
  6488. {
  6489. result = llm.build_refact();
  6490. } break;
  6491. case LLM_ARCH_BERT:
  6492. case LLM_ARCH_NOMIC_BERT:
  6493. {
  6494. result = llm.build_bert();
  6495. } break;
  6496. case LLM_ARCH_BLOOM:
  6497. {
  6498. result = llm.build_bloom();
  6499. } break;
  6500. case LLM_ARCH_MPT:
  6501. {
  6502. result = llm.build_mpt();
  6503. } break;
  6504. case LLM_ARCH_STABLELM:
  6505. {
  6506. result = llm.build_stablelm();
  6507. } break;
  6508. case LLM_ARCH_QWEN:
  6509. {
  6510. result = llm.build_qwen();
  6511. } break;
  6512. case LLM_ARCH_QWEN2:
  6513. {
  6514. result = llm.build_qwen2();
  6515. } break;
  6516. case LLM_ARCH_PHI2:
  6517. {
  6518. result = llm.build_phi2();
  6519. } break;
  6520. case LLM_ARCH_PLAMO:
  6521. {
  6522. result = llm.build_plamo();
  6523. } break;
  6524. case LLM_ARCH_GPT2:
  6525. {
  6526. result = llm.build_gpt2();
  6527. } break;
  6528. case LLM_ARCH_CODESHELL:
  6529. {
  6530. result = llm.build_codeshell();
  6531. } break;
  6532. case LLM_ARCH_ORION:
  6533. {
  6534. result = llm.build_orion();
  6535. } break;
  6536. case LLM_ARCH_INTERNLM2:
  6537. {
  6538. result = llm.build_internlm2();
  6539. } break;
  6540. case LLM_ARCH_MINICPM:
  6541. {
  6542. result = llm.build_minicpm();
  6543. } break;
  6544. case LLM_ARCH_GEMMA:
  6545. {
  6546. result = llm.build_gemma();
  6547. } break;
  6548. case LLM_ARCH_STARCODER2:
  6549. {
  6550. result = llm.build_starcoder2();
  6551. } break;
  6552. default:
  6553. GGML_ASSERT(false);
  6554. }
  6555. llm.free();
  6556. return result;
  6557. }
  6558. static void llama_set_k_shift(llama_context & lctx) {
  6559. const auto & cparams = lctx.cparams;
  6560. const int64_t n_ctx = cparams.n_ctx;
  6561. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  6562. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  6563. for (int i = 0; i < n_ctx; ++i) {
  6564. data[i] = lctx.kv_self.cells[i].delta;
  6565. }
  6566. }
  6567. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  6568. //
  6569. // set input data
  6570. //
  6571. const auto & hparams = lctx.model.hparams;
  6572. const auto & cparams = lctx.cparams;
  6573. const auto & kv_self = lctx.kv_self;
  6574. if (batch.token) {
  6575. const int64_t n_tokens = batch.n_tokens;
  6576. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  6577. }
  6578. if (batch.embd) {
  6579. const int64_t n_embd = hparams.n_embd;
  6580. const int64_t n_tokens = batch.n_tokens;
  6581. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  6582. }
  6583. if (batch.pos) {
  6584. const int64_t n_tokens = batch.n_tokens;
  6585. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  6586. }
  6587. {
  6588. const int64_t n_kv = kv_self.n;
  6589. const int64_t n_tokens = batch.n_tokens;
  6590. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6591. float * data = (float *) lctx.inp_KQ_mask->data;
  6592. for (int h = 0; h < 1; ++h) {
  6593. for (int j = 0; j < n_tokens; ++j) {
  6594. const llama_pos pos = batch.pos[j];
  6595. const llama_seq_id seq_id = batch.seq_id[j][0];
  6596. for (int i = 0; i < n_kv; ++i) {
  6597. float f;
  6598. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) ||
  6599. (hparams.causal_attn && lctx.kv_self.cells[i].pos > pos)) {
  6600. f = -INFINITY;
  6601. } else {
  6602. f = 0;
  6603. }
  6604. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  6605. }
  6606. }
  6607. }
  6608. }
  6609. if (hparams.need_kq_pos) {
  6610. const int64_t n_kv = kv_self.n;
  6611. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  6612. float * data = (float *) lctx.inp_KQ_pos->data;
  6613. for (int i = 0; i < n_kv; ++i) {
  6614. data[i] = float(lctx.kv_self.cells[i].pos);
  6615. }
  6616. }
  6617. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  6618. const int64_t n_tokens = batch.n_tokens;
  6619. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  6620. float * data = (float *) lctx.inp_mean->data;
  6621. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  6622. std::vector<uint64_t> sum(n_tokens, 0);
  6623. for (int i = 0; i < n_tokens; ++i) {
  6624. const llama_seq_id seq_id = batch.seq_id[i][0];
  6625. sum[seq_id] += 1;
  6626. }
  6627. std::vector<float> div(n_tokens, 0.0f);
  6628. for (int i = 0; i < n_tokens; ++i) {
  6629. const uint64_t s = sum[i];
  6630. if (s > 0) {
  6631. div[i] = 1.0f/float(s);
  6632. }
  6633. }
  6634. for (int i = 0; i < n_tokens; ++i) {
  6635. const llama_seq_id seq_id = batch.seq_id[i][0];
  6636. data[seq_id*n_tokens + i] = div[seq_id];
  6637. }
  6638. }
  6639. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  6640. const int64_t n_tokens = batch.n_tokens;
  6641. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  6642. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  6643. for (int i = 0; i < n_tokens; ++i) {
  6644. const llama_seq_id seq_id = batch.seq_id[i][0];
  6645. const llama_pos pos = batch.pos[i];
  6646. if (pos == 0) {
  6647. data[seq_id] = i;
  6648. }
  6649. }
  6650. }
  6651. }
  6652. static void llama_graph_compute(
  6653. llama_context & lctx,
  6654. ggml_cgraph * gf,
  6655. int n_threads) {
  6656. #ifdef GGML_USE_MPI
  6657. const int64_t n_layer = lctx.model.hparams.n_layer;
  6658. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  6659. #endif
  6660. #ifdef GGML_USE_METAL
  6661. if (ggml_backend_is_metal(lctx.backend_metal)) {
  6662. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  6663. }
  6664. #endif
  6665. if (lctx.backend_cpu != nullptr) {
  6666. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  6667. }
  6668. ggml_backend_sched_graph_compute(lctx.sched, gf);
  6669. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6670. #ifdef GGML_USE_MPI
  6671. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  6672. #endif
  6673. }
  6674. // decode a batch of tokens by evaluating the transformer
  6675. //
  6676. // - lctx: llama context
  6677. // - batch: batch to evaluate
  6678. //
  6679. // return 0 on success
  6680. // return positive int on warning
  6681. // return negative int on error
  6682. //
  6683. static int llama_decode_internal(
  6684. llama_context & lctx,
  6685. llama_batch batch) {
  6686. const uint32_t n_tokens = batch.n_tokens;
  6687. if (n_tokens == 0) {
  6688. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  6689. return -1;
  6690. }
  6691. const auto & model = lctx.model;
  6692. const auto & hparams = model.hparams;
  6693. const auto & cparams = lctx.cparams;
  6694. const auto n_batch = cparams.n_batch;
  6695. GGML_ASSERT(n_tokens <= n_batch);
  6696. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6697. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6698. const int64_t t_start_us = ggml_time_us();
  6699. #ifdef GGML_USE_MPI
  6700. // TODO: needs fix after #3228
  6701. GGML_ASSERT(false && "not implemented");
  6702. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  6703. #endif
  6704. GGML_ASSERT(n_threads > 0);
  6705. auto & kv_self = lctx.kv_self;
  6706. const int64_t n_embd = hparams.n_embd;
  6707. const int64_t n_vocab = hparams.n_vocab;
  6708. // helpers for smoother batch API transition
  6709. // after deprecating the llama_eval calls, these will be removed
  6710. std::vector<llama_pos> pos;
  6711. std::vector<int32_t> n_seq_id;
  6712. std::vector<llama_seq_id *> seq_id_arr;
  6713. std::vector<std::vector<llama_seq_id>> seq_id;
  6714. if (batch.pos == nullptr) {
  6715. pos.resize(n_tokens);
  6716. for (uint32_t i = 0; i < n_tokens; i++) {
  6717. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  6718. }
  6719. batch.pos = pos.data();
  6720. }
  6721. if (batch.seq_id == nullptr) {
  6722. n_seq_id.resize(n_tokens);
  6723. seq_id.resize(n_tokens);
  6724. seq_id_arr.resize(n_tokens);
  6725. for (uint32_t i = 0; i < n_tokens; i++) {
  6726. n_seq_id[i] = 1;
  6727. seq_id[i].resize(1);
  6728. seq_id[i][0] = batch.all_seq_id;
  6729. seq_id_arr[i] = seq_id[i].data();
  6730. }
  6731. batch.n_seq_id = n_seq_id.data();
  6732. batch.seq_id = seq_id_arr.data();
  6733. }
  6734. llama_kv_cache_update(&lctx);
  6735. // if we have enough unused cells before the current head ->
  6736. // better to start searching from the beginning of the cache, hoping to fill it
  6737. if (kv_self.head > kv_self.used + 2*n_tokens) {
  6738. kv_self.head = 0;
  6739. }
  6740. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  6741. return 1;
  6742. }
  6743. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6744. // after enough generations, the benefit from this heuristic disappears
  6745. // if we start defragmenting the cache, the benefit from this will be more important
  6746. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  6747. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6748. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6749. ggml_backend_sched_reset(lctx.sched);
  6750. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6751. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  6752. // the output is always the last tensor in the graph
  6753. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  6754. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  6755. if (strcmp(res->name, "result_output") == 0) {
  6756. // the embeddings could be the second to last tensor, or the third to last tensor
  6757. if (strcmp(embeddings->name, "result_norm") != 0) {
  6758. embeddings = gf->nodes[gf->n_nodes - 3];
  6759. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  6760. }
  6761. } else if (strcmp(res->name, "result_embd") == 0) {
  6762. embeddings = res;
  6763. res = nullptr;
  6764. } else {
  6765. GGML_ASSERT(false);
  6766. }
  6767. // 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);
  6768. // for big prompts, if BLAS is enabled, it is better to use only one thread
  6769. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  6770. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  6771. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  6772. // with the BLAS calls. need a better solution
  6773. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  6774. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  6775. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  6776. n_threads = std::min(4, n_threads);
  6777. }
  6778. llama_set_inputs(lctx, batch);
  6779. llama_graph_compute(lctx, gf, n_threads);
  6780. // update the kv ring buffer
  6781. {
  6782. kv_self.head += n_tokens;
  6783. // Ensure kv cache head points to a valid index.
  6784. if (kv_self.head >= kv_self.size) {
  6785. kv_self.head = 0;
  6786. }
  6787. }
  6788. // decide if we need to defrag the kv cache
  6789. if (cparams.defrag_thold >= 0.0f) {
  6790. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used + n_tokens)/float(kv_self.n) : 0.0f;
  6791. // queue defragmentation for next llama_kv_cache_update
  6792. if (fragmentation > cparams.defrag_thold) {
  6793. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  6794. llama_kv_cache_defrag(kv_self);
  6795. }
  6796. }
  6797. #ifdef GGML_PERF
  6798. // print timing information per ggml operation (for debugging purposes)
  6799. // requires GGML_PERF to be defined
  6800. ggml_graph_print(gf);
  6801. #endif
  6802. // plot the computation graph in dot format (for debugging purposes)
  6803. //if (n_past%100 == 0) {
  6804. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6805. //}
  6806. // extract logits
  6807. // TODO: do not compute and extract logits if only embeddings are needed
  6808. // need to update the graphs to skip "result_output"
  6809. if (res) {
  6810. auto & logits_out = lctx.logits;
  6811. #ifndef NDEBUG
  6812. auto & logits_valid = lctx.logits_valid;
  6813. logits_valid.clear();
  6814. logits_valid.resize(n_tokens);
  6815. logits_out.clear();
  6816. #endif
  6817. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  6818. GGML_ASSERT(res_backend != nullptr);
  6819. if (batch.logits) {
  6820. logits_out.resize(n_vocab * n_tokens);
  6821. for (uint32_t i = 0; i < n_tokens; i++) {
  6822. if (batch.logits[i] == 0) {
  6823. continue;
  6824. }
  6825. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  6826. #ifndef NDEBUG
  6827. logits_valid[i] = true;
  6828. #endif
  6829. }
  6830. } else if (lctx.logits_all) {
  6831. logits_out.resize(n_vocab * n_tokens);
  6832. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  6833. #ifndef NDEBUG
  6834. std::fill(logits_valid.begin(), logits_valid.end(), true);
  6835. #endif
  6836. } else {
  6837. logits_out.resize(n_vocab);
  6838. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  6839. #ifndef NDEBUG
  6840. logits_valid[0] = true;
  6841. #endif
  6842. }
  6843. ggml_backend_synchronize(res_backend);
  6844. }
  6845. // extract embeddings
  6846. if (!lctx.embedding.empty()) {
  6847. auto & embedding_out = lctx.embedding;
  6848. const int64_t embd_pos = res ? n_embd * (n_tokens-1) : 0;
  6849. const int64_t embd_size = res ? n_embd : n_embd * n_tokens;
  6850. embedding_out.resize(embd_size);
  6851. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  6852. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), embd_pos*sizeof(float), embd_size*sizeof(float));
  6853. ggml_backend_synchronize(embeddings_backend);
  6854. }
  6855. // measure the performance only for the single-token evals
  6856. if (n_tokens == 1) {
  6857. lctx.t_eval_us += ggml_time_us() - t_start_us;
  6858. lctx.n_eval++;
  6859. }
  6860. else if (n_tokens > 1) {
  6861. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  6862. lctx.n_p_eval += n_tokens;
  6863. }
  6864. // get a more accurate load time, upon first eval
  6865. // TODO: fix this
  6866. if (!lctx.has_evaluated_once) {
  6867. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  6868. lctx.has_evaluated_once = true;
  6869. }
  6870. return 0;
  6871. }
  6872. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  6873. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  6874. auto & kv_self = lctx.kv_self;
  6875. const auto & hparams = lctx.model.hparams;
  6876. const uint32_t n_layer = hparams.n_layer;
  6877. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  6878. const uint32_t n_used = kv_self.used;
  6879. assert(n_used <= n_kv);
  6880. //const int64_t t_start = ggml_time_us();
  6881. // number of cells moved
  6882. uint32_t n_moves = 0;
  6883. // determine which KV cells to move where
  6884. //
  6885. // cell i moves to ids[i]
  6886. //
  6887. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  6888. //
  6889. std::vector<uint32_t> ids(n_kv, n_kv);
  6890. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  6891. const auto & cell0 = kv_self.cells[i0];
  6892. if (!cell0.is_empty()) {
  6893. ids[i0] = i0;
  6894. continue;
  6895. }
  6896. // found a hole - fill it with data from the end of the cache
  6897. uint32_t nh = 1;
  6898. // determine the size of the hole
  6899. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  6900. nh++;
  6901. }
  6902. // each move requires 6*n_layer tensors (see build_defrag)
  6903. // - source view, destination view, copy operation
  6904. // - x2 for keys and values
  6905. //
  6906. if (6*(n_moves + nh)*n_layer >= LLAMA_MAX_NODES) {
  6907. // the graph is too big, we cannot move more cells
  6908. break;
  6909. }
  6910. uint32_t nf = 0;
  6911. uint32_t is = n_kv - 1;
  6912. // starting from the end, find nh non-empty cells
  6913. for (; is > i0; --is) {
  6914. const auto & cell1 = kv_self.cells[is];
  6915. if (cell1.is_empty() || ids[is] != n_kv) {
  6916. continue;
  6917. }
  6918. // non-empty cell which is not yet moved
  6919. nf++;
  6920. if (nf == nh) {
  6921. break;
  6922. }
  6923. }
  6924. // this can only happen if `n_used` is not accurate, which would be a bug
  6925. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  6926. nf = 0;
  6927. uint32_t i1 = is;
  6928. // are we moving a continuous block of memory?
  6929. bool cont = false;
  6930. // go back and move the nf cells to the hole
  6931. for (; i1 < n_kv; ++i1) {
  6932. auto & cell1 = kv_self.cells[i1];
  6933. if (cell1.is_empty() || ids[i1] != n_kv) {
  6934. cont = false;
  6935. continue;
  6936. }
  6937. // this cell goes to (i0 + nf)
  6938. ids[i1] = i0 + nf;
  6939. // move the cell meta data
  6940. kv_self.cells[i0 + nf] = cell1;
  6941. // clear the old cell and move the head there
  6942. cell1 = llama_kv_cell();
  6943. kv_self.head = n_used;
  6944. if (!cont) {
  6945. n_moves++;
  6946. cont = true;
  6947. }
  6948. nf++;
  6949. if (nf == nh) {
  6950. break;
  6951. }
  6952. }
  6953. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  6954. i0 += nh - 1;
  6955. }
  6956. if (n_moves == 0) {
  6957. return;
  6958. }
  6959. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  6960. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  6961. #if 0
  6962. // CPU defrag
  6963. //
  6964. // TODO: optimizations are possible:
  6965. // - multiple threads
  6966. // - avoid copying to the host memory when already there
  6967. //
  6968. // likely not worth the effort, as we have ggml_graph based defrag
  6969. //
  6970. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  6971. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  6972. const uint32_t kv_size = kv_self.size;
  6973. std::vector<uint8_t> buf_k;
  6974. std::vector<uint8_t> buf_v;
  6975. for (uint32_t il = 0; il < n_layer; ++il) {
  6976. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  6977. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  6978. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  6979. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  6980. buf_k.resize(k_size);
  6981. buf_v.resize(v_size);
  6982. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  6983. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  6984. // batch move [i, i+nm) to [id, id+nm)
  6985. // note: cells can move only to a lower index
  6986. for (uint32_t i = 0; i < n_kv; ++i) {
  6987. const uint32_t id = ids[i];
  6988. if (i == id || id == n_kv) {
  6989. continue;
  6990. }
  6991. uint32_t nm = 1;
  6992. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  6993. nm++;
  6994. }
  6995. // move keys
  6996. {
  6997. const int64_t os = i*k_size_row;
  6998. const int64_t od = id*k_size_row;
  6999. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  7000. }
  7001. // move values (note: they are transposed)
  7002. {
  7003. const int64_t os = i;
  7004. const int64_t od = id;
  7005. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  7006. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  7007. }
  7008. }
  7009. i += nm - 1;
  7010. }
  7011. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7012. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7013. }
  7014. #else
  7015. // ggml_graph defrag
  7016. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  7017. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7018. #endif
  7019. //const int64_t t_end = ggml_time_us();
  7020. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  7021. }
  7022. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  7023. // apply K-shift if needed
  7024. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  7025. llama_set_k_shift(lctx);
  7026. {
  7027. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  7028. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7029. }
  7030. {
  7031. auto & kv_self = lctx.kv_self;
  7032. kv_self.has_shift = false;
  7033. for (uint32_t i = 0; i < kv_self.size; ++i) {
  7034. kv_self.cells[i].delta = 0;
  7035. }
  7036. }
  7037. }
  7038. // defragment the KV cache if needed
  7039. if (lctx.kv_self.do_defrag) {
  7040. llama_kv_cache_defrag_internal(lctx);
  7041. lctx.kv_self.do_defrag = false;
  7042. }
  7043. }
  7044. //
  7045. // tokenizer
  7046. //
  7047. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  7048. return vocab.type;
  7049. }
  7050. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  7051. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  7052. }
  7053. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  7054. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  7055. }
  7056. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  7057. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  7058. }
  7059. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  7060. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  7061. }
  7062. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  7063. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  7064. }
  7065. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  7066. GGML_ASSERT(llama_is_byte_token(vocab, id));
  7067. const auto& token_data = vocab.id_to_token.at(id);
  7068. switch (llama_vocab_get_type(vocab)) {
  7069. case LLAMA_VOCAB_TYPE_SPM: {
  7070. auto buf = token_data.text.substr(3, 2);
  7071. return strtol(buf.c_str(), NULL, 16);
  7072. }
  7073. case LLAMA_VOCAB_TYPE_BPE: {
  7074. GGML_ASSERT(false);
  7075. return unicode_to_bytes_bpe(token_data.text);
  7076. }
  7077. case LLAMA_VOCAB_TYPE_WPM: {
  7078. GGML_ASSERT(false);
  7079. }
  7080. default:
  7081. GGML_ASSERT(false);
  7082. }
  7083. }
  7084. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  7085. static const char * hex = "0123456789ABCDEF";
  7086. switch (llama_vocab_get_type(vocab)) {
  7087. case LLAMA_VOCAB_TYPE_SPM: {
  7088. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  7089. auto token = vocab.token_to_id.find(buf);
  7090. if (token != vocab.token_to_id.end()) {
  7091. return (*token).second;
  7092. }
  7093. // Try to fall back to just the byte as a string
  7094. const char buf2[2] = { (char)ch, 0 };
  7095. return vocab.token_to_id.at(buf2);
  7096. }
  7097. case LLAMA_VOCAB_TYPE_WPM:
  7098. case LLAMA_VOCAB_TYPE_BPE: {
  7099. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  7100. }
  7101. default:
  7102. GGML_ASSERT(false);
  7103. }
  7104. }
  7105. static void llama_escape_whitespace(std::string & text) {
  7106. replace_all(text, " ", "\xe2\x96\x81");
  7107. }
  7108. static void llama_unescape_whitespace(std::string & word) {
  7109. replace_all(word, "\xe2\x96\x81", " ");
  7110. }
  7111. struct llm_symbol {
  7112. using index = int;
  7113. index prev;
  7114. index next;
  7115. const char * text;
  7116. size_t n;
  7117. };
  7118. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  7119. // SPM tokenizer
  7120. // original implementation:
  7121. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  7122. struct llm_bigram_spm {
  7123. struct comparator {
  7124. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  7125. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  7126. }
  7127. };
  7128. using queue_storage = std::vector<llm_bigram_spm>;
  7129. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  7130. llm_symbol::index left;
  7131. llm_symbol::index right;
  7132. float score;
  7133. size_t size;
  7134. };
  7135. struct llm_tokenizer_spm {
  7136. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  7137. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7138. // split string into utf8 chars
  7139. int index = 0;
  7140. size_t offs = 0;
  7141. while (offs < text.size()) {
  7142. llm_symbol sym;
  7143. size_t len = utf8_len(text[offs]);
  7144. sym.text = text.c_str() + offs;
  7145. sym.n = std::min(len, text.size() - offs);
  7146. offs += sym.n;
  7147. sym.prev = index - 1;
  7148. sym.next = offs == text.size() ? -1 : index + 1;
  7149. index++;
  7150. symbols.emplace_back(sym);
  7151. }
  7152. // seed the work queue with all possible 2-character tokens.
  7153. for (size_t i = 1; i < symbols.size(); ++i) {
  7154. try_add_bigram(i - 1, i);
  7155. }
  7156. // keep substituting the highest frequency pairs for as long as we can.
  7157. while (!work_queue.empty()) {
  7158. auto bigram = work_queue.top();
  7159. work_queue.pop();
  7160. auto & left_sym = symbols[bigram.left];
  7161. auto & right_sym = symbols[bigram.right];
  7162. // if one of the symbols already got merged, skip it.
  7163. if (left_sym.n == 0 || right_sym.n == 0 ||
  7164. left_sym.n + right_sym.n != bigram.size) {
  7165. continue;
  7166. }
  7167. // merge the right sym into the left one
  7168. left_sym.n += right_sym.n;
  7169. right_sym.n = 0;
  7170. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  7171. // remove the right sym from the chain
  7172. left_sym.next = right_sym.next;
  7173. if (right_sym.next >= 0) {
  7174. symbols[right_sym.next].prev = bigram.left;
  7175. }
  7176. // find more substitutions
  7177. try_add_bigram(left_sym.prev, bigram.left);
  7178. try_add_bigram(bigram.left, left_sym.next);
  7179. }
  7180. for (int i = 0; i != -1; i = symbols[i].next) {
  7181. auto & symbol = symbols[i];
  7182. resegment(symbol, output);
  7183. }
  7184. }
  7185. private:
  7186. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  7187. auto text = std::string(symbol.text, symbol.n);
  7188. auto token = vocab.token_to_id.find(text);
  7189. // Do we need to support is_unused?
  7190. if (token != vocab.token_to_id.end()) {
  7191. output.push_back((*token).second);
  7192. return;
  7193. }
  7194. const auto p = rev_merge.find(text);
  7195. if (p == rev_merge.end()) {
  7196. // output any symbols that did not form tokens as bytes.
  7197. output.reserve(output.size() + symbol.n);
  7198. for (int j = 0; j < (int)symbol.n; ++j) {
  7199. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  7200. output.push_back(token_id);
  7201. }
  7202. return;
  7203. }
  7204. resegment(symbols[p->second.first], output);
  7205. resegment(symbols[p->second.second], output);
  7206. }
  7207. void try_add_bigram(int left, int right) {
  7208. if (left == -1 || right == -1) {
  7209. return;
  7210. }
  7211. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  7212. auto token = vocab.token_to_id.find(text);
  7213. if (token == vocab.token_to_id.end()) {
  7214. return;
  7215. }
  7216. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  7217. return;
  7218. }
  7219. const auto & tok_data = vocab.id_to_token[(*token).second];
  7220. llm_bigram_spm bigram;
  7221. bigram.left = left;
  7222. bigram.right = right;
  7223. bigram.score = tok_data.score;
  7224. bigram.size = text.size();
  7225. work_queue.push(bigram);
  7226. // Do we need to support is_unused?
  7227. rev_merge[text] = std::make_pair(left, right);
  7228. }
  7229. const llama_vocab & vocab;
  7230. std::vector<llm_symbol> symbols;
  7231. llm_bigram_spm::queue work_queue;
  7232. std::map<std::string, std::pair<int, int>> rev_merge;
  7233. };
  7234. // BPE tokenizer
  7235. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  7236. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  7237. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  7238. struct llm_bigram_bpe {
  7239. struct comparator {
  7240. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  7241. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  7242. }
  7243. };
  7244. using queue_storage = std::vector<llm_bigram_bpe>;
  7245. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  7246. llm_symbol::index left;
  7247. llm_symbol::index right;
  7248. std::string text;
  7249. int rank;
  7250. size_t size;
  7251. };
  7252. struct llm_tokenizer_bpe {
  7253. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  7254. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7255. int final_prev_index = -1;
  7256. auto word_collection = bpe_gpt2_preprocess(text);
  7257. symbols_final.clear();
  7258. for (auto & word : word_collection) {
  7259. work_queue = llm_bigram_bpe::queue();
  7260. symbols.clear();
  7261. int index = 0;
  7262. size_t offset = 0;
  7263. while (offset < word.size()) {
  7264. llm_symbol sym;
  7265. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  7266. sym.text = word.c_str() + offset;
  7267. sym.n = char_len;
  7268. offset += sym.n;
  7269. sym.prev = index - 1;
  7270. sym.next = offset == word.size() ? -1 : index + 1;
  7271. index++;
  7272. symbols.emplace_back(sym);
  7273. }
  7274. for (size_t i = 1; i < symbols.size(); ++i) {
  7275. add_new_bigram(i - 1, i);
  7276. }
  7277. // build token(s)
  7278. while (!work_queue.empty()) {
  7279. auto bigram = work_queue.top();
  7280. work_queue.pop();
  7281. auto & left_symbol = symbols[bigram.left];
  7282. auto & right_symbol = symbols[bigram.right];
  7283. if (left_symbol.n == 0 || right_symbol.n == 0) {
  7284. continue;
  7285. }
  7286. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  7287. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  7288. if (left_token + right_token != bigram.text) {
  7289. continue; // Skip this bigram if it's outdated
  7290. }
  7291. // merge the right sym into the left one
  7292. left_symbol.n += right_symbol.n;
  7293. right_symbol.n = 0;
  7294. // remove the right sym from the chain
  7295. left_symbol.next = right_symbol.next;
  7296. if (right_symbol.next >= 0) {
  7297. symbols[right_symbol.next].prev = bigram.left;
  7298. }
  7299. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  7300. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  7301. }
  7302. // add the fnished tokens to the final list keeping correct order for next and prev
  7303. for (auto & sym : symbols) {
  7304. if (sym.n > 0) {
  7305. sym.prev = final_prev_index;
  7306. sym.next = -1;
  7307. if (final_prev_index != -1) {
  7308. symbols_final[final_prev_index].next = symbols_final.size();
  7309. }
  7310. symbols_final.emplace_back(sym);
  7311. final_prev_index = symbols_final.size() - 1;
  7312. }
  7313. }
  7314. }
  7315. symbols = symbols_final;
  7316. if (!symbols.empty()) {
  7317. for (int i = 0; i != -1; i = symbols[i].next) {
  7318. auto & symbol = symbols[i];
  7319. if (symbol.n == 0) {
  7320. continue;
  7321. }
  7322. const std::string str = std::string(symbol.text, symbol.n);
  7323. const auto token = vocab.token_to_id.find(str);
  7324. if (token == vocab.token_to_id.end()) {
  7325. for (auto j = str.begin(); j != str.end(); ++j) {
  7326. std::string byte_str(1, *j);
  7327. auto token_multibyte = vocab.token_to_id.find(byte_str);
  7328. if (token_multibyte == vocab.token_to_id.end()) {
  7329. throw std::runtime_error("ERROR: byte not found in vocab");
  7330. }
  7331. output.push_back((*token_multibyte).second);
  7332. }
  7333. } else {
  7334. output.push_back((*token).second);
  7335. }
  7336. }
  7337. }
  7338. }
  7339. private:
  7340. void add_new_bigram(int left, int right) {
  7341. if (left == -1 || right == -1) {
  7342. return;
  7343. }
  7344. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  7345. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  7346. int rank_found = -1;
  7347. rank_found = vocab.find_bpe_rank(left_token, right_token);
  7348. if (rank_found < 0) {
  7349. return;
  7350. }
  7351. llm_bigram_bpe bigram;
  7352. bigram.left = left;
  7353. bigram.right = right;
  7354. bigram.text = left_token + right_token;
  7355. bigram.size = left_token.size() + right_token.size();
  7356. bigram.rank = rank_found;
  7357. work_queue.push(bigram);
  7358. }
  7359. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  7360. std::vector<std::string> bpe_words;
  7361. std::vector<std::string> bpe_encoded_words;
  7362. std::string token = "";
  7363. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  7364. bool collecting_numeric = false;
  7365. bool collecting_letter = false;
  7366. bool collecting_special = false;
  7367. bool collecting_whitespace_lookahead = false;
  7368. bool collecting = false;
  7369. std::vector<std::string> text_utf;
  7370. text_utf.reserve(text.size());
  7371. bpe_words.reserve(text.size());
  7372. bpe_encoded_words.reserve(text.size());
  7373. auto cps = codepoints_from_utf8(text);
  7374. for (size_t i = 0; i < cps.size(); ++i)
  7375. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  7376. for (int i = 0; i < (int)text_utf.size(); i++) {
  7377. const std::string & utf_char = text_utf[i];
  7378. bool split_condition = false;
  7379. int bytes_remain = text_utf.size() - i;
  7380. // forward backward lookups
  7381. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  7382. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  7383. // handling contractions
  7384. if (!split_condition && bytes_remain >= 2) {
  7385. // 's|'t|'m|'d
  7386. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  7387. split_condition = true;
  7388. }
  7389. if (split_condition) {
  7390. if (token.size()) {
  7391. bpe_words.emplace_back(token); // push previous content as token
  7392. }
  7393. token = utf_char + utf_char_next;
  7394. bpe_words.emplace_back(token);
  7395. token = "";
  7396. i++;
  7397. continue;
  7398. }
  7399. }
  7400. if (!split_condition && bytes_remain >= 3) {
  7401. // 're|'ve|'ll
  7402. if (utf_char == "\'" && (
  7403. (utf_char_next == "r" && utf_char_next_next == "e") ||
  7404. (utf_char_next == "v" && utf_char_next_next == "e") ||
  7405. (utf_char_next == "l" && utf_char_next_next == "l"))
  7406. ) {
  7407. split_condition = true;
  7408. }
  7409. if (split_condition) {
  7410. // current token + next token can be defined
  7411. if (token.size()) {
  7412. bpe_words.emplace_back(token); // push previous content as token
  7413. }
  7414. token = utf_char + utf_char_next + utf_char_next_next;
  7415. bpe_words.emplace_back(token); // the contraction
  7416. token = "";
  7417. i += 2;
  7418. continue;
  7419. }
  7420. }
  7421. if (!split_condition && !collecting) {
  7422. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  7423. collecting_letter = true;
  7424. collecting = true;
  7425. }
  7426. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7427. collecting_numeric = true;
  7428. collecting = true;
  7429. }
  7430. else if (
  7431. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  7432. (!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)
  7433. ) {
  7434. collecting_special = true;
  7435. collecting = true;
  7436. }
  7437. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  7438. collecting_whitespace_lookahead = true;
  7439. collecting = true;
  7440. }
  7441. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  7442. split_condition = true;
  7443. }
  7444. }
  7445. else if (!split_condition && collecting) {
  7446. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  7447. split_condition = true;
  7448. }
  7449. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  7450. split_condition = true;
  7451. }
  7452. 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)) {
  7453. split_condition = true;
  7454. }
  7455. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7456. split_condition = true;
  7457. }
  7458. }
  7459. if (utf_char_next == "") {
  7460. split_condition = true; // final
  7461. token += utf_char;
  7462. }
  7463. if (split_condition) {
  7464. if (token.size()) {
  7465. bpe_words.emplace_back(token);
  7466. }
  7467. token = utf_char;
  7468. collecting = false;
  7469. collecting_letter = false;
  7470. collecting_numeric = false;
  7471. collecting_special = false;
  7472. collecting_whitespace_lookahead = false;
  7473. }
  7474. else {
  7475. token += utf_char;
  7476. }
  7477. }
  7478. for (std::string & word : bpe_words) {
  7479. std::string encoded_token = "";
  7480. for (char & c : word) {
  7481. encoded_token += bytes_to_unicode_bpe(c);
  7482. }
  7483. bpe_encoded_words.emplace_back(encoded_token);
  7484. }
  7485. return bpe_encoded_words;
  7486. }
  7487. const llama_vocab & vocab;
  7488. std::vector<llm_symbol> symbols;
  7489. std::vector<llm_symbol> symbols_final;
  7490. llm_bigram_bpe::queue work_queue;
  7491. };
  7492. struct llm_tokenizer_wpm {
  7493. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  7494. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7495. auto * token_map = &vocab.token_to_id;
  7496. // normalize and split by whitespace
  7497. std::vector<std::string> words = preprocess(text);
  7498. // bos token prepended already
  7499. // find the longest tokens that form the words
  7500. for (const std::string &word : words) {
  7501. // skip empty words
  7502. if (word.size() == 0) {
  7503. continue;
  7504. }
  7505. // prepend phantom space
  7506. std::string word1 = "\xe2\x96\x81" + word;
  7507. int n = word1.size();
  7508. // we're at the start of a new word
  7509. int i = 0;
  7510. bool match_any = false;
  7511. // move through character position in word
  7512. while (i < n) {
  7513. // loop through possible match length
  7514. bool match = false;
  7515. for (int j = n; j > i; j--) {
  7516. auto it = token_map->find(word1.substr(i, j - i));
  7517. if (it != token_map->end()) {
  7518. output.push_back(it->second);
  7519. match = true;
  7520. match_any = true;
  7521. i = j;
  7522. break;
  7523. }
  7524. }
  7525. // must be an unknown character
  7526. if (!match) {
  7527. i++;
  7528. }
  7529. }
  7530. // we didn't find any matches for this word
  7531. if (!match_any) {
  7532. output.push_back(vocab.special_unk_id);
  7533. }
  7534. }
  7535. // append eos token
  7536. output.push_back(vocab.special_eos_id);
  7537. }
  7538. std::vector<std::string> preprocess(const std::string & text) {
  7539. // normalalization form D
  7540. std::vector<uint32_t> codepoints = codepoints_from_utf8(text);
  7541. std::vector<uint32_t> nfd_codepoints;
  7542. for (uint32_t code : codepoints) {
  7543. auto it = nfd_map.equal_range(code);
  7544. if (it.first != it.second) {
  7545. for (auto jt = it.first; jt != it.second; jt++) {
  7546. nfd_codepoints.push_back(jt->second);
  7547. }
  7548. } else {
  7549. nfd_codepoints.push_back(code);
  7550. }
  7551. }
  7552. // strip accents, strip control, uniformize whitespace,
  7553. // to lowercase, pad chinese characters, pad punctuation
  7554. std::string new_str = "";
  7555. for (uint32_t code : nfd_codepoints) {
  7556. int type = codepoint_type(code);
  7557. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  7558. continue;
  7559. }
  7560. code = to_lower(code);
  7561. if (type == CODEPOINT_TYPE_WHITESPACE) {
  7562. code = ' ';
  7563. }
  7564. std::string s = codepoint_to_utf8(code);
  7565. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  7566. new_str += " ";
  7567. new_str += s;
  7568. new_str += " ";
  7569. } else {
  7570. new_str += s;
  7571. }
  7572. }
  7573. // split by whitespace
  7574. uint64_t l = 0;
  7575. uint64_t r = 0;
  7576. std::vector<std::string> words;
  7577. while (r < new_str.size()) {
  7578. // if is whitespace
  7579. if (isspace(new_str[r])) {
  7580. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  7581. l = r + 1;
  7582. r = l;
  7583. }
  7584. else {
  7585. r += 1;
  7586. }
  7587. }
  7588. if (r > l) {
  7589. words.push_back(new_str.substr(l, (r - l)));
  7590. }
  7591. return words;
  7592. }
  7593. uint32_t to_lower(uint32_t code) {
  7594. static const std::locale locale("en_US.UTF-8");
  7595. #if defined(_WIN32)
  7596. if (code > 0xFFFF) {
  7597. return code;
  7598. }
  7599. #endif
  7600. return std::tolower(wchar_t(code), locale);
  7601. }
  7602. bool is_ascii_punct(uint32_t code) {
  7603. return code < 256 && ispunct(code);
  7604. }
  7605. bool is_chinese_char(uint32_t codepoint) {
  7606. if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) ||
  7607. (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
  7608. (codepoint >= 0x20000 && codepoint <= 0x2A6DF) ||
  7609. (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
  7610. (codepoint >= 0x2B740 && codepoint <= 0x2B81F) ||
  7611. (codepoint >= 0x2B920 && codepoint <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  7612. (codepoint >= 0xF900 && codepoint <= 0xFAFF) ||
  7613. (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
  7614. (codepoint >= 0x3000 && codepoint <= 0x303F) ||
  7615. (codepoint >= 0xFF00 && codepoint <= 0xFFEF)) {
  7616. return true; // NOLINT
  7617. }
  7618. return false;
  7619. }
  7620. const llama_vocab & vocab;
  7621. };
  7622. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  7623. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  7624. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  7625. } FRAGMENT_BUFFER_VARIANT_TYPE;
  7626. struct fragment_buffer_variant {
  7627. fragment_buffer_variant(llama_vocab::id _token)
  7628. :
  7629. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  7630. token(_token),
  7631. raw_text(_dummy),
  7632. offset(0),
  7633. length(0) {}
  7634. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  7635. :
  7636. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  7637. token((llama_vocab::id) - 1),
  7638. raw_text(_raw_text),
  7639. offset(_offset),
  7640. length(_length){
  7641. GGML_ASSERT(_offset >= 0);
  7642. GGML_ASSERT(_length >= 1);
  7643. GGML_ASSERT(offset + length <= raw_text.length());
  7644. }
  7645. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  7646. const llama_vocab::id token;
  7647. const std::string _dummy;
  7648. const std::string & raw_text;
  7649. const uint64_t offset;
  7650. const uint64_t length;
  7651. };
  7652. // #define PRETOKENIZERDEBUG
  7653. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  7654. // for each special token
  7655. for (const auto & st: vocab.special_tokens_cache) {
  7656. const auto & special_token = st.first;
  7657. const auto & special_id = st.second;
  7658. // for each text fragment
  7659. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  7660. while (it != buffer.end()) {
  7661. auto & fragment = (*it);
  7662. // if a fragment is text ( not yet processed )
  7663. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7664. auto * raw_text = &(fragment.raw_text);
  7665. auto raw_text_base_offset = fragment.offset;
  7666. auto raw_text_base_length = fragment.length;
  7667. // loop over the text
  7668. while (true) {
  7669. // find the first occurrence of a given special token in this fragment
  7670. // passing offset argument only limit the "search area" but match coordinates
  7671. // are still relative to the source full raw_text
  7672. auto match = raw_text->find(special_token, raw_text_base_offset);
  7673. // no occurrences found, stop processing this fragment for a given special token
  7674. if (match == std::string::npos) break;
  7675. // check if match is within bounds of offset <-> length
  7676. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  7677. #ifdef PRETOKENIZERDEBUG
  7678. 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());
  7679. #endif
  7680. auto source = std::distance(buffer.begin(), it);
  7681. // if match is further than base offset
  7682. // then we have some text to the left of it
  7683. if (match > raw_text_base_offset) {
  7684. // left
  7685. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  7686. const int64_t left_reminder_length = match - raw_text_base_offset;
  7687. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  7688. #ifdef PRETOKENIZERDEBUG
  7689. 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());
  7690. #endif
  7691. it++;
  7692. }
  7693. // special token
  7694. buffer.emplace_after(it, special_id);
  7695. it++;
  7696. // right
  7697. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  7698. const int64_t right_reminder_offset = match + special_token.length();
  7699. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  7700. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  7701. #ifdef PRETOKENIZERDEBUG
  7702. 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());
  7703. #endif
  7704. it++;
  7705. if (source == 0) {
  7706. buffer.erase_after(buffer.before_begin());
  7707. } else {
  7708. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7709. }
  7710. // repeat for the right side
  7711. raw_text_base_offset = right_reminder_offset;
  7712. raw_text_base_length = right_reminder_length;
  7713. #ifdef PRETOKENIZERDEBUG
  7714. 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());
  7715. #endif
  7716. } else {
  7717. if (source == 0) {
  7718. buffer.erase_after(buffer.before_begin());
  7719. } else {
  7720. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7721. }
  7722. break;
  7723. }
  7724. }
  7725. }
  7726. it++;
  7727. }
  7728. }
  7729. }
  7730. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  7731. std::vector<llama_vocab::id> output;
  7732. // OG tokenizer behavior:
  7733. //
  7734. // tokenizer.encode('', add_bos=True) returns [1]
  7735. // tokenizer.encode('', add_bos=False) returns []
  7736. if (bos && vocab.special_bos_id != -1) {
  7737. output.push_back(vocab.special_bos_id);
  7738. }
  7739. if (raw_text.empty()) {
  7740. return output;
  7741. }
  7742. std::forward_list<fragment_buffer_variant> fragment_buffer;
  7743. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  7744. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  7745. switch (vocab.type) {
  7746. case LLAMA_VOCAB_TYPE_SPM:
  7747. {
  7748. for (const auto & fragment : fragment_buffer) {
  7749. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7750. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  7751. // TODO: It's likely possible to get rid of this string copy entirely
  7752. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  7753. // and passing 'add space prefix' as bool argument
  7754. //
  7755. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7756. if (&fragment == &fragment_buffer.front()) {
  7757. if (vocab.add_space_prefix) {
  7758. raw_text = " " + raw_text; // prefix with space if the first token is not special
  7759. }
  7760. }
  7761. #ifdef PRETOKENIZERDEBUG
  7762. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7763. #endif
  7764. llm_tokenizer_spm tokenizer(vocab);
  7765. llama_escape_whitespace(raw_text);
  7766. tokenizer.tokenize(raw_text, output);
  7767. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7768. output.push_back(fragment.token);
  7769. }
  7770. }
  7771. } break;
  7772. case LLAMA_VOCAB_TYPE_BPE:
  7773. {
  7774. for (const auto & fragment : fragment_buffer) {
  7775. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7776. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7777. #ifdef PRETOKENIZERDEBUG
  7778. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7779. #endif
  7780. llm_tokenizer_bpe tokenizer(vocab);
  7781. tokenizer.tokenize(raw_text, output);
  7782. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7783. output.push_back(fragment.token);
  7784. }
  7785. }
  7786. } break;
  7787. case LLAMA_VOCAB_TYPE_WPM:
  7788. {
  7789. for (const auto & fragment : fragment_buffer) {
  7790. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7791. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7792. #ifdef PRETOKENIZERDEBUG
  7793. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7794. #endif
  7795. llm_tokenizer_wpm tokenizer(vocab);
  7796. tokenizer.tokenize(raw_text, output);
  7797. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7798. output.push_back(fragment.token);
  7799. }
  7800. }
  7801. } break;
  7802. }
  7803. return output;
  7804. }
  7805. //
  7806. // grammar - internal
  7807. //
  7808. struct llama_partial_utf8 {
  7809. uint32_t value; // bit value so far (unshifted)
  7810. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  7811. };
  7812. struct llama_grammar {
  7813. const std::vector<std::vector<llama_grammar_element>> rules;
  7814. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7815. // buffer for partially generated UTF-8 sequence from accepted tokens
  7816. llama_partial_utf8 partial_utf8;
  7817. };
  7818. struct llama_grammar_candidate {
  7819. size_t index;
  7820. const uint32_t * code_points;
  7821. llama_partial_utf8 partial_utf8;
  7822. };
  7823. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  7824. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  7825. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  7826. const std::string & src,
  7827. llama_partial_utf8 partial_start) {
  7828. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  7829. const char * pos = src.c_str();
  7830. std::vector<uint32_t> code_points;
  7831. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  7832. code_points.reserve(src.size() + 1);
  7833. uint32_t value = partial_start.value;
  7834. int n_remain = partial_start.n_remain;
  7835. // continue previous decode, if applicable
  7836. while (*pos != 0 && n_remain > 0) {
  7837. uint8_t next_byte = static_cast<uint8_t>(*pos);
  7838. if ((next_byte >> 6) != 2) {
  7839. // invalid sequence, abort
  7840. code_points.push_back(0);
  7841. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  7842. }
  7843. value = (value << 6) + (next_byte & 0x3F);
  7844. ++pos;
  7845. --n_remain;
  7846. }
  7847. if (partial_start.n_remain > 0 && n_remain == 0) {
  7848. code_points.push_back(value);
  7849. }
  7850. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  7851. while (*pos != 0) {
  7852. uint8_t first_byte = static_cast<uint8_t>(*pos);
  7853. uint8_t highbits = first_byte >> 4;
  7854. n_remain = lookup[highbits] - 1;
  7855. if (n_remain < 0) {
  7856. // invalid sequence, abort
  7857. code_points.clear();
  7858. code_points.push_back(0);
  7859. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  7860. }
  7861. uint8_t mask = (1 << (7 - n_remain)) - 1;
  7862. value = first_byte & mask;
  7863. ++pos;
  7864. while (*pos != 0 && n_remain > 0) {
  7865. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  7866. ++pos;
  7867. --n_remain;
  7868. }
  7869. if (n_remain == 0) {
  7870. code_points.push_back(value);
  7871. }
  7872. }
  7873. code_points.push_back(0);
  7874. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  7875. }
  7876. // returns true iff pos points to the end of one of the definitions of a rule
  7877. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  7878. switch (pos->type) {
  7879. case LLAMA_GRETYPE_END: return true; // NOLINT
  7880. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  7881. default: return false;
  7882. }
  7883. }
  7884. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  7885. // asserts that pos is pointing to a char range element
  7886. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  7887. const llama_grammar_element * pos,
  7888. const uint32_t chr) {
  7889. bool found = false;
  7890. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7891. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  7892. do {
  7893. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7894. // inclusive range, e.g. [a-z]
  7895. found = found || (pos->value <= chr && chr <= pos[1].value);
  7896. pos += 2;
  7897. } else {
  7898. // exact char match, e.g. [a] or "a"
  7899. found = found || pos->value == chr;
  7900. pos += 1;
  7901. }
  7902. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7903. return std::make_pair(found == is_positive_char, pos);
  7904. }
  7905. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  7906. // range at pos (regular or inverse range)
  7907. // asserts that pos is pointing to a char range element
  7908. static bool llama_grammar_match_partial_char(
  7909. const llama_grammar_element * pos,
  7910. const llama_partial_utf8 partial_utf8) {
  7911. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7912. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  7913. uint32_t partial_value = partial_utf8.value;
  7914. int n_remain = partial_utf8.n_remain;
  7915. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  7916. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  7917. return false;
  7918. }
  7919. // range of possible code points this partial UTF-8 sequence could complete to
  7920. uint32_t low = partial_value << (n_remain * 6);
  7921. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  7922. if (low == 0) {
  7923. if (n_remain == 2) {
  7924. low = 1 << 11;
  7925. } else if (n_remain == 3) {
  7926. low = 1 << 16;
  7927. }
  7928. }
  7929. do {
  7930. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7931. // inclusive range, e.g. [a-z]
  7932. if (pos->value <= high && low <= pos[1].value) {
  7933. return is_positive_char;
  7934. }
  7935. pos += 2;
  7936. } else {
  7937. // exact char match, e.g. [a] or "a"
  7938. if (low <= pos->value && pos->value <= high) {
  7939. return is_positive_char;
  7940. }
  7941. pos += 1;
  7942. }
  7943. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7944. return !is_positive_char;
  7945. }
  7946. // transforms a grammar pushdown stack into N possible stacks, all ending
  7947. // at a character range (terminal element)
  7948. static void llama_grammar_advance_stack(
  7949. const std::vector<std::vector<llama_grammar_element>> & rules,
  7950. const std::vector<const llama_grammar_element *> & stack,
  7951. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  7952. if (stack.empty()) {
  7953. new_stacks.emplace_back(stack);
  7954. return;
  7955. }
  7956. const llama_grammar_element * pos = stack.back();
  7957. switch (pos->type) {
  7958. case LLAMA_GRETYPE_RULE_REF: {
  7959. const size_t rule_id = static_cast<size_t>(pos->value);
  7960. const llama_grammar_element * subpos = rules[rule_id].data();
  7961. do {
  7962. // init new stack without the top (pos)
  7963. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7964. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  7965. // if this rule ref is followed by another element, add that to stack
  7966. new_stack.push_back(pos + 1);
  7967. }
  7968. if (!llama_grammar_is_end_of_sequence(subpos)) {
  7969. // if alternate is nonempty, add to stack
  7970. new_stack.push_back(subpos);
  7971. }
  7972. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7973. while (!llama_grammar_is_end_of_sequence(subpos)) {
  7974. // scan to end of alternate def
  7975. subpos++;
  7976. }
  7977. if (subpos->type == LLAMA_GRETYPE_ALT) {
  7978. // there's another alternate def of this rule to process
  7979. subpos++;
  7980. } else {
  7981. break;
  7982. }
  7983. } while (true);
  7984. break;
  7985. }
  7986. case LLAMA_GRETYPE_CHAR:
  7987. case LLAMA_GRETYPE_CHAR_NOT:
  7988. new_stacks.emplace_back(stack);
  7989. break;
  7990. default:
  7991. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  7992. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  7993. // those
  7994. GGML_ASSERT(false);
  7995. }
  7996. }
  7997. // takes a set of possible pushdown stacks on a grammar, which are required to
  7998. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  7999. // produces the N possible stacks if the given char is accepted at those
  8000. // positions
  8001. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  8002. const std::vector<std::vector<llama_grammar_element>> & rules,
  8003. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8004. const uint32_t chr) {
  8005. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  8006. for (const auto & stack : stacks) {
  8007. if (stack.empty()) {
  8008. continue;
  8009. }
  8010. auto match = llama_grammar_match_char(stack.back(), chr);
  8011. if (match.first) {
  8012. const llama_grammar_element * pos = match.second;
  8013. // update top of stack to next element, if any
  8014. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8015. if (!llama_grammar_is_end_of_sequence(pos)) {
  8016. new_stack.push_back(pos);
  8017. }
  8018. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8019. }
  8020. }
  8021. return new_stacks;
  8022. }
  8023. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8024. const std::vector<std::vector<llama_grammar_element>> & rules,
  8025. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8026. const std::vector<llama_grammar_candidate> & candidates);
  8027. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  8028. const std::vector<std::vector<llama_grammar_element>> & rules,
  8029. const std::vector<const llama_grammar_element *> & stack,
  8030. const std::vector<llama_grammar_candidate> & candidates) {
  8031. std::vector<llama_grammar_candidate> rejects;
  8032. if (stack.empty()) {
  8033. for (const auto & tok : candidates) {
  8034. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  8035. rejects.push_back(tok);
  8036. }
  8037. }
  8038. return rejects;
  8039. }
  8040. const llama_grammar_element * stack_pos = stack.back();
  8041. std::vector<llama_grammar_candidate> next_candidates;
  8042. for (const auto & tok : candidates) {
  8043. if (*tok.code_points == 0) {
  8044. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  8045. // that cannot satisfy this position in grammar
  8046. if (tok.partial_utf8.n_remain != 0 &&
  8047. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  8048. rejects.push_back(tok);
  8049. }
  8050. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  8051. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  8052. } else {
  8053. rejects.push_back(tok);
  8054. }
  8055. }
  8056. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  8057. // update top of stack to next element, if any
  8058. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  8059. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  8060. stack_after.push_back(stack_pos_after);
  8061. }
  8062. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  8063. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  8064. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  8065. for (const auto & tok : next_rejects) {
  8066. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  8067. }
  8068. return rejects;
  8069. }
  8070. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8071. const std::vector<std::vector<llama_grammar_element>> & rules,
  8072. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8073. const std::vector<llama_grammar_candidate> & candidates) {
  8074. GGML_ASSERT(!stacks.empty()); // REVIEW
  8075. if (candidates.empty()) {
  8076. return std::vector<llama_grammar_candidate>();
  8077. }
  8078. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  8079. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  8080. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  8081. }
  8082. return rejects;
  8083. }
  8084. //
  8085. // grammar - external
  8086. //
  8087. struct llama_grammar * llama_grammar_init(
  8088. const llama_grammar_element ** rules,
  8089. size_t n_rules,
  8090. size_t start_rule_index) {
  8091. const llama_grammar_element * pos;
  8092. // copy rule definitions into vectors
  8093. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  8094. for (size_t i = 0; i < n_rules; i++) {
  8095. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  8096. vec_rules[i].push_back(*pos);
  8097. }
  8098. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  8099. }
  8100. // loop over alternates of start rule to build initial stacks
  8101. std::vector<std::vector<const llama_grammar_element *>> stacks;
  8102. pos = rules[start_rule_index];
  8103. do {
  8104. std::vector<const llama_grammar_element *> stack;
  8105. if (!llama_grammar_is_end_of_sequence(pos)) {
  8106. // if alternate is nonempty, add to stack
  8107. stack.push_back(pos);
  8108. }
  8109. llama_grammar_advance_stack(vec_rules, stack, stacks);
  8110. while (!llama_grammar_is_end_of_sequence(pos)) {
  8111. // scan to end of alternate def
  8112. pos++;
  8113. }
  8114. if (pos->type == LLAMA_GRETYPE_ALT) {
  8115. // there's another alternate def of this rule to process
  8116. pos++;
  8117. } else {
  8118. break;
  8119. }
  8120. } while (true);
  8121. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  8122. }
  8123. void llama_grammar_free(struct llama_grammar * grammar) {
  8124. delete grammar;
  8125. }
  8126. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  8127. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  8128. // redirect elements in stacks to point to new rules
  8129. for (size_t is = 0; is < result->stacks.size(); is++) {
  8130. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  8131. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  8132. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  8133. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  8134. result->stacks[is][ie] = &result->rules[ir0][ir1];
  8135. }
  8136. }
  8137. }
  8138. }
  8139. }
  8140. return result;
  8141. }
  8142. //
  8143. // sampling
  8144. //
  8145. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  8146. if (seed == LLAMA_DEFAULT_SEED) {
  8147. seed = time(NULL);
  8148. }
  8149. ctx->rng.seed(seed);
  8150. }
  8151. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  8152. GGML_ASSERT(candidates->size > 0);
  8153. const int64_t t_start_sample_us = ggml_time_us();
  8154. // Sort the logits in descending order
  8155. if (!candidates->sorted) {
  8156. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8157. return a.logit > b.logit;
  8158. });
  8159. candidates->sorted = true;
  8160. }
  8161. float max_l = candidates->data[0].logit;
  8162. float cum_sum = 0.0f;
  8163. for (size_t i = 0; i < candidates->size; ++i) {
  8164. float p = expf(candidates->data[i].logit - max_l);
  8165. candidates->data[i].p = p;
  8166. cum_sum += p;
  8167. }
  8168. for (size_t i = 0; i < candidates->size; ++i) {
  8169. candidates->data[i].p /= cum_sum;
  8170. }
  8171. if (ctx) {
  8172. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8173. }
  8174. }
  8175. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  8176. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  8177. // if (k >= (int32_t)candidates->size) {
  8178. // return;
  8179. // }
  8180. const int64_t t_start_sample_us = ggml_time_us();
  8181. if (k <= 0) {
  8182. k = candidates->size;
  8183. }
  8184. k = std::max(k, (int) min_keep);
  8185. k = std::min(k, (int) candidates->size);
  8186. // Sort scores in descending order
  8187. if (!candidates->sorted) {
  8188. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  8189. return a.logit > b.logit;
  8190. };
  8191. if (k <= 128) {
  8192. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  8193. } else {
  8194. constexpr int nbuckets = 128;
  8195. constexpr float bucket_low = -10.0f;
  8196. constexpr float bucket_high = 10.0f;
  8197. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  8198. constexpr float bucker_inter = -bucket_low * bucket_scale;
  8199. std::vector<int> bucket_idx(candidates->size);
  8200. std::vector<int> histo(nbuckets, 0);
  8201. for (int i = 0; i < (int)candidates->size; ++i) {
  8202. const float val = candidates->data[i].logit;
  8203. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  8204. ib = std::max(0, std::min(nbuckets-1, ib));
  8205. bucket_idx[i] = ib;
  8206. ++histo[ib];
  8207. }
  8208. int nhave = 0;
  8209. int ib = nbuckets - 1;
  8210. for ( ; ib >= 0; --ib) {
  8211. nhave += histo[ib];
  8212. if (nhave >= k) break;
  8213. }
  8214. std::vector<llama_token_data> tmp_tokens(nhave);
  8215. auto ptr = tmp_tokens.data();
  8216. std::vector<llama_token_data*> bucket_ptrs;
  8217. bucket_ptrs.reserve(nbuckets - ib);
  8218. for (int j = nbuckets - 1; j >= ib; --j) {
  8219. bucket_ptrs.push_back(ptr);
  8220. ptr += histo[j];
  8221. }
  8222. for (int i = 0; i < (int)candidates->size; ++i) {
  8223. int j = bucket_idx[i];
  8224. if (j >= ib) {
  8225. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  8226. }
  8227. }
  8228. ptr = tmp_tokens.data();
  8229. int ndone = 0;
  8230. for (int j = nbuckets-1; j > ib; --j) {
  8231. std::sort(ptr, ptr + histo[j], comp);
  8232. ptr += histo[j];
  8233. ndone += histo[j];
  8234. }
  8235. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  8236. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  8237. }
  8238. candidates->sorted = true;
  8239. }
  8240. candidates->size = k;
  8241. if (ctx) {
  8242. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8243. }
  8244. }
  8245. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8246. if (p >= 1.0f) {
  8247. return;
  8248. }
  8249. llama_sample_softmax(ctx, candidates);
  8250. const int64_t t_start_sample_us = ggml_time_us();
  8251. // Compute the cumulative probabilities
  8252. float cum_sum = 0.0f;
  8253. size_t last_idx = candidates->size;
  8254. for (size_t i = 0; i < candidates->size; ++i) {
  8255. cum_sum += candidates->data[i].p;
  8256. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  8257. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  8258. if (cum_sum >= p && i + 1 >= min_keep) {
  8259. last_idx = i + 1;
  8260. break;
  8261. }
  8262. }
  8263. // Resize the output vector to keep only the top-p tokens
  8264. candidates->size = last_idx;
  8265. if (ctx) {
  8266. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8267. }
  8268. }
  8269. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8270. if (p <= 0.0f || !candidates->size) {
  8271. return;
  8272. }
  8273. const int64_t t_start_sample_us = ggml_time_us();
  8274. bool min_p_applied = false;
  8275. // if the candidates aren't sorted, try the unsorted implementation first
  8276. if (!candidates->sorted) {
  8277. std::vector<llama_token_data> filtered_tokens;
  8278. float max_logit = -FLT_MAX;
  8279. for (size_t i = 0; i < candidates->size; ++i) {
  8280. max_logit = std::max(max_logit, candidates->data[i].logit);
  8281. }
  8282. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  8283. for (size_t i = 0; i < candidates->size; ++i) {
  8284. if (candidates->data[i].logit >= min_logit) {
  8285. filtered_tokens.push_back(candidates->data[i]);
  8286. }
  8287. }
  8288. // if we have enough values the operation was a success
  8289. if (filtered_tokens.size() >= min_keep) {
  8290. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  8291. candidates->size = filtered_tokens.size();
  8292. min_p_applied = true;
  8293. }
  8294. }
  8295. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  8296. if (!min_p_applied) {
  8297. // Sort the logits in descending order
  8298. if (!candidates->sorted) {
  8299. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8300. return a.logit > b.logit;
  8301. });
  8302. candidates->sorted = true;
  8303. }
  8304. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  8305. size_t i = 1; // first token always matches
  8306. for (; i < candidates->size; ++i) {
  8307. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  8308. break; // prob too small
  8309. }
  8310. }
  8311. // Resize the output vector to keep only the matching tokens
  8312. candidates->size = i;
  8313. }
  8314. if (ctx) {
  8315. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8316. }
  8317. }
  8318. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  8319. if (z >= 1.0f || candidates->size <= 2) {
  8320. return;
  8321. }
  8322. llama_sample_softmax(nullptr, candidates);
  8323. const int64_t t_start_sample_us = ggml_time_us();
  8324. // Compute the first and second derivatives
  8325. std::vector<float> first_derivatives(candidates->size - 1);
  8326. std::vector<float> second_derivatives(candidates->size - 2);
  8327. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  8328. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  8329. }
  8330. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8331. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  8332. }
  8333. // Calculate absolute value of second derivatives
  8334. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8335. second_derivatives[i] = std::abs(second_derivatives[i]);
  8336. }
  8337. // Normalize the second derivatives
  8338. {
  8339. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  8340. if (second_derivatives_sum > 1e-6f) {
  8341. for (float & value : second_derivatives) {
  8342. value /= second_derivatives_sum;
  8343. }
  8344. } else {
  8345. for (float & value : second_derivatives) {
  8346. value = 1.0f / second_derivatives.size();
  8347. }
  8348. }
  8349. }
  8350. float cum_sum = 0.0f;
  8351. size_t last_idx = candidates->size;
  8352. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8353. cum_sum += second_derivatives[i];
  8354. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  8355. if (cum_sum > z && i >= min_keep) {
  8356. last_idx = i;
  8357. break;
  8358. }
  8359. }
  8360. // Resize the output vector to keep only the tokens above the tail location
  8361. candidates->size = last_idx;
  8362. if (ctx) {
  8363. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8364. }
  8365. }
  8366. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8367. // Reference implementation:
  8368. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  8369. if (p >= 1.0f) {
  8370. return;
  8371. }
  8372. // Compute the softmax of logits and calculate entropy
  8373. llama_sample_softmax(nullptr, candidates);
  8374. const int64_t t_start_sample_us = ggml_time_us();
  8375. float entropy = 0.0f;
  8376. for (size_t i = 0; i < candidates->size; ++i) {
  8377. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  8378. }
  8379. // Compute the absolute difference between negative log probability and entropy for each candidate
  8380. std::vector<float> shifted_scores;
  8381. for (size_t i = 0; i < candidates->size; ++i) {
  8382. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  8383. shifted_scores.push_back(shifted_score);
  8384. }
  8385. // Sort tokens based on the shifted_scores and their corresponding indices
  8386. std::vector<size_t> indices(candidates->size);
  8387. std::iota(indices.begin(), indices.end(), 0);
  8388. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  8389. return shifted_scores[a] < shifted_scores[b];
  8390. });
  8391. // Compute the cumulative probabilities
  8392. float cum_sum = 0.0f;
  8393. size_t last_idx = indices.size();
  8394. for (size_t i = 0; i < indices.size(); ++i) {
  8395. size_t idx = indices[i];
  8396. cum_sum += candidates->data[idx].p;
  8397. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  8398. if (cum_sum > p && i >= min_keep - 1) {
  8399. last_idx = i + 1;
  8400. break;
  8401. }
  8402. }
  8403. // Resize the output vector to keep only the locally typical tokens
  8404. std::vector<llama_token_data> new_candidates;
  8405. for (size_t i = 0; i < last_idx; ++i) {
  8406. size_t idx = indices[i];
  8407. new_candidates.push_back(candidates->data[idx]);
  8408. }
  8409. // Replace the data in candidates with the new_candidates data
  8410. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  8411. candidates->size = new_candidates.size();
  8412. candidates->sorted = false;
  8413. if (ctx) {
  8414. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8415. }
  8416. }
  8417. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  8418. const int64_t t_start_sample_us = ggml_time_us();
  8419. // no need to do anything if there is only one (or zero) candidates
  8420. if(candidates_p->size <= 1) {
  8421. return;
  8422. }
  8423. // Calculate maximum possible entropy
  8424. float max_entropy = -logf(1.0f / candidates_p->size);
  8425. llama_sample_softmax(nullptr, candidates_p);
  8426. // Calculate entropy of the softmax probabilities
  8427. float entropy = 0.0f;
  8428. for (size_t i = 0; i < candidates_p->size; ++i) {
  8429. float prob = candidates_p->data[i].p;
  8430. if (prob > 0.0f) { // Ensure no log(0)
  8431. entropy -= prob * logf(prob);
  8432. }
  8433. }
  8434. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  8435. float normalized_entropy = entropy / max_entropy;
  8436. // Map the normalized entropy to the desired temperature range using the power function
  8437. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  8438. #ifdef DEBUG
  8439. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  8440. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  8441. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  8442. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  8443. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  8444. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  8445. #endif
  8446. // Apply the dynamically calculated temperature scaling
  8447. for (size_t i = 0; i < candidates_p->size; ++i) {
  8448. candidates_p->data[i].logit /= dyn_temp;
  8449. }
  8450. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  8451. double max_l_double = candidates_p->data[0].logit;
  8452. double cum_sum_double = 0.0;
  8453. for (size_t i = 0; i < candidates_p->size; ++i) {
  8454. double p = exp(candidates_p->data[i].logit - max_l_double);
  8455. candidates_p->data[i].p = p; // Store the scaled probability
  8456. cum_sum_double += p;
  8457. }
  8458. for (size_t i = 0; i < candidates_p->size; ++i) {
  8459. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  8460. }
  8461. #ifdef DEBUG
  8462. // Print the updated top 25 probabilities after temperature scaling
  8463. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  8464. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  8465. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  8466. }
  8467. #endif
  8468. if (ctx) {
  8469. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8470. }
  8471. }
  8472. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8473. const int64_t t_start_sample_us = ggml_time_us();
  8474. for (size_t i = 0; i < candidates_p->size; ++i) {
  8475. candidates_p->data[i].logit /= temp;
  8476. }
  8477. if (ctx) {
  8478. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8479. }
  8480. }
  8481. void llama_sample_repetition_penalties(
  8482. struct llama_context * ctx,
  8483. llama_token_data_array * candidates,
  8484. const llama_token * last_tokens,
  8485. size_t penalty_last_n,
  8486. float penalty_repeat,
  8487. float penalty_freq,
  8488. float penalty_present) {
  8489. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  8490. return;
  8491. }
  8492. const int64_t t_start_sample_us = ggml_time_us();
  8493. // Create a frequency map to count occurrences of each token in last_tokens
  8494. std::unordered_map<llama_token, int> token_count;
  8495. for (size_t i = 0; i < penalty_last_n; ++i) {
  8496. token_count[last_tokens[i]]++;
  8497. }
  8498. // Apply frequency and presence penalties to the candidates
  8499. for (size_t i = 0; i < candidates->size; ++i) {
  8500. const auto token_iter = token_count.find(candidates->data[i].id);
  8501. if (token_iter == token_count.end()) {
  8502. continue;
  8503. }
  8504. const int count = token_iter->second;
  8505. // 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.
  8506. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  8507. if (candidates->data[i].logit <= 0) {
  8508. candidates->data[i].logit *= penalty_repeat;
  8509. } else {
  8510. candidates->data[i].logit /= penalty_repeat;
  8511. }
  8512. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  8513. }
  8514. candidates->sorted = false;
  8515. if (ctx) {
  8516. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8517. }
  8518. }
  8519. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  8520. GGML_ASSERT(ctx);
  8521. const int64_t t_start_sample_us = ggml_time_us();
  8522. bool allow_eos = false;
  8523. for (const auto & stack : grammar->stacks) {
  8524. if (stack.empty()) {
  8525. allow_eos = true;
  8526. break;
  8527. }
  8528. }
  8529. const llama_token eos = llama_token_eos(&ctx->model);
  8530. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  8531. candidates_decoded.reserve(candidates->size);
  8532. std::vector<llama_grammar_candidate> candidates_grammar;
  8533. candidates_grammar.reserve(candidates->size);
  8534. for (size_t i = 0; i < candidates->size; ++i) {
  8535. const llama_token id = candidates->data[i].id;
  8536. const std::string piece = llama_token_to_piece(ctx, id);
  8537. if (id == eos) {
  8538. if (!allow_eos) {
  8539. candidates->data[i].logit = -INFINITY;
  8540. }
  8541. } else if (piece.empty() || piece[0] == 0) {
  8542. candidates->data[i].logit = -INFINITY;
  8543. } else {
  8544. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  8545. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  8546. }
  8547. }
  8548. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  8549. for (const auto & reject : rejects) {
  8550. candidates->data[reject.index].logit = -INFINITY;
  8551. }
  8552. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8553. }
  8554. static void llama_log_softmax(float * array, size_t size) {
  8555. float max_l = *std::max_element(array, array + size);
  8556. float sum = 0.f;
  8557. for (size_t i = 0; i < size; ++i) {
  8558. float p = expf(array[i] - max_l);
  8559. sum += p;
  8560. array[i] = p;
  8561. }
  8562. for (size_t i = 0; i < size; ++i) {
  8563. array[i] = logf(array[i] / sum);
  8564. }
  8565. }
  8566. void llama_sample_apply_guidance(
  8567. struct llama_context * ctx,
  8568. float * logits,
  8569. float * logits_guidance,
  8570. float scale) {
  8571. GGML_ASSERT(ctx);
  8572. const auto t_start_sample_us = ggml_time_us();
  8573. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  8574. llama_log_softmax(logits, n_vocab);
  8575. llama_log_softmax(logits_guidance, n_vocab);
  8576. for (int i = 0; i < n_vocab; ++i) {
  8577. auto & l = logits[i];
  8578. const auto & g = logits_guidance[i];
  8579. l = scale * (l - g) + g;
  8580. }
  8581. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8582. }
  8583. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  8584. GGML_ASSERT(ctx);
  8585. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  8586. int64_t t_start_sample_us;
  8587. t_start_sample_us = ggml_time_us();
  8588. llama_sample_softmax(nullptr, candidates);
  8589. // Estimate s_hat using the most probable m tokens
  8590. float s_hat = 0.0;
  8591. float sum_ti_bi = 0.0;
  8592. float sum_ti_sq = 0.0;
  8593. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  8594. float t_i = logf(float(i + 2) / float(i + 1));
  8595. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  8596. sum_ti_bi += t_i * b_i;
  8597. sum_ti_sq += t_i * t_i;
  8598. }
  8599. s_hat = sum_ti_bi / sum_ti_sq;
  8600. // Compute k from the estimated s_hat and target surprise value
  8601. float epsilon_hat = s_hat - 1;
  8602. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  8603. // Sample the next word X using top-k sampling
  8604. llama_sample_top_k(nullptr, candidates, int(k), 1);
  8605. if (ctx) {
  8606. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8607. }
  8608. llama_token X = llama_sample_token(ctx, candidates);
  8609. t_start_sample_us = ggml_time_us();
  8610. // Compute error as the difference between observed surprise and target surprise value
  8611. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8612. return candidate.id == X;
  8613. }));
  8614. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8615. float e = observed_surprise - tau;
  8616. // Update mu using the learning rate and error
  8617. *mu = *mu - eta * e;
  8618. if (ctx) {
  8619. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8620. }
  8621. return X;
  8622. }
  8623. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  8624. int64_t t_start_sample_us;
  8625. t_start_sample_us = ggml_time_us();
  8626. llama_sample_softmax(ctx, candidates);
  8627. // Truncate the words with surprise values greater than mu
  8628. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8629. return -log2f(candidate.p) > *mu;
  8630. }));
  8631. if (candidates->size == 0) {
  8632. candidates->size = 1;
  8633. }
  8634. if (ctx) {
  8635. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8636. }
  8637. // Normalize the probabilities of the remaining words
  8638. llama_sample_softmax(ctx, candidates);
  8639. // Sample the next word X from the remaining words
  8640. llama_token X = llama_sample_token(ctx, candidates);
  8641. t_start_sample_us = ggml_time_us();
  8642. // Compute error as the difference between observed surprise and target surprise value
  8643. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8644. return candidate.id == X;
  8645. }));
  8646. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8647. float e = observed_surprise - tau;
  8648. // Update mu using the learning rate and error
  8649. *mu = *mu - eta * e;
  8650. if (ctx) {
  8651. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8652. }
  8653. return X;
  8654. }
  8655. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  8656. const int64_t t_start_sample_us = ggml_time_us();
  8657. // Find max element
  8658. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8659. return a.logit < b.logit;
  8660. });
  8661. llama_token result = max_iter->id;
  8662. if (ctx) {
  8663. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8664. ctx->n_sample++;
  8665. }
  8666. return result;
  8667. }
  8668. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  8669. GGML_ASSERT(ctx);
  8670. const int64_t t_start_sample_us = ggml_time_us();
  8671. llama_sample_softmax(nullptr, candidates);
  8672. std::vector<float> probs;
  8673. probs.reserve(candidates->size);
  8674. for (size_t i = 0; i < candidates->size; ++i) {
  8675. probs.push_back(candidates->data[i].p);
  8676. }
  8677. std::discrete_distribution<> dist(probs.begin(), probs.end());
  8678. auto & rng = ctx->rng;
  8679. int idx = dist(rng);
  8680. llama_token result = candidates->data[idx].id;
  8681. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8682. ctx->n_sample++;
  8683. return result;
  8684. }
  8685. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  8686. const int64_t t_start_sample_us = ggml_time_us();
  8687. if (token == llama_token_eos(&ctx->model)) {
  8688. for (const auto & stack : grammar->stacks) {
  8689. if (stack.empty()) {
  8690. return;
  8691. }
  8692. }
  8693. GGML_ASSERT(false);
  8694. }
  8695. const std::string piece = llama_token_to_piece(ctx, token);
  8696. // Note terminating 0 in decoded string
  8697. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  8698. const auto & code_points = decoded.first;
  8699. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  8700. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  8701. }
  8702. grammar->partial_utf8 = decoded.second;
  8703. GGML_ASSERT(!grammar->stacks.empty());
  8704. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8705. }
  8706. //
  8707. // Beam search
  8708. //
  8709. struct llama_beam {
  8710. std::vector<llama_token> tokens;
  8711. float p; // Cumulative beam probability (renormalized relative to all beams)
  8712. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  8713. // Sort beams by probability. In case of ties, prefer beams at eob.
  8714. bool operator<(const llama_beam & rhs) const {
  8715. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  8716. }
  8717. // Shift off first n tokens and discard them.
  8718. void shift_tokens(const size_t n) {
  8719. if (n) {
  8720. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  8721. tokens.resize(tokens.size() - n);
  8722. }
  8723. }
  8724. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  8725. };
  8726. // A struct for calculating logit-related info.
  8727. struct llama_logit_info {
  8728. const float * const logits;
  8729. const int n_vocab;
  8730. const float max_l;
  8731. const float normalizer;
  8732. struct sum_exp {
  8733. float max_l;
  8734. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  8735. };
  8736. llama_logit_info(llama_context * ctx)
  8737. : logits(llama_get_logits(ctx))
  8738. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  8739. , max_l(*std::max_element(logits, logits + n_vocab))
  8740. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  8741. { }
  8742. llama_token_data get_token_data(const llama_token token_id) const {
  8743. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  8744. return {token_id, logits[token_id], p};
  8745. }
  8746. // Return top k token_data by logit.
  8747. std::vector<llama_token_data> top_k(size_t k) {
  8748. std::vector<llama_token_data> min_heap; // min-heap by logit
  8749. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  8750. min_heap.reserve(k_min);
  8751. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  8752. min_heap.push_back(get_token_data(token_id));
  8753. }
  8754. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  8755. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  8756. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  8757. if (min_heap.front().logit < logits[token_id]) {
  8758. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  8759. min_heap.back().id = token_id;
  8760. min_heap.back().logit = logits[token_id];
  8761. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  8762. }
  8763. }
  8764. return min_heap;
  8765. }
  8766. float probability_from_logit(float logit) const {
  8767. return normalizer * std::exp(logit - max_l);
  8768. }
  8769. };
  8770. struct llama_beam_search_data {
  8771. llama_context * ctx;
  8772. size_t n_beams;
  8773. int n_past;
  8774. int n_predict;
  8775. std::vector<llama_beam> beams;
  8776. std::vector<llama_beam> next_beams;
  8777. // Re-calculated on each loop iteration
  8778. size_t common_prefix_length;
  8779. // Used to communicate to/from callback on beams state.
  8780. std::vector<llama_beam_view> beam_views;
  8781. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  8782. : ctx(ctx)
  8783. , n_beams(n_beams)
  8784. , n_past(n_past)
  8785. , n_predict(n_predict)
  8786. , beam_views(n_beams) {
  8787. beams.reserve(n_beams);
  8788. next_beams.reserve(n_beams);
  8789. }
  8790. // Collapse beams to a single beam given by index.
  8791. void collapse_beams(const size_t beam_idx) {
  8792. if (0u < beam_idx) {
  8793. std::swap(beams[0], beams[beam_idx]);
  8794. }
  8795. beams.resize(1);
  8796. }
  8797. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  8798. // The repetitive patterns below reflect the 2 stages of heaps:
  8799. // * Gather elements until the vector is full, then call std::make_heap() on it.
  8800. // * If the heap is full and a new element is found that should be included, pop the
  8801. // least element to the back(), replace it with the new, then push it into the heap.
  8802. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  8803. // Min-heaps use a greater-than comparator.
  8804. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  8805. if (beam.eob) {
  8806. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  8807. if (next_beams.size() < n_beams) {
  8808. next_beams.push_back(std::move(beam));
  8809. if (next_beams.size() == n_beams) {
  8810. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8811. }
  8812. } else if (next_beams.front().p < beam.p) {
  8813. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8814. next_beams.back() = std::move(beam);
  8815. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8816. }
  8817. } else {
  8818. // beam is not at end-of-sentence, so branch with next top_k tokens.
  8819. if (!beam.tokens.empty()) {
  8820. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  8821. }
  8822. llama_logit_info logit_info(ctx);
  8823. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  8824. size_t i=0;
  8825. if (next_beams.size() < n_beams) {
  8826. for (; next_beams.size() < n_beams ; ++i) {
  8827. llama_beam next_beam = beam;
  8828. next_beam.tokens.push_back(next_tokens[i].id);
  8829. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8830. next_beams.push_back(std::move(next_beam));
  8831. }
  8832. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8833. } else {
  8834. for (; next_beams.front().p == 0.0f ; ++i) {
  8835. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8836. next_beams.back() = beam;
  8837. next_beams.back().tokens.push_back(next_tokens[i].id);
  8838. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8839. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8840. }
  8841. }
  8842. for (; i < n_beams ; ++i) {
  8843. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  8844. if (next_beams.front().p < next_p) {
  8845. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8846. next_beams.back() = beam;
  8847. next_beams.back().tokens.push_back(next_tokens[i].id);
  8848. next_beams.back().p = next_p;
  8849. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8850. }
  8851. }
  8852. }
  8853. }
  8854. // Find common_prefix_length based on beams.
  8855. // Requires beams is not empty.
  8856. size_t find_common_prefix_length() {
  8857. size_t common_prefix_length = beams[0].tokens.size();
  8858. for (size_t i = 1 ; i < beams.size() ; ++i) {
  8859. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  8860. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  8861. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  8862. common_prefix_length = j;
  8863. break;
  8864. }
  8865. }
  8866. }
  8867. return common_prefix_length;
  8868. }
  8869. // Construct beams_state to send back to caller via the callback function.
  8870. // Side effect: set common_prefix_length = find_common_prefix_length();
  8871. llama_beams_state get_beams_state(const bool last_call) {
  8872. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8873. beam_views[i] = beams[i].view();
  8874. }
  8875. common_prefix_length = find_common_prefix_length();
  8876. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  8877. }
  8878. // Loop:
  8879. // * while i < n_predict, AND
  8880. // * any of the beams have not yet reached end-of-beam (eob), AND
  8881. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  8882. // (since all other beam probabilities can only decrease)
  8883. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  8884. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  8885. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  8886. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  8887. !beams[top_beam_index()].eob ; ++i) {
  8888. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  8889. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  8890. if (common_prefix_length) {
  8891. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  8892. n_past += common_prefix_length;
  8893. }
  8894. // Zero-out next_beam probabilities to place them last in following min-heap.
  8895. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  8896. for (llama_beam & beam : beams) {
  8897. beam.shift_tokens(common_prefix_length);
  8898. fill_next_beams_by_top_probabilities(beam);
  8899. }
  8900. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  8901. beams.swap(next_beams);
  8902. renormalize_beam_probabilities(beams);
  8903. }
  8904. collapse_beams(top_beam_index());
  8905. callback(callback_data, get_beams_state(true));
  8906. }
  8907. // As beams grow, the cumulative probabilities decrease.
  8908. // Renormalize them to avoid floating point underflow.
  8909. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  8910. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  8911. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  8912. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  8913. }
  8914. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  8915. size_t top_beam_index() {
  8916. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  8917. }
  8918. // Copy (p,eob) for each beam which may have been changed by the callback.
  8919. void update_beams_from_beam_views() {
  8920. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8921. beams[i].p = beam_views[i].p;
  8922. beams[i].eob = beam_views[i].eob;
  8923. }
  8924. }
  8925. };
  8926. void llama_beam_search(llama_context * ctx,
  8927. llama_beam_search_callback_fn_t callback, void * callback_data,
  8928. size_t n_beams, int n_past, int n_predict) {
  8929. assert(ctx);
  8930. const int64_t t_start_sample_us = ggml_time_us();
  8931. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  8932. beam_search_data.loop(callback, callback_data);
  8933. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8934. ctx->n_sample++;
  8935. }
  8936. //
  8937. // quantization
  8938. //
  8939. struct quantize_state_internal {
  8940. const llama_model & model;
  8941. const llama_model_quantize_params * params;
  8942. int n_attention_wv = 0;
  8943. int n_ffn_down = 0;
  8944. int n_ffn_gate = 0;
  8945. int n_ffn_up = 0;
  8946. int i_attention_wv = 0;
  8947. int i_ffn_down = 0;
  8948. int i_ffn_gate = 0;
  8949. int i_ffn_up = 0;
  8950. int n_k_quantized = 0;
  8951. int n_fallback = 0;
  8952. bool has_imatrix = false;
  8953. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  8954. : model(model)
  8955. , params(params)
  8956. {}
  8957. };
  8958. static void llama_convert_tensor_internal(
  8959. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  8960. const size_t nelements, const int nthread
  8961. ) {
  8962. if (output.size() < nelements) {
  8963. output.resize(nelements);
  8964. }
  8965. float * f32_output = (float *) output.data();
  8966. ggml_type_traits_t qtype;
  8967. if (ggml_is_quantized(tensor->type)) {
  8968. qtype = ggml_internal_get_type_traits(tensor->type);
  8969. if (qtype.to_float == NULL) {
  8970. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  8971. }
  8972. } else if (tensor->type != GGML_TYPE_F16) {
  8973. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  8974. }
  8975. if (nthread < 2) {
  8976. if (tensor->type == GGML_TYPE_F16) {
  8977. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  8978. } else if (ggml_is_quantized(tensor->type)) {
  8979. qtype.to_float(tensor->data, f32_output, nelements);
  8980. } else {
  8981. GGML_ASSERT(false); // unreachable
  8982. }
  8983. return;
  8984. }
  8985. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  8986. size_t block_size_bytes = ggml_type_size(tensor->type);
  8987. GGML_ASSERT(nelements % block_size == 0);
  8988. size_t nblocks = nelements / block_size;
  8989. size_t blocks_per_thread = nblocks / nthread;
  8990. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  8991. size_t in_buff_offs = 0;
  8992. size_t out_buff_offs = 0;
  8993. for (int tnum = 0; tnum < nthread; tnum++) {
  8994. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  8995. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  8996. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  8997. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  8998. if (typ == GGML_TYPE_F16) {
  8999. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  9000. } else {
  9001. qtype.to_float(inbuf, outbuf, nels);
  9002. }
  9003. };
  9004. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  9005. in_buff_offs += thr_block_bytes;
  9006. out_buff_offs += thr_elems;
  9007. }
  9008. for (auto & w : workers) { w.join(); }
  9009. workers.clear();
  9010. }
  9011. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  9012. const std::string name = ggml_get_name(tensor);
  9013. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9014. const llm_arch arch = qs.model.arch;
  9015. const auto tn = LLM_TN(arch);
  9016. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  9017. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  9018. };
  9019. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  9020. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  9021. if (n_expert > 1) {
  9022. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  9023. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  9024. // for getting the current layer as I initially thought, and we need to resort to parsing the
  9025. // tensor name.
  9026. n_layer /= n_expert;
  9027. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  9028. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  9029. }
  9030. if (i_layer < 0 || i_layer >= n_layer) {
  9031. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  9032. }
  9033. }
  9034. return std::make_pair(i_layer, n_layer);
  9035. };
  9036. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  9037. // with the quantization of the output tensor
  9038. if (name == tn(LLM_TENSOR_OUTPUT, "weight") ||
  9039. (LLM_TENSOR_NAMES.at(arch).find(LLM_TENSOR_OUTPUT) == LLM_TENSOR_NAMES.at(arch).end() && name == "token_embd.weight")) {
  9040. int nx = tensor->ne[0];
  9041. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  9042. new_type = GGML_TYPE_Q8_0;
  9043. }
  9044. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9045. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9046. new_type = GGML_TYPE_Q5_K;
  9047. }
  9048. else if (new_type != GGML_TYPE_Q8_0) {
  9049. new_type = GGML_TYPE_Q6_K;
  9050. }
  9051. } else if (name == "token_embd.weight") {
  9052. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  9053. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  9054. new_type = GGML_TYPE_Q2_K;
  9055. }
  9056. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9057. new_type = GGML_TYPE_IQ3_S;
  9058. }
  9059. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9060. new_type = GGML_TYPE_IQ3_S;
  9061. }
  9062. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  9063. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9064. if (name.find("attn_v.weight") != std::string::npos) {
  9065. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  9066. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9067. ++qs.i_attention_wv;
  9068. }
  9069. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  9070. new_type = GGML_TYPE_Q4_K;
  9071. }
  9072. else if (name.find("ffn_down") != std::string::npos) {
  9073. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  9074. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9075. }
  9076. ++qs.i_ffn_down;
  9077. }
  9078. else if (name.find("attn_output.weight") != std::string::npos) {
  9079. if (qs.model.hparams.n_expert == 8) {
  9080. new_type = GGML_TYPE_Q5_K;
  9081. } else {
  9082. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  9083. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  9084. }
  9085. }
  9086. } else if (name.find("attn_v.weight") != std::string::npos) {
  9087. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  9088. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9089. }
  9090. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  9091. new_type = GGML_TYPE_Q4_K;
  9092. }
  9093. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9094. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  9095. }
  9096. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9097. new_type = GGML_TYPE_Q4_K;
  9098. }
  9099. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9100. new_type = GGML_TYPE_Q4_K;
  9101. }
  9102. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9103. new_type = GGML_TYPE_Q4_K;
  9104. }
  9105. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9106. new_type = GGML_TYPE_Q4_K;
  9107. }
  9108. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9109. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9110. }
  9111. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  9112. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  9113. new_type = GGML_TYPE_Q5_K;
  9114. }
  9115. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  9116. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  9117. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  9118. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  9119. (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;
  9120. if (qs.model.type == MODEL_70B) {
  9121. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  9122. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  9123. // nearly negligible increase in model size by quantizing this tensor with more bits:
  9124. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  9125. }
  9126. if (qs.model.hparams.n_expert == 8) {
  9127. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9128. // TODO: explore better strategies
  9129. new_type = GGML_TYPE_Q8_0;
  9130. }
  9131. ++qs.i_attention_wv;
  9132. } else if (name.find("attn_k.weight") != std::string::npos) {
  9133. if (qs.model.hparams.n_expert == 8) {
  9134. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9135. // TODO: explore better strategies
  9136. new_type = GGML_TYPE_Q8_0;
  9137. }
  9138. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9139. new_type = GGML_TYPE_IQ3_XXS;
  9140. }
  9141. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9142. new_type = GGML_TYPE_IQ2_S;
  9143. }
  9144. } else if (name.find("attn_q.weight") != std::string::npos) {
  9145. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9146. new_type = GGML_TYPE_IQ3_XXS;
  9147. }
  9148. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9149. new_type = GGML_TYPE_IQ2_S;
  9150. }
  9151. } else if (name.find("ffn_down") != std::string::npos) {
  9152. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  9153. int i_layer = info.first, n_layer = info.second;
  9154. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9155. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  9156. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  9157. }
  9158. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  9159. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9160. }
  9161. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9162. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  9163. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  9164. : GGML_TYPE_Q3_K;
  9165. }
  9166. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  9167. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  9168. new_type = GGML_TYPE_Q4_K;
  9169. }
  9170. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  9171. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  9172. }
  9173. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  9174. if (arch == LLM_ARCH_FALCON) {
  9175. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  9176. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9177. } else {
  9178. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9179. }
  9180. }
  9181. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  9182. new_type = GGML_TYPE_Q5_K;
  9183. }
  9184. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9185. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  9186. new_type = GGML_TYPE_Q5_K;
  9187. }
  9188. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  9189. && qs.has_imatrix && i_layer < n_layer/8) {
  9190. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  9191. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  9192. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  9193. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  9194. }
  9195. ++qs.i_ffn_down;
  9196. } else if (name.find("attn_output.weight") != std::string::npos) {
  9197. if (arch != LLM_ARCH_FALCON) {
  9198. if (qs.model.hparams.n_expert == 8) {
  9199. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9200. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  9201. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  9202. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  9203. new_type = GGML_TYPE_Q5_K;
  9204. }
  9205. } else {
  9206. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  9207. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  9208. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  9209. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  9210. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  9211. }
  9212. } else {
  9213. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  9214. }
  9215. }
  9216. else if (name.find("attn_qkv.weight") != std::string::npos) {
  9217. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9218. new_type = GGML_TYPE_Q4_K;
  9219. }
  9220. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  9221. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  9222. }
  9223. else if (name.find("ffn_gate") != std::string::npos) {
  9224. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  9225. int i_layer = info.first, n_layer = info.second;
  9226. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9227. new_type = GGML_TYPE_IQ3_XXS;
  9228. }
  9229. ++qs.i_ffn_gate;
  9230. }
  9231. else if (name.find("ffn_up") != std::string::npos) {
  9232. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  9233. int i_layer = info.first, n_layer = info.second;
  9234. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9235. new_type = GGML_TYPE_IQ3_XXS;
  9236. }
  9237. ++qs.i_ffn_up;
  9238. }
  9239. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9240. //}
  9241. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  9242. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  9243. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9244. //}
  9245. // This can be used to reduce the size of the Q5_K_S model.
  9246. // The associated PPL increase is fully in line with the size reduction
  9247. //else {
  9248. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  9249. //}
  9250. bool convert_incompatible_tensor = false;
  9251. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  9252. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  9253. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  9254. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  9255. int nx = tensor->ne[0];
  9256. int ny = tensor->ne[1];
  9257. if (nx % QK_K != 0) {
  9258. 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));
  9259. convert_incompatible_tensor = true;
  9260. } else {
  9261. ++qs.n_k_quantized;
  9262. }
  9263. }
  9264. if (convert_incompatible_tensor) {
  9265. switch (new_type) {
  9266. case GGML_TYPE_IQ2_XXS:
  9267. case GGML_TYPE_IQ2_XS:
  9268. case GGML_TYPE_IQ2_S:
  9269. case GGML_TYPE_IQ3_XXS:
  9270. case GGML_TYPE_IQ3_S:
  9271. case GGML_TYPE_IQ1_S:
  9272. case GGML_TYPE_Q2_K:
  9273. case GGML_TYPE_Q3_K:
  9274. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  9275. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  9276. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  9277. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  9278. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  9279. }
  9280. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  9281. ++qs.n_fallback;
  9282. }
  9283. return new_type;
  9284. }
  9285. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  9286. ggml_type quantized_type;
  9287. llama_ftype ftype = params->ftype;
  9288. switch (params->ftype) {
  9289. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  9290. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  9291. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  9292. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  9293. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  9294. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  9295. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  9296. // K-quants
  9297. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  9298. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  9299. case LLAMA_FTYPE_MOSTLY_IQ3_XS: quantized_type = GGML_TYPE_IQ3_S; break;
  9300. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  9301. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  9302. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  9303. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  9304. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  9305. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  9306. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  9307. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  9308. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: quantized_type = GGML_TYPE_IQ2_XXS; break;
  9309. case LLAMA_FTYPE_MOSTLY_IQ2_XS: quantized_type = GGML_TYPE_IQ2_XS; break;
  9310. case LLAMA_FTYPE_MOSTLY_IQ2_S: quantized_type = GGML_TYPE_IQ2_XS; break;
  9311. case LLAMA_FTYPE_MOSTLY_IQ2_M: quantized_type = GGML_TYPE_IQ2_S; break;
  9312. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: quantized_type = GGML_TYPE_IQ3_XXS; break;
  9313. case LLAMA_FTYPE_MOSTLY_IQ1_S: quantized_type = GGML_TYPE_IQ1_S; break;
  9314. case LLAMA_FTYPE_MOSTLY_IQ4_NL: quantized_type = GGML_TYPE_IQ4_NL; break;
  9315. case LLAMA_FTYPE_MOSTLY_IQ4_XS: quantized_type = GGML_TYPE_IQ4_XS; break;
  9316. case LLAMA_FTYPE_MOSTLY_IQ3_S: quantized_type = GGML_TYPE_IQ3_S; break;
  9317. case LLAMA_FTYPE_MOSTLY_IQ3_M: quantized_type = GGML_TYPE_IQ3_S; break;
  9318. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  9319. }
  9320. int nthread = params->nthread;
  9321. if (nthread <= 0) {
  9322. nthread = std::thread::hardware_concurrency();
  9323. }
  9324. // mmap consistently increases speed Linux, and also increases speed on Windows with
  9325. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  9326. #if defined(__linux__) || defined(_WIN32)
  9327. constexpr bool use_mmap = true;
  9328. #else
  9329. constexpr bool use_mmap = false;
  9330. #endif
  9331. llama_model_loader ml(fname_inp, use_mmap, NULL);
  9332. ml.init_mapping(false); // no prefetching?
  9333. llama_model model;
  9334. llm_load_arch(ml, model);
  9335. llm_load_hparams(ml, model);
  9336. struct quantize_state_internal qs(model, params);
  9337. if (params->only_copy) {
  9338. ftype = model.ftype;
  9339. }
  9340. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  9341. if (params->imatrix) {
  9342. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  9343. if (imatrix_data) {
  9344. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  9345. qs.has_imatrix = true;
  9346. }
  9347. }
  9348. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  9349. struct gguf_context * ctx_out = gguf_init_empty();
  9350. // copy the KV pairs from the input file
  9351. gguf_set_kv (ctx_out, ml.ctx_gguf);
  9352. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  9353. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  9354. for (int i = 0; i < ml.n_tensors; ++i) {
  9355. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9356. const std::string name = ggml_get_name(meta);
  9357. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9358. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  9359. ++qs.n_attention_wv;
  9360. }
  9361. else if (name.find("ffn_down") != std::string::npos) {
  9362. ++qs.n_ffn_down;
  9363. }
  9364. else if (name.find("ffn_gate") != std::string::npos) {
  9365. ++qs.n_ffn_gate;
  9366. }
  9367. else if (name.find("ffn_up") != std::string::npos) {
  9368. ++qs.n_ffn_up;
  9369. }
  9370. }
  9371. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  9372. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  9373. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  9374. }
  9375. size_t total_size_org = 0;
  9376. size_t total_size_new = 0;
  9377. std::vector<int64_t> hist_all(1 << 4, 0);
  9378. std::vector<std::thread> workers;
  9379. workers.reserve(nthread);
  9380. std::mutex mutex;
  9381. int idx = 0;
  9382. std::vector<no_init<uint8_t>> read_data;
  9383. std::vector<no_init<uint8_t>> work;
  9384. std::vector<no_init<float>> f32_conv_buf;
  9385. // populate the original tensors so we get an initial meta data
  9386. for (int i = 0; i < ml.n_tensors; ++i) {
  9387. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9388. gguf_add_tensor(ctx_out, meta);
  9389. }
  9390. std::ofstream fout(fname_out, std::ios::binary);
  9391. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  9392. const size_t meta_size = gguf_get_meta_size(ctx_out);
  9393. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  9394. // placeholder for the meta data
  9395. ::zeros(fout, meta_size);
  9396. for (int i = 0; i < ml.n_tensors; ++i) {
  9397. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  9398. const std::string name = ggml_get_name(tensor);
  9399. if (!ml.use_mmap) {
  9400. if (read_data.size() < ggml_nbytes(tensor)) {
  9401. read_data.resize(ggml_nbytes(tensor));
  9402. }
  9403. tensor->data = read_data.data();
  9404. }
  9405. ml.load_data_for(tensor);
  9406. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  9407. ++idx, ml.n_tensors,
  9408. ggml_get_name(tensor),
  9409. llama_format_tensor_shape(tensor).c_str(),
  9410. ggml_type_name(tensor->type));
  9411. // This used to be a regex, but <regex> has an extreme cost to compile times.
  9412. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  9413. // quantize only 2D tensors
  9414. quantize &= (ggml_n_dims(tensor) == 2);
  9415. quantize &= params->quantize_output_tensor || name != "output.weight";
  9416. quantize &= !params->only_copy;
  9417. // do not quantize expert gating tensors
  9418. // NOTE: can't use LLM_TN here because the layer number is not known
  9419. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  9420. // do not quantize positional embeddings and token types (BERT)
  9421. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  9422. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  9423. enum ggml_type new_type;
  9424. void * new_data;
  9425. size_t new_size;
  9426. if (quantize) {
  9427. new_type = quantized_type;
  9428. if (!params->pure) {
  9429. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  9430. }
  9431. // If we've decided to quantize to the same type the tensor is already
  9432. // in then there's nothing to do.
  9433. quantize = tensor->type != new_type;
  9434. }
  9435. if (!quantize) {
  9436. new_type = tensor->type;
  9437. new_data = tensor->data;
  9438. new_size = ggml_nbytes(tensor);
  9439. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  9440. } else {
  9441. const size_t nelements = ggml_nelements(tensor);
  9442. const float * imatrix = nullptr;
  9443. if (imatrix_data) {
  9444. auto it = imatrix_data->find(tensor->name);
  9445. if (it == imatrix_data->end()) {
  9446. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  9447. } else {
  9448. if (it->second.size() == (size_t)tensor->ne[0]) {
  9449. imatrix = it->second.data();
  9450. } else {
  9451. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  9452. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  9453. }
  9454. }
  9455. }
  9456. if ((new_type == GGML_TYPE_IQ2_XXS ||
  9457. new_type == GGML_TYPE_IQ2_XS ||
  9458. new_type == GGML_TYPE_IQ2_S ||
  9459. new_type == GGML_TYPE_IQ1_S ||
  9460. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  9461. LLAMA_LOG_ERROR("\n\n============================================================\n");
  9462. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  9463. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  9464. LLAMA_LOG_ERROR("============================================================\n\n");
  9465. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  9466. }
  9467. float * f32_data;
  9468. if (tensor->type == GGML_TYPE_F32) {
  9469. f32_data = (float *) tensor->data;
  9470. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  9471. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  9472. } else {
  9473. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  9474. f32_data = (float *) f32_conv_buf.data();
  9475. }
  9476. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  9477. fflush(stdout);
  9478. if (work.size() < nelements * 4) {
  9479. work.resize(nelements * 4); // upper bound on size
  9480. }
  9481. new_data = work.data();
  9482. std::array<int64_t, 1 << 4> hist_cur = {};
  9483. const int n_per_row = tensor->ne[0];
  9484. const int nrows = nelements / n_per_row;
  9485. static const int min_chunk_size = 32 * 512;
  9486. 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);
  9487. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  9488. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  9489. if (nthread_use < 2) {
  9490. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  9491. } else {
  9492. int counter = 0;
  9493. new_size = 0;
  9494. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  9495. nrows, n_per_row, imatrix]() {
  9496. std::array<int64_t, 1 << 4> local_hist = {};
  9497. const int nrows_per_chunk = chunk_size / n_per_row;
  9498. size_t local_size = 0;
  9499. while (true) {
  9500. std::unique_lock<std::mutex> lock(mutex);
  9501. int first_row = counter; counter += nrows_per_chunk;
  9502. if (first_row >= nrows) {
  9503. if (local_size > 0) {
  9504. for (int j=0; j<int(local_hist.size()); ++j) {
  9505. hist_cur[j] += local_hist[j];
  9506. }
  9507. new_size += local_size;
  9508. }
  9509. break;
  9510. }
  9511. lock.unlock();
  9512. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  9513. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  9514. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  9515. }
  9516. };
  9517. for (int it = 0; it < nthread_use - 1; ++it) {
  9518. workers.emplace_back(compute);
  9519. }
  9520. compute();
  9521. for (auto & w : workers) { w.join(); }
  9522. workers.clear();
  9523. }
  9524. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  9525. int64_t tot_count = 0;
  9526. for (size_t i = 0; i < hist_cur.size(); i++) {
  9527. hist_all[i] += hist_cur[i];
  9528. tot_count += hist_cur[i];
  9529. }
  9530. if (tot_count > 0) {
  9531. LLAMA_LOG_INFO(" | hist: ");
  9532. for (size_t i = 0; i < hist_cur.size(); i++) {
  9533. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  9534. }
  9535. }
  9536. LLAMA_LOG_INFO("\n");
  9537. }
  9538. total_size_org += ggml_nbytes(tensor);
  9539. total_size_new += new_size;
  9540. // update the gguf meta data as we go
  9541. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  9542. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  9543. // write tensor data + padding
  9544. fout.write((const char *) new_data, new_size);
  9545. zeros(fout, GGML_PAD(new_size, align) - new_size);
  9546. }
  9547. // go back to beginning of file and write the updated meta data
  9548. {
  9549. fout.seekp(0);
  9550. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  9551. gguf_get_meta_data(ctx_out, data.data());
  9552. fout.write((const char *) data.data(), data.size());
  9553. }
  9554. fout.close();
  9555. gguf_free(ctx_out);
  9556. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  9557. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  9558. // print histogram for all tensors
  9559. {
  9560. int64_t sum_all = 0;
  9561. for (size_t i = 0; i < hist_all.size(); i++) {
  9562. sum_all += hist_all[i];
  9563. }
  9564. if (sum_all > 0) {
  9565. LLAMA_LOG_INFO("%s: hist: ", __func__);
  9566. for (size_t i = 0; i < hist_all.size(); i++) {
  9567. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  9568. }
  9569. LLAMA_LOG_INFO("\n");
  9570. }
  9571. }
  9572. if (qs.n_fallback > 0) {
  9573. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  9574. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  9575. }
  9576. }
  9577. static int llama_apply_lora_from_file_internal(
  9578. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  9579. ) {
  9580. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  9581. const int64_t t_start_lora_us = ggml_time_us();
  9582. llama_file fin(path_lora, "rb");
  9583. // verify magic and version
  9584. {
  9585. uint32_t magic = fin.read_u32();
  9586. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  9587. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  9588. return 1;
  9589. }
  9590. uint32_t format_version = fin.read_u32();
  9591. if (format_version != 1) {
  9592. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  9593. return 1;
  9594. }
  9595. }
  9596. int32_t lora_r = fin.read_u32();
  9597. int32_t lora_alpha = fin.read_u32();
  9598. float scaling = scale * (float)lora_alpha / (float)lora_r;
  9599. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  9600. // load base model
  9601. std::unique_ptr<llama_model_loader> ml;
  9602. if (path_base_model) {
  9603. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  9604. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  9605. ml->init_mapping(/*prefetch*/ false); // no prefetching
  9606. }
  9607. struct tensor_meta {
  9608. std::string name;
  9609. ggml_type type;
  9610. int32_t ne[2];
  9611. size_t offset;
  9612. };
  9613. std::map<std::string, tensor_meta> tensor_meta_map;
  9614. // load all tensor meta
  9615. while (true) {
  9616. if (fin.tell() == fin.size) {
  9617. // eof
  9618. break;
  9619. }
  9620. int32_t n_dims;
  9621. int32_t name_len;
  9622. int32_t ftype;
  9623. fin.read_raw(&n_dims, sizeof(n_dims));
  9624. fin.read_raw(&name_len, sizeof(name_len));
  9625. fin.read_raw(&ftype, sizeof(ftype));
  9626. if (n_dims != 1 && n_dims != 2) {
  9627. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  9628. return 1;
  9629. }
  9630. int32_t ne[2] = { 1, 1 };
  9631. for (int i = 0; i < n_dims; ++i) {
  9632. fin.read_raw(&ne[i], sizeof(ne[i]));
  9633. }
  9634. std::string name;
  9635. {
  9636. GGML_ASSERT(name_len < GGML_MAX_NAME);
  9637. char buf[GGML_MAX_NAME];
  9638. fin.read_raw(buf, name_len);
  9639. name = std::string(buf, name_len);
  9640. }
  9641. // check for lora suffix
  9642. std::string lora_suffix;
  9643. if (name.length() > 6) {
  9644. lora_suffix = name.substr(name.length() - 6);
  9645. }
  9646. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  9647. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  9648. return 1;
  9649. }
  9650. // tensor type
  9651. ggml_type wtype;
  9652. switch (ftype) {
  9653. case 0: wtype = GGML_TYPE_F32; break;
  9654. case 1: wtype = GGML_TYPE_F16; break;
  9655. default:
  9656. {
  9657. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  9658. __func__, ftype);
  9659. return 1;
  9660. }
  9661. }
  9662. // data offset
  9663. size_t offset = fin.tell();
  9664. offset = (offset + 31) & -32;
  9665. // skip tensor data
  9666. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  9667. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  9668. }
  9669. bool warned = false;
  9670. int n_tensors = 0;
  9671. // apply
  9672. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  9673. if (backend_cpu == nullptr) {
  9674. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  9675. return 1;
  9676. }
  9677. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  9678. std::vector<no_init<uint8_t>> read_buf;
  9679. for (const auto & it : model.tensors_by_name) {
  9680. const std::string & base_name = it.first;
  9681. ggml_tensor * model_t = it.second;
  9682. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  9683. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  9684. continue;
  9685. }
  9686. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  9687. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  9688. ggml_init_params lora_init_params = {
  9689. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  9690. /* .mem_buffer */ nullptr,
  9691. /* .no_alloc */ true,
  9692. };
  9693. ggml_context * lora_ctx = ggml_init(lora_init_params);
  9694. if (lora_ctx == nullptr) {
  9695. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  9696. ggml_backend_free(backend_cpu);
  9697. return 1;
  9698. }
  9699. // create tensors
  9700. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  9701. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  9702. ggml_set_name(loraA, metaA.name.c_str());
  9703. ggml_set_name(loraB, metaB.name.c_str());
  9704. ggml_tensor * base_t;
  9705. if (ml) {
  9706. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  9707. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  9708. return 1;
  9709. }
  9710. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  9711. } else {
  9712. base_t = ggml_dup_tensor(lora_ctx, model_t);
  9713. }
  9714. ggml_set_name(base_t, base_name.c_str());
  9715. // allocate in backend buffer
  9716. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9717. if (lora_buf == nullptr) {
  9718. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  9719. return 1;
  9720. }
  9721. // load tensor data
  9722. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  9723. read_buf.resize(ggml_nbytes(tensor));
  9724. fin.seek(tensor_meta.offset, SEEK_SET);
  9725. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  9726. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  9727. };
  9728. load_tensor(metaA, loraA);
  9729. load_tensor(metaB, loraB);
  9730. // load base model tensor data
  9731. if (ml) {
  9732. ml->load_data_for(base_t);
  9733. } else {
  9734. ggml_backend_tensor_copy(model_t, base_t);
  9735. }
  9736. if (ggml_is_quantized(base_t->type) && !warned) {
  9737. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  9738. "use a f16 or f32 base model with --lora-base\n", __func__);
  9739. warned = true;
  9740. }
  9741. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  9742. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  9743. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  9744. ggml_free(lora_ctx);
  9745. ggml_backend_buffer_free(lora_buf);
  9746. ggml_backend_free(backend_cpu);
  9747. return 1;
  9748. }
  9749. auto build_lora_graph = [&]() {
  9750. // w = w + BA*s
  9751. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  9752. ggml_set_name(BA, "BA");
  9753. if (scaling != 1.0f) {
  9754. BA = ggml_scale(lora_ctx, BA, scaling);
  9755. ggml_set_name(BA, "BA_scaled");
  9756. }
  9757. ggml_tensor * r;
  9758. r = ggml_add_inplace(lora_ctx, base_t, BA);
  9759. ggml_set_name(r, "r_add");
  9760. if (base_t->type != model_t->type) {
  9761. // convert the result to the model type
  9762. r = ggml_cast(lora_ctx, r, model_t->type);
  9763. ggml_set_name(r, "r_cast");
  9764. }
  9765. return r;
  9766. };
  9767. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  9768. ggml_tensor * r = build_lora_graph();
  9769. ggml_build_forward_expand(gf, r);
  9770. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9771. if (graph_buf == nullptr) {
  9772. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  9773. ggml_free(lora_ctx);
  9774. ggml_backend_buffer_free(lora_buf);
  9775. ggml_backend_free(backend_cpu);
  9776. return 1;
  9777. }
  9778. ggml_backend_graph_compute(backend_cpu, gf);
  9779. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  9780. #if 0
  9781. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  9782. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  9783. // sched compute
  9784. ggml_build_forward_expand(gf, build_graph());
  9785. ggml_backend_sched_init_measure(sched, gf);
  9786. // create the graph again, since the previous one was destroyed by the measure
  9787. ggml_graph_clear(gf);
  9788. ggml_build_forward_expand(gf, build_graph());
  9789. ggml_backend_sched_graph_compute(sched, gf);
  9790. ggml_backend_sched_free(sched);
  9791. #endif
  9792. ggml_backend_buffer_free(lora_buf);
  9793. ggml_backend_buffer_free(graph_buf);
  9794. ggml_free(lora_ctx);
  9795. n_tensors++;
  9796. if (n_tensors % 4 == 0) {
  9797. LLAMA_LOG_INFO(".");
  9798. }
  9799. }
  9800. ggml_backend_free(backend_cpu);
  9801. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  9802. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  9803. return 0;
  9804. }
  9805. //
  9806. // interface implementation
  9807. //
  9808. struct llama_model_params llama_model_default_params() {
  9809. struct llama_model_params result = {
  9810. /*.n_gpu_layers =*/ 0,
  9811. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  9812. /*.main_gpu =*/ 0,
  9813. /*.tensor_split =*/ nullptr,
  9814. /*.progress_callback =*/ nullptr,
  9815. /*.progress_callback_user_data =*/ nullptr,
  9816. /*.kv_overrides =*/ nullptr,
  9817. /*.vocab_only =*/ false,
  9818. /*.use_mmap =*/ true,
  9819. /*.use_mlock =*/ false,
  9820. };
  9821. #ifdef GGML_USE_METAL
  9822. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  9823. result.n_gpu_layers = 999;
  9824. #endif
  9825. return result;
  9826. }
  9827. struct llama_context_params llama_context_default_params() {
  9828. struct llama_context_params result = {
  9829. /*.seed =*/ LLAMA_DEFAULT_SEED,
  9830. /*.n_ctx =*/ 512,
  9831. /*.n_batch =*/ 512,
  9832. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  9833. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  9834. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  9835. /*.rope_freq_base =*/ 0.0f,
  9836. /*.rope_freq_scale =*/ 0.0f,
  9837. /*.yarn_ext_factor =*/ -1.0f,
  9838. /*.yarn_attn_factor =*/ 1.0f,
  9839. /*.yarn_beta_fast =*/ 32.0f,
  9840. /*.yarn_beta_slow =*/ 1.0f,
  9841. /*.yarn_orig_ctx =*/ 0,
  9842. /*.defrag_thold =*/ -1.0f,
  9843. /*.cb_eval =*/ nullptr,
  9844. /*.cb_eval_user_data =*/ nullptr,
  9845. /*.type_k =*/ GGML_TYPE_F16,
  9846. /*.type_v =*/ GGML_TYPE_F16,
  9847. /*.logits_all =*/ false,
  9848. /*.embedding =*/ false,
  9849. /*.offload_kqv =*/ true,
  9850. /*.do_pooling =*/ true,
  9851. };
  9852. return result;
  9853. }
  9854. struct llama_model_quantize_params llama_model_quantize_default_params() {
  9855. struct llama_model_quantize_params result = {
  9856. /*.nthread =*/ 0,
  9857. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  9858. /*.allow_requantize =*/ false,
  9859. /*.quantize_output_tensor =*/ true,
  9860. /*.only_copy =*/ false,
  9861. /*.pure =*/ false,
  9862. /*.imatrix =*/ nullptr,
  9863. };
  9864. return result;
  9865. }
  9866. size_t llama_max_devices(void) {
  9867. #if defined(GGML_USE_METAL)
  9868. return 1;
  9869. #elif defined(GGML_USE_CUBLAS)
  9870. return GGML_CUDA_MAX_DEVICES;
  9871. #elif defined(GGML_USE_SYCL)
  9872. return GGML_SYCL_MAX_DEVICES;
  9873. #elif defined(GGML_USE_VULKAN)
  9874. return GGML_VK_MAX_DEVICES;
  9875. #else
  9876. return 1;
  9877. #endif
  9878. }
  9879. bool llama_supports_mmap(void) {
  9880. return llama_mmap::SUPPORTED;
  9881. }
  9882. bool llama_supports_mlock(void) {
  9883. return llama_mlock::SUPPORTED;
  9884. }
  9885. bool llama_supports_gpu_offload(void) {
  9886. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  9887. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  9888. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  9889. return true;
  9890. #else
  9891. return false;
  9892. #endif
  9893. }
  9894. void llama_backend_init(void) {
  9895. ggml_time_init();
  9896. // needed to initialize f16 tables
  9897. {
  9898. struct ggml_init_params params = { 0, NULL, false };
  9899. struct ggml_context * ctx = ggml_init(params);
  9900. ggml_free(ctx);
  9901. }
  9902. #ifdef GGML_USE_MPI
  9903. ggml_mpi_backend_init();
  9904. #endif
  9905. }
  9906. void llama_numa_init(enum ggml_numa_strategy numa) {
  9907. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  9908. ggml_numa_init(numa);
  9909. }
  9910. }
  9911. void llama_backend_free(void) {
  9912. #ifdef GGML_USE_MPI
  9913. ggml_mpi_backend_free();
  9914. #endif
  9915. ggml_quantize_free();
  9916. }
  9917. int64_t llama_time_us(void) {
  9918. return ggml_time_us();
  9919. }
  9920. struct llama_model * llama_load_model_from_file(
  9921. const char * path_model,
  9922. struct llama_model_params params) {
  9923. ggml_time_init();
  9924. llama_model * model = new llama_model;
  9925. unsigned cur_percentage = 0;
  9926. if (params.progress_callback == NULL) {
  9927. params.progress_callback_user_data = &cur_percentage;
  9928. params.progress_callback = [](float progress, void * ctx) {
  9929. unsigned * cur_percentage_p = (unsigned *) ctx;
  9930. unsigned percentage = (unsigned) (100 * progress);
  9931. while (percentage > *cur_percentage_p) {
  9932. *cur_percentage_p = percentage;
  9933. LLAMA_LOG_INFO(".");
  9934. if (percentage >= 100) {
  9935. LLAMA_LOG_INFO("\n");
  9936. }
  9937. }
  9938. return true;
  9939. };
  9940. }
  9941. int status = llama_model_load(path_model, *model, params);
  9942. GGML_ASSERT(status <= 0);
  9943. if (status < 0) {
  9944. if (status == -1) {
  9945. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  9946. } else if (status == -2) {
  9947. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  9948. }
  9949. delete model;
  9950. return nullptr;
  9951. }
  9952. return model;
  9953. }
  9954. void llama_free_model(struct llama_model * model) {
  9955. delete model;
  9956. }
  9957. struct llama_context * llama_new_context_with_model(
  9958. struct llama_model * model,
  9959. struct llama_context_params params) {
  9960. if (!model) {
  9961. return nullptr;
  9962. }
  9963. llama_context * ctx = new llama_context(*model);
  9964. const auto & hparams = model->hparams;
  9965. auto & cparams = ctx->cparams;
  9966. cparams.n_batch = params.n_batch;
  9967. cparams.n_threads = params.n_threads;
  9968. cparams.n_threads_batch = params.n_threads_batch;
  9969. cparams.yarn_ext_factor = params.yarn_ext_factor;
  9970. cparams.yarn_attn_factor = params.yarn_attn_factor;
  9971. cparams.yarn_beta_fast = params.yarn_beta_fast;
  9972. cparams.yarn_beta_slow = params.yarn_beta_slow;
  9973. cparams.defrag_thold = params.defrag_thold;
  9974. cparams.offload_kqv = params.offload_kqv;
  9975. cparams.do_pooling = params.do_pooling;
  9976. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  9977. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  9978. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  9979. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  9980. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  9981. hparams.n_ctx_train;
  9982. cparams.cb_eval = params.cb_eval;
  9983. cparams.cb_eval_user_data = params.cb_eval_user_data;
  9984. auto rope_scaling_type = params.rope_scaling_type;
  9985. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  9986. rope_scaling_type = hparams.rope_scaling_type_train;
  9987. }
  9988. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  9989. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  9990. }
  9991. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  9992. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  9993. }
  9994. if (params.seed == LLAMA_DEFAULT_SEED) {
  9995. params.seed = time(NULL);
  9996. }
  9997. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  9998. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  9999. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  10000. ctx->rng = std::mt19937(params.seed);
  10001. ctx->logits_all = params.logits_all;
  10002. const ggml_type type_k = params.type_k;
  10003. const ggml_type type_v = params.type_v;
  10004. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  10005. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  10006. if (!hparams.vocab_only) {
  10007. // initialize backends
  10008. #ifdef GGML_USE_METAL
  10009. if (model->n_gpu_layers > 0) {
  10010. ctx->backend_metal = ggml_backend_metal_init();
  10011. if (ctx->backend_metal == nullptr) {
  10012. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  10013. llama_free(ctx);
  10014. return nullptr;
  10015. }
  10016. ctx->backends.push_back(ctx->backend_metal);
  10017. }
  10018. #elif defined(GGML_USE_CUBLAS)
  10019. if (model->n_gpu_layers > 0) {
  10020. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  10021. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  10022. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  10023. if (backend == nullptr) {
  10024. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  10025. llama_free(ctx);
  10026. return nullptr;
  10027. }
  10028. ctx->backends.push_back(backend);
  10029. } else {
  10030. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  10031. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  10032. ggml_backend_t backend = ggml_backend_cuda_init(device);
  10033. if (backend == nullptr) {
  10034. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  10035. llama_free(ctx);
  10036. return nullptr;
  10037. }
  10038. ctx->backends.push_back(backend);
  10039. }
  10040. }
  10041. }
  10042. #elif defined(GGML_USE_VULKAN)
  10043. if (model->n_gpu_layers > 0) {
  10044. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  10045. ggml_backend_t backend = ggml_backend_vk_init(device);
  10046. if (backend == nullptr) {
  10047. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  10048. llama_free(ctx);
  10049. return nullptr;
  10050. }
  10051. ctx->backends.push_back(backend);
  10052. }
  10053. }
  10054. #elif defined(GGML_USE_SYCL)
  10055. if (model->n_gpu_layers > 0) {
  10056. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  10057. if (backend == nullptr) {
  10058. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  10059. llama_free(ctx);
  10060. return nullptr;
  10061. }
  10062. ctx->backends.push_back(backend);
  10063. }
  10064. #elif defined(GGML_USE_KOMPUTE)
  10065. if (model->n_gpu_layers > 0) {
  10066. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  10067. if (backend == nullptr) {
  10068. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  10069. llama_free(ctx);
  10070. return nullptr;
  10071. }
  10072. ctx->backends.push_back(backend);
  10073. }
  10074. #endif
  10075. ctx->backend_cpu = ggml_backend_cpu_init();
  10076. if (ctx->backend_cpu == nullptr) {
  10077. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  10078. llama_free(ctx);
  10079. return nullptr;
  10080. }
  10081. ctx->backends.push_back(ctx->backend_cpu);
  10082. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, cparams.n_ctx, cparams.offload_kqv)) {
  10083. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  10084. llama_free(ctx);
  10085. return nullptr;
  10086. }
  10087. {
  10088. size_t memory_size_k = 0;
  10089. size_t memory_size_v = 0;
  10090. for (auto & k : ctx->kv_self.k_l) {
  10091. memory_size_k += ggml_nbytes(k);
  10092. }
  10093. for (auto & v : ctx->kv_self.v_l) {
  10094. memory_size_v += ggml_nbytes(v);
  10095. }
  10096. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  10097. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  10098. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  10099. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  10100. }
  10101. // resized during inference, reserve maximum
  10102. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  10103. if (params.embedding) {
  10104. ctx->embedding.resize(hparams.n_embd);
  10105. }
  10106. // graph inputs
  10107. {
  10108. ggml_init_params init_params = {
  10109. /* .mem_size */ ggml_tensor_overhead()*8,
  10110. /* .mem_buffer */ nullptr,
  10111. /* .no_alloc */ true,
  10112. };
  10113. ctx->ctx_input = ggml_init(init_params);
  10114. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  10115. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  10116. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  10117. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  10118. ctx->inp_KQ_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx);
  10119. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  10120. ctx->inp_mean = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_batch, cparams.n_batch);
  10121. ctx->inp_cls = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  10122. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  10123. ggml_set_name(ctx->inp_embd, "inp_embd");
  10124. ggml_set_name(ctx->inp_pos, "inp_pos");
  10125. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  10126. ggml_set_name(ctx->inp_KQ_pos, "inp_KQ_pos");
  10127. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  10128. ggml_set_name(ctx->inp_mean, "inp_mean");
  10129. ggml_set_name(ctx->inp_cls, "inp_cls");
  10130. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  10131. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  10132. ggml_backend_buffer_name(ctx->buf_input),
  10133. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  10134. }
  10135. // scheduler and compute buffers
  10136. {
  10137. // buffer types used for the compute buffer of each backend
  10138. std::vector<ggml_backend_buffer_type_t> backend_buft;
  10139. for (auto * backend : ctx->backends) {
  10140. if (ggml_backend_is_cpu(backend)) {
  10141. // use host buffers for the CPU backend compute buffer
  10142. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  10143. } else {
  10144. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  10145. }
  10146. }
  10147. // buffer used to store the computation graph and the tensor meta data
  10148. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  10149. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  10150. // build worst-case graph
  10151. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  10152. int n_past = cparams.n_ctx - n_tokens;
  10153. 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
  10154. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  10155. // initialize scheduler with the worst-case graph
  10156. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  10157. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  10158. llama_free(ctx);
  10159. return nullptr;
  10160. }
  10161. for (size_t i = 0; i < ctx->backends.size(); i++) {
  10162. ggml_backend_t backend = ctx->backends[i];
  10163. ggml_backend_buffer_type_t buft = backend_buft[i];
  10164. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  10165. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  10166. ggml_backend_buft_name(buft),
  10167. size / 1024.0 / 1024.0);
  10168. }
  10169. // note: the number of splits during measure is higher than during inference due to the kv shift
  10170. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  10171. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  10172. }
  10173. }
  10174. #ifdef GGML_USE_MPI
  10175. ctx->ctx_mpi = ggml_mpi_init();
  10176. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  10177. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  10178. // TODO: needs fix after #3228
  10179. GGML_ASSERT(false && "not implemented");
  10180. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  10181. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  10182. llama_backend_free();
  10183. exit(1);
  10184. }
  10185. #endif
  10186. return ctx;
  10187. }
  10188. void llama_free(struct llama_context * ctx) {
  10189. delete ctx;
  10190. }
  10191. const llama_model * llama_get_model(const struct llama_context * ctx) {
  10192. return &ctx->model;
  10193. }
  10194. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  10195. return ctx->cparams.n_ctx;
  10196. }
  10197. uint32_t llama_n_batch(const struct llama_context * ctx) {
  10198. return ctx->cparams.n_batch;
  10199. }
  10200. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  10201. return model->vocab.type;
  10202. }
  10203. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  10204. switch (model->arch) {
  10205. // these models do not use RoPE
  10206. case LLM_ARCH_GPT2:
  10207. case LLM_ARCH_GPTJ:
  10208. case LLM_ARCH_GPTNEOX:
  10209. case LLM_ARCH_MPT:
  10210. case LLM_ARCH_REFACT:
  10211. case LLM_ARCH_BLOOM:
  10212. return LLAMA_ROPE_TYPE_NONE;
  10213. // use what we call a normal RoPE, operating on pairs of consecutive head values
  10214. case LLM_ARCH_LLAMA:
  10215. case LLM_ARCH_BAICHUAN:
  10216. case LLM_ARCH_STARCODER:
  10217. case LLM_ARCH_PLAMO:
  10218. case LLM_ARCH_CODESHELL:
  10219. case LLM_ARCH_ORION:
  10220. case LLM_ARCH_INTERNLM2:
  10221. case LLM_ARCH_MINICPM:
  10222. return LLAMA_ROPE_TYPE_NORM;
  10223. // the pairs of head values are offset by n_rot/2
  10224. case LLM_ARCH_FALCON:
  10225. case LLM_ARCH_PERSIMMON:
  10226. case LLM_ARCH_BERT:
  10227. case LLM_ARCH_NOMIC_BERT:
  10228. case LLM_ARCH_STABLELM:
  10229. case LLM_ARCH_QWEN:
  10230. case LLM_ARCH_QWEN2:
  10231. case LLM_ARCH_PHI2:
  10232. case LLM_ARCH_GEMMA:
  10233. case LLM_ARCH_STARCODER2:
  10234. return LLAMA_ROPE_TYPE_NEOX;
  10235. // all model arches should be listed explicitly here
  10236. case LLM_ARCH_UNKNOWN:
  10237. GGML_ASSERT(false && "unknown architecture");
  10238. break;
  10239. }
  10240. return LLAMA_ROPE_TYPE_NONE;
  10241. }
  10242. int32_t llama_n_vocab(const struct llama_model * model) {
  10243. return model->vocab.id_to_token.size();
  10244. }
  10245. int32_t llama_n_ctx_train(const struct llama_model * model) {
  10246. return model->hparams.n_ctx_train;
  10247. }
  10248. int32_t llama_n_embd(const struct llama_model * model) {
  10249. return model->hparams.n_embd;
  10250. }
  10251. float llama_rope_freq_scale_train(const struct llama_model * model) {
  10252. return model->hparams.rope_freq_scale_train;
  10253. }
  10254. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  10255. const auto & it = model->gguf_kv.find(key);
  10256. if (it == model->gguf_kv.end()) {
  10257. if (buf_size > 0) {
  10258. buf[0] = '\0';
  10259. }
  10260. return -1;
  10261. }
  10262. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10263. }
  10264. int32_t llama_model_meta_count(const struct llama_model * model) {
  10265. return (int)model->gguf_kv.size();
  10266. }
  10267. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  10268. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10269. if (buf_size > 0) {
  10270. buf[0] = '\0';
  10271. }
  10272. return -1;
  10273. }
  10274. auto it = model->gguf_kv.begin();
  10275. std::advance(it, i);
  10276. return snprintf(buf, buf_size, "%s", it->first.c_str());
  10277. }
  10278. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  10279. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10280. if (buf_size > 0) {
  10281. buf[0] = '\0';
  10282. }
  10283. return -1;
  10284. }
  10285. auto it = model->gguf_kv.begin();
  10286. std::advance(it, i);
  10287. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10288. }
  10289. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  10290. return snprintf(buf, buf_size, "%s %s %s",
  10291. llama_model_arch_name(model->arch),
  10292. llama_model_type_name(model->type),
  10293. llama_model_ftype_name(model->ftype).c_str());
  10294. }
  10295. uint64_t llama_model_size(const struct llama_model * model) {
  10296. uint64_t size = 0;
  10297. for (const auto & it : model->tensors_by_name) {
  10298. size += ggml_nbytes(it.second);
  10299. }
  10300. return size;
  10301. }
  10302. uint64_t llama_model_n_params(const struct llama_model * model) {
  10303. uint64_t nparams = 0;
  10304. for (const auto & it : model->tensors_by_name) {
  10305. nparams += ggml_nelements(it.second);
  10306. }
  10307. return nparams;
  10308. }
  10309. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  10310. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  10311. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  10312. return it.first == name;
  10313. });
  10314. if (it == model->tensors_by_name.end()) {
  10315. return nullptr;
  10316. }
  10317. return it->second;
  10318. }
  10319. uint32_t llama_model_quantize(
  10320. const char * fname_inp,
  10321. const char * fname_out,
  10322. const llama_model_quantize_params * params) {
  10323. try {
  10324. llama_model_quantize_internal(fname_inp, fname_out, params);
  10325. return 0;
  10326. } catch (const std::exception & err) {
  10327. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  10328. return 1;
  10329. }
  10330. }
  10331. 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) {
  10332. try {
  10333. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  10334. } catch (const std::exception & err) {
  10335. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  10336. return 1;
  10337. }
  10338. }
  10339. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  10340. struct llama_kv_cache_view result = {
  10341. /*.n_cells = */ 0,
  10342. /*.n_max_seq = */ n_max_seq,
  10343. /*.token_count = */ 0,
  10344. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  10345. /*.max_contiguous = */ 0,
  10346. /*.max_contiguous_idx = */ -1,
  10347. /*.cells = */ nullptr,
  10348. /*.cells_sequences = */ nullptr,
  10349. };
  10350. return result;
  10351. }
  10352. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  10353. if (view->cells != nullptr) {
  10354. free(view->cells);
  10355. view->cells = nullptr;
  10356. }
  10357. if (view->cells_sequences != nullptr) {
  10358. free(view->cells_sequences);
  10359. view->cells_sequences = nullptr;
  10360. }
  10361. }
  10362. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  10363. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  10364. view->n_cells = int32_t(ctx->kv_self.size);
  10365. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  10366. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  10367. view->cells = (struct llama_kv_cache_view_cell *)p;
  10368. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  10369. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  10370. view->cells_sequences = (llama_seq_id *)p;
  10371. }
  10372. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  10373. llama_kv_cache_view_cell * c_curr = view->cells;
  10374. llama_seq_id * cs_curr = view->cells_sequences;
  10375. int32_t used_cells = 0;
  10376. int32_t token_count = 0;
  10377. int32_t curr_contig_idx = -1;
  10378. uint32_t max_contig = 0;
  10379. int32_t max_contig_idx = -1;
  10380. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  10381. const size_t curr_size = kv_cells[i].seq_id.size();
  10382. token_count += curr_size;
  10383. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  10384. if (curr_size > 0) {
  10385. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  10386. max_contig = i - curr_contig_idx;
  10387. max_contig_idx = curr_contig_idx;
  10388. }
  10389. curr_contig_idx = -1;
  10390. } else if (curr_contig_idx < 0) {
  10391. curr_contig_idx = i;
  10392. }
  10393. int seq_idx = 0;
  10394. for (const llama_seq_id it : kv_cells[i].seq_id) {
  10395. if (seq_idx >= view->n_max_seq) {
  10396. break;
  10397. }
  10398. cs_curr[seq_idx] = it;
  10399. seq_idx++;
  10400. }
  10401. if (seq_idx != 0) {
  10402. used_cells++;
  10403. }
  10404. for (; seq_idx < view->n_max_seq; seq_idx++) {
  10405. cs_curr[seq_idx] = -1;
  10406. }
  10407. }
  10408. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  10409. max_contig_idx = curr_contig_idx;
  10410. max_contig = kv_cells.size() - curr_contig_idx;
  10411. }
  10412. view->max_contiguous = max_contig;
  10413. view->max_contiguous_idx = max_contig_idx;
  10414. view->token_count = token_count;
  10415. view->used_cells = used_cells;
  10416. if (uint32_t(used_cells) != ctx->kv_self.used) {
  10417. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  10418. __func__, ctx->kv_self.used, used_cells);
  10419. }
  10420. }
  10421. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  10422. int result = 0;
  10423. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  10424. result += ctx->kv_self.cells[i].seq_id.size();
  10425. }
  10426. return result;
  10427. }
  10428. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  10429. return ctx->kv_self.used;
  10430. }
  10431. void llama_kv_cache_clear(struct llama_context * ctx) {
  10432. llama_kv_cache_clear(ctx->kv_self);
  10433. }
  10434. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  10435. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  10436. }
  10437. 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) {
  10438. if (seq_id_src == seq_id_dst) {
  10439. return;
  10440. }
  10441. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  10442. }
  10443. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  10444. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  10445. }
  10446. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  10447. if (delta == 0) {
  10448. return;
  10449. }
  10450. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  10451. }
  10452. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  10453. if (d == 1) {
  10454. return;
  10455. }
  10456. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  10457. }
  10458. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  10459. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  10460. }
  10461. void llama_kv_cache_defrag(struct llama_context * ctx) {
  10462. llama_kv_cache_defrag(ctx->kv_self);
  10463. }
  10464. void llama_kv_cache_update(struct llama_context * ctx) {
  10465. llama_kv_cache_update_internal(*ctx);
  10466. }
  10467. // Returns the *maximum* size of the state
  10468. size_t llama_get_state_size(const struct llama_context * ctx) {
  10469. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  10470. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  10471. const size_t s_rng_size = sizeof(size_t);
  10472. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  10473. const size_t s_logits_size = sizeof(size_t);
  10474. // assume worst case for logits although only currently set ones are serialized
  10475. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  10476. const size_t s_embedding_size = sizeof(size_t);
  10477. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  10478. const size_t s_kv_size = sizeof(size_t);
  10479. const size_t s_kv_ntok = sizeof(int);
  10480. const size_t s_kv = ctx->kv_self.total_size();
  10481. const size_t s_total = (
  10482. + s_rng_size
  10483. + s_rng
  10484. + s_logits_size
  10485. + s_logits
  10486. + s_embedding_size
  10487. + s_embedding
  10488. + s_kv_size
  10489. + s_kv_ntok
  10490. + s_kv
  10491. );
  10492. return s_total;
  10493. }
  10494. // llama_context_data
  10495. struct llama_data_context {
  10496. virtual void write(const void * src, size_t size) = 0;
  10497. virtual size_t get_size_written() = 0;
  10498. virtual ~llama_data_context() = default;
  10499. };
  10500. struct llama_data_buffer_context : llama_data_context {
  10501. uint8_t * ptr;
  10502. size_t size_written = 0;
  10503. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  10504. void write(const void * src, size_t size) override {
  10505. memcpy(ptr, src, size);
  10506. ptr += size;
  10507. size_written += size;
  10508. }
  10509. size_t get_size_written() override {
  10510. return size_written;
  10511. }
  10512. };
  10513. struct llama_data_file_context : llama_data_context {
  10514. llama_file * file;
  10515. size_t size_written = 0;
  10516. llama_data_file_context(llama_file * f) : file(f) {}
  10517. void write(const void * src, size_t size) override {
  10518. file->write_raw(src, size);
  10519. size_written += size;
  10520. }
  10521. size_t get_size_written() override {
  10522. return size_written;
  10523. }
  10524. };
  10525. /** copy state data into either a buffer or file depending on the passed in context
  10526. *
  10527. * file context:
  10528. * llama_file file("/path", "wb");
  10529. * llama_data_file_context data_ctx(&file);
  10530. * llama_copy_state_data(ctx, &data_ctx);
  10531. *
  10532. * buffer context:
  10533. * std::vector<uint8_t> buf(max_size, 0);
  10534. * llama_data_buffer_context data_ctx(&buf.data());
  10535. * llama_copy_state_data(ctx, &data_ctx);
  10536. *
  10537. */
  10538. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  10539. // copy rng
  10540. {
  10541. std::ostringstream rng_ss;
  10542. rng_ss << ctx->rng;
  10543. const std::string & rng_str = rng_ss.str();
  10544. const size_t rng_size = rng_str.size();
  10545. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10546. data_ctx->write(&rng_size, sizeof(rng_size));
  10547. data_ctx->write(rng_str.data(), rng_size);
  10548. }
  10549. // copy logits
  10550. {
  10551. const size_t logits_size = ctx->logits.size();
  10552. data_ctx->write(&logits_size, sizeof(logits_size));
  10553. if (logits_size) {
  10554. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  10555. }
  10556. }
  10557. // copy embeddings
  10558. {
  10559. const size_t embedding_size = ctx->embedding.size();
  10560. data_ctx->write(&embedding_size, sizeof(embedding_size));
  10561. if (embedding_size) {
  10562. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  10563. }
  10564. }
  10565. // copy kv cache
  10566. {
  10567. const auto & kv_self = ctx->kv_self;
  10568. const auto & hparams = ctx->model.hparams;
  10569. const auto & cparams = ctx->cparams;
  10570. const uint32_t n_layer = hparams.n_layer;
  10571. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10572. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10573. const uint32_t n_ctx = cparams.n_ctx;
  10574. const size_t kv_buf_size = kv_self.total_size();
  10575. const uint32_t kv_head = kv_self.head;
  10576. const uint32_t kv_size = kv_self.size;
  10577. const uint32_t kv_used = kv_self.used;
  10578. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  10579. data_ctx->write(&kv_head, sizeof(kv_head));
  10580. data_ctx->write(&kv_size, sizeof(kv_size));
  10581. data_ctx->write(&kv_used, sizeof(kv_used));
  10582. if (kv_buf_size) {
  10583. std::vector<uint8_t> tmp_buf;
  10584. for (int il = 0; il < (int) n_layer; ++il) {
  10585. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10586. tmp_buf.resize(k_size);
  10587. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  10588. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10589. // v is not contiguous, copy row by row
  10590. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10591. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10592. tmp_buf.resize(v_row_size);
  10593. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10594. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  10595. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10596. }
  10597. }
  10598. }
  10599. for (uint32_t i = 0; i < kv_size; ++i) {
  10600. const auto & cell = kv_self.cells[i];
  10601. const llama_pos pos = cell.pos;
  10602. const size_t seq_id_size = cell.seq_id.size();
  10603. data_ctx->write(&pos, sizeof(pos));
  10604. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  10605. for (auto seq_id : cell.seq_id) {
  10606. data_ctx->write(&seq_id, sizeof(seq_id));
  10607. }
  10608. }
  10609. }
  10610. }
  10611. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  10612. llama_data_buffer_context data_ctx(dst);
  10613. llama_copy_state_data_internal(ctx, &data_ctx);
  10614. return data_ctx.get_size_written();
  10615. }
  10616. // Sets the state reading from the specified source address
  10617. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  10618. const uint8_t * inp = src;
  10619. // set rng
  10620. {
  10621. size_t rng_size;
  10622. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  10623. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10624. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  10625. std::istringstream rng_ss(rng_str);
  10626. rng_ss >> ctx->rng;
  10627. GGML_ASSERT(!rng_ss.fail());
  10628. }
  10629. // set logits
  10630. {
  10631. size_t logits_size;
  10632. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  10633. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  10634. if (logits_size) {
  10635. ctx->logits.resize(logits_size);
  10636. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  10637. inp += logits_size * sizeof(float);
  10638. }
  10639. }
  10640. // set embeddings
  10641. {
  10642. size_t embedding_size;
  10643. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  10644. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  10645. if (embedding_size) {
  10646. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  10647. inp += embedding_size * sizeof(float);
  10648. }
  10649. }
  10650. // set kv cache
  10651. {
  10652. const auto & kv_self = ctx->kv_self;
  10653. const auto & hparams = ctx->model.hparams;
  10654. const auto & cparams = ctx->cparams;
  10655. const uint32_t n_layer = hparams.n_layer;
  10656. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10657. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10658. const uint32_t n_ctx = cparams.n_ctx;
  10659. size_t kv_buf_size;
  10660. uint32_t kv_head;
  10661. uint32_t kv_size;
  10662. uint32_t kv_used;
  10663. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  10664. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  10665. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  10666. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  10667. if (kv_buf_size) {
  10668. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  10669. for (int il = 0; il < (int) n_layer; ++il) {
  10670. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10671. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  10672. inp += k_size;
  10673. // v is not contiguous, copy row by row
  10674. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10675. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10676. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10677. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  10678. inp += v_row_size;
  10679. }
  10680. }
  10681. }
  10682. ctx->kv_self.head = kv_head;
  10683. ctx->kv_self.size = kv_size;
  10684. ctx->kv_self.used = kv_used;
  10685. ctx->kv_self.cells.resize(kv_size);
  10686. for (uint32_t i = 0; i < kv_size; ++i) {
  10687. llama_pos pos;
  10688. size_t seq_id_size;
  10689. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  10690. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  10691. ctx->kv_self.cells[i].pos = pos;
  10692. llama_seq_id seq_id;
  10693. for (size_t j = 0; j < seq_id_size; ++j) {
  10694. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  10695. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  10696. }
  10697. }
  10698. }
  10699. const size_t nread = inp - src;
  10700. const size_t max_size = llama_get_state_size(ctx);
  10701. GGML_ASSERT(nread <= max_size);
  10702. return nread;
  10703. }
  10704. 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) {
  10705. llama_file file(path_session, "rb");
  10706. // sanity checks
  10707. {
  10708. const uint32_t magic = file.read_u32();
  10709. const uint32_t version = file.read_u32();
  10710. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  10711. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  10712. return false;
  10713. }
  10714. llama_hparams session_hparams;
  10715. file.read_raw(&session_hparams, sizeof(llama_hparams));
  10716. if (session_hparams != ctx->model.hparams) {
  10717. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  10718. return false;
  10719. }
  10720. }
  10721. // load the prompt
  10722. {
  10723. const uint32_t n_token_count = file.read_u32();
  10724. if (n_token_count > n_token_capacity) {
  10725. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  10726. return false;
  10727. }
  10728. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  10729. *n_token_count_out = n_token_count;
  10730. }
  10731. // restore the context state
  10732. {
  10733. const size_t n_state_size_cur = file.size - file.tell();
  10734. const size_t n_state_size_max = llama_get_state_size(ctx);
  10735. if (n_state_size_cur > n_state_size_max) {
  10736. 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);
  10737. return false;
  10738. }
  10739. std::vector<uint8_t> state_data(n_state_size_max);
  10740. file.read_raw(state_data.data(), n_state_size_cur);
  10741. llama_set_state_data(ctx, state_data.data());
  10742. }
  10743. return true;
  10744. }
  10745. 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) {
  10746. try {
  10747. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  10748. } catch (const std::exception & err) {
  10749. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  10750. return false;
  10751. }
  10752. }
  10753. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  10754. llama_file file(path_session, "wb");
  10755. file.write_u32(LLAMA_SESSION_MAGIC);
  10756. file.write_u32(LLAMA_SESSION_VERSION);
  10757. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  10758. // save the prompt
  10759. file.write_u32((uint32_t) n_token_count);
  10760. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  10761. // save the context state using stream saving
  10762. llama_data_file_context data_ctx(&file);
  10763. llama_copy_state_data_internal(ctx, &data_ctx);
  10764. return true;
  10765. }
  10766. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  10767. ctx->cparams.n_threads = n_threads;
  10768. ctx->cparams.n_threads_batch = n_threads_batch;
  10769. }
  10770. struct llama_batch llama_batch_get_one(
  10771. llama_token * tokens,
  10772. int32_t n_tokens,
  10773. llama_pos pos_0,
  10774. llama_seq_id seq_id) {
  10775. return {
  10776. /*n_tokens =*/ n_tokens,
  10777. /*tokens =*/ tokens,
  10778. /*embd =*/ nullptr,
  10779. /*pos =*/ nullptr,
  10780. /*n_seq_id =*/ nullptr,
  10781. /*seq_id =*/ nullptr,
  10782. /*logits =*/ nullptr,
  10783. /*all_pos_0 =*/ pos_0,
  10784. /*all_pos_1 =*/ 1,
  10785. /*all_seq_id =*/ seq_id,
  10786. };
  10787. }
  10788. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  10789. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  10790. if (embd) {
  10791. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  10792. } else {
  10793. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  10794. }
  10795. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  10796. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  10797. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  10798. for (int i = 0; i < n_tokens_alloc; ++i) {
  10799. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  10800. }
  10801. batch.seq_id[n_tokens_alloc] = nullptr;
  10802. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  10803. return batch;
  10804. }
  10805. void llama_batch_free(struct llama_batch batch) {
  10806. if (batch.token) free(batch.token);
  10807. if (batch.embd) free(batch.embd);
  10808. if (batch.pos) free(batch.pos);
  10809. if (batch.n_seq_id) free(batch.n_seq_id);
  10810. if (batch.seq_id) {
  10811. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  10812. free(batch.seq_id[i]);
  10813. }
  10814. free(batch.seq_id);
  10815. }
  10816. if (batch.logits) free(batch.logits);
  10817. }
  10818. int32_t llama_decode(
  10819. struct llama_context * ctx,
  10820. struct llama_batch batch) {
  10821. const int ret = llama_decode_internal(*ctx, batch);
  10822. if (ret < 0) {
  10823. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10824. }
  10825. return ret;
  10826. }
  10827. float * llama_get_logits(struct llama_context * ctx) {
  10828. return ctx->logits.data();
  10829. }
  10830. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  10831. assert(ctx->logits_valid.at(i));
  10832. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  10833. }
  10834. float * llama_get_embeddings(struct llama_context * ctx) {
  10835. return ctx->embedding.data();
  10836. }
  10837. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  10838. return ctx->embedding.data() + i*ctx->model.hparams.n_embd;
  10839. }
  10840. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  10841. return model->vocab.id_to_token[token].text.c_str();
  10842. }
  10843. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  10844. return model->vocab.id_to_token[token].score;
  10845. }
  10846. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  10847. return model->vocab.id_to_token[token].type;
  10848. }
  10849. llama_token llama_token_bos(const struct llama_model * model) {
  10850. return model->vocab.special_bos_id;
  10851. }
  10852. llama_token llama_token_eos(const struct llama_model * model) {
  10853. return model->vocab.special_eos_id;
  10854. }
  10855. llama_token llama_token_nl(const struct llama_model * model) {
  10856. return model->vocab.linefeed_id;
  10857. }
  10858. int32_t llama_add_bos_token(const struct llama_model * model) {
  10859. return model->vocab.special_add_bos;
  10860. }
  10861. int32_t llama_add_eos_token(const struct llama_model * model) {
  10862. return model->vocab.special_add_eos;
  10863. }
  10864. llama_token llama_token_prefix(const struct llama_model * model) {
  10865. return model->vocab.special_prefix_id;
  10866. }
  10867. llama_token llama_token_middle(const struct llama_model * model) {
  10868. return model->vocab.special_middle_id;
  10869. }
  10870. llama_token llama_token_suffix(const struct llama_model * model) {
  10871. return model->vocab.special_suffix_id;
  10872. }
  10873. llama_token llama_token_eot(const struct llama_model * model) {
  10874. return model->vocab.special_eot_id;
  10875. }
  10876. int32_t llama_tokenize(
  10877. const struct llama_model * model,
  10878. const char * text,
  10879. int32_t text_len,
  10880. llama_token * tokens,
  10881. int32_t n_max_tokens,
  10882. bool add_bos,
  10883. bool special) {
  10884. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  10885. if (n_max_tokens < (int) res.size()) {
  10886. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  10887. return -((int) res.size());
  10888. }
  10889. for (size_t i = 0; i < res.size(); i++) {
  10890. tokens[i] = res[i];
  10891. }
  10892. return res.size();
  10893. }
  10894. static std::string llama_decode_text(const std::string & text) {
  10895. std::string decoded_text;
  10896. auto unicode_sequences = codepoints_from_utf8(text);
  10897. for (auto& unicode_sequence : unicode_sequences) {
  10898. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  10899. }
  10900. return decoded_text;
  10901. }
  10902. // does not write null-terminator to buf
  10903. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  10904. if (0 <= token && token < llama_n_vocab(model)) {
  10905. switch (llama_vocab_get_type(model->vocab)) {
  10906. case LLAMA_VOCAB_TYPE_WPM:
  10907. case LLAMA_VOCAB_TYPE_SPM: {
  10908. // NOTE: we accept all unsupported token types,
  10909. // suppressing them like CONTROL tokens.
  10910. if (llama_is_normal_token(model->vocab, token)) {
  10911. std::string result = model->vocab.id_to_token[token].text;
  10912. llama_unescape_whitespace(result);
  10913. if (length < (int) result.length()) {
  10914. return -(int) result.length();
  10915. }
  10916. memcpy(buf, result.c_str(), result.length());
  10917. return result.length();
  10918. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10919. std::string result = model->vocab.id_to_token[token].text;
  10920. if (length < (int) result.length()) {
  10921. return -result.length();
  10922. }
  10923. memcpy(buf, result.c_str(), result.length());
  10924. return result.length();
  10925. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  10926. if (length < 3) {
  10927. return -3;
  10928. }
  10929. memcpy(buf, "\xe2\x96\x85", 3);
  10930. return 3;
  10931. } else if (llama_is_control_token(model->vocab, token)) {
  10932. ;
  10933. } else if (llama_is_byte_token(model->vocab, token)) {
  10934. if (length < 1) {
  10935. return -1;
  10936. }
  10937. buf[0] = llama_token_to_byte(model->vocab, token);
  10938. return 1;
  10939. }
  10940. break;
  10941. }
  10942. case LLAMA_VOCAB_TYPE_BPE: {
  10943. // NOTE: we accept all unsupported token types,
  10944. // suppressing them like CONTROL tokens.
  10945. if (llama_is_normal_token(model->vocab, token)) {
  10946. std::string result = model->vocab.id_to_token[token].text;
  10947. result = llama_decode_text(result);
  10948. if (length < (int) result.length()) {
  10949. return -(int) result.length();
  10950. }
  10951. memcpy(buf, result.c_str(), result.length());
  10952. return result.length();
  10953. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10954. std::string result = model->vocab.id_to_token[token].text;
  10955. if (length < (int) result.length()) {
  10956. return -result.length();
  10957. }
  10958. memcpy(buf, result.c_str(), result.length());
  10959. return result.length();
  10960. } else if (llama_is_control_token(model->vocab, token)) {
  10961. ;
  10962. }
  10963. break;
  10964. }
  10965. default:
  10966. GGML_ASSERT(false);
  10967. }
  10968. }
  10969. return 0;
  10970. }
  10971. // trim whitespace from the beginning and end of a string
  10972. static std::string trim(const std::string & str) {
  10973. size_t start = 0;
  10974. size_t end = str.size();
  10975. while (start < end && isspace(str[start])) {
  10976. start += 1;
  10977. }
  10978. while (end > start && isspace(str[end - 1])) {
  10979. end -= 1;
  10980. }
  10981. return str.substr(start, end - start);
  10982. }
  10983. // Simple version of "llama_apply_chat_template" that only works with strings
  10984. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  10985. static int32_t llama_chat_apply_template_internal(
  10986. const std::string & tmpl,
  10987. const std::vector<const llama_chat_message *> & chat,
  10988. std::string & dest, bool add_ass) {
  10989. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  10990. std::stringstream ss;
  10991. if (tmpl.find("<|im_start|>") != std::string::npos) {
  10992. // chatml template
  10993. for (auto message : chat) {
  10994. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  10995. }
  10996. if (add_ass) {
  10997. ss << "<|im_start|>assistant\n";
  10998. }
  10999. } else if (tmpl.find("[INST]") != std::string::npos) {
  11000. // llama2 template and its variants
  11001. // [variant] support system message
  11002. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  11003. // [variant] space before + after response
  11004. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  11005. // [variant] add BOS inside history
  11006. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  11007. // [variant] trim spaces from the input message
  11008. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  11009. // construct the prompt
  11010. bool is_inside_turn = true; // skip BOS at the beginning
  11011. ss << "[INST] ";
  11012. for (auto message : chat) {
  11013. std::string content = strip_message ? trim(message->content) : message->content;
  11014. std::string role(message->role);
  11015. if (!is_inside_turn) {
  11016. is_inside_turn = true;
  11017. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  11018. }
  11019. if (role == "system") {
  11020. if (support_system_message) {
  11021. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  11022. } else {
  11023. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  11024. ss << content << "\n";
  11025. }
  11026. } else if (role == "user") {
  11027. ss << content << " [/INST]";
  11028. } else {
  11029. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  11030. is_inside_turn = false;
  11031. }
  11032. }
  11033. // llama2 templates seem to not care about "add_generation_prompt"
  11034. } else if (tmpl.find("<|user|>") != std::string::npos) {
  11035. // zephyr template
  11036. for (auto message : chat) {
  11037. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  11038. }
  11039. if (add_ass) {
  11040. ss << "<|assistant|>\n";
  11041. }
  11042. } else if (tmpl.find("bos_token + message['role']") != std::string::npos) {
  11043. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  11044. for (auto message : chat) {
  11045. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  11046. ss << bos << message->role << "\n" << message->content << "</s>\n";
  11047. }
  11048. if (add_ass) {
  11049. ss << "<s>assistant\n";
  11050. }
  11051. } else if (tmpl.find("<start_of_turn>") != std::string::npos) {
  11052. // google/gemma-7b-it
  11053. std::string system_prompt = "";
  11054. for (auto message : chat) {
  11055. std::string role(message->role);
  11056. if (role == "system") {
  11057. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  11058. system_prompt = trim(message->content);
  11059. continue;
  11060. }
  11061. // in gemma, "assistant" is "model"
  11062. role = role == "assistant" ? "model" : message->role;
  11063. ss << "<start_of_turn>" << role << "\n";
  11064. if (!system_prompt.empty() && role != "model") {
  11065. ss << system_prompt << "\n\n";
  11066. system_prompt = "";
  11067. }
  11068. ss << trim(message->content) << "<end_of_turn>\n";
  11069. }
  11070. if (add_ass) {
  11071. ss << "<start_of_turn>model\n";
  11072. }
  11073. } else {
  11074. // template not supported
  11075. return -1;
  11076. }
  11077. dest = ss.str();
  11078. return dest.size();
  11079. }
  11080. LLAMA_API int32_t llama_chat_apply_template(
  11081. const struct llama_model * model,
  11082. const char * tmpl,
  11083. const struct llama_chat_message * chat,
  11084. size_t n_msg,
  11085. bool add_ass,
  11086. char * buf,
  11087. int32_t length) {
  11088. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  11089. if (tmpl == nullptr) {
  11090. GGML_ASSERT(model != nullptr);
  11091. // load template from model
  11092. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  11093. std::string template_key = "tokenizer.chat_template";
  11094. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  11095. if (res < 0) {
  11096. // worst case: there is no information about template, we will use chatml by default
  11097. curr_tmpl = "<|im_start|>"; // see llama_chat_apply_template_internal
  11098. } else {
  11099. curr_tmpl = std::string(model_template.data(), model_template.size());
  11100. }
  11101. }
  11102. // format the chat to string
  11103. std::vector<const llama_chat_message *> chat_vec;
  11104. chat_vec.resize(n_msg);
  11105. for (size_t i = 0; i < n_msg; i++) {
  11106. chat_vec[i] = &chat[i];
  11107. }
  11108. std::string formatted_chat;
  11109. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  11110. if (res < 0) {
  11111. return res;
  11112. }
  11113. strncpy(buf, formatted_chat.c_str(), length);
  11114. return res;
  11115. }
  11116. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  11117. struct llama_timings result = {
  11118. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  11119. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  11120. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  11121. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  11122. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  11123. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  11124. /*.n_sample =*/ std::max(1, ctx->n_sample),
  11125. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  11126. /*.n_eval =*/ std::max(1, ctx->n_eval),
  11127. };
  11128. return result;
  11129. }
  11130. void llama_print_timings(struct llama_context * ctx) {
  11131. const llama_timings timings = llama_get_timings(ctx);
  11132. LLAMA_LOG_INFO("\n");
  11133. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  11134. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11135. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  11136. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  11137. __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);
  11138. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11139. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  11140. 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));
  11141. }
  11142. void llama_reset_timings(struct llama_context * ctx) {
  11143. ctx->t_start_us = ggml_time_us();
  11144. ctx->t_sample_us = ctx->n_sample = 0;
  11145. ctx->t_eval_us = ctx->n_eval = 0;
  11146. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  11147. }
  11148. const char * llama_print_system_info(void) {
  11149. static std::string s;
  11150. s = "";
  11151. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  11152. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  11153. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  11154. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  11155. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  11156. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  11157. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  11158. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  11159. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  11160. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  11161. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  11162. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  11163. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  11164. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  11165. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  11166. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  11167. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  11168. return s.c_str();
  11169. }
  11170. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  11171. fprintf(stream, "\n");
  11172. fprintf(stream, "###########\n");
  11173. fprintf(stream, "# Timings #\n");
  11174. fprintf(stream, "###########\n");
  11175. fprintf(stream, "\n");
  11176. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  11177. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  11178. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  11179. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  11180. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  11181. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  11182. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  11183. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  11184. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  11185. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  11186. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  11187. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  11188. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  11189. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  11190. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  11191. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  11192. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  11193. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  11194. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  11195. }
  11196. // For internal test use
  11197. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  11198. struct llama_context * ctx
  11199. ) {
  11200. return ctx->model.tensors_by_name;
  11201. }
  11202. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  11203. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  11204. g_state.log_callback_user_data = user_data;
  11205. #ifdef GGML_USE_METAL
  11206. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  11207. #endif
  11208. }
  11209. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  11210. va_list args_copy;
  11211. va_copy(args_copy, args);
  11212. char buffer[128];
  11213. int len = vsnprintf(buffer, 128, format, args);
  11214. if (len < 128) {
  11215. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  11216. } else {
  11217. char* buffer2 = new char[len+1];
  11218. vsnprintf(buffer2, len+1, format, args_copy);
  11219. buffer2[len] = 0;
  11220. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  11221. delete[] buffer2;
  11222. }
  11223. va_end(args_copy);
  11224. }
  11225. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  11226. va_list args;
  11227. va_start(args, format);
  11228. llama_log_internal_v(level, format, args);
  11229. va_end(args);
  11230. }
  11231. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  11232. (void) level;
  11233. (void) user_data;
  11234. fputs(text, stderr);
  11235. fflush(stderr);
  11236. }