llama.cpp 503 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944
  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 <forward_list>
  65. #include <fstream>
  66. #include <functional>
  67. #include <initializer_list>
  68. #include <map>
  69. #include <memory>
  70. #include <mutex>
  71. #include <numeric>
  72. #include <queue>
  73. #include <random>
  74. #include <regex>
  75. #include <set>
  76. #include <sstream>
  77. #include <thread>
  78. #include <type_traits>
  79. #include <unordered_map>
  80. #if defined(_MSC_VER)
  81. #pragma warning(disable: 4244 4267) // possible loss of data
  82. #endif
  83. #ifdef __GNUC__
  84. #ifdef __MINGW32__
  85. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  86. #else
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  88. #endif
  89. #else
  90. #define LLAMA_ATTRIBUTE_FORMAT(...)
  91. #endif
  92. #define LLAMA_MAX_NODES 8192
  93. #define LLAMA_MAX_EXPERTS 8
  94. //
  95. // logging
  96. //
  97. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  98. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  99. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  100. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  101. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  102. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  103. //
  104. // helpers
  105. //
  106. static size_t utf8_len(char src) {
  107. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  108. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  109. return lookup[highbits];
  110. }
  111. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  112. std::string result;
  113. for (size_t pos = 0; ; pos += search.length()) {
  114. auto new_pos = s.find(search, pos);
  115. if (new_pos == std::string::npos) {
  116. result += s.substr(pos, s.size() - pos);
  117. break;
  118. }
  119. result += s.substr(pos, new_pos - pos) + replace;
  120. pos = new_pos;
  121. }
  122. s = std::move(result);
  123. }
  124. static bool is_float_close(float a, float b, float abs_tol) {
  125. // Check for non-negative tolerance
  126. if (abs_tol < 0.0) {
  127. throw std::invalid_argument("Tolerance must be non-negative");
  128. }
  129. // Exact equality check
  130. if (a == b) {
  131. return true;
  132. }
  133. // Check for infinities
  134. if (std::isinf(a) || std::isinf(b)) {
  135. return false;
  136. }
  137. // Regular comparison using the provided absolute tolerance
  138. return std::fabs(b - a) <= abs_tol;
  139. }
  140. static void zeros(std::ofstream & file, size_t n) {
  141. char zero = 0;
  142. for (size_t i = 0; i < n; ++i) {
  143. file.write(&zero, 1);
  144. }
  145. }
  146. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  147. static std::string format(const char * fmt, ...) {
  148. va_list ap;
  149. va_list ap2;
  150. va_start(ap, fmt);
  151. va_copy(ap2, ap);
  152. int size = vsnprintf(NULL, 0, fmt, ap);
  153. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  154. std::vector<char> buf(size + 1);
  155. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  156. GGML_ASSERT(size2 == size);
  157. va_end(ap2);
  158. va_end(ap);
  159. return std::string(buf.data(), size);
  160. }
  161. //
  162. // gguf constants (sync with gguf.py)
  163. //
  164. enum llm_arch {
  165. LLM_ARCH_LLAMA,
  166. LLM_ARCH_FALCON,
  167. LLM_ARCH_BAICHUAN,
  168. LLM_ARCH_GPT2,
  169. LLM_ARCH_GPTJ,
  170. LLM_ARCH_GPTNEOX,
  171. LLM_ARCH_MPT,
  172. LLM_ARCH_STARCODER,
  173. LLM_ARCH_PERSIMMON,
  174. LLM_ARCH_REFACT,
  175. LLM_ARCH_BERT,
  176. LLM_ARCH_NOMIC_BERT,
  177. LLM_ARCH_BLOOM,
  178. LLM_ARCH_STABLELM,
  179. LLM_ARCH_QWEN,
  180. LLM_ARCH_QWEN2,
  181. LLM_ARCH_PHI2,
  182. LLM_ARCH_PLAMO,
  183. LLM_ARCH_CODESHELL,
  184. LLM_ARCH_ORION,
  185. LLM_ARCH_INTERNLM2,
  186. LLM_ARCH_MINICPM,
  187. LLM_ARCH_GEMMA,
  188. LLM_ARCH_UNKNOWN,
  189. };
  190. static std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  191. { LLM_ARCH_LLAMA, "llama" },
  192. { LLM_ARCH_FALCON, "falcon" },
  193. { LLM_ARCH_GPT2, "gpt2" },
  194. { LLM_ARCH_GPTJ, "gptj" },
  195. { LLM_ARCH_GPTNEOX, "gptneox" },
  196. { LLM_ARCH_MPT, "mpt" },
  197. { LLM_ARCH_BAICHUAN, "baichuan" },
  198. { LLM_ARCH_STARCODER, "starcoder" },
  199. { LLM_ARCH_PERSIMMON, "persimmon" },
  200. { LLM_ARCH_REFACT, "refact" },
  201. { LLM_ARCH_BERT, "bert" },
  202. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  203. { LLM_ARCH_BLOOM, "bloom" },
  204. { LLM_ARCH_STABLELM, "stablelm" },
  205. { LLM_ARCH_QWEN, "qwen" },
  206. { LLM_ARCH_QWEN2, "qwen2" },
  207. { LLM_ARCH_PHI2, "phi2" },
  208. { LLM_ARCH_PLAMO, "plamo" },
  209. { LLM_ARCH_CODESHELL, "codeshell" },
  210. { LLM_ARCH_ORION, "orion" },
  211. { LLM_ARCH_INTERNLM2, "internlm2" },
  212. { LLM_ARCH_MINICPM, "minicpm" },
  213. { LLM_ARCH_GEMMA, "gemma" },
  214. };
  215. enum llm_kv {
  216. LLM_KV_GENERAL_ARCHITECTURE,
  217. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  218. LLM_KV_GENERAL_ALIGNMENT,
  219. LLM_KV_GENERAL_NAME,
  220. LLM_KV_GENERAL_AUTHOR,
  221. LLM_KV_GENERAL_URL,
  222. LLM_KV_GENERAL_DESCRIPTION,
  223. LLM_KV_GENERAL_LICENSE,
  224. LLM_KV_GENERAL_SOURCE_URL,
  225. LLM_KV_GENERAL_SOURCE_HF_REPO,
  226. LLM_KV_CONTEXT_LENGTH,
  227. LLM_KV_EMBEDDING_LENGTH,
  228. LLM_KV_BLOCK_COUNT,
  229. LLM_KV_FEED_FORWARD_LENGTH,
  230. LLM_KV_USE_PARALLEL_RESIDUAL,
  231. LLM_KV_TENSOR_DATA_LAYOUT,
  232. LLM_KV_EXPERT_COUNT,
  233. LLM_KV_EXPERT_USED_COUNT,
  234. LLM_KV_POOLING_TYPE,
  235. LLM_KV_ATTENTION_HEAD_COUNT,
  236. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  237. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  238. LLM_KV_ATTENTION_CLAMP_KQV,
  239. LLM_KV_ATTENTION_KEY_LENGTH,
  240. LLM_KV_ATTENTION_VALUE_LENGTH,
  241. LLM_KV_ATTENTION_LAYERNORM_EPS,
  242. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  243. LLM_KV_ATTENTION_CAUSAL,
  244. LLM_KV_ROPE_DIMENSION_COUNT,
  245. LLM_KV_ROPE_FREQ_BASE,
  246. LLM_KV_ROPE_SCALE_LINEAR,
  247. LLM_KV_ROPE_SCALING_TYPE,
  248. LLM_KV_ROPE_SCALING_FACTOR,
  249. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  250. LLM_KV_ROPE_SCALING_FINETUNED,
  251. LLM_KV_TOKENIZER_MODEL,
  252. LLM_KV_TOKENIZER_LIST,
  253. LLM_KV_TOKENIZER_TOKEN_TYPE,
  254. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  255. LLM_KV_TOKENIZER_SCORES,
  256. LLM_KV_TOKENIZER_MERGES,
  257. LLM_KV_TOKENIZER_BOS_ID,
  258. LLM_KV_TOKENIZER_EOS_ID,
  259. LLM_KV_TOKENIZER_UNK_ID,
  260. LLM_KV_TOKENIZER_SEP_ID,
  261. LLM_KV_TOKENIZER_PAD_ID,
  262. LLM_KV_TOKENIZER_ADD_BOS,
  263. LLM_KV_TOKENIZER_ADD_EOS,
  264. LLM_KV_TOKENIZER_ADD_PREFIX,
  265. LLM_KV_TOKENIZER_HF_JSON,
  266. LLM_KV_TOKENIZER_RWKV,
  267. };
  268. static std::map<llm_kv, const char *> LLM_KV_NAMES = {
  269. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  270. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  271. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  272. { LLM_KV_GENERAL_NAME, "general.name" },
  273. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  274. { LLM_KV_GENERAL_URL, "general.url" },
  275. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  276. { LLM_KV_GENERAL_LICENSE, "general.license" },
  277. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  278. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  279. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  280. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  281. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  282. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  283. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  284. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  285. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  286. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  287. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  288. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  289. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  290. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  291. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  292. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  293. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  294. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  295. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  296. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  297. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  298. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  299. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  300. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  301. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  302. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  303. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  304. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  305. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  306. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  307. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  308. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  309. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  310. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  311. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  312. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  313. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  314. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  315. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  316. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  317. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  318. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  319. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  320. };
  321. struct LLM_KV {
  322. LLM_KV(llm_arch arch) : arch(arch) {}
  323. llm_arch arch;
  324. std::string operator()(llm_kv kv) const {
  325. return ::format(LLM_KV_NAMES[kv], LLM_ARCH_NAMES[arch]);
  326. }
  327. };
  328. enum llm_tensor {
  329. LLM_TENSOR_TOKEN_EMBD,
  330. LLM_TENSOR_TOKEN_EMBD_NORM,
  331. LLM_TENSOR_TOKEN_TYPES,
  332. LLM_TENSOR_POS_EMBD,
  333. LLM_TENSOR_OUTPUT,
  334. LLM_TENSOR_OUTPUT_NORM,
  335. LLM_TENSOR_ROPE_FREQS,
  336. LLM_TENSOR_ATTN_Q,
  337. LLM_TENSOR_ATTN_K,
  338. LLM_TENSOR_ATTN_V,
  339. LLM_TENSOR_ATTN_QKV,
  340. LLM_TENSOR_ATTN_OUT,
  341. LLM_TENSOR_ATTN_NORM,
  342. LLM_TENSOR_ATTN_NORM_2,
  343. LLM_TENSOR_ATTN_OUT_NORM,
  344. LLM_TENSOR_ATTN_ROT_EMBD,
  345. LLM_TENSOR_FFN_GATE_INP,
  346. LLM_TENSOR_FFN_NORM,
  347. LLM_TENSOR_FFN_GATE,
  348. LLM_TENSOR_FFN_DOWN,
  349. LLM_TENSOR_FFN_UP,
  350. LLM_TENSOR_FFN_ACT,
  351. LLM_TENSOR_FFN_DOWN_EXP,
  352. LLM_TENSOR_FFN_GATE_EXP,
  353. LLM_TENSOR_FFN_UP_EXP,
  354. LLM_TENSOR_ATTN_Q_NORM,
  355. LLM_TENSOR_ATTN_K_NORM,
  356. LLM_TENSOR_LAYER_OUT_NORM,
  357. };
  358. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  359. {
  360. LLM_ARCH_LLAMA,
  361. {
  362. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  363. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  364. { LLM_TENSOR_OUTPUT, "output" },
  365. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  366. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  367. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  368. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  369. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  370. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  371. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  372. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  373. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  374. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  375. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  376. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  377. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  378. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  379. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  380. },
  381. },
  382. {
  383. LLM_ARCH_BAICHUAN,
  384. {
  385. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  386. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  387. { LLM_TENSOR_OUTPUT, "output" },
  388. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  389. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  390. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  391. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  392. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  393. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  394. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  395. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  396. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  397. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  398. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  399. },
  400. },
  401. {
  402. LLM_ARCH_FALCON,
  403. {
  404. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  405. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  406. { LLM_TENSOR_OUTPUT, "output" },
  407. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  408. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  409. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  410. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  411. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  412. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  413. },
  414. },
  415. {
  416. LLM_ARCH_GPT2,
  417. {
  418. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  419. { LLM_TENSOR_POS_EMBD, "position_embd" },
  420. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  421. { LLM_TENSOR_OUTPUT, "output" },
  422. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  423. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  424. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  425. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  426. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  427. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  428. },
  429. },
  430. {
  431. LLM_ARCH_GPTJ,
  432. {
  433. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  434. },
  435. },
  436. {
  437. LLM_ARCH_GPTNEOX,
  438. {
  439. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  440. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  441. { LLM_TENSOR_OUTPUT, "output" },
  442. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  443. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  444. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  445. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  446. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  447. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  448. },
  449. },
  450. {
  451. LLM_ARCH_PERSIMMON,
  452. {
  453. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  454. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  455. { LLM_TENSOR_OUTPUT, "output"},
  456. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  457. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  458. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  459. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  460. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  461. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  462. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  463. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  464. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  465. },
  466. },
  467. {
  468. LLM_ARCH_MPT,
  469. {
  470. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  471. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  472. { LLM_TENSOR_OUTPUT, "output" },
  473. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  474. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  475. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  476. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  477. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  478. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  479. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  480. },
  481. },
  482. {
  483. LLM_ARCH_STARCODER,
  484. {
  485. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  486. { LLM_TENSOR_POS_EMBD, "position_embd" },
  487. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  488. { LLM_TENSOR_OUTPUT, "output" },
  489. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  490. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  491. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  492. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  493. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  494. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  495. },
  496. },
  497. {
  498. LLM_ARCH_REFACT,
  499. {
  500. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  501. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  502. { LLM_TENSOR_OUTPUT, "output" },
  503. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  504. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  505. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  506. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  507. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  508. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  509. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  510. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  511. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  512. },
  513. },
  514. {
  515. LLM_ARCH_BERT,
  516. {
  517. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  518. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  519. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  520. { LLM_TENSOR_POS_EMBD, "position_embd" },
  521. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  522. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  523. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  524. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  525. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  526. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  527. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  528. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  529. },
  530. },
  531. {
  532. LLM_ARCH_NOMIC_BERT,
  533. {
  534. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  535. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  536. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  537. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  538. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  539. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  540. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  541. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  542. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  543. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  544. },
  545. },
  546. {
  547. LLM_ARCH_BLOOM,
  548. {
  549. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  550. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  551. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  552. { LLM_TENSOR_OUTPUT, "output" },
  553. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  554. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  555. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  556. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  557. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  558. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  559. },
  560. },
  561. {
  562. LLM_ARCH_STABLELM,
  563. {
  564. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  565. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  566. { LLM_TENSOR_OUTPUT, "output" },
  567. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  568. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  569. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  570. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  571. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  572. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  573. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  574. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  575. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  576. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  577. },
  578. },
  579. {
  580. LLM_ARCH_QWEN,
  581. {
  582. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  583. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  584. { LLM_TENSOR_OUTPUT, "output" },
  585. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  586. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  587. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  588. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  589. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  590. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  591. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  592. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  593. },
  594. },
  595. {
  596. LLM_ARCH_QWEN2,
  597. {
  598. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  599. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  600. { LLM_TENSOR_OUTPUT, "output" },
  601. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  602. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  603. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  604. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  605. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  606. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  607. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  608. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  609. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  610. },
  611. },
  612. {
  613. LLM_ARCH_PHI2,
  614. {
  615. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  616. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  617. { LLM_TENSOR_OUTPUT, "output" },
  618. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  619. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  620. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  621. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  622. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  623. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  624. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  625. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  626. },
  627. },
  628. {
  629. LLM_ARCH_PLAMO,
  630. {
  631. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  632. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  633. { LLM_TENSOR_OUTPUT, "output" },
  634. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  635. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  636. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  637. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  638. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  639. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  640. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  641. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  642. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  643. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  644. },
  645. },
  646. {
  647. LLM_ARCH_CODESHELL,
  648. {
  649. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  650. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  651. { LLM_TENSOR_OUTPUT, "output" },
  652. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  653. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  654. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  655. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  656. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  657. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  658. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  659. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  660. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  661. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  662. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  663. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  664. },
  665. },
  666. {
  667. LLM_ARCH_ORION,
  668. {
  669. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  670. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  671. { LLM_TENSOR_OUTPUT, "output" },
  672. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  673. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  674. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  675. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  676. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  677. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  678. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  679. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  680. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  681. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  682. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  683. },
  684. },
  685. {
  686. LLM_ARCH_INTERNLM2,
  687. {
  688. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  689. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  690. { LLM_TENSOR_OUTPUT, "output" },
  691. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  692. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  693. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  694. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  695. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  696. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  697. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  698. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  699. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  700. },
  701. },
  702. {
  703. LLM_ARCH_MINICPM,
  704. {
  705. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  706. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  707. { LLM_TENSOR_OUTPUT, "output" },
  708. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  709. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  710. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  711. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  712. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  713. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  714. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  715. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  716. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  717. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  718. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  719. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  720. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  721. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  722. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  723. },
  724. },
  725. {
  726. LLM_ARCH_GEMMA,
  727. {
  728. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  729. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  730. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  731. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  732. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  733. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  734. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  735. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  736. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  737. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  738. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  739. },
  740. },
  741. {
  742. LLM_ARCH_UNKNOWN,
  743. {
  744. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  745. },
  746. },
  747. };
  748. static llm_arch llm_arch_from_string(const std::string & name) {
  749. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  750. if (kv.second == name) {
  751. return kv.first;
  752. }
  753. }
  754. return LLM_ARCH_UNKNOWN;
  755. }
  756. // helper to handle gguf constants
  757. // usage:
  758. //
  759. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  760. //
  761. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  762. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  763. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  764. //
  765. struct LLM_TN {
  766. LLM_TN(llm_arch arch) : arch(arch) {}
  767. llm_arch arch;
  768. std::string operator()(llm_tensor tensor) const {
  769. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  770. return "__missing__";
  771. }
  772. return LLM_TENSOR_NAMES[arch].at(tensor);
  773. }
  774. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  775. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  776. return "__missing__";
  777. }
  778. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  779. }
  780. std::string operator()(llm_tensor tensor, int bid) const {
  781. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  782. return "__missing__";
  783. }
  784. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  785. }
  786. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  787. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  788. return "__missing__";
  789. }
  790. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  791. }
  792. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  793. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  794. return "__missing__";
  795. }
  796. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  797. }
  798. };
  799. //
  800. // gguf helpers
  801. //
  802. static std::map<int32_t, const char *> LLAMA_ROPE_SCALING_TYPES = {
  803. { LLAMA_ROPE_SCALING_NONE, "none" },
  804. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  805. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  806. };
  807. static int32_t llama_rope_scaling_type_from_string(const std::string & name) {
  808. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  809. if (kv.second == name) {
  810. return kv.first;
  811. }
  812. }
  813. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  814. }
  815. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  816. switch (type) {
  817. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  818. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  819. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  820. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  821. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  822. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  823. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  824. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  825. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  826. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  827. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  828. default: return format("unknown type %d", type);
  829. }
  830. }
  831. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  832. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  833. switch (type) {
  834. case GGUF_TYPE_STRING:
  835. return gguf_get_val_str(ctx_gguf, i);
  836. case GGUF_TYPE_ARRAY:
  837. {
  838. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  839. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  840. const void * data = gguf_get_arr_data(ctx_gguf, i);
  841. std::stringstream ss;
  842. ss << "[";
  843. for (int j = 0; j < arr_n; j++) {
  844. if (arr_type == GGUF_TYPE_STRING) {
  845. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  846. // escape quotes
  847. replace_all(val, "\\", "\\\\");
  848. replace_all(val, "\"", "\\\"");
  849. ss << '"' << val << '"';
  850. } else if (arr_type == GGUF_TYPE_ARRAY) {
  851. ss << "???";
  852. } else {
  853. ss << gguf_data_to_str(arr_type, data, j);
  854. }
  855. if (j < arr_n - 1) {
  856. ss << ", ";
  857. }
  858. }
  859. ss << "]";
  860. return ss.str();
  861. }
  862. default:
  863. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  864. }
  865. }
  866. //
  867. // ggml helpers
  868. //
  869. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  870. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  871. if (plan.work_size > 0) {
  872. buf.resize(plan.work_size);
  873. plan.work_data = buf.data();
  874. }
  875. ggml_graph_compute(graph, &plan);
  876. }
  877. //
  878. // llama helpers
  879. //
  880. #if defined(_WIN32)
  881. static std::string llama_format_win_err(DWORD err) {
  882. LPSTR buf;
  883. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  884. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  885. if (!size) {
  886. return "FormatMessageA failed";
  887. }
  888. std::string ret(buf, size);
  889. LocalFree(buf);
  890. return ret;
  891. }
  892. #endif
  893. template <typename T>
  894. struct no_init {
  895. T value;
  896. no_init() { /* do nothing */ }
  897. };
  898. struct llama_file {
  899. // use FILE * so we don't have to re-open the file to mmap
  900. FILE * fp;
  901. size_t size;
  902. llama_file(const char * fname, const char * mode) {
  903. fp = std::fopen(fname, mode);
  904. if (fp == NULL) {
  905. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  906. }
  907. seek(0, SEEK_END);
  908. size = tell();
  909. seek(0, SEEK_SET);
  910. }
  911. size_t tell() const {
  912. #ifdef _WIN32
  913. __int64 ret = _ftelli64(fp);
  914. #else
  915. long ret = std::ftell(fp);
  916. #endif
  917. GGML_ASSERT(ret != -1); // this really shouldn't fail
  918. return (size_t) ret;
  919. }
  920. void seek(size_t offset, int whence) const {
  921. #ifdef _WIN32
  922. int ret = _fseeki64(fp, (__int64) offset, whence);
  923. #else
  924. int ret = std::fseek(fp, (long) offset, whence);
  925. #endif
  926. GGML_ASSERT(ret == 0); // same
  927. }
  928. void read_raw(void * ptr, size_t len) const {
  929. if (len == 0) {
  930. return;
  931. }
  932. errno = 0;
  933. std::size_t ret = std::fread(ptr, len, 1, fp);
  934. if (ferror(fp)) {
  935. throw std::runtime_error(format("read error: %s", strerror(errno)));
  936. }
  937. if (ret != 1) {
  938. throw std::runtime_error("unexpectedly reached end of file");
  939. }
  940. }
  941. uint32_t read_u32() const {
  942. uint32_t ret;
  943. read_raw(&ret, sizeof(ret));
  944. return ret;
  945. }
  946. void write_raw(const void * ptr, size_t len) const {
  947. if (len == 0) {
  948. return;
  949. }
  950. errno = 0;
  951. size_t ret = std::fwrite(ptr, len, 1, fp);
  952. if (ret != 1) {
  953. throw std::runtime_error(format("write error: %s", strerror(errno)));
  954. }
  955. }
  956. void write_u32(std::uint32_t val) const {
  957. write_raw(&val, sizeof(val));
  958. }
  959. ~llama_file() {
  960. if (fp) {
  961. std::fclose(fp);
  962. }
  963. }
  964. };
  965. struct llama_mmap {
  966. void * addr;
  967. size_t size;
  968. llama_mmap(const llama_mmap &) = delete;
  969. #ifdef _POSIX_MAPPED_FILES
  970. static constexpr bool SUPPORTED = true;
  971. // list of mapped fragments (first_offset, last_offset)
  972. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  973. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  974. size = file->size;
  975. int fd = fileno(file->fp);
  976. int flags = MAP_SHARED;
  977. // prefetch/readahead impairs performance on NUMA systems
  978. if (numa) { prefetch = 0; }
  979. #ifdef __linux__
  980. // advise the kernel to read the file sequentially (increases readahead)
  981. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  982. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  983. strerror(errno));
  984. }
  985. if (prefetch) { flags |= MAP_POPULATE; }
  986. #endif
  987. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  988. if (addr == MAP_FAILED) { // NOLINT
  989. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  990. }
  991. if (prefetch > 0) {
  992. // advise the kernel to preload the mapped memory
  993. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  994. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  995. strerror(errno));
  996. }
  997. }
  998. if (numa) {
  999. // advise the kernel not to use readahead
  1000. // (because the next page might not belong on the same node)
  1001. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1002. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1003. strerror(errno));
  1004. }
  1005. }
  1006. // initialize list of mapped_fragments
  1007. mapped_fragments.emplace_back(0, file->size);
  1008. }
  1009. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1010. // align first to the next page
  1011. size_t offset_in_page = *first & (page_size - 1);
  1012. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1013. *first += offset_to_page;
  1014. // align last to the previous page
  1015. *last = *last & ~(page_size - 1);
  1016. if (*last <= *first) {
  1017. *last = *first;
  1018. }
  1019. }
  1020. // partially unmap the file in the range [first, last)
  1021. void unmap_fragment(size_t first, size_t last) {
  1022. // note: this function must not be called multiple times with overlapping ranges
  1023. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1024. int page_size = sysconf(_SC_PAGESIZE);
  1025. align_range(&first, &last, page_size);
  1026. size_t len = last - first;
  1027. if (len == 0) {
  1028. return;
  1029. }
  1030. GGML_ASSERT(first % page_size == 0);
  1031. GGML_ASSERT(last % page_size == 0);
  1032. GGML_ASSERT(last > first);
  1033. void * next_page_start = (uint8_t *) addr + first;
  1034. // unmap the range
  1035. if (munmap(next_page_start, len)) {
  1036. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1037. }
  1038. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1039. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1040. for (const auto & frag : mapped_fragments) {
  1041. if (frag.first < first && frag.second > last) {
  1042. // the range is in the middle of the fragment, split it
  1043. new_mapped_fragments.emplace_back(frag.first, first);
  1044. new_mapped_fragments.emplace_back(last, frag.second);
  1045. } else if (frag.first < first && frag.second > first) {
  1046. // the range starts in the middle of the fragment
  1047. new_mapped_fragments.emplace_back(frag.first, first);
  1048. } else if (frag.first < last && frag.second > last) {
  1049. // the range ends in the middle of the fragment
  1050. new_mapped_fragments.emplace_back(last, frag.second);
  1051. } else if (frag.first >= first && frag.second <= last) {
  1052. // the range covers the entire fragment
  1053. } else {
  1054. // the range is outside the fragment
  1055. new_mapped_fragments.push_back(frag);
  1056. }
  1057. }
  1058. mapped_fragments = std::move(new_mapped_fragments);
  1059. }
  1060. ~llama_mmap() {
  1061. for (const auto & frag : mapped_fragments) {
  1062. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1063. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1064. }
  1065. }
  1066. }
  1067. #elif defined(_WIN32)
  1068. static constexpr bool SUPPORTED = true;
  1069. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1070. GGML_UNUSED(numa);
  1071. size = file->size;
  1072. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1073. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1074. if (hMapping == NULL) {
  1075. DWORD error = GetLastError();
  1076. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1077. }
  1078. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1079. DWORD error = GetLastError();
  1080. CloseHandle(hMapping);
  1081. if (addr == NULL) {
  1082. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1083. }
  1084. if (prefetch > 0) {
  1085. #if _WIN32_WINNT >= 0x602
  1086. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1087. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1088. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1089. // may fail on pre-Windows 8 systems
  1090. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1091. if (pPrefetchVirtualMemory) {
  1092. // advise the kernel to preload the mapped memory
  1093. WIN32_MEMORY_RANGE_ENTRY range;
  1094. range.VirtualAddress = addr;
  1095. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1096. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1097. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1098. llama_format_win_err(GetLastError()).c_str());
  1099. }
  1100. }
  1101. #else
  1102. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1103. #endif
  1104. }
  1105. }
  1106. void unmap_fragment(size_t first, size_t last) {
  1107. // not supported
  1108. GGML_UNUSED(first);
  1109. GGML_UNUSED(last);
  1110. }
  1111. ~llama_mmap() {
  1112. if (!UnmapViewOfFile(addr)) {
  1113. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1114. llama_format_win_err(GetLastError()).c_str());
  1115. }
  1116. }
  1117. #else
  1118. static constexpr bool SUPPORTED = false;
  1119. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1120. GGML_UNUSED(file);
  1121. GGML_UNUSED(prefetch);
  1122. GGML_UNUSED(numa);
  1123. throw std::runtime_error("mmap not supported");
  1124. }
  1125. void unmap_fragment(size_t first, size_t last) {
  1126. GGML_UNUSED(first);
  1127. GGML_UNUSED(last);
  1128. throw std::runtime_error("mmap not supported");
  1129. }
  1130. #endif
  1131. };
  1132. // Represents some region of memory being locked using mlock or VirtualLock;
  1133. // will automatically unlock on destruction.
  1134. struct llama_mlock {
  1135. void * addr = NULL;
  1136. size_t size = 0;
  1137. bool failed_already = false;
  1138. llama_mlock() {}
  1139. llama_mlock(const llama_mlock &) = delete;
  1140. ~llama_mlock() {
  1141. if (size) {
  1142. raw_unlock(addr, size);
  1143. }
  1144. }
  1145. void init(void * ptr) {
  1146. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1147. addr = ptr;
  1148. }
  1149. void grow_to(size_t target_size) {
  1150. GGML_ASSERT(addr);
  1151. if (failed_already) {
  1152. return;
  1153. }
  1154. size_t granularity = lock_granularity();
  1155. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1156. if (target_size > size) {
  1157. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1158. size = target_size;
  1159. } else {
  1160. failed_already = true;
  1161. }
  1162. }
  1163. }
  1164. #ifdef _POSIX_MEMLOCK_RANGE
  1165. static constexpr bool SUPPORTED = true;
  1166. static size_t lock_granularity() {
  1167. return (size_t) sysconf(_SC_PAGESIZE);
  1168. }
  1169. #ifdef __APPLE__
  1170. #define MLOCK_SUGGESTION \
  1171. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1172. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1173. #else
  1174. #define MLOCK_SUGGESTION \
  1175. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1176. #endif
  1177. bool raw_lock(const void * addr, size_t size) const {
  1178. if (!mlock(addr, size)) {
  1179. return true;
  1180. }
  1181. char* errmsg = std::strerror(errno);
  1182. bool suggest = (errno == ENOMEM);
  1183. // Check if the resource limit is fine after all
  1184. struct rlimit lock_limit;
  1185. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1186. suggest = false;
  1187. }
  1188. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1189. suggest = false;
  1190. }
  1191. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1192. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1193. return false;
  1194. }
  1195. #undef MLOCK_SUGGESTION
  1196. static void raw_unlock(void * addr, size_t size) {
  1197. if (munlock(addr, size)) {
  1198. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1199. }
  1200. }
  1201. #elif defined(_WIN32)
  1202. static constexpr bool SUPPORTED = true;
  1203. static size_t lock_granularity() {
  1204. SYSTEM_INFO si;
  1205. GetSystemInfo(&si);
  1206. return (size_t) si.dwPageSize;
  1207. }
  1208. bool raw_lock(void * ptr, size_t len) const {
  1209. for (int tries = 1; ; tries++) {
  1210. if (VirtualLock(ptr, len)) {
  1211. return true;
  1212. }
  1213. if (tries == 2) {
  1214. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1215. len, size, llama_format_win_err(GetLastError()).c_str());
  1216. return false;
  1217. }
  1218. // It failed but this was only the first try; increase the working
  1219. // set size and try again.
  1220. SIZE_T min_ws_size, max_ws_size;
  1221. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1222. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1223. llama_format_win_err(GetLastError()).c_str());
  1224. return false;
  1225. }
  1226. // Per MSDN: "The maximum number of pages that a process can lock
  1227. // is equal to the number of pages in its minimum working set minus
  1228. // a small overhead."
  1229. // Hopefully a megabyte is enough overhead:
  1230. size_t increment = len + 1048576;
  1231. // The minimum must be <= the maximum, so we need to increase both:
  1232. min_ws_size += increment;
  1233. max_ws_size += increment;
  1234. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1235. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1236. llama_format_win_err(GetLastError()).c_str());
  1237. return false;
  1238. }
  1239. }
  1240. }
  1241. static void raw_unlock(void * ptr, size_t len) {
  1242. if (!VirtualUnlock(ptr, len)) {
  1243. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1244. llama_format_win_err(GetLastError()).c_str());
  1245. }
  1246. }
  1247. #else
  1248. static constexpr bool SUPPORTED = false;
  1249. static size_t lock_granularity() {
  1250. return (size_t) 65536;
  1251. }
  1252. bool raw_lock(const void * addr, size_t len) const {
  1253. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1254. return false;
  1255. }
  1256. static void raw_unlock(const void * addr, size_t len) {}
  1257. #endif
  1258. };
  1259. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1260. std::vector<char> result(8, 0);
  1261. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1262. if (n_tokens < 0) {
  1263. result.resize(-n_tokens);
  1264. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1265. GGML_ASSERT(check == -n_tokens);
  1266. }
  1267. else {
  1268. result.resize(n_tokens);
  1269. }
  1270. return std::string(result.data(), result.size());
  1271. }
  1272. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1273. ggml_backend_buffer_type_t buft = nullptr;
  1274. #if defined(GGML_USE_CUBLAS)
  1275. // host buffers should only be used when data is expected to be copied to/from the GPU
  1276. if (host_buffer) {
  1277. buft = ggml_backend_cuda_host_buffer_type();
  1278. }
  1279. #elif defined(GGML_USE_SYCL)
  1280. buft = ggml_backend_sycl_host_buffer_type();
  1281. #elif defined(GGML_USE_CPU_HBM)
  1282. buft = ggml_backend_cpu_hbm_buffer_type();
  1283. #elif defined(GGML_USE_VULKAN)
  1284. if (host_buffer) {
  1285. buft = ggml_backend_vk_host_buffer_type();
  1286. }
  1287. #endif
  1288. if (buft == nullptr) {
  1289. buft = ggml_backend_cpu_buffer_type();
  1290. }
  1291. return buft;
  1292. GGML_UNUSED(host_buffer);
  1293. }
  1294. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1295. ggml_backend_buffer_type_t buft = nullptr;
  1296. #ifdef GGML_USE_METAL
  1297. buft = ggml_backend_metal_buffer_type();
  1298. #elif defined(GGML_USE_CUBLAS)
  1299. buft = ggml_backend_cuda_buffer_type(gpu);
  1300. #elif defined(GGML_USE_VULKAN)
  1301. buft = ggml_backend_vk_buffer_type(gpu);
  1302. #elif defined(GGML_USE_SYCL)
  1303. buft = ggml_backend_sycl_buffer_type(gpu);
  1304. #elif defined(GGML_USE_CLBLAST)
  1305. buft = ggml_backend_opencl_buffer_type();
  1306. #elif defined(GGML_USE_KOMPUTE)
  1307. buft = ggml_backend_kompute_buffer_type(gpu);
  1308. if (buft == nullptr) {
  1309. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1310. }
  1311. #endif
  1312. if (buft == nullptr) {
  1313. buft = llama_default_buffer_type_cpu(true);
  1314. }
  1315. return buft;
  1316. GGML_UNUSED(gpu);
  1317. }
  1318. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1319. ggml_backend_buffer_type_t buft = nullptr;
  1320. #ifdef GGML_USE_CUBLAS
  1321. if (ggml_backend_cuda_get_device_count() > 1) {
  1322. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1323. }
  1324. #endif
  1325. if (buft == nullptr) {
  1326. buft = llama_default_buffer_type_offload(fallback_gpu);
  1327. }
  1328. return buft;
  1329. GGML_UNUSED(tensor_split);
  1330. }
  1331. static size_t llama_get_device_count() {
  1332. #if defined(GGML_USE_CUBLAS)
  1333. return ggml_backend_cuda_get_device_count();
  1334. #elif defined(GGML_USE_VULKAN)
  1335. return ggml_backend_vk_get_device_count();
  1336. #else
  1337. return 1;
  1338. #endif
  1339. }
  1340. static size_t llama_get_device_memory(int device) {
  1341. #if defined(GGML_USE_CUBLAS)
  1342. size_t total;
  1343. size_t free;
  1344. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1345. return free;
  1346. #elif defined(GGML_USE_VULKAN)
  1347. size_t total;
  1348. size_t free;
  1349. ggml_backend_vk_get_device_memory(device, &total, &free);
  1350. return free;
  1351. #else
  1352. return 1;
  1353. GGML_UNUSED(device);
  1354. #endif
  1355. }
  1356. //
  1357. // globals
  1358. //
  1359. struct llama_state {
  1360. llama_state() {
  1361. #ifdef GGML_USE_METAL
  1362. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1363. #endif
  1364. }
  1365. // We save the log callback globally
  1366. ggml_log_callback log_callback = llama_log_callback_default;
  1367. void * log_callback_user_data = nullptr;
  1368. };
  1369. static llama_state g_state;
  1370. // available llama models
  1371. enum e_model {
  1372. MODEL_UNKNOWN,
  1373. MODEL_17M,
  1374. MODEL_22M,
  1375. MODEL_33M,
  1376. MODEL_109M,
  1377. MODEL_137M,
  1378. MODEL_335M,
  1379. MODEL_0_5B,
  1380. MODEL_1B,
  1381. MODEL_2B,
  1382. MODEL_3B,
  1383. MODEL_4B,
  1384. MODEL_7B,
  1385. MODEL_8B,
  1386. MODEL_13B,
  1387. MODEL_14B,
  1388. MODEL_15B,
  1389. MODEL_20B,
  1390. MODEL_30B,
  1391. MODEL_34B,
  1392. MODEL_40B,
  1393. MODEL_65B,
  1394. MODEL_70B,
  1395. MODEL_SMALL,
  1396. MODEL_MEDIUM,
  1397. MODEL_LARGE,
  1398. MODEL_XL,
  1399. };
  1400. static const size_t kiB = 1024;
  1401. static const size_t MiB = 1024*kiB;
  1402. static const size_t GiB = 1024*MiB;
  1403. struct llama_hparams {
  1404. bool vocab_only;
  1405. bool rope_finetuned;
  1406. uint32_t n_vocab;
  1407. uint32_t n_ctx_train; // context size the model was trained on
  1408. uint32_t n_embd;
  1409. uint32_t n_head;
  1410. uint32_t n_head_kv;
  1411. uint32_t n_layer;
  1412. uint32_t n_rot;
  1413. 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
  1414. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1415. uint32_t n_ff;
  1416. uint32_t n_expert = 0;
  1417. uint32_t n_expert_used = 0;
  1418. uint32_t n_vocab_type = 0; // for BERT-style token types
  1419. float f_norm_eps;
  1420. float f_norm_rms_eps;
  1421. float rope_freq_base_train;
  1422. float rope_freq_scale_train;
  1423. uint32_t n_yarn_orig_ctx;
  1424. int32_t rope_scaling_type_train;
  1425. float f_clamp_kqv = 0.0f;
  1426. float f_max_alibi_bias = 0.0f;
  1427. bool causal_attn = true;
  1428. bool need_kq_pos = false;
  1429. uint32_t pooling_type = LLAMA_POOLING_NONE;
  1430. bool operator!=(const llama_hparams & other) const {
  1431. if (this->vocab_only != other.vocab_only) return true;
  1432. if (this->n_vocab != other.n_vocab) return true;
  1433. if (this->n_ctx_train != other.n_ctx_train) return true;
  1434. if (this->n_embd != other.n_embd) return true;
  1435. if (this->n_head != other.n_head) return true;
  1436. if (this->n_head_kv != other.n_head_kv) return true;
  1437. if (this->n_layer != other.n_layer) return true;
  1438. if (this->n_rot != other.n_rot) return true;
  1439. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1440. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1441. if (this->n_ff != other.n_ff) return true;
  1442. if (this->n_expert != other.n_expert) return true;
  1443. if (this->n_expert_used != other.n_expert_used) return true;
  1444. if (this->rope_finetuned != other.rope_finetuned) return true;
  1445. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1446. const float EPSILON = 1e-9f;
  1447. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1448. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1449. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1450. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1451. return false;
  1452. }
  1453. uint32_t n_gqa() const {
  1454. return n_head/n_head_kv;
  1455. }
  1456. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1457. return n_embd_head_k * n_head_kv;
  1458. }
  1459. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1460. return n_embd_head_v * n_head_kv;
  1461. }
  1462. };
  1463. struct llama_cparams {
  1464. uint32_t n_ctx; // context size used during inference
  1465. uint32_t n_batch;
  1466. uint32_t n_threads; // number of threads to use for generation
  1467. uint32_t n_threads_batch; // number of threads to use for batch processing
  1468. float rope_freq_base;
  1469. float rope_freq_scale;
  1470. uint32_t n_yarn_orig_ctx;
  1471. // These hyperparameters are not exposed in GGUF, because all
  1472. // existing YaRN models use the same values for them.
  1473. float yarn_ext_factor;
  1474. float yarn_attn_factor;
  1475. float yarn_beta_fast;
  1476. float yarn_beta_slow;
  1477. bool mul_mat_q;
  1478. bool offload_kqv;
  1479. bool do_pooling;
  1480. ggml_backend_sched_eval_callback cb_eval;
  1481. void * cb_eval_user_data;
  1482. };
  1483. struct llama_layer {
  1484. // normalization
  1485. struct ggml_tensor * attn_norm;
  1486. struct ggml_tensor * attn_norm_b;
  1487. struct ggml_tensor * attn_norm_2;
  1488. struct ggml_tensor * attn_norm_2_b;
  1489. struct ggml_tensor * attn_q_norm;
  1490. struct ggml_tensor * attn_q_norm_b;
  1491. struct ggml_tensor * attn_k_norm;
  1492. struct ggml_tensor * attn_k_norm_b;
  1493. struct ggml_tensor * attn_out_norm;
  1494. struct ggml_tensor * attn_out_norm_b;
  1495. // attention
  1496. struct ggml_tensor * wq;
  1497. struct ggml_tensor * wk;
  1498. struct ggml_tensor * wv;
  1499. struct ggml_tensor * wo;
  1500. struct ggml_tensor * wqkv;
  1501. // attention bias
  1502. struct ggml_tensor * bq;
  1503. struct ggml_tensor * bk;
  1504. struct ggml_tensor * bv;
  1505. struct ggml_tensor * bo;
  1506. struct ggml_tensor * bqkv;
  1507. // normalization
  1508. struct ggml_tensor * ffn_norm;
  1509. struct ggml_tensor * ffn_norm_b;
  1510. struct ggml_tensor * layer_out_norm;
  1511. struct ggml_tensor * layer_out_norm_b;
  1512. // ff
  1513. struct ggml_tensor * ffn_gate; // w1
  1514. struct ggml_tensor * ffn_down; // w2
  1515. struct ggml_tensor * ffn_up; // w3
  1516. // ff MoE
  1517. struct ggml_tensor * ffn_gate_inp;
  1518. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1519. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1520. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1521. // ff bias
  1522. struct ggml_tensor * ffn_down_b; // b2
  1523. struct ggml_tensor * ffn_up_b; // b3
  1524. struct ggml_tensor * ffn_act;
  1525. };
  1526. struct llama_kv_cell {
  1527. llama_pos pos = -1;
  1528. llama_pos delta = 0;
  1529. std::set<llama_seq_id> seq_id;
  1530. bool has_seq_id(const llama_seq_id & id) const {
  1531. return seq_id.find(id) != seq_id.end();
  1532. }
  1533. };
  1534. // ring-buffer of cached KV data
  1535. struct llama_kv_cache {
  1536. bool has_shift = false;
  1537. // Note: The value of head isn't only used to optimize searching
  1538. // for a free KV slot. llama_decode_internal also uses it, so it
  1539. // cannot be freely changed after a slot has been allocated.
  1540. uint32_t head = 0;
  1541. uint32_t size = 0;
  1542. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1543. // computed before each graph build
  1544. uint32_t n = 0;
  1545. std::vector<llama_kv_cell> cells;
  1546. std::vector<struct ggml_tensor *> k_l; // per layer
  1547. std::vector<struct ggml_tensor *> v_l;
  1548. std::vector<struct ggml_context *> ctxs;
  1549. std::vector<ggml_backend_buffer_t> bufs;
  1550. size_t total_size() const {
  1551. size_t size = 0;
  1552. for (ggml_backend_buffer_t buf : bufs) {
  1553. size += ggml_backend_buffer_get_size(buf);
  1554. }
  1555. return size;
  1556. }
  1557. ~llama_kv_cache() {
  1558. for (struct ggml_context * ctx : ctxs) {
  1559. ggml_free(ctx);
  1560. }
  1561. for (ggml_backend_buffer_t buf : bufs) {
  1562. ggml_backend_buffer_free(buf);
  1563. }
  1564. }
  1565. };
  1566. struct llama_vocab {
  1567. using id = int32_t;
  1568. using token = std::string;
  1569. using ttype = llama_token_type;
  1570. struct token_data {
  1571. token text;
  1572. float score;
  1573. ttype type;
  1574. };
  1575. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1576. std::unordered_map<token, id> token_to_id;
  1577. std::vector<token_data> id_to_token;
  1578. std::unordered_map<token, id> special_tokens_cache;
  1579. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1580. // default LLaMA special tokens
  1581. id special_bos_id = 1;
  1582. id special_eos_id = 2;
  1583. id special_unk_id = 0;
  1584. id special_sep_id = -1;
  1585. id special_pad_id = -1;
  1586. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1587. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1588. id linefeed_id = 13;
  1589. id special_prefix_id = 32007;
  1590. id special_middle_id = 32009;
  1591. id special_suffix_id = 32008;
  1592. id special_eot_id = 32010;
  1593. bool add_space_prefix = true;
  1594. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1595. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1596. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1597. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1598. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1599. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1600. if (it == bpe_ranks.end()) {
  1601. return -1;
  1602. }
  1603. return it->second;
  1604. }
  1605. };
  1606. struct llama_model {
  1607. e_model type = MODEL_UNKNOWN;
  1608. llm_arch arch = LLM_ARCH_UNKNOWN;
  1609. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1610. std::string name = "n/a";
  1611. llama_hparams hparams = {};
  1612. llama_vocab vocab;
  1613. struct ggml_tensor * tok_embd;
  1614. struct ggml_tensor * type_embd;
  1615. struct ggml_tensor * pos_embd;
  1616. struct ggml_tensor * tok_norm;
  1617. struct ggml_tensor * tok_norm_b;
  1618. struct ggml_tensor * output_norm;
  1619. struct ggml_tensor * output_norm_b;
  1620. struct ggml_tensor * output;
  1621. struct ggml_tensor * output_b;
  1622. std::vector<llama_layer> layers;
  1623. llama_split_mode split_mode;
  1624. int main_gpu;
  1625. int n_gpu_layers;
  1626. // gguf metadata
  1627. std::unordered_map<std::string, std::string> gguf_kv;
  1628. // layer -> buffer type mapping
  1629. struct layer_buft {
  1630. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1631. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1632. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1633. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1634. ggml_backend_buffer_type_t buft; // everything else
  1635. };
  1636. layer_buft buft_input;
  1637. layer_buft buft_output;
  1638. std::vector<layer_buft> buft_layer;
  1639. // contexts where the model tensors metadata is stored
  1640. std::vector<struct ggml_context *> ctxs;
  1641. // the model memory buffers for the tensor data
  1642. std::vector<ggml_backend_buffer_t> bufs;
  1643. // model memory mapped file
  1644. std::unique_ptr<llama_mmap> mapping;
  1645. // objects representing data potentially being locked in memory
  1646. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1647. llama_mlock mlock_mmap;
  1648. // for quantize-stats only
  1649. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1650. int64_t t_load_us = 0;
  1651. int64_t t_start_us = 0;
  1652. ~llama_model() {
  1653. for (struct ggml_context * ctx : ctxs) {
  1654. ggml_free(ctx);
  1655. }
  1656. for (ggml_backend_buffer_t buf : bufs) {
  1657. ggml_backend_buffer_free(buf);
  1658. }
  1659. }
  1660. };
  1661. struct llama_context {
  1662. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1663. ~llama_context() {
  1664. ggml_backend_sched_free(sched);
  1665. for (ggml_backend_t backend : backends) {
  1666. ggml_backend_free(backend);
  1667. }
  1668. #ifdef GGML_USE_VULKAN
  1669. ggml_vk_free_cpu_assist();
  1670. #endif
  1671. ggml_backend_buffer_free(buf_input);
  1672. ggml_free(ctx_input);
  1673. }
  1674. llama_cparams cparams;
  1675. std::vector<ggml_backend_t> backends;
  1676. #ifdef GGML_USE_METAL
  1677. ggml_backend_t backend_metal = nullptr;
  1678. #endif
  1679. ggml_backend_t backend_cpu = nullptr;
  1680. const llama_model & model;
  1681. // key + value cache for the self attention
  1682. struct llama_kv_cache kv_self;
  1683. std::mt19937 rng;
  1684. bool has_evaluated_once = false;
  1685. int64_t t_start_us;
  1686. int64_t t_load_us;
  1687. int64_t t_sample_us = 0;
  1688. int64_t t_p_eval_us = 0;
  1689. int64_t t_eval_us = 0;
  1690. int32_t n_sample = 0; // number of tokens sampled
  1691. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1692. int32_t n_eval = 0; // number of eval calls
  1693. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1694. std::vector<float> logits;
  1695. #ifndef NDEBUG
  1696. // guard against access to unset logits
  1697. std::vector<bool> logits_valid;
  1698. #endif
  1699. bool logits_all = false;
  1700. // input embedding (1-dimensional array: [n_embd])
  1701. std::vector<float> embedding;
  1702. // memory buffers used to evaluate the model
  1703. std::vector<uint8_t> buf_compute_meta;
  1704. ggml_backend_sched_t sched = nullptr;
  1705. // input tensors
  1706. ggml_backend_buffer_t buf_input = nullptr;
  1707. ggml_context * ctx_input = nullptr;
  1708. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1709. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1710. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1711. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1712. struct ggml_tensor * inp_KQ_pos; // F32 [n_ctx]
  1713. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1714. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1715. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1716. #ifdef GGML_USE_MPI
  1717. ggml_mpi_context * ctx_mpi = NULL;
  1718. #endif
  1719. };
  1720. //
  1721. // kv cache helpers
  1722. //
  1723. static bool llama_kv_cache_init(
  1724. struct llama_kv_cache & cache,
  1725. const llama_model & model,
  1726. ggml_type ktype,
  1727. ggml_type vtype,
  1728. uint32_t n_ctx,
  1729. bool offload) {
  1730. const struct llama_hparams & hparams = model.hparams;
  1731. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1732. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1733. const int64_t n_layer = hparams.n_layer;
  1734. cache.has_shift = false;
  1735. cache.head = 0;
  1736. cache.size = n_ctx;
  1737. cache.used = 0;
  1738. cache.cells.clear();
  1739. cache.cells.resize(n_ctx);
  1740. #ifdef GGML_USE_CLBLAST
  1741. offload = false;
  1742. #endif
  1743. // count used buffer types
  1744. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1745. if (offload) {
  1746. for (int64_t i = 0; i < n_layer; ++i) {
  1747. buft_layer_count[model.buft_layer[i].buft]++;
  1748. }
  1749. } else {
  1750. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1751. }
  1752. // create a context for each buffer type
  1753. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1754. for (auto & it : buft_layer_count) {
  1755. int n_layers = it.second;
  1756. struct ggml_init_params params = {
  1757. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1758. /*.mem_buffer =*/ NULL,
  1759. /*.no_alloc =*/ true,
  1760. };
  1761. ggml_context * ctx = ggml_init(params);
  1762. if (!ctx) {
  1763. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1764. return false;
  1765. }
  1766. ctx_map[it.first] = ctx;
  1767. cache.ctxs.push_back(ctx);
  1768. }
  1769. cache.k_l.reserve(n_layer);
  1770. cache.v_l.reserve(n_layer);
  1771. for (int i = 0; i < (int) n_layer; i++) {
  1772. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1773. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1774. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1775. ggml_format_name(k, "cache_k_l%d", i);
  1776. ggml_format_name(v, "cache_v_l%d", i);
  1777. cache.k_l.push_back(k);
  1778. cache.v_l.push_back(v);
  1779. }
  1780. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1781. for (auto it : ctx_map) {
  1782. ggml_backend_buffer_type_t buft = it.first;
  1783. ggml_context * ctx = it.second;
  1784. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1785. if (!buf) {
  1786. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1787. return false;
  1788. }
  1789. ggml_backend_buffer_clear(buf, 0);
  1790. 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);
  1791. cache.bufs.push_back(buf);
  1792. }
  1793. return true;
  1794. }
  1795. // find an empty slot of size "n_tokens" in the cache
  1796. // updates the cache head
  1797. // Note: On success, it's important that cache.head points
  1798. // to the first cell of the slot.
  1799. static bool llama_kv_cache_find_slot(
  1800. struct llama_kv_cache & cache,
  1801. const struct llama_batch & batch) {
  1802. const uint32_t n_ctx = cache.size;
  1803. const uint32_t n_tokens = batch.n_tokens;
  1804. if (n_tokens > n_ctx) {
  1805. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1806. return false;
  1807. }
  1808. uint32_t n_tested = 0;
  1809. while (true) {
  1810. if (cache.head + n_tokens > n_ctx) {
  1811. n_tested += n_ctx - cache.head;
  1812. cache.head = 0;
  1813. continue;
  1814. }
  1815. bool found = true;
  1816. for (uint32_t i = 0; i < n_tokens; i++) {
  1817. if (cache.cells[cache.head + i].pos >= 0) {
  1818. found = false;
  1819. cache.head += i + 1;
  1820. n_tested += i + 1;
  1821. break;
  1822. }
  1823. }
  1824. if (found) {
  1825. break;
  1826. }
  1827. if (n_tested >= n_ctx) {
  1828. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1829. return false;
  1830. }
  1831. }
  1832. for (uint32_t i = 0; i < n_tokens; i++) {
  1833. cache.cells[cache.head + i].pos = batch.pos[i];
  1834. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1835. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1836. }
  1837. }
  1838. cache.used += n_tokens;
  1839. return true;
  1840. }
  1841. // find how many cells are currently in use
  1842. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1843. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1844. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1845. return i + 1;
  1846. }
  1847. }
  1848. return 0;
  1849. }
  1850. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1851. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1852. cache.cells[i].pos = -1;
  1853. cache.cells[i].seq_id.clear();
  1854. }
  1855. cache.head = 0;
  1856. cache.used = 0;
  1857. }
  1858. static void llama_kv_cache_seq_rm(
  1859. struct llama_kv_cache & cache,
  1860. llama_seq_id seq_id,
  1861. llama_pos p0,
  1862. llama_pos p1) {
  1863. uint32_t new_head = cache.size;
  1864. if (p0 < 0) p0 = 0;
  1865. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1866. for (uint32_t i = 0; i < cache.size; ++i) {
  1867. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1868. if (seq_id < 0) {
  1869. cache.cells[i].seq_id.clear();
  1870. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1871. cache.cells[i].seq_id.erase(seq_id);
  1872. } else {
  1873. continue;
  1874. }
  1875. if (cache.cells[i].seq_id.empty()) {
  1876. // keep count of the number of used cells
  1877. if (cache.cells[i].pos >= 0) cache.used--;
  1878. cache.cells[i].pos = -1;
  1879. if (new_head == cache.size) new_head = i;
  1880. }
  1881. }
  1882. }
  1883. // If we freed up a slot, set head to it so searching can start there.
  1884. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1885. }
  1886. static void llama_kv_cache_seq_cp(
  1887. struct llama_kv_cache & cache,
  1888. llama_seq_id seq_id_src,
  1889. llama_seq_id seq_id_dst,
  1890. llama_pos p0,
  1891. llama_pos p1) {
  1892. if (p0 < 0) p0 = 0;
  1893. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1894. cache.head = 0;
  1895. for (uint32_t i = 0; i < cache.size; ++i) {
  1896. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1897. cache.cells[i].seq_id.insert(seq_id_dst);
  1898. }
  1899. }
  1900. }
  1901. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1902. uint32_t new_head = cache.size;
  1903. for (uint32_t i = 0; i < cache.size; ++i) {
  1904. if (!cache.cells[i].has_seq_id(seq_id)) {
  1905. if (cache.cells[i].pos >= 0) cache.used--;
  1906. cache.cells[i].pos = -1;
  1907. cache.cells[i].seq_id.clear();
  1908. if (new_head == cache.size) new_head = i;
  1909. } else {
  1910. cache.cells[i].seq_id.clear();
  1911. cache.cells[i].seq_id.insert(seq_id);
  1912. }
  1913. }
  1914. // If we freed up a slot, set head to it so searching can start there.
  1915. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1916. }
  1917. static void llama_kv_cache_seq_shift(
  1918. struct llama_kv_cache & cache,
  1919. llama_seq_id seq_id,
  1920. llama_pos p0,
  1921. llama_pos p1,
  1922. llama_pos delta) {
  1923. uint32_t new_head = cache.size;
  1924. if (p0 < 0) p0 = 0;
  1925. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1926. for (uint32_t i = 0; i < cache.size; ++i) {
  1927. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1928. cache.has_shift = true;
  1929. cache.cells[i].pos += delta;
  1930. cache.cells[i].delta += delta;
  1931. if (cache.cells[i].pos < 0) {
  1932. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1933. cache.cells[i].pos = -1;
  1934. cache.cells[i].seq_id.clear();
  1935. if (new_head == cache.size) new_head = i;
  1936. }
  1937. }
  1938. }
  1939. // If we freed up a slot, set head to it so searching can start there.
  1940. // Otherwise we just start the next search from the beginning.
  1941. cache.head = new_head != cache.size ? new_head : 0;
  1942. }
  1943. static void llama_kv_cache_seq_div(
  1944. struct llama_kv_cache & cache,
  1945. llama_seq_id seq_id,
  1946. llama_pos p0,
  1947. llama_pos p1,
  1948. int d) {
  1949. if (p0 < 0) p0 = 0;
  1950. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1951. for (uint32_t i = 0; i < cache.size; ++i) {
  1952. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1953. cache.has_shift = true;
  1954. {
  1955. llama_pos p_old = cache.cells[i].pos;
  1956. cache.cells[i].pos /= d;
  1957. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1958. }
  1959. }
  1960. }
  1961. }
  1962. //
  1963. // model loading and saving
  1964. //
  1965. enum llama_fver {
  1966. GGUF_FILE_VERSION_V1 = 1,
  1967. GGUF_FILE_VERSION_V2 = 2,
  1968. GGUF_FILE_VERSION_V3 = 3,
  1969. };
  1970. static const char * llama_file_version_name(llama_fver version) {
  1971. switch (version) {
  1972. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1973. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1974. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1975. }
  1976. return "unknown";
  1977. }
  1978. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1979. char buf[256];
  1980. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1981. for (size_t i = 1; i < ne.size(); i++) {
  1982. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1983. }
  1984. return buf;
  1985. }
  1986. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1987. char buf[256];
  1988. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1989. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1990. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1991. }
  1992. return buf;
  1993. }
  1994. namespace GGUFMeta {
  1995. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1996. struct GKV_Base_Type {
  1997. static constexpr gguf_type gt = gt_;
  1998. static T getter(const gguf_context * ctx, const int kid) {
  1999. return gfun(ctx, kid);
  2000. }
  2001. };
  2002. template<typename T> struct GKV_Base;
  2003. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2004. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2005. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2006. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2007. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2008. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2009. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2010. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2011. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2012. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2013. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2014. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2015. template<> struct GKV_Base<std::string> {
  2016. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2017. static std::string getter(const gguf_context * ctx, const int kid) {
  2018. return gguf_get_val_str(ctx, kid);
  2019. }
  2020. };
  2021. struct ArrayInfo{
  2022. const gguf_type gt;
  2023. const size_t length;
  2024. const void * data;
  2025. };
  2026. template<> struct GKV_Base<ArrayInfo> {
  2027. public:
  2028. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2029. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2030. return ArrayInfo {
  2031. gguf_get_arr_type(ctx, k),
  2032. size_t(gguf_get_arr_n(ctx, k)),
  2033. gguf_get_arr_data(ctx, k),
  2034. };
  2035. }
  2036. };
  2037. template<typename T>
  2038. class GKV: public GKV_Base<T> {
  2039. GKV() = delete;
  2040. public:
  2041. static T get_kv(const gguf_context * ctx, const int k) {
  2042. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2043. if (kt != GKV::gt) {
  2044. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2045. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2046. }
  2047. return GKV::getter(ctx, k);
  2048. }
  2049. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2050. switch (ty) {
  2051. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  2052. case LLAMA_KV_OVERRIDE_INT: return "int";
  2053. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  2054. }
  2055. return "unknown";
  2056. }
  2057. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  2058. if (!override) { return false; }
  2059. if (override->tag == expected_type) {
  2060. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2061. __func__, override_type_to_str(override->tag), override->key);
  2062. switch (override->tag) {
  2063. case LLAMA_KV_OVERRIDE_BOOL: {
  2064. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  2065. } break;
  2066. case LLAMA_KV_OVERRIDE_INT: {
  2067. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  2068. } break;
  2069. case LLAMA_KV_OVERRIDE_FLOAT: {
  2070. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  2071. } break;
  2072. default:
  2073. // Shouldn't be possible to end up here, but just in case...
  2074. throw std::runtime_error(
  2075. format("Unsupported attempt to override %s type for metadata key %s\n",
  2076. override_type_to_str(override->tag), override->key));
  2077. }
  2078. return true;
  2079. }
  2080. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2081. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  2082. return false;
  2083. }
  2084. template<typename OT>
  2085. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2086. try_override(OT & target, const struct llama_model_kv_override *override) {
  2087. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  2088. target = override->bool_value;
  2089. return true;
  2090. }
  2091. return false;
  2092. }
  2093. template<typename OT>
  2094. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2095. try_override(OT & target, const struct llama_model_kv_override *override) {
  2096. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  2097. target = override->int_value;
  2098. return true;
  2099. }
  2100. return false;
  2101. }
  2102. template<typename OT>
  2103. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2104. try_override(T & target, const struct llama_model_kv_override *override) {
  2105. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  2106. target = override->float_value;
  2107. return true;
  2108. }
  2109. return false;
  2110. }
  2111. template<typename OT>
  2112. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2113. try_override(T & target, const struct llama_model_kv_override *override) {
  2114. (void)target;
  2115. (void)override;
  2116. if (!override) { return false; }
  2117. // Currently, we should never end up here so it would be a bug if we do.
  2118. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2119. override ? override->key : "NULL"));
  2120. }
  2121. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  2122. if (try_override<T>(target, override)) {
  2123. return true;
  2124. }
  2125. if (k < 0) { return false; }
  2126. target = get_kv(ctx, k);
  2127. return true;
  2128. }
  2129. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  2130. return set(ctx, gguf_find_key(ctx, key), target, override);
  2131. }
  2132. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  2133. return set(ctx, key.c_str(), target, override);
  2134. }
  2135. };
  2136. }
  2137. struct llama_model_loader {
  2138. int n_kv = 0;
  2139. int n_tensors = 0;
  2140. int n_created = 0;
  2141. int64_t n_elements = 0;
  2142. size_t n_bytes = 0;
  2143. bool use_mmap = false;
  2144. llama_file file;
  2145. llama_ftype ftype;
  2146. llama_fver fver;
  2147. std::unique_ptr<llama_mmap> mapping;
  2148. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2149. struct gguf_context * ctx_gguf = NULL;
  2150. struct ggml_context * ctx_meta = NULL;
  2151. std::string arch_name;
  2152. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2153. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2154. int trace = 0;
  2155. if (getenv("LLAMA_TRACE")) {
  2156. trace = atoi(getenv("LLAMA_TRACE"));
  2157. }
  2158. struct gguf_init_params params = {
  2159. /*.no_alloc = */ true,
  2160. /*.ctx = */ &ctx_meta,
  2161. };
  2162. if (param_overrides_p != nullptr) {
  2163. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2164. kv_overrides.insert({std::string(p->key), *p});
  2165. }
  2166. }
  2167. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2168. if (!ctx_gguf) {
  2169. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2170. }
  2171. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2172. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2173. n_kv = gguf_get_n_kv(ctx_gguf);
  2174. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2175. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2176. for (int i = 0; i < n_tensors; i++) {
  2177. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2178. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2179. n_elements += ggml_nelements(t);
  2180. n_bytes += ggml_nbytes(t);
  2181. }
  2182. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2183. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2184. // determine file type based on the number of tensors for each quantization and print meta data
  2185. // TODO: make optional
  2186. {
  2187. std::map<enum ggml_type, uint32_t> n_type;
  2188. uint32_t n_type_max = 0;
  2189. enum ggml_type type_max = GGML_TYPE_F32;
  2190. for (int i = 0; i < n_tensors; i++) {
  2191. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2192. n_type[type]++;
  2193. if (n_type_max < n_type[type]) {
  2194. n_type_max = n_type[type];
  2195. type_max = type;
  2196. }
  2197. if (trace > 0) {
  2198. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2199. 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());
  2200. }
  2201. }
  2202. switch (type_max) {
  2203. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2204. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2205. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2206. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2207. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2208. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2209. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2210. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2211. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2212. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2213. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2214. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2215. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2216. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2217. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2218. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2219. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2220. default:
  2221. {
  2222. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2223. ftype = LLAMA_FTYPE_ALL_F32;
  2224. } break;
  2225. }
  2226. // this is a way to mark that we have "guessed" the file type
  2227. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2228. {
  2229. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2230. if (kid >= 0) {
  2231. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2232. }
  2233. }
  2234. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2235. for (int i = 0; i < n_kv; i++) {
  2236. const char * name = gguf_get_key(ctx_gguf, i);
  2237. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2238. const std::string type_name =
  2239. type == GGUF_TYPE_ARRAY
  2240. ? 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))
  2241. : gguf_type_name(type);
  2242. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2243. const size_t MAX_VALUE_LEN = 40;
  2244. if (value.size() > MAX_VALUE_LEN) {
  2245. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2246. }
  2247. replace_all(value, "\n", "\\n");
  2248. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2249. }
  2250. // print type counts
  2251. for (auto & kv : n_type) {
  2252. if (kv.second == 0) {
  2253. continue;
  2254. }
  2255. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2256. }
  2257. }
  2258. if (!llama_mmap::SUPPORTED) {
  2259. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2260. use_mmap = false;
  2261. }
  2262. this->use_mmap = use_mmap;
  2263. }
  2264. ~llama_model_loader() {
  2265. if (ctx_gguf) {
  2266. gguf_free(ctx_gguf);
  2267. }
  2268. if (ctx_meta) {
  2269. ggml_free(ctx_meta);
  2270. }
  2271. }
  2272. template<typename T>
  2273. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2274. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2275. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2276. if (kid < 0) {
  2277. if (required) {
  2278. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2279. }
  2280. return false;
  2281. }
  2282. struct GGUFMeta::ArrayInfo arr_info =
  2283. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2284. result = arr_info.length;
  2285. return true;
  2286. }
  2287. template<typename T>
  2288. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2289. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2290. return get_arr_n(llm_kv(kid), result, required);
  2291. }
  2292. template<typename T>
  2293. bool get_key(const std::string & key, T & result, const bool required = true) {
  2294. auto it = kv_overrides.find(key);
  2295. const struct llama_model_kv_override * override =
  2296. it != kv_overrides.end() ? &it->second : nullptr;
  2297. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2298. if (required && !found) {
  2299. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2300. }
  2301. return found;
  2302. }
  2303. template<typename T>
  2304. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2305. return get_key(llm_kv(kid), result, required);
  2306. }
  2307. std::string get_arch_name() const {
  2308. return arch_name;
  2309. }
  2310. enum llm_arch get_arch() const {
  2311. return llm_kv.arch;
  2312. }
  2313. const char * get_tensor_name(int i) const {
  2314. return gguf_get_tensor_name(ctx_gguf, i);
  2315. }
  2316. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2317. return ggml_get_tensor(ctx_meta, name);
  2318. }
  2319. struct ggml_tensor * get_tensor_meta(int i) const {
  2320. return get_tensor_meta(get_tensor_name(i));
  2321. }
  2322. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2323. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2324. ggml_set_name(tensor, ggml_get_name(meta));
  2325. n_created++;
  2326. return tensor;
  2327. }
  2328. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2329. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2330. if (cur == NULL) {
  2331. if (!required) {
  2332. return NULL;
  2333. }
  2334. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2335. }
  2336. {
  2337. bool is_ok = true;
  2338. for (size_t i = 0; i < ne.size(); ++i) {
  2339. if (ne[i] != cur->ne[i]) {
  2340. is_ok = false;
  2341. break;
  2342. }
  2343. }
  2344. if (!is_ok) {
  2345. throw std::runtime_error(
  2346. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2347. __func__, name.c_str(),
  2348. llama_format_tensor_shape(ne).c_str(),
  2349. llama_format_tensor_shape(cur).c_str()));
  2350. }
  2351. }
  2352. return create_tensor_for(ctx, cur);
  2353. }
  2354. void done_getting_tensors() const {
  2355. if (n_created != n_tensors) {
  2356. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2357. }
  2358. }
  2359. size_t file_offset(const char * name) const {
  2360. const int idx = gguf_find_tensor(ctx_gguf, name);
  2361. if (idx < 0) {
  2362. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2363. }
  2364. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2365. }
  2366. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2367. // prefetch the whole file - all the data is needed anyway
  2368. if (use_mmap) {
  2369. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2370. }
  2371. // compute the total size of all tensors for progress reporting
  2372. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2373. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2374. size_data += ggml_nbytes(cur);
  2375. }
  2376. if (use_mmap && mapping) {
  2377. if (lmlock) {
  2378. lmlock->init(mapping->addr);
  2379. }
  2380. mmap_used_first = mapping->size;
  2381. }
  2382. }
  2383. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2384. GGML_ASSERT(mapping);
  2385. *first = mapping->size;
  2386. *last = 0;
  2387. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2388. const size_t offs = file_offset(ggml_get_name(tensor));
  2389. *first = std::min(*first, offs);
  2390. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2391. }
  2392. }
  2393. // for backwards compatibility, does not support ggml-backend
  2394. void load_data_for(struct ggml_tensor * cur) const {
  2395. const size_t offs = file_offset(ggml_get_name(cur));
  2396. if (use_mmap && mapping) {
  2397. if (cur->data == nullptr) {
  2398. cur->data = (uint8_t *)mapping->addr + offs;
  2399. } else {
  2400. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2401. }
  2402. } else {
  2403. GGML_ASSERT(cur->data != nullptr);
  2404. file.seek(offs, SEEK_SET);
  2405. file.read_raw(cur->data, ggml_nbytes(cur));
  2406. }
  2407. }
  2408. size_t size_done = 0;
  2409. size_t size_data = 0;
  2410. size_t mmap_used_first = -1;
  2411. size_t mmap_used_last = 0;
  2412. // Returns false if cancelled by progress_callback
  2413. 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) {
  2414. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2415. std::vector<no_init<uint8_t>> read_buf;
  2416. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2417. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2418. if (!cur) {
  2419. // some tensors may be allocated in a different context
  2420. continue;
  2421. }
  2422. if (progress_callback) {
  2423. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2424. return false;
  2425. }
  2426. }
  2427. const size_t offs = file_offset(ggml_get_name(cur));
  2428. if (use_mmap && mapping) {
  2429. if (buf_mmap && cur->data == nullptr) {
  2430. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2431. if (lmlock) {
  2432. lmlock->grow_to(offs + ggml_nbytes(cur));
  2433. }
  2434. mmap_used_first = std::min(mmap_used_first, offs);
  2435. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2436. } else {
  2437. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2438. }
  2439. } else {
  2440. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2441. file.seek(offs, SEEK_SET);
  2442. file.read_raw(cur->data, ggml_nbytes(cur));
  2443. } else {
  2444. read_buf.resize(ggml_nbytes(cur));
  2445. file.seek(offs, SEEK_SET);
  2446. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2447. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2448. }
  2449. }
  2450. size_done += ggml_nbytes(cur);
  2451. }
  2452. // check if this is the last call and do final cleanup
  2453. if (size_done >= size_data) {
  2454. // unmap offloaded tensors and metadata
  2455. if (use_mmap && mapping) {
  2456. mapping->unmap_fragment(0, mmap_used_first);
  2457. if (mmap_used_last != 0) {
  2458. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2459. }
  2460. }
  2461. if (progress_callback) {
  2462. // Even though the model is done loading, we still honor
  2463. // cancellation since we need to free allocations.
  2464. return progress_callback(1.0f, progress_callback_user_data);
  2465. }
  2466. }
  2467. return true;
  2468. }
  2469. };
  2470. //
  2471. // load LLaMA models
  2472. //
  2473. static const char * llama_model_arch_name(llm_arch arch) {
  2474. auto it = LLM_ARCH_NAMES.find(arch);
  2475. if (it == LLM_ARCH_NAMES.end()) {
  2476. return "unknown";
  2477. }
  2478. return it->second;
  2479. }
  2480. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2481. if (ftype & LLAMA_FTYPE_GUESSED) {
  2482. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2483. }
  2484. switch (ftype) {
  2485. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2486. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2487. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2488. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2489. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2490. return "Q4_1, some F16";
  2491. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2492. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2493. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2494. // K-quants
  2495. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2496. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2497. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2498. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2499. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2500. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2501. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2502. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2503. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2504. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2505. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2506. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2507. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:return "Q3_K - Extra small";
  2508. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2509. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2510. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2511. default: return "unknown, may not work";
  2512. }
  2513. }
  2514. static const char * llama_model_type_name(e_model type) {
  2515. switch (type) {
  2516. case MODEL_22M: return "22M";
  2517. case MODEL_33M: return "33M";
  2518. case MODEL_109M: return "109M";
  2519. case MODEL_137M: return "137M";
  2520. case MODEL_0_5B: return "0.5B";
  2521. case MODEL_1B: return "1B";
  2522. case MODEL_2B: return "2B";
  2523. case MODEL_3B: return "3B";
  2524. case MODEL_7B: return "7B";
  2525. case MODEL_8B: return "8B";
  2526. case MODEL_13B: return "13B";
  2527. case MODEL_14B: return "14B";
  2528. case MODEL_15B: return "15B";
  2529. case MODEL_20B: return "20B";
  2530. case MODEL_30B: return "30B";
  2531. case MODEL_34B: return "34B";
  2532. case MODEL_40B: return "40B";
  2533. case MODEL_65B: return "65B";
  2534. case MODEL_70B: return "70B";
  2535. case MODEL_SMALL: return "0.1B";
  2536. case MODEL_MEDIUM: return "0.4B";
  2537. case MODEL_LARGE: return "0.8B";
  2538. case MODEL_XL: return "1.5B";
  2539. default: return "?B";
  2540. }
  2541. }
  2542. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2543. switch (type) {
  2544. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2545. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2546. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2547. default: return "unknown";
  2548. }
  2549. }
  2550. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2551. model.arch = ml.get_arch();
  2552. if (model.arch == LLM_ARCH_UNKNOWN) {
  2553. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2554. }
  2555. }
  2556. static void llm_load_hparams(
  2557. llama_model_loader & ml,
  2558. llama_model & model) {
  2559. auto & hparams = model.hparams;
  2560. const gguf_context * ctx = ml.ctx_gguf;
  2561. // get metadata as string
  2562. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2563. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2564. if (type == GGUF_TYPE_ARRAY) {
  2565. continue;
  2566. }
  2567. const char * name = gguf_get_key(ctx, i);
  2568. const std::string value = gguf_kv_to_str(ctx, i);
  2569. model.gguf_kv.emplace(name, value);
  2570. }
  2571. // get general kv
  2572. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2573. // get hparams kv
  2574. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2575. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2576. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2577. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2578. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2579. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2580. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2581. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2582. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2583. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2584. if (hparams.n_expert > 0) {
  2585. GGML_ASSERT(hparams.n_expert_used > 0);
  2586. } else {
  2587. GGML_ASSERT(hparams.n_expert_used == 0);
  2588. }
  2589. // n_head_kv is optional, default to n_head
  2590. hparams.n_head_kv = hparams.n_head;
  2591. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2592. bool rope_finetuned = false;
  2593. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2594. hparams.rope_finetuned = rope_finetuned;
  2595. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2596. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2597. // rope_freq_base (optional)
  2598. hparams.rope_freq_base_train = 10000.0f;
  2599. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2600. std::string rope_scaling("linear");
  2601. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2602. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2603. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2604. // rope_freq_scale (inverse of the kv) is optional
  2605. float ropescale = 0.0f;
  2606. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2607. // try the old key name
  2608. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2609. }
  2610. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2611. // sanity check for n_rot (optional)
  2612. {
  2613. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2614. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2615. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2616. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2617. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2618. }
  2619. }
  2620. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2621. // gpt-j n_rot = rotary_dim
  2622. }
  2623. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2624. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2625. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2626. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2627. // arch-specific KVs
  2628. switch (model.arch) {
  2629. case LLM_ARCH_LLAMA:
  2630. {
  2631. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2632. switch (hparams.n_layer) {
  2633. case 22: model.type = e_model::MODEL_1B; break;
  2634. case 26: model.type = e_model::MODEL_3B; break;
  2635. case 32: model.type = e_model::MODEL_7B; break;
  2636. case 40: model.type = e_model::MODEL_13B; break;
  2637. case 48: model.type = e_model::MODEL_34B; break;
  2638. case 60: model.type = e_model::MODEL_30B; break;
  2639. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2640. default: model.type = e_model::MODEL_UNKNOWN;
  2641. }
  2642. } break;
  2643. case LLM_ARCH_MINICPM:
  2644. {
  2645. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2646. switch (hparams.n_layer) {
  2647. case 40: model.type = e_model::MODEL_2B; break;
  2648. default: model.type = e_model::MODEL_UNKNOWN;
  2649. }
  2650. } break;
  2651. case LLM_ARCH_FALCON:
  2652. {
  2653. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2654. switch (hparams.n_layer) {
  2655. case 32: model.type = e_model::MODEL_7B; break;
  2656. case 60: model.type = e_model::MODEL_40B; break;
  2657. default: model.type = e_model::MODEL_UNKNOWN;
  2658. }
  2659. } break;
  2660. case LLM_ARCH_BAICHUAN:
  2661. {
  2662. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2663. switch (hparams.n_layer) {
  2664. case 32: model.type = e_model::MODEL_7B; break;
  2665. case 40: model.type = e_model::MODEL_13B; break;
  2666. default: model.type = e_model::MODEL_UNKNOWN;
  2667. }
  2668. if (model.type == e_model::MODEL_13B) {
  2669. // TODO: become GGUF KV parameter
  2670. hparams.f_max_alibi_bias = 8.0f;
  2671. }
  2672. } break;
  2673. case LLM_ARCH_STARCODER:
  2674. {
  2675. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2676. switch (hparams.n_layer) {
  2677. case 24: model.type = e_model::MODEL_1B; break;
  2678. case 36: model.type = e_model::MODEL_3B; break;
  2679. case 42: model.type = e_model::MODEL_7B; break;
  2680. case 40: model.type = e_model::MODEL_15B; break;
  2681. default: model.type = e_model::MODEL_UNKNOWN;
  2682. }
  2683. } break;
  2684. case LLM_ARCH_PERSIMMON:
  2685. {
  2686. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2687. switch (hparams.n_layer) {
  2688. case 36: model.type = e_model::MODEL_8B; break;
  2689. default: model.type = e_model::MODEL_UNKNOWN;
  2690. }
  2691. } break;
  2692. case LLM_ARCH_REFACT:
  2693. {
  2694. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2695. switch (hparams.n_layer) {
  2696. case 32: model.type = e_model::MODEL_1B; break;
  2697. default: model.type = e_model::MODEL_UNKNOWN;
  2698. }
  2699. // TODO: become GGUF KV parameter
  2700. hparams.f_max_alibi_bias = 8.0f;
  2701. } break;
  2702. case LLM_ARCH_BERT:
  2703. {
  2704. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2705. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2706. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2707. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2708. switch (hparams.n_layer) {
  2709. case 3:
  2710. model.type = e_model::MODEL_17M; break; // bge-micro
  2711. case 6:
  2712. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2713. case 12:
  2714. switch (hparams.n_embd) {
  2715. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2716. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2717. } break;
  2718. case 24:
  2719. model.type = e_model::MODEL_335M; break; // bge-large
  2720. }
  2721. } break;
  2722. case LLM_ARCH_NOMIC_BERT:
  2723. {
  2724. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2725. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2726. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2727. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2728. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  2729. model.type = e_model::MODEL_137M;
  2730. }
  2731. } break;
  2732. case LLM_ARCH_BLOOM:
  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 30:
  2738. switch (hparams.n_embd) {
  2739. case 2560: model.type = e_model::MODEL_3B; break;
  2740. case 4096: model.type = e_model::MODEL_7B; break;
  2741. } break;
  2742. }
  2743. // TODO: become GGUF KV parameter
  2744. hparams.f_max_alibi_bias = 8.0f;
  2745. } break;
  2746. case LLM_ARCH_MPT:
  2747. {
  2748. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2749. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2750. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2751. switch (hparams.n_layer) {
  2752. case 32: model.type = e_model::MODEL_7B; break;
  2753. case 48: model.type = e_model::MODEL_30B; break;
  2754. default: model.type = e_model::MODEL_UNKNOWN;
  2755. }
  2756. } break;
  2757. case LLM_ARCH_STABLELM:
  2758. {
  2759. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2760. switch (hparams.n_layer) {
  2761. case 24: model.type = e_model::MODEL_1B; break;
  2762. case 32: model.type = e_model::MODEL_3B; break;
  2763. default: model.type = e_model::MODEL_UNKNOWN;
  2764. }
  2765. } break;
  2766. case LLM_ARCH_QWEN:
  2767. {
  2768. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2769. switch (hparams.n_layer) {
  2770. case 32: model.type = e_model::MODEL_7B; break;
  2771. case 40: model.type = e_model::MODEL_13B; break;
  2772. default: model.type = e_model::MODEL_UNKNOWN;
  2773. }
  2774. } break;
  2775. case LLM_ARCH_QWEN2:
  2776. {
  2777. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2778. switch (hparams.n_layer) {
  2779. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2780. case 32: model.type = e_model::MODEL_7B; break;
  2781. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2782. case 80: model.type = e_model::MODEL_70B; break;
  2783. default: model.type = e_model::MODEL_UNKNOWN;
  2784. }
  2785. } break;
  2786. case LLM_ARCH_PHI2:
  2787. {
  2788. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2789. switch (hparams.n_layer) {
  2790. case 24: model.type = e_model::MODEL_1B; break;
  2791. case 32: model.type = e_model::MODEL_3B; break;
  2792. default: model.type = e_model::MODEL_UNKNOWN;
  2793. }
  2794. } break;
  2795. case LLM_ARCH_PLAMO:
  2796. {
  2797. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2798. switch (hparams.n_layer) {
  2799. case 40: model.type = e_model::MODEL_13B; break;
  2800. default: model.type = e_model::MODEL_UNKNOWN;
  2801. }
  2802. } break;
  2803. case LLM_ARCH_GPT2:
  2804. {
  2805. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2806. switch (hparams.n_layer) {
  2807. case 12: model.type = e_model::MODEL_SMALL; break;
  2808. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2809. case 36: model.type = e_model::MODEL_LARGE; break;
  2810. case 48: model.type = e_model::MODEL_XL; break;
  2811. default: model.type = e_model::MODEL_UNKNOWN;
  2812. }
  2813. } break;
  2814. case LLM_ARCH_CODESHELL:
  2815. {
  2816. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2817. switch (hparams.n_layer) {
  2818. case 42: model.type = e_model::MODEL_SMALL; break;
  2819. default: model.type = e_model::MODEL_UNKNOWN;
  2820. }
  2821. } break;
  2822. case LLM_ARCH_ORION:
  2823. {
  2824. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2825. switch (hparams.n_layer) {
  2826. case 40: model.type = e_model::MODEL_14B; break;
  2827. default: model.type = e_model::MODEL_UNKNOWN;
  2828. }
  2829. } break;
  2830. case LLM_ARCH_INTERNLM2:
  2831. {
  2832. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2833. switch (hparams.n_layer) {
  2834. case 32: model.type = e_model::MODEL_7B; break;
  2835. case 48: model.type = e_model::MODEL_20B; break;
  2836. default: model.type = e_model::MODEL_UNKNOWN;
  2837. }
  2838. } break;
  2839. case LLM_ARCH_GEMMA:
  2840. {
  2841. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2842. switch (hparams.n_layer) {
  2843. case 18: model.type = e_model::MODEL_2B; break;
  2844. case 28: model.type = e_model::MODEL_7B; break;
  2845. default: model.type = e_model::MODEL_UNKNOWN;
  2846. }
  2847. } break;
  2848. default: (void)0;
  2849. }
  2850. model.ftype = ml.ftype;
  2851. if (hparams.f_max_alibi_bias > 0.0f) {
  2852. hparams.need_kq_pos = true;
  2853. }
  2854. }
  2855. // TODO: This should probably be in llama.h
  2856. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2857. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2858. static void llm_load_vocab(
  2859. llama_model_loader & ml,
  2860. llama_model & model) {
  2861. auto & vocab = model.vocab;
  2862. struct gguf_context * ctx = ml.ctx_gguf;
  2863. const auto kv = LLM_KV(model.arch);
  2864. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2865. if (token_idx == -1) {
  2866. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2867. }
  2868. const float * scores = nullptr;
  2869. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2870. if (score_idx != -1) {
  2871. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2872. }
  2873. const int * toktypes = nullptr;
  2874. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2875. if (toktype_idx != -1) {
  2876. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2877. }
  2878. // determine vocab type
  2879. {
  2880. std::string tokenizer_name;
  2881. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2882. if (tokenizer_name == "llama") {
  2883. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2884. // default special tokens
  2885. vocab.special_bos_id = 1;
  2886. vocab.special_eos_id = 2;
  2887. vocab.special_unk_id = 0;
  2888. vocab.special_sep_id = -1;
  2889. vocab.special_pad_id = -1;
  2890. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2891. if (add_space_prefix_keyidx != -1) {
  2892. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2893. } // The default value of add_space_prefix is true.
  2894. } else if (tokenizer_name == "gpt2") {
  2895. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2896. // read bpe merges and populate bpe ranks
  2897. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2898. if (merges_keyidx == -1) {
  2899. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2900. }
  2901. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2902. for (int i = 0; i < n_merges; i++) {
  2903. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2904. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2905. std::string first;
  2906. std::string second;
  2907. const size_t pos = word.find(' ', 1);
  2908. if (pos != std::string::npos) {
  2909. first = word.substr(0, pos);
  2910. second = word.substr(pos + 1);
  2911. }
  2912. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2913. }
  2914. // default special tokens
  2915. vocab.special_bos_id = 11;
  2916. vocab.special_eos_id = 11;
  2917. vocab.special_unk_id = -1;
  2918. vocab.special_sep_id = -1;
  2919. vocab.special_pad_id = -1;
  2920. } else if (tokenizer_name == "bert") {
  2921. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  2922. // default special tokens
  2923. vocab.special_bos_id = 101;
  2924. vocab.special_eos_id = 102;
  2925. vocab.special_unk_id = 100;
  2926. vocab.special_sep_id = -1;
  2927. vocab.special_pad_id = -1;
  2928. vocab.add_space_prefix = false;
  2929. } else {
  2930. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2931. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2932. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2933. }
  2934. }
  2935. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2936. vocab.id_to_token.resize(n_vocab);
  2937. for (uint32_t i = 0; i < n_vocab; i++) {
  2938. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2939. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2940. vocab.token_to_id[word] = i;
  2941. auto & token_data = vocab.id_to_token[i];
  2942. token_data.text = std::move(word);
  2943. token_data.score = scores ? scores[i] : 0.0f;
  2944. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2945. }
  2946. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2947. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2948. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2949. try {
  2950. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2951. } catch (const std::exception & e) {
  2952. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  2953. vocab.linefeed_id = vocab.special_pad_id;
  2954. }
  2955. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  2956. vocab.linefeed_id = vocab.special_pad_id;
  2957. } else {
  2958. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2959. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2960. vocab.linefeed_id = ids[0];
  2961. }
  2962. // special tokens
  2963. {
  2964. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2965. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2966. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2967. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2968. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2969. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2970. };
  2971. for (const auto & it : special_token_types) {
  2972. const std::string & key = kv(std::get<0>(it));
  2973. int32_t & id = std::get<1>(it);
  2974. uint32_t new_id;
  2975. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2976. continue;
  2977. }
  2978. if (new_id >= vocab.id_to_token.size()) {
  2979. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2980. __func__, key.c_str(), new_id, id);
  2981. } else {
  2982. id = new_id;
  2983. }
  2984. }
  2985. // Handle add_bos_token and add_eos_token
  2986. {
  2987. bool temp = true;
  2988. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2989. vocab.special_add_bos = int(temp);
  2990. }
  2991. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2992. vocab.special_add_eos = int(temp);
  2993. }
  2994. }
  2995. }
  2996. // build special tokens cache
  2997. {
  2998. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2999. // and will always be correctly labeled in 'added_tokens.json' etc.
  3000. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3001. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3002. // are special tokens.
  3003. // From testing, this appears to correlate 1:1 with special tokens.
  3004. //
  3005. // Counting special tokens and verifying in only one direction
  3006. // is sufficient to detect difference in those two sets.
  3007. //
  3008. uint32_t special_tokens_count_by_type = 0;
  3009. uint32_t special_tokens_count_from_verification = 0;
  3010. bool special_tokens_definition_mismatch = false;
  3011. for (const auto & t : vocab.token_to_id) {
  3012. const auto & token = t.first;
  3013. const auto & id = t.second;
  3014. // Count all non-normal tokens in the vocab while iterating
  3015. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3016. special_tokens_count_by_type++;
  3017. }
  3018. // Skip single character tokens
  3019. if (token.length() > 1) {
  3020. bool is_tokenizable = false;
  3021. // Split token string representation in two, in all possible ways
  3022. // and check if both halves can be matched to a valid token
  3023. for (unsigned i = 1; i < token.length();) {
  3024. const auto left = token.substr(0, i);
  3025. const auto right = token.substr(i);
  3026. // check if we didnt partition in the middle of a utf sequence
  3027. auto utf = utf8_len(left.at(left.length() - 1));
  3028. if (utf == 1) {
  3029. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3030. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3031. is_tokenizable = true;
  3032. break;
  3033. }
  3034. i++;
  3035. } else {
  3036. // skip over the rest of multibyte utf sequence
  3037. i += utf - 1;
  3038. }
  3039. }
  3040. if (!is_tokenizable) {
  3041. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3042. // it's faster to re-filter them here, since there are way less candidates now
  3043. // Calculate a total "utf" length of a token string representation
  3044. size_t utf8_str_len = 0;
  3045. for (unsigned i = 0; i < token.length();) {
  3046. utf8_str_len++;
  3047. i += utf8_len(token.at(i));
  3048. }
  3049. // And skip the ones which are one character
  3050. if (utf8_str_len > 1) {
  3051. // At this point what we have left are special tokens only
  3052. vocab.special_tokens_cache[token] = id;
  3053. // Count manually found special tokens
  3054. special_tokens_count_from_verification++;
  3055. // If this manually found special token is not marked as such, flag a mismatch
  3056. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3057. special_tokens_definition_mismatch = true;
  3058. }
  3059. }
  3060. }
  3061. }
  3062. }
  3063. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3064. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3065. __func__,
  3066. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3067. special_tokens_count_by_type, vocab.id_to_token.size()
  3068. );
  3069. } else {
  3070. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3071. __func__,
  3072. special_tokens_count_from_verification, vocab.id_to_token.size()
  3073. );
  3074. }
  3075. }
  3076. }
  3077. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3078. const auto & hparams = model.hparams;
  3079. const auto & vocab = model.vocab;
  3080. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3081. // hparams
  3082. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3083. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3084. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3085. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3086. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3087. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3088. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3089. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3090. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3091. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3092. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3093. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3094. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3095. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3096. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3097. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3098. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3099. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3100. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3101. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3102. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3103. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3104. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3105. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3106. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3107. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3108. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3109. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3110. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3111. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3112. if (ml.n_elements >= 1e12) {
  3113. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3114. } else if (ml.n_elements >= 1e9) {
  3115. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3116. } else if (ml.n_elements >= 1e6) {
  3117. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3118. } else {
  3119. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3120. }
  3121. if (ml.n_bytes < GiB) {
  3122. 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);
  3123. } else {
  3124. 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);
  3125. }
  3126. // general kv
  3127. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3128. // special tokens
  3129. 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() ); }
  3130. 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() ); }
  3131. 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() ); }
  3132. 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() ); }
  3133. 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() ); }
  3134. 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() ); }
  3135. }
  3136. // Returns false if cancelled by progress_callback
  3137. static bool llm_load_tensors(
  3138. llama_model_loader & ml,
  3139. llama_model & model,
  3140. int n_gpu_layers,
  3141. enum llama_split_mode split_mode,
  3142. int main_gpu,
  3143. const float * tensor_split,
  3144. bool use_mlock,
  3145. llama_progress_callback progress_callback,
  3146. void * progress_callback_user_data) {
  3147. model.t_start_us = ggml_time_us();
  3148. auto & hparams = model.hparams;
  3149. model.split_mode = split_mode;
  3150. model.main_gpu = main_gpu;
  3151. model.n_gpu_layers = n_gpu_layers;
  3152. const int64_t n_layer = hparams.n_layer;
  3153. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3154. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3155. model.buft_input = llama_default_buffer_type_cpu(true);
  3156. model.buft_layer.resize(n_layer);
  3157. // assign cpu layers
  3158. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3159. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3160. }
  3161. if (split_mode == LLAMA_SPLIT_LAYER) {
  3162. // calculate the split points
  3163. int device_count = llama_get_device_count();
  3164. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3165. std::vector<float> splits(device_count);
  3166. if (all_zero) {
  3167. // default split, by free memory
  3168. for (int i = 0; i < device_count; ++i) {
  3169. splits[i] = llama_get_device_memory(i);
  3170. }
  3171. } else {
  3172. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3173. }
  3174. // sum and normalize the splits to get the split points
  3175. float split_sum = 0.0f;
  3176. for (int i = 0; i < device_count; ++i) {
  3177. split_sum += splits[i];
  3178. splits[i] = split_sum;
  3179. }
  3180. for (int i = 0; i < device_count; ++i) {
  3181. splits[i] /= split_sum;
  3182. }
  3183. // assign the repeating layers to the devices according to the splits
  3184. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3185. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3186. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3187. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3188. }
  3189. // assign the output layer
  3190. if (n_gpu_layers > n_layer) {
  3191. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3192. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3193. } else {
  3194. model.buft_output = llama_default_buffer_type_cpu(true);
  3195. }
  3196. } else {
  3197. ggml_backend_buffer_type_t split_buft;
  3198. if (split_mode == LLAMA_SPLIT_ROW) {
  3199. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3200. } else {
  3201. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  3202. split_buft = llama_default_buffer_type_offload(main_gpu);
  3203. }
  3204. // assign the repeating layers
  3205. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3206. model.buft_layer[i] = {
  3207. split_buft,
  3208. llama_default_buffer_type_offload(main_gpu)
  3209. };
  3210. }
  3211. // assign the output layer
  3212. if (n_gpu_layers > n_layer) {
  3213. model.buft_output = {
  3214. split_buft,
  3215. llama_default_buffer_type_offload(main_gpu)
  3216. };
  3217. } else {
  3218. model.buft_output = llama_default_buffer_type_cpu(true);
  3219. }
  3220. }
  3221. // count used buffer types
  3222. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3223. buft_layer_count[model.buft_input.buft]++;
  3224. buft_layer_count[model.buft_input.buft_matrix]++;
  3225. buft_layer_count[model.buft_output.buft]++;
  3226. buft_layer_count[model.buft_output.buft_matrix]++;
  3227. for (int64_t i = 0; i < n_layer; ++i) {
  3228. buft_layer_count[model.buft_layer[i].buft]++;
  3229. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3230. }
  3231. // create one context per buffer type
  3232. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  3233. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3234. for (auto & it : buft_layer_count) {
  3235. struct ggml_init_params params = {
  3236. /*.mem_size =*/ ctx_size,
  3237. /*.mem_buffer =*/ NULL,
  3238. /*.no_alloc =*/ true,
  3239. };
  3240. ggml_context * ctx = ggml_init(params);
  3241. if (!ctx) {
  3242. throw std::runtime_error(format("failed to create context"));
  3243. }
  3244. ctx_map[it.first] = ctx;
  3245. model.ctxs.push_back(ctx);
  3246. }
  3247. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3248. // create tensors for the weights
  3249. {
  3250. const int64_t n_embd = hparams.n_embd;
  3251. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3252. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3253. const int64_t n_embd_gqa = n_embd_v_gqa;
  3254. const int64_t n_vocab = hparams.n_vocab;
  3255. const int64_t n_vocab_type = hparams.n_vocab_type;
  3256. const int64_t n_ff = hparams.n_ff;
  3257. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3258. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3259. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3260. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3261. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3262. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3263. model.layers.resize(n_layer);
  3264. const auto tn = LLM_TN(model.arch);
  3265. switch (model.arch) {
  3266. case LLM_ARCH_LLAMA:
  3267. case LLM_ARCH_REFACT:
  3268. case LLM_ARCH_MINICPM:
  3269. {
  3270. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3271. // output
  3272. {
  3273. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3274. if (model.arch != LLM_ARCH_MINICPM){
  3275. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3276. }
  3277. }
  3278. for (int i = 0; i < n_layer; ++i) {
  3279. ggml_context * ctx_layer = ctx_for_layer(i);
  3280. ggml_context * ctx_split = ctx_for_layer_split(i);
  3281. auto & layer = model.layers[i];
  3282. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3283. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3284. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3285. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3286. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3287. // optional bias tensors
  3288. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3289. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3290. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3291. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3292. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3293. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3294. if (layer.ffn_gate_inp == nullptr) {
  3295. GGML_ASSERT(hparams.n_expert == 0);
  3296. GGML_ASSERT(hparams.n_expert_used == 0);
  3297. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3298. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3299. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3300. } else {
  3301. GGML_ASSERT(hparams.n_expert > 0);
  3302. GGML_ASSERT(hparams.n_expert_used > 0);
  3303. // MoE branch
  3304. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3305. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3306. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3307. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3308. }
  3309. }
  3310. }
  3311. } break;
  3312. case LLM_ARCH_BAICHUAN:
  3313. {
  3314. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3315. {
  3316. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3317. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3318. }
  3319. for (int i = 0; i < n_layer; ++i) {
  3320. ggml_context * ctx_layer = ctx_for_layer(i);
  3321. ggml_context * ctx_split = ctx_for_layer_split(i);
  3322. auto & layer = model.layers[i];
  3323. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3324. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3325. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3326. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3327. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3328. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3329. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3330. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3331. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3332. }
  3333. } break;
  3334. case LLM_ARCH_FALCON:
  3335. {
  3336. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3337. // output
  3338. {
  3339. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3340. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3341. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3342. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3343. } else {
  3344. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3345. ml.n_created--; // artificial tensor
  3346. }
  3347. }
  3348. for (int i = 0; i < n_layer; ++i) {
  3349. ggml_context * ctx_layer = ctx_for_layer(i);
  3350. ggml_context * ctx_split = ctx_for_layer_split(i);
  3351. auto & layer = model.layers[i];
  3352. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3353. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3354. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3355. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3356. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3357. }
  3358. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3359. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3360. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3361. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3362. }
  3363. } break;
  3364. case LLM_ARCH_STARCODER:
  3365. {
  3366. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3367. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3368. // output
  3369. {
  3370. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3371. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3372. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3373. }
  3374. for (int i = 0; i < n_layer; ++i) {
  3375. ggml_context * ctx_layer = ctx_for_layer(i);
  3376. ggml_context * ctx_split = ctx_for_layer_split(i);
  3377. auto & layer = model.layers[i];
  3378. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3379. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3380. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3381. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3382. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3383. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3384. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3385. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3386. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3387. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3388. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3389. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3390. }
  3391. } break;
  3392. case LLM_ARCH_PERSIMMON:
  3393. {
  3394. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3395. {
  3396. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3397. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3398. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3399. }
  3400. for (int i = 0; i < n_layer; ++i) {
  3401. ggml_context * ctx_layer = ctx_for_layer(i);
  3402. ggml_context * ctx_split = ctx_for_layer_split(i);
  3403. auto & layer = model.layers[i];
  3404. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3405. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3406. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3407. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3408. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3409. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3410. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3411. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3412. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3413. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3414. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3415. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3416. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3417. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3418. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3419. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3420. }
  3421. } break;
  3422. case LLM_ARCH_BERT:
  3423. case LLM_ARCH_NOMIC_BERT:
  3424. {
  3425. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3426. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3427. if (model.arch == LLM_ARCH_BERT) {
  3428. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3429. }
  3430. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3431. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3432. for (int i = 0; i < n_layer; ++i) {
  3433. ggml_context * ctx_layer = ctx_for_layer(i);
  3434. ggml_context * ctx_split = ctx_for_layer_split(i);
  3435. auto & layer = model.layers[i];
  3436. if (model.arch == LLM_ARCH_BERT) {
  3437. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3438. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3439. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3440. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3441. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3442. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3443. } else {
  3444. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3445. }
  3446. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3447. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3448. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3449. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3450. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3451. if (model.arch == LLM_ARCH_BERT) {
  3452. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3453. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3454. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3455. } else {
  3456. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3457. }
  3458. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3459. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3460. }
  3461. } break;
  3462. case LLM_ARCH_BLOOM:
  3463. {
  3464. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3465. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3466. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3467. // output
  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_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3484. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3485. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3486. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3487. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3488. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3489. }
  3490. } break;
  3491. case LLM_ARCH_MPT:
  3492. {
  3493. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3494. // output
  3495. {
  3496. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3497. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3498. }
  3499. for (int i = 0; i < n_layer; ++i) {
  3500. ggml_context * ctx_layer = ctx_for_layer(i);
  3501. ggml_context * ctx_split = ctx_for_layer_split(i);
  3502. auto & layer = model.layers[i];
  3503. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3504. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3505. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3506. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3507. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3508. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3509. // AWQ ScaleActivation layer
  3510. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3511. }
  3512. } break;
  3513. case LLM_ARCH_STABLELM:
  3514. {
  3515. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3516. // output
  3517. {
  3518. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3519. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3520. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3521. }
  3522. for (int i = 0; i < n_layer; ++i) {
  3523. ggml_context * ctx_layer = ctx_for_layer(i);
  3524. ggml_context * ctx_split = ctx_for_layer_split(i);
  3525. auto & layer = model.layers[i];
  3526. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3527. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3528. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3529. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3530. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3531. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3532. // optional bias tensors, present in Stable LM 2 1.6B
  3533. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3534. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3535. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3536. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3537. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3538. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3539. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3540. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3541. }
  3542. } break;
  3543. case LLM_ARCH_QWEN:
  3544. {
  3545. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3546. // output
  3547. {
  3548. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3549. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3550. }
  3551. for (int i = 0; i < n_layer; ++i) {
  3552. ggml_context * ctx_layer = ctx_for_layer(i);
  3553. ggml_context * ctx_split = ctx_for_layer_split(i);
  3554. auto & layer = model.layers[i];
  3555. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3556. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3557. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3558. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3559. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3560. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3561. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3562. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3563. }
  3564. } break;
  3565. case LLM_ARCH_QWEN2:
  3566. {
  3567. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3568. // output
  3569. {
  3570. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3571. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3572. }
  3573. for (int i = 0; i < n_layer; ++i) {
  3574. ggml_context * ctx_layer = ctx_for_layer(i);
  3575. ggml_context * ctx_split = ctx_for_layer_split(i);
  3576. auto & layer = model.layers[i];
  3577. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3578. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3579. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3580. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3581. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3582. // optional bias tensors
  3583. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3584. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3585. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3586. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3587. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3588. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3589. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3590. }
  3591. } break;
  3592. case LLM_ARCH_PHI2:
  3593. {
  3594. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3595. // output
  3596. {
  3597. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3598. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3599. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3600. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3601. }
  3602. for (int i = 0; i < n_layer; ++i) {
  3603. ggml_context * ctx_layer = ctx_for_layer(i);
  3604. ggml_context * ctx_split = ctx_for_layer_split(i);
  3605. auto & layer = model.layers[i];
  3606. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3607. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3608. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3609. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3610. if (layer.wqkv == nullptr) {
  3611. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3612. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3613. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3614. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3615. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3616. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3617. }
  3618. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3619. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3620. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3621. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3622. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3623. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3624. }
  3625. } break;
  3626. case LLM_ARCH_PLAMO:
  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.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3640. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3641. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3642. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3643. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3644. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3645. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3646. }
  3647. } break;
  3648. case LLM_ARCH_GPT2:
  3649. {
  3650. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3651. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3652. // output
  3653. {
  3654. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3655. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3656. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3657. }
  3658. for (int i = 0; i < n_layer; ++i) {
  3659. ggml_context * ctx_layer = ctx_for_layer(i);
  3660. ggml_context * ctx_split = ctx_for_layer_split(i);
  3661. auto & layer = model.layers[i];
  3662. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3663. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3664. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3665. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3666. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3667. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3668. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3669. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3670. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3671. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3672. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3673. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3674. }
  3675. } break;
  3676. case LLM_ARCH_CODESHELL:
  3677. {
  3678. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3679. // output
  3680. {
  3681. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3682. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3683. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, 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});
  3692. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3693. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3694. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3695. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3696. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3697. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3698. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3699. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3700. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3701. }
  3702. } break;
  3703. case LLM_ARCH_ORION:
  3704. {
  3705. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3706. {
  3707. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3708. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3709. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3710. }
  3711. for (int i = 0; i < n_layer; ++i) {
  3712. ggml_context * ctx_layer = ctx_for_layer(i);
  3713. ggml_context * ctx_split = ctx_for_layer_split(i);
  3714. auto & layer = model.layers[i];
  3715. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3716. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3717. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3718. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3719. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3720. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3721. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3722. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3723. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3724. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3725. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3726. }
  3727. } break;
  3728. case LLM_ARCH_INTERNLM2:
  3729. {
  3730. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3731. // output
  3732. {
  3733. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3734. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3735. }
  3736. for (int i = 0; i < n_layer; ++i) {
  3737. ggml_context * ctx_layer = ctx_for_layer(i);
  3738. ggml_context * ctx_split = ctx_for_layer_split(i);
  3739. auto & layer = model.layers[i];
  3740. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3741. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3742. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3743. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3744. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3745. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3746. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3747. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3748. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3749. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3750. }
  3751. } break;
  3752. case LLM_ARCH_GEMMA:
  3753. {
  3754. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3755. // output
  3756. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3757. 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
  3758. ml.n_created--; // artificial tensor
  3759. const int64_t n_ff = hparams.n_ff;
  3760. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3761. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3762. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3763. for (uint32_t i = 0; i < n_layer; ++i) {
  3764. ggml_context * ctx_layer = ctx_for_layer(i);
  3765. ggml_context * ctx_split = ctx_for_layer_split(i);
  3766. auto & layer = model.layers[i];
  3767. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3768. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  3769. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  3770. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  3771. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  3772. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3773. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3774. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3775. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3776. }
  3777. } break;
  3778. default:
  3779. throw std::runtime_error("unknown architecture");
  3780. }
  3781. }
  3782. ml.done_getting_tensors();
  3783. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3784. // create the backend buffers
  3785. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3786. for (auto & it : ctx_map) {
  3787. ggml_backend_buffer_type_t buft = it.first;
  3788. ggml_context * ctx = it.second;
  3789. ggml_backend_buffer_t buf = nullptr;
  3790. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3791. // 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
  3792. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3793. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3794. size_t first, last;
  3795. ml.get_mapping_range(&first, &last, ctx);
  3796. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3797. }
  3798. #ifdef GGML_USE_METAL
  3799. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3800. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3801. size_t first, last;
  3802. ml.get_mapping_range(&first, &last, ctx);
  3803. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3804. }
  3805. #endif
  3806. else {
  3807. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3808. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3809. model.mlock_bufs.emplace_back(new llama_mlock);
  3810. auto & mlock_buf = model.mlock_bufs.back();
  3811. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3812. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3813. }
  3814. }
  3815. if (buf == nullptr) {
  3816. throw std::runtime_error("failed to allocate buffer");
  3817. }
  3818. // indicate that this buffer contains weights
  3819. // 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
  3820. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3821. model.bufs.push_back(buf);
  3822. ctx_bufs.emplace_back(ctx, buf);
  3823. }
  3824. if (llama_supports_gpu_offload()) {
  3825. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3826. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3827. if (n_gpu_layers > (int) hparams.n_layer) {
  3828. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3829. }
  3830. const int max_backend_supported_layers = hparams.n_layer + 1;
  3831. const int max_offloadable_layers = hparams.n_layer + 1;
  3832. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3833. }
  3834. // print memory requirements
  3835. for (ggml_backend_buffer_t buf : model.bufs) {
  3836. 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);
  3837. }
  3838. // populate tensors_by_name
  3839. for (ggml_context * ctx : model.ctxs) {
  3840. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3841. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3842. }
  3843. }
  3844. // load tensor data
  3845. for (auto & it : ctx_bufs) {
  3846. ggml_context * ctx = it.first;
  3847. ggml_backend_buffer_t buf = it.second;
  3848. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3849. return false;
  3850. }
  3851. }
  3852. model.mapping = std::move(ml.mapping);
  3853. // loading time will be recalculate after the first eval, so
  3854. // we take page faults deferred by mmap() into consideration
  3855. model.t_load_us = ggml_time_us() - model.t_start_us;
  3856. return true;
  3857. }
  3858. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3859. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  3860. try {
  3861. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3862. model.hparams.vocab_only = params.vocab_only;
  3863. try {
  3864. llm_load_arch(ml, model);
  3865. } catch(const std::exception & e) {
  3866. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  3867. }
  3868. try {
  3869. llm_load_hparams(ml, model);
  3870. } catch(const std::exception & e) {
  3871. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  3872. }
  3873. try {
  3874. llm_load_vocab(ml, model);
  3875. } catch(const std::exception & e) {
  3876. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  3877. }
  3878. llm_load_print_meta(ml, model);
  3879. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3880. throw std::runtime_error("vocab size mismatch");
  3881. }
  3882. if (params.vocab_only) {
  3883. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3884. return 0;
  3885. }
  3886. #ifdef GGML_USE_KOMPUTE
  3887. if (params.n_gpu_layers > 0 && (
  3888. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  3889. || !(
  3890. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  3891. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  3892. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  3893. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  3894. )
  3895. )) {
  3896. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  3897. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  3898. params.n_gpu_layers = 0;
  3899. }
  3900. #endif
  3901. if (!llm_load_tensors(
  3902. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3903. params.progress_callback, params.progress_callback_user_data
  3904. )) {
  3905. return -2;
  3906. }
  3907. } catch (const std::exception & err) {
  3908. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3909. return -1;
  3910. }
  3911. return 0;
  3912. }
  3913. //
  3914. // llm_build
  3915. //
  3916. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3917. enum llm_rope_type {
  3918. LLM_ROPE,
  3919. LLM_ROPE_NEOX,
  3920. LLM_ROPE_GLM,
  3921. };
  3922. enum llm_ffn_op_type {
  3923. LLM_FFN_SILU,
  3924. LLM_FFN_GELU,
  3925. LLM_FFN_RELU,
  3926. LLM_FFN_RELU_SQR,
  3927. };
  3928. enum llm_ffn_gate_type {
  3929. LLM_FFN_SEQ,
  3930. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3931. };
  3932. enum llm_norm_type {
  3933. LLM_NORM,
  3934. LLM_NORM_RMS,
  3935. };
  3936. static struct ggml_tensor * llm_build_inp_embd(
  3937. struct ggml_context * ctx,
  3938. const llama_hparams & hparams,
  3939. const llama_batch & batch,
  3940. struct ggml_tensor * tok_embd,
  3941. struct ggml_tensor * inp_tokens,
  3942. struct ggml_tensor * inp_embd,
  3943. const llm_build_cb & cb) {
  3944. const int64_t n_embd = hparams.n_embd;
  3945. struct ggml_tensor * inpL;
  3946. if (batch.token) {
  3947. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3948. cb(inp_tokens, "inp_tokens", -1);
  3949. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  3950. } else {
  3951. #ifdef GGML_USE_MPI
  3952. GGML_ASSERT(false && "not implemented");
  3953. #endif
  3954. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  3955. }
  3956. return inpL;
  3957. }
  3958. // Persimmon: n_rot = n_embd_head_k/2
  3959. // Other: n_rot = n_embd_head_k
  3960. static void llm_build_k_shift(
  3961. struct ggml_context * ctx,
  3962. const llama_hparams & hparams,
  3963. const llama_cparams & cparams,
  3964. const llama_kv_cache & kv,
  3965. struct ggml_cgraph * graph,
  3966. struct ggml_tensor * K_shift,
  3967. llm_rope_type type,
  3968. int64_t n_ctx,
  3969. float freq_base,
  3970. float freq_scale,
  3971. const llm_build_cb & cb) {
  3972. const int64_t n_layer = hparams.n_layer;
  3973. const int64_t n_head_kv = hparams.n_head_kv;
  3974. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3975. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3976. const int32_t n_rot = hparams.n_rot;
  3977. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3978. const float ext_factor = cparams.yarn_ext_factor;
  3979. const float attn_factor = cparams.yarn_attn_factor;
  3980. const float beta_fast = cparams.yarn_beta_fast;
  3981. const float beta_slow = cparams.yarn_beta_slow;
  3982. int rope_type = 0;
  3983. switch (type) {
  3984. case LLM_ROPE: rope_type = 0; break;
  3985. case LLM_ROPE_NEOX: rope_type = 2; break;
  3986. case LLM_ROPE_GLM: rope_type = 4; break;
  3987. }
  3988. for (int il = 0; il < n_layer; ++il) {
  3989. struct ggml_tensor * tmp =
  3990. // we rotate only the first n_rot dimensions
  3991. ggml_rope_custom_inplace(ctx,
  3992. ggml_view_3d(ctx, kv.k_l[il],
  3993. n_embd_head_k, n_head_kv, n_ctx,
  3994. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3995. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3996. 0),
  3997. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3998. ext_factor, attn_factor, beta_fast, beta_slow);
  3999. cb(tmp, "K_shifted", il);
  4000. ggml_build_forward_expand(graph, tmp);
  4001. }
  4002. }
  4003. static void llm_build_kv_store(
  4004. struct ggml_context * ctx,
  4005. const llama_hparams & hparams,
  4006. const llama_kv_cache & kv,
  4007. struct ggml_cgraph * graph,
  4008. struct ggml_tensor * k_cur,
  4009. struct ggml_tensor * v_cur,
  4010. int64_t n_ctx,
  4011. int32_t n_tokens,
  4012. int32_t kv_head,
  4013. const llm_build_cb & cb,
  4014. int64_t il) {
  4015. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4016. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4017. // compute the transposed [n_tokens, n_embd] V matrix
  4018. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4019. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4020. cb(v_cur_t, "v_cur_t", il);
  4021. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4022. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4023. cb(k_cache_view, "k_cache_view", il);
  4024. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4025. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4026. (kv_head)*ggml_element_size(kv.v_l[il]));
  4027. cb(v_cache_view, "v_cache_view", il);
  4028. // important: storing RoPE-ed version of K in the KV cache!
  4029. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4030. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4031. }
  4032. static struct ggml_tensor * llm_build_norm(
  4033. struct ggml_context * ctx,
  4034. struct ggml_tensor * cur,
  4035. const llama_hparams & hparams,
  4036. struct ggml_tensor * mw,
  4037. struct ggml_tensor * mb,
  4038. llm_norm_type type,
  4039. const llm_build_cb & cb,
  4040. int il) {
  4041. switch (type) {
  4042. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4043. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4044. }
  4045. if (mw || mb) {
  4046. cb(cur, "norm", il);
  4047. }
  4048. if (mw) {
  4049. cur = ggml_mul(ctx, cur, mw);
  4050. if (mb) {
  4051. cb(cur, "norm_w", il);
  4052. }
  4053. }
  4054. if (mb) {
  4055. cur = ggml_add(ctx, cur, mb);
  4056. }
  4057. return cur;
  4058. }
  4059. static struct ggml_tensor * llm_build_ffn(
  4060. struct ggml_context * ctx,
  4061. struct ggml_tensor * cur,
  4062. struct ggml_tensor * up,
  4063. struct ggml_tensor * up_b,
  4064. struct ggml_tensor * gate,
  4065. struct ggml_tensor * gate_b,
  4066. struct ggml_tensor * down,
  4067. struct ggml_tensor * down_b,
  4068. struct ggml_tensor * act_scales,
  4069. llm_ffn_op_type type_op,
  4070. llm_ffn_gate_type type_gate,
  4071. const llm_build_cb & cb,
  4072. int il) {
  4073. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4074. cb(tmp, "ffn_up", il);
  4075. if (up_b) {
  4076. tmp = ggml_add(ctx, tmp, up_b);
  4077. cb(tmp, "ffn_up_b", il);
  4078. }
  4079. if (gate) {
  4080. switch (type_gate) {
  4081. case LLM_FFN_SEQ:
  4082. {
  4083. cur = ggml_mul_mat(ctx, gate, tmp);
  4084. cb(cur, "ffn_gate", il);
  4085. } break;
  4086. case LLM_FFN_PAR:
  4087. {
  4088. cur = ggml_mul_mat(ctx, gate, cur);
  4089. cb(cur, "ffn_gate", il);
  4090. } break;
  4091. }
  4092. if (gate_b) {
  4093. cur = ggml_add(ctx, cur, gate_b);
  4094. cb(cur, "ffn_gate_b", il);
  4095. }
  4096. } else {
  4097. cur = tmp;
  4098. }
  4099. switch (type_op) {
  4100. case LLM_FFN_SILU:
  4101. {
  4102. cur = ggml_silu(ctx, cur);
  4103. cb(cur, "ffn_silu", il);
  4104. } break;
  4105. case LLM_FFN_GELU:
  4106. {
  4107. cur = ggml_gelu(ctx, cur);
  4108. cb(cur, "ffn_gelu", il);
  4109. if (act_scales != NULL) {
  4110. cur = ggml_div(ctx, cur, act_scales);
  4111. cb(cur, "ffn_act", il);
  4112. }
  4113. } break;
  4114. case LLM_FFN_RELU:
  4115. {
  4116. cur = ggml_relu(ctx, cur);
  4117. cb(cur, "ffn_relu", il);
  4118. } break;
  4119. case LLM_FFN_RELU_SQR:
  4120. {
  4121. cur = ggml_relu(ctx, cur);
  4122. cb(cur, "ffn_relu", il);
  4123. cur = ggml_sqr(ctx, cur);
  4124. cb(cur, "ffn_sqr(relu)", il);
  4125. } break;
  4126. }
  4127. if (type_gate == LLM_FFN_PAR) {
  4128. cur = ggml_mul(ctx, cur, tmp);
  4129. cb(cur, "ffn_gate_par", il);
  4130. }
  4131. cur = ggml_mul_mat(ctx, down, cur);
  4132. if (down_b) {
  4133. cb(cur, "ffn_down", il);
  4134. }
  4135. if (down_b) {
  4136. cur = ggml_add(ctx, cur, down_b);
  4137. }
  4138. return cur;
  4139. }
  4140. // if max_alibi_bias > 0 then apply ALiBi
  4141. static struct ggml_tensor * llm_build_kqv(
  4142. struct ggml_context * ctx,
  4143. const llama_model & model,
  4144. const llama_hparams & hparams,
  4145. const llama_kv_cache & kv,
  4146. struct ggml_cgraph * graph,
  4147. struct ggml_tensor * wo,
  4148. struct ggml_tensor * wo_b,
  4149. struct ggml_tensor * q_cur,
  4150. struct ggml_tensor * kq_mask,
  4151. struct ggml_tensor * kq_pos,
  4152. int64_t n_ctx,
  4153. int32_t n_tokens,
  4154. int32_t n_kv,
  4155. float kq_scale,
  4156. const llm_build_cb & cb,
  4157. int il) {
  4158. const int64_t n_head = hparams.n_head;
  4159. const int64_t n_head_kv = hparams.n_head_kv;
  4160. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4161. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4162. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4163. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4164. cb(q, "q", il);
  4165. struct ggml_tensor * k =
  4166. ggml_view_3d(ctx, kv.k_l[il],
  4167. n_embd_head_k, n_kv, n_head_kv,
  4168. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4169. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4170. 0);
  4171. cb(k, "k", il);
  4172. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4173. cb(kq, "kq", il);
  4174. if (model.arch == LLM_ARCH_PHI2) {
  4175. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4176. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4177. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4178. }
  4179. #if defined(GGML_USE_VULKAN) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_SYCL)
  4180. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Vulkan, Kompute, and SYCL")
  4181. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4182. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4183. if (hparams.f_max_alibi_bias > 0.0f) {
  4184. kq = ggml_scale(ctx, kq, kq_scale);
  4185. cb(kq, "kq_scaled", il);
  4186. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4187. cb(kq, "kq_scaled_alibi", il);
  4188. kq = ggml_add(ctx, kq, kq_mask);
  4189. cb(kq, "kq_masked", il);
  4190. kq = ggml_soft_max(ctx, kq);
  4191. cb(kq, "kq_soft_max", il);
  4192. } else
  4193. #endif
  4194. {
  4195. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4196. cb(kq, "kq_soft_max_ext", il);
  4197. }
  4198. // split cached v into n_head heads
  4199. struct ggml_tensor * v =
  4200. ggml_view_3d(ctx, kv.v_l[il],
  4201. n_kv, n_embd_head_v, n_head_kv,
  4202. ggml_element_size(kv.v_l[il])*n_ctx,
  4203. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4204. 0);
  4205. cb(v, "v", il);
  4206. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4207. cb(kqv, "kqv", il);
  4208. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4209. cb(kqv_merged, "kqv_merged", il);
  4210. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4211. cb(cur, "kqv_merged_cont", il);
  4212. ggml_build_forward_expand(graph, cur);
  4213. cur = ggml_mul_mat(ctx, wo, cur);
  4214. if (wo_b) {
  4215. cb(cur, "kqv_wo", il);
  4216. }
  4217. if (wo_b) {
  4218. cur = ggml_add(ctx, cur, wo_b);
  4219. }
  4220. return cur;
  4221. }
  4222. static struct ggml_tensor * llm_build_kv(
  4223. struct ggml_context * ctx,
  4224. const llama_model & model,
  4225. const llama_hparams & hparams,
  4226. const llama_kv_cache & kv,
  4227. struct ggml_cgraph * graph,
  4228. struct ggml_tensor * wo,
  4229. struct ggml_tensor * wo_b,
  4230. struct ggml_tensor * k_cur,
  4231. struct ggml_tensor * v_cur,
  4232. struct ggml_tensor * q_cur,
  4233. struct ggml_tensor * kq_mask,
  4234. struct ggml_tensor * kq_pos,
  4235. int64_t n_ctx,
  4236. int32_t n_tokens,
  4237. int32_t kv_head,
  4238. int32_t n_kv,
  4239. float kq_scale,
  4240. const llm_build_cb & cb,
  4241. int il) {
  4242. // these nodes are added to the graph together so that they are not reordered
  4243. // by doing so, the number of splits in the graph is reduced
  4244. ggml_build_forward_expand(graph, q_cur);
  4245. ggml_build_forward_expand(graph, k_cur);
  4246. ggml_build_forward_expand(graph, v_cur);
  4247. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4248. struct ggml_tensor * cur;
  4249. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4250. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4251. cb(cur, "kqv_out", il);
  4252. return cur;
  4253. }
  4254. struct llm_build_context {
  4255. const llama_model & model;
  4256. const llama_context & lctx;
  4257. const llama_hparams & hparams;
  4258. const llama_cparams & cparams;
  4259. const llama_batch & batch;
  4260. const llama_kv_cache & kv_self;
  4261. const int64_t n_embd;
  4262. const int64_t n_layer;
  4263. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4264. const int64_t n_head;
  4265. const int64_t n_head_kv;
  4266. const int64_t n_embd_head_k;
  4267. const int64_t n_embd_k_gqa;
  4268. const int64_t n_embd_head_v;
  4269. const int64_t n_embd_v_gqa;
  4270. const int64_t n_expert;
  4271. const int64_t n_expert_used;
  4272. const float freq_base;
  4273. const float freq_scale;
  4274. const float ext_factor;
  4275. const float attn_factor;
  4276. const float beta_fast;
  4277. const float beta_slow;
  4278. const float norm_eps;
  4279. const float norm_rms_eps;
  4280. const int32_t n_tokens;
  4281. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4282. const int32_t kv_head; // index of where we store new KV data in the cache
  4283. const int32_t n_orig_ctx;
  4284. const bool do_rope_shift;
  4285. const uint32_t pooling_type;
  4286. const llm_build_cb & cb;
  4287. std::vector<uint8_t> & buf_compute_meta;
  4288. struct ggml_context * ctx0 = nullptr;
  4289. // TODO: consider making the entire interface noexcept
  4290. llm_build_context(
  4291. llama_context & lctx,
  4292. const llama_batch & batch,
  4293. const llm_build_cb & cb,
  4294. bool worst_case) :
  4295. model (lctx.model),
  4296. lctx (lctx),
  4297. hparams (model.hparams),
  4298. cparams (lctx.cparams),
  4299. batch (batch),
  4300. kv_self (lctx.kv_self),
  4301. n_embd (hparams.n_embd),
  4302. n_layer (hparams.n_layer),
  4303. n_ctx (cparams.n_ctx),
  4304. n_head (hparams.n_head),
  4305. n_head_kv (hparams.n_head_kv),
  4306. n_embd_head_k (hparams.n_embd_head_k),
  4307. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4308. n_embd_head_v (hparams.n_embd_head_v),
  4309. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4310. n_expert (hparams.n_expert),
  4311. n_expert_used (hparams.n_expert_used),
  4312. freq_base (cparams.rope_freq_base),
  4313. freq_scale (cparams.rope_freq_scale),
  4314. ext_factor (cparams.yarn_ext_factor),
  4315. attn_factor (cparams.yarn_attn_factor),
  4316. beta_fast (cparams.yarn_beta_fast),
  4317. beta_slow (cparams.yarn_beta_slow),
  4318. norm_eps (hparams.f_norm_eps),
  4319. norm_rms_eps (hparams.f_norm_rms_eps),
  4320. n_tokens (batch.n_tokens),
  4321. n_kv (worst_case ? n_ctx : kv_self.n),
  4322. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4323. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4324. do_rope_shift (worst_case || kv_self.has_shift),
  4325. pooling_type (cparams.do_pooling ? hparams.pooling_type : (uint32_t)LLAMA_POOLING_NONE),
  4326. cb (cb),
  4327. buf_compute_meta (lctx.buf_compute_meta) {
  4328. // all initializations should be done in init()
  4329. }
  4330. void init() {
  4331. struct ggml_init_params params = {
  4332. /*.mem_size =*/ buf_compute_meta.size(),
  4333. /*.mem_buffer =*/ buf_compute_meta.data(),
  4334. /*.no_alloc =*/ true,
  4335. };
  4336. ctx0 = ggml_init(params);
  4337. }
  4338. void free() {
  4339. if (ctx0) {
  4340. ggml_free(ctx0);
  4341. ctx0 = nullptr;
  4342. }
  4343. }
  4344. struct ggml_cgraph * build_llama() {
  4345. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4346. const int64_t n_embd_head = hparams.n_embd_head_v;
  4347. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4348. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4349. struct ggml_tensor * cur;
  4350. struct ggml_tensor * inpL;
  4351. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4352. cb(inpL, "inp_embd", -1);
  4353. // inp_pos - contains the positions
  4354. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4355. cb(inp_pos, "inp_pos", -1);
  4356. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4357. 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);
  4358. cb(KQ_mask, "KQ_mask", -1);
  4359. // shift the entire K-cache if needed
  4360. if (do_rope_shift) {
  4361. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4362. }
  4363. for (int il = 0; il < n_layer; ++il) {
  4364. struct ggml_tensor * inpSA = inpL;
  4365. // norm
  4366. cur = llm_build_norm(ctx0, inpL, hparams,
  4367. model.layers[il].attn_norm, NULL,
  4368. LLM_NORM_RMS, cb, il);
  4369. cb(cur, "attn_norm", il);
  4370. // self-attention
  4371. {
  4372. // compute Q and K and RoPE them
  4373. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4374. cb(Qcur, "Qcur", il);
  4375. if (model.layers[il].bq) {
  4376. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4377. cb(Qcur, "Qcur", il);
  4378. }
  4379. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4380. cb(Kcur, "Kcur", il);
  4381. if (model.layers[il].bk) {
  4382. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4383. cb(Kcur, "Kcur", il);
  4384. }
  4385. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4386. cb(Vcur, "Vcur", il);
  4387. if (model.layers[il].bv) {
  4388. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4389. cb(Vcur, "Vcur", il);
  4390. }
  4391. Qcur = ggml_rope_custom(
  4392. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4393. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4394. ext_factor, attn_factor, beta_fast, beta_slow
  4395. );
  4396. cb(Qcur, "Qcur", il);
  4397. Kcur = ggml_rope_custom(
  4398. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4399. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4400. ext_factor, attn_factor, beta_fast, beta_slow
  4401. );
  4402. cb(Kcur, "Kcur", il);
  4403. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4404. model.layers[il].wo, model.layers[il].bo,
  4405. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4406. cb(cur, "kqv_out", il);
  4407. }
  4408. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4409. cb(ffn_inp, "ffn_inp", il);
  4410. // feed-forward network
  4411. if (model.layers[il].ffn_gate_inp == nullptr) {
  4412. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4413. model.layers[il].ffn_norm, NULL,
  4414. LLM_NORM_RMS, cb, il);
  4415. cb(cur, "ffn_norm", il);
  4416. cur = llm_build_ffn(ctx0, cur,
  4417. model.layers[il].ffn_up, NULL,
  4418. model.layers[il].ffn_gate, NULL,
  4419. model.layers[il].ffn_down, NULL,
  4420. NULL,
  4421. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4422. cb(cur, "ffn_out", il);
  4423. } else {
  4424. // MoE branch
  4425. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4426. model.layers[il].ffn_norm, NULL,
  4427. LLM_NORM_RMS, cb, il);
  4428. cb(cur, "ffn_norm", il);
  4429. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4430. cb(logits, "ffn_moe_logits", il);
  4431. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4432. cb(probs, "ffn_moe_probs", il);
  4433. // select experts
  4434. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4435. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4436. ggml_tensor * weights = ggml_get_rows(ctx0,
  4437. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4438. cb(weights, "ffn_moe_weights", il);
  4439. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4440. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4441. cb(weights_sum, "ffn_moe_weights_sum", il);
  4442. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4443. cb(weights, "ffn_moe_weights_norm", il);
  4444. // compute expert outputs
  4445. ggml_tensor * moe_out = nullptr;
  4446. for (int i = 0; i < n_expert_used; ++i) {
  4447. ggml_tensor * cur_expert;
  4448. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4449. cb(cur_up, "ffn_moe_up", il);
  4450. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4451. cb(cur_gate, "ffn_moe_gate", il);
  4452. cur_gate = ggml_silu(ctx0, cur_gate);
  4453. cb(cur_gate, "ffn_moe_silu", il);
  4454. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4455. cb(cur_expert, "ffn_moe_gate_par", il);
  4456. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4457. cb(cur_expert, "ffn_moe_down", il);
  4458. cur_expert = ggml_mul(ctx0, cur_expert,
  4459. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4460. cb(cur_expert, "ffn_moe_weighted", il);
  4461. if (i == 0) {
  4462. moe_out = cur_expert;
  4463. } else {
  4464. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4465. cb(moe_out, "ffn_moe_out", il);
  4466. }
  4467. }
  4468. cur = moe_out;
  4469. }
  4470. cur = ggml_add(ctx0, cur, ffn_inp);
  4471. cb(cur, "l_out", il);
  4472. // input for next layer
  4473. inpL = cur;
  4474. }
  4475. cur = inpL;
  4476. cur = llm_build_norm(ctx0, cur, hparams,
  4477. model.output_norm, NULL,
  4478. LLM_NORM_RMS, cb, -1);
  4479. cb(cur, "result_norm", -1);
  4480. // lm_head
  4481. cur = ggml_mul_mat(ctx0, model.output, cur);
  4482. cb(cur, "result_output", -1);
  4483. ggml_build_forward_expand(gf, cur);
  4484. return gf;
  4485. }
  4486. struct ggml_cgraph * build_baichuan() {
  4487. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4488. const int64_t n_embd_head = hparams.n_embd_head_v;
  4489. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4490. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4491. struct ggml_tensor * cur;
  4492. struct ggml_tensor * inpL;
  4493. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4494. cb(inpL, "inp_embd", -1);
  4495. // inp_pos - contains the positions
  4496. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4497. cb(inp_pos, "inp_pos", -1);
  4498. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4499. 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);
  4500. cb(KQ_mask, "KQ_mask", -1);
  4501. // positions of the tokens in the KV cache
  4502. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4503. cb(KQ_pos, "KQ_pos", -1);
  4504. // shift the entire K-cache if needed
  4505. if (do_rope_shift) {
  4506. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4507. }
  4508. for (int il = 0; il < n_layer; ++il) {
  4509. struct ggml_tensor * inpSA = inpL;
  4510. cur = llm_build_norm(ctx0, inpL, hparams,
  4511. model.layers[il].attn_norm, NULL,
  4512. LLM_NORM_RMS, cb, il);
  4513. cb(cur, "attn_norm", il);
  4514. // self-attention
  4515. {
  4516. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4517. cb(Qcur, "Qcur", il);
  4518. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4519. cb(Kcur, "Kcur", il);
  4520. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4521. cb(Vcur, "Vcur", il);
  4522. switch (model.type) {
  4523. case MODEL_7B:
  4524. Qcur = ggml_rope_custom(
  4525. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4526. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4527. ext_factor, attn_factor, beta_fast, beta_slow
  4528. );
  4529. Kcur = ggml_rope_custom(
  4530. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4531. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4532. ext_factor, attn_factor, beta_fast, beta_slow
  4533. );
  4534. break;
  4535. case MODEL_13B:
  4536. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4537. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4538. break;
  4539. default:
  4540. GGML_ASSERT(false);
  4541. }
  4542. cb(Qcur, "Qcur", il);
  4543. cb(Kcur, "Kcur", il);
  4544. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4545. model.layers[il].wo, NULL,
  4546. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4547. cb(cur, "kqv_out", il);
  4548. }
  4549. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4550. cb(ffn_inp, "ffn_inp", il);
  4551. // feed-forward network
  4552. {
  4553. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4554. model.layers[il].ffn_norm, NULL,
  4555. LLM_NORM_RMS, cb, il);
  4556. cb(cur, "ffn_norm", il);
  4557. cur = llm_build_ffn(ctx0, cur,
  4558. model.layers[il].ffn_up, NULL,
  4559. model.layers[il].ffn_gate, NULL,
  4560. model.layers[il].ffn_down, NULL,
  4561. NULL,
  4562. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4563. cb(cur, "ffn_out", il);
  4564. }
  4565. cur = ggml_add(ctx0, cur, ffn_inp);
  4566. cb(cur, "l_out", il);
  4567. // input for next layer
  4568. inpL = cur;
  4569. }
  4570. cur = inpL;
  4571. cur = llm_build_norm(ctx0, cur, hparams,
  4572. model.output_norm, NULL,
  4573. LLM_NORM_RMS, cb, -1);
  4574. cb(cur, "result_norm", -1);
  4575. // lm_head
  4576. cur = ggml_mul_mat(ctx0, model.output, cur);
  4577. cb(cur, "result_output", -1);
  4578. ggml_build_forward_expand(gf, cur);
  4579. return gf;
  4580. }
  4581. struct ggml_cgraph * build_falcon() {
  4582. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4583. const int64_t n_embd_head = hparams.n_embd_head_v;
  4584. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4585. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4586. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4587. struct ggml_tensor * cur;
  4588. struct ggml_tensor * inpL;
  4589. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4590. cb(inpL, "inp_embd", -1);
  4591. // inp_pos - contains the positions
  4592. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4593. cb(inp_pos, "inp_pos", -1);
  4594. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4595. 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);
  4596. cb(KQ_mask, "KQ_mask", -1);
  4597. // shift the entire K-cache if needed
  4598. if (do_rope_shift) {
  4599. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4600. }
  4601. for (int il = 0; il < n_layer; ++il) {
  4602. struct ggml_tensor * attn_norm;
  4603. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4604. model.layers[il].attn_norm,
  4605. model.layers[il].attn_norm_b,
  4606. LLM_NORM, cb, il);
  4607. cb(attn_norm, "attn_norm", il);
  4608. // self-attention
  4609. {
  4610. if (model.layers[il].attn_norm_2) {
  4611. // Falcon-40B
  4612. cur = llm_build_norm(ctx0, inpL, hparams,
  4613. model.layers[il].attn_norm_2,
  4614. model.layers[il].attn_norm_2_b,
  4615. LLM_NORM, cb, il);
  4616. cb(cur, "attn_norm_2", il);
  4617. } else {
  4618. cur = attn_norm;
  4619. }
  4620. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4621. cb(cur, "wqkv", il);
  4622. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4623. 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)));
  4624. 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)));
  4625. cb(Qcur, "Qcur", il);
  4626. cb(Kcur, "Kcur", il);
  4627. cb(Vcur, "Vcur", il);
  4628. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4629. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4630. // using mode = 2 for neox mode
  4631. Qcur = ggml_rope_custom(
  4632. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4633. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4634. );
  4635. cb(Qcur, "Qcur", il);
  4636. Kcur = ggml_rope_custom(
  4637. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4638. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4639. );
  4640. cb(Kcur, "Kcur", il);
  4641. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4642. model.layers[il].wo, NULL,
  4643. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4644. cb(cur, "kqv_out", il);
  4645. }
  4646. struct ggml_tensor * ffn_inp = cur;
  4647. // feed forward
  4648. {
  4649. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4650. model.layers[il].ffn_up, NULL,
  4651. NULL, NULL,
  4652. model.layers[il].ffn_down, NULL,
  4653. NULL,
  4654. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4655. cb(cur, "ffn_out", il);
  4656. }
  4657. cur = ggml_add(ctx0, cur, ffn_inp);
  4658. cb(cur, "l_out", il);
  4659. cur = ggml_add(ctx0, cur, inpL);
  4660. cb(cur, "l_out", il);
  4661. // input for next layer
  4662. inpL = cur;
  4663. }
  4664. cur = inpL;
  4665. // norm
  4666. cur = llm_build_norm(ctx0, cur, hparams,
  4667. model.output_norm,
  4668. model.output_norm_b,
  4669. LLM_NORM, cb, -1);
  4670. cb(cur, "result_norm", -1);
  4671. cur = ggml_mul_mat(ctx0, model.output, cur);
  4672. cb(cur, "result_output", -1);
  4673. ggml_build_forward_expand(gf, cur);
  4674. return gf;
  4675. }
  4676. struct ggml_cgraph * build_starcoder() {
  4677. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4678. const int64_t n_embd_head = hparams.n_embd_head_v;
  4679. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4680. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4681. struct ggml_tensor * cur;
  4682. struct ggml_tensor * pos;
  4683. struct ggml_tensor * inpL;
  4684. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4685. cb(inpL, "inp_embd", -1);
  4686. // inp_pos - contains the positions
  4687. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4688. cb(inp_pos, "inp_pos", -1);
  4689. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4690. 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);
  4691. cb(KQ_mask, "KQ_mask", -1);
  4692. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4693. cb(pos, "pos_embd", -1);
  4694. inpL = ggml_add(ctx0, inpL, pos);
  4695. cb(inpL, "inpL", -1);
  4696. for (int il = 0; il < n_layer; ++il) {
  4697. cur = llm_build_norm(ctx0, inpL, hparams,
  4698. model.layers[il].attn_norm,
  4699. model.layers[il].attn_norm_b,
  4700. LLM_NORM, cb, il);
  4701. cb(cur, "attn_norm", il);
  4702. // self-attention
  4703. {
  4704. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4705. cb(cur, "wqkv", il);
  4706. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4707. cb(cur, "bqkv", il);
  4708. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4709. 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)));
  4710. 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)));
  4711. cb(Qcur, "Qcur", il);
  4712. cb(Kcur, "Kcur", il);
  4713. cb(Vcur, "Vcur", il);
  4714. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4715. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4716. model.layers[il].wo, model.layers[il].bo,
  4717. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4718. cb(cur, "kqv_out", il);
  4719. }
  4720. // add the input
  4721. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4722. cb(ffn_inp, "ffn_inp", il);
  4723. // FF
  4724. {
  4725. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4726. model.layers[il].ffn_norm,
  4727. model.layers[il].ffn_norm_b,
  4728. LLM_NORM, cb, il);
  4729. cb(cur, "ffn_norm", il);
  4730. cur = llm_build_ffn(ctx0, cur,
  4731. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4732. NULL, NULL,
  4733. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4734. NULL,
  4735. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4736. cb(cur, "ffn_out", il);
  4737. }
  4738. inpL = ggml_add(ctx0, cur, ffn_inp);
  4739. cb(inpL, "l_out", il);
  4740. }
  4741. cur = llm_build_norm(ctx0, inpL, hparams,
  4742. model.output_norm,
  4743. model.output_norm_b,
  4744. LLM_NORM, cb, -1);
  4745. cb(cur, "result_norm", -1);
  4746. cur = ggml_mul_mat(ctx0, model.output, cur);
  4747. cb(cur, "result_output", -1);
  4748. ggml_build_forward_expand(gf, cur);
  4749. return gf;
  4750. }
  4751. struct ggml_cgraph * build_persimmon() {
  4752. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4753. const int64_t n_embd_head = hparams.n_embd_head_v;
  4754. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4755. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4756. struct ggml_tensor * cur;
  4757. struct ggml_tensor * inpL;
  4758. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4759. cb(inpL, "inp_embd", -1);
  4760. // inp_pos - contains the positions
  4761. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4762. cb(inp_pos, "inp_pos", -1);
  4763. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4764. 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);
  4765. cb(KQ_mask, "KQ_mask", -1);
  4766. if (do_rope_shift) {
  4767. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4768. }
  4769. for (int il = 0; il < n_layer; ++il) {
  4770. struct ggml_tensor * residual = inpL;
  4771. cur = llm_build_norm(ctx0, inpL, hparams,
  4772. model.layers[il].attn_norm,
  4773. model.layers[il].attn_norm_b,
  4774. LLM_NORM, cb, il);
  4775. cb(cur, "attn_norm", il);
  4776. // self attention
  4777. {
  4778. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4779. cb(cur, "wqkv", il);
  4780. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4781. cb(cur, "bqkv", il);
  4782. // split qkv
  4783. GGML_ASSERT(n_head_kv == n_head);
  4784. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4785. cb(tmpqkv, "tmpqkv", il);
  4786. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4787. cb(tmpqkv_perm, "tmpqkv", il);
  4788. struct ggml_tensor * tmpq = ggml_view_3d(
  4789. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4790. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4791. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4792. 0
  4793. );
  4794. cb(tmpq, "tmpq", il);
  4795. struct ggml_tensor * tmpk = ggml_view_3d(
  4796. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4797. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4798. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4799. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4800. );
  4801. cb(tmpk, "tmpk", il);
  4802. // Q/K Layernorm
  4803. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4804. model.layers[il].attn_q_norm,
  4805. model.layers[il].attn_q_norm_b,
  4806. LLM_NORM, cb, il);
  4807. cb(tmpq, "tmpq", il);
  4808. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4809. model.layers[il].attn_k_norm,
  4810. model.layers[il].attn_k_norm_b,
  4811. LLM_NORM, cb, il);
  4812. cb(tmpk, "tmpk", il);
  4813. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4814. struct ggml_tensor * qrot = ggml_view_3d(
  4815. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4816. ggml_element_size(tmpq) * n_embd_head,
  4817. ggml_element_size(tmpq) * n_embd_head * n_head,
  4818. 0
  4819. );
  4820. cb(qrot, "qrot", il);
  4821. struct ggml_tensor * krot = ggml_view_3d(
  4822. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4823. ggml_element_size(tmpk) * n_embd_head,
  4824. ggml_element_size(tmpk) * n_embd_head * n_head,
  4825. 0
  4826. );
  4827. cb(krot, "krot", il);
  4828. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4829. struct ggml_tensor * qpass = ggml_view_3d(
  4830. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4831. ggml_element_size(tmpq) * n_embd_head,
  4832. ggml_element_size(tmpq) * n_embd_head * n_head,
  4833. ggml_element_size(tmpq) * hparams.n_rot
  4834. );
  4835. cb(qpass, "qpass", il);
  4836. struct ggml_tensor * kpass = ggml_view_3d(
  4837. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4838. ggml_element_size(tmpk) * n_embd_head,
  4839. ggml_element_size(tmpk) * n_embd_head * n_head,
  4840. ggml_element_size(tmpk) * hparams.n_rot
  4841. );
  4842. cb(kpass, "kpass", il);
  4843. struct ggml_tensor * qrotated = ggml_rope_custom(
  4844. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4845. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4846. );
  4847. cb(qrotated, "qrotated", il);
  4848. struct ggml_tensor * krotated = ggml_rope_custom(
  4849. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4850. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4851. );
  4852. cb(krotated, "krotated", il);
  4853. // ggml currently only supports concatenation on dim=2
  4854. // so we need to permute qrot, qpass, concat, then permute back.
  4855. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4856. cb(qrotated, "qrotated", il);
  4857. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4858. cb(krotated, "krotated", il);
  4859. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4860. cb(qpass, "qpass", il);
  4861. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4862. cb(kpass, "kpass", il);
  4863. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4864. cb(Qcur, "Qcur", il);
  4865. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4866. cb(Kcur, "Kcur", il);
  4867. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4868. cb(Q, "Q", il);
  4869. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4870. cb(Kcur, "Kcur", il);
  4871. struct ggml_tensor * Vcur = ggml_view_3d(
  4872. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4873. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4874. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4875. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4876. );
  4877. cb(Vcur, "Vcur", il);
  4878. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4879. model.layers[il].wo, model.layers[il].bo,
  4880. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4881. cb(cur, "kqv_out", il);
  4882. }
  4883. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4884. cb(ffn_inp, "ffn_inp", il);
  4885. // feed-forward network
  4886. {
  4887. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4888. model.layers[il].ffn_norm,
  4889. model.layers[il].ffn_norm_b,
  4890. LLM_NORM, cb, il);
  4891. cb(cur, "ffn_norm", il);
  4892. cur = llm_build_ffn(ctx0, cur,
  4893. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4894. NULL, NULL,
  4895. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4896. NULL,
  4897. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4898. cb(cur, "ffn_out", il);
  4899. }
  4900. cur = ggml_add(ctx0, cur, ffn_inp);
  4901. cb(cur, "l_out", il);
  4902. inpL = cur;
  4903. }
  4904. cur = inpL;
  4905. cur = llm_build_norm(ctx0, cur, hparams,
  4906. model.output_norm,
  4907. model.output_norm_b,
  4908. LLM_NORM, cb, -1);
  4909. cb(cur, "result_norm", -1);
  4910. cur = ggml_mul_mat(ctx0, model.output, cur);
  4911. cb(cur, "result_output", -1);
  4912. ggml_build_forward_expand(gf, cur);
  4913. return gf;
  4914. }
  4915. struct ggml_cgraph * build_refact() {
  4916. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4917. const int64_t n_embd_head = hparams.n_embd_head_v;
  4918. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4919. struct ggml_tensor * cur;
  4920. struct ggml_tensor * inpL;
  4921. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4922. cb(inpL, "inp_embd", -1);
  4923. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4924. 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);
  4925. cb(KQ_mask, "KQ_mask", -1);
  4926. // positions of the tokens in the KV cache
  4927. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4928. cb(KQ_pos, "KQ_pos", -1);
  4929. for (int il = 0; il < n_layer; ++il) {
  4930. struct ggml_tensor * inpSA = inpL;
  4931. cur = llm_build_norm(ctx0, inpL, hparams,
  4932. model.layers[il].attn_norm, NULL,
  4933. LLM_NORM_RMS, cb, il);
  4934. cb(cur, "attn_norm", il);
  4935. // self-attention
  4936. {
  4937. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4938. cb(Qcur, "Qcur", il);
  4939. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4940. cb(Kcur, "Kcur", il);
  4941. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4942. cb(Vcur, "Vcur", il);
  4943. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4944. cb(Kcur, "Kcur", il);
  4945. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4946. cb(Qcur, "Qcur", il);
  4947. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4948. model.layers[il].wo, NULL,
  4949. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4950. cb(cur, "kqv_out", il);
  4951. }
  4952. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4953. cb(ffn_inp, "ffn_inp", il);
  4954. // feed-forward network
  4955. {
  4956. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4957. model.layers[il].ffn_norm, NULL,
  4958. LLM_NORM_RMS, cb, il);
  4959. cb(cur, "ffn_norm", il);
  4960. cur = llm_build_ffn(ctx0, cur,
  4961. model.layers[il].ffn_up, NULL,
  4962. model.layers[il].ffn_gate, NULL,
  4963. model.layers[il].ffn_down, NULL,
  4964. NULL,
  4965. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4966. cb(cur, "ffn_out", il);
  4967. }
  4968. cur = ggml_add(ctx0, cur, ffn_inp);
  4969. cb(cur, "l_out", il);
  4970. // input for next layer
  4971. inpL = cur;
  4972. }
  4973. cur = inpL;
  4974. cur = llm_build_norm(ctx0, cur, hparams,
  4975. model.output_norm, NULL,
  4976. LLM_NORM_RMS, cb, -1);
  4977. cb(cur, "result_norm", -1);
  4978. // lm_head
  4979. cur = ggml_mul_mat(ctx0, model.output, cur);
  4980. cb(cur, "result_output", -1);
  4981. ggml_build_forward_expand(gf, cur);
  4982. return gf;
  4983. }
  4984. struct ggml_cgraph * build_bert() {
  4985. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4986. const int64_t n_embd_head = hparams.n_embd_head_v;
  4987. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4988. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4989. struct ggml_tensor * cur;
  4990. struct ggml_tensor * inpL;
  4991. // get input vectors with right size
  4992. const size_t stride1 = n_tokens * ggml_type_size(lctx.inp_tokens->type);
  4993. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4994. struct ggml_tensor * inp_mean = ggml_view_2d(ctx0, lctx.inp_mean, n_tokens, n_tokens, stride1, 0);
  4995. struct ggml_tensor * inp_cls = ggml_view_1d(ctx0, lctx.inp_cls, n_tokens, 0);
  4996. // construct input embeddings (token, type, position)
  4997. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4998. // token types are hardcoded to zero ("Sentence A")
  4999. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5000. inpL = ggml_add(ctx0, inpL, type_row0);
  5001. if (model.arch == LLM_ARCH_BERT) {
  5002. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5003. }
  5004. cb(inpL, "inp_embd", -1);
  5005. // embed layer norm
  5006. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5007. cb(inpL, "inp_norm", -1);
  5008. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5009. 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);
  5010. cb(KQ_mask, "KQ_mask", -1); // [n_kv, n_tokens]
  5011. // iterate layers
  5012. for (int il = 0; il < n_layer; ++il) {
  5013. struct ggml_tensor * cur = inpL;
  5014. // self-attention
  5015. if (model.arch == LLM_ARCH_BERT) {
  5016. struct ggml_tensor * Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5017. cb(Qcur, "Qcur", il);
  5018. struct ggml_tensor * Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5019. cb(Kcur, "Kcur", il);
  5020. struct ggml_tensor * Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5021. cb(Vcur, "Vcur", il);
  5022. // seems like we just need to do this for Q?
  5023. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5024. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5025. model.layers[il].wo, model.layers[il].bo,
  5026. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5027. cb(cur, "kqv_out", il);
  5028. } else {
  5029. // compute Q and K and RoPE them
  5030. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5031. cb(cur, "wqkv", il);
  5032. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5033. 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)));
  5034. 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)));
  5035. cb(Qcur, "Qcur", il);
  5036. cb(Kcur, "Kcur", il);
  5037. cb(Vcur, "Vcur", il);
  5038. Qcur = ggml_rope_custom(
  5039. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5040. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5041. ext_factor, attn_factor, beta_fast, beta_slow
  5042. );
  5043. cb(Qcur, "Qcur", il);
  5044. Kcur = ggml_rope_custom(
  5045. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5046. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5047. ext_factor, attn_factor, beta_fast, beta_slow
  5048. );
  5049. cb(Kcur, "Kcur", il);
  5050. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5051. model.layers[il].wo, model.layers[il].bo,
  5052. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5053. cb(cur, "kqv_out", il);
  5054. }
  5055. // re-add the layer input
  5056. cur = ggml_add(ctx0, cur, inpL);
  5057. // attention layer norm
  5058. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5059. struct ggml_tensor * ffn_inp = cur;
  5060. cb(ffn_inp, "ffn_inp", il);
  5061. // feed-forward network
  5062. if (model.arch == LLM_ARCH_BERT) {
  5063. cur = llm_build_ffn(ctx0, cur,
  5064. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5065. NULL, NULL,
  5066. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5067. NULL,
  5068. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5069. } else {
  5070. cur = llm_build_ffn(ctx0, cur,
  5071. model.layers[il].ffn_up, NULL,
  5072. model.layers[il].ffn_gate, NULL,
  5073. model.layers[il].ffn_down, NULL,
  5074. NULL,
  5075. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5076. }
  5077. cb(cur, "ffn_out", il);
  5078. // attentions bypass the intermediate layer
  5079. cur = ggml_add(ctx0, cur, ffn_inp);
  5080. // output layer norm
  5081. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5082. // input for next layer
  5083. inpL = cur;
  5084. }
  5085. // final output
  5086. cur = inpL;
  5087. // pooling layer
  5088. if (pooling_type == LLAMA_POOLING_MEAN) {
  5089. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5090. } else if (pooling_type == LLAMA_POOLING_CLS) {
  5091. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5092. } else {
  5093. GGML_ASSERT(pooling_type == LLAMA_POOLING_NONE && "Invalid pooling type");
  5094. }
  5095. cb(cur, "result_embd", -1);
  5096. ggml_build_forward_expand(gf, cur);
  5097. return gf;
  5098. }
  5099. struct ggml_cgraph * build_bloom() {
  5100. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5101. const int64_t n_embd_head = hparams.n_embd_head_v;
  5102. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5103. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5104. struct ggml_tensor * cur;
  5105. struct ggml_tensor * inpL;
  5106. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5107. cb(inpL, "inp_embd", -1);
  5108. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5109. 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);
  5110. cb(KQ_mask, "KQ_mask", -1);
  5111. // positions of the tokens in the KV cache
  5112. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5113. cb(KQ_pos, "KQ_pos", -1);
  5114. inpL = llm_build_norm(ctx0, inpL, hparams,
  5115. model.tok_norm,
  5116. model.tok_norm_b,
  5117. LLM_NORM, cb, -1);
  5118. cb(inpL, "inp_norm", -1);
  5119. for (int il = 0; il < n_layer; ++il) {
  5120. cur = llm_build_norm(ctx0, inpL, hparams,
  5121. model.layers[il].attn_norm,
  5122. model.layers[il].attn_norm_b,
  5123. LLM_NORM, cb, il);
  5124. cb(cur, "attn_norm", il);
  5125. // self-attention
  5126. {
  5127. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5128. cb(cur, "wqkv", il);
  5129. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5130. cb(cur, "bqkv", il);
  5131. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5132. 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)));
  5133. 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)));
  5134. cb(Qcur, "Qcur", il);
  5135. cb(Kcur, "Kcur", il);
  5136. cb(Vcur, "Vcur", il);
  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, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5141. cb(cur, "kqv_out", il);
  5142. }
  5143. // Add the input
  5144. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5145. cb(ffn_inp, "ffn_inp", il);
  5146. // FF
  5147. {
  5148. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5149. model.layers[il].ffn_norm,
  5150. model.layers[il].ffn_norm_b,
  5151. LLM_NORM, cb, il);
  5152. cb(cur, "ffn_norm", il);
  5153. cur = llm_build_ffn(ctx0, cur,
  5154. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5155. NULL, NULL,
  5156. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5157. NULL,
  5158. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5159. cb(cur, "ffn_out", il);
  5160. }
  5161. inpL = ggml_add(ctx0, cur, ffn_inp);
  5162. cb(inpL, "l_out", il);
  5163. }
  5164. cur = llm_build_norm(ctx0, inpL, hparams,
  5165. model.output_norm,
  5166. model.output_norm_b,
  5167. LLM_NORM, cb, -1);
  5168. cb(cur, "result_norm", -1);
  5169. cur = ggml_mul_mat(ctx0, model.output, cur);
  5170. cb(cur, "result_output", -1);
  5171. ggml_build_forward_expand(gf, cur);
  5172. return gf;
  5173. }
  5174. struct ggml_cgraph * build_mpt() {
  5175. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5176. const int64_t n_embd_head = hparams.n_embd_head_v;
  5177. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5178. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5179. struct ggml_tensor * cur;
  5180. struct ggml_tensor * inpL;
  5181. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5182. cb(inpL, "inp_embd", -1);
  5183. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5184. 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);
  5185. cb(KQ_mask, "KQ_mask", -1);
  5186. // positions of the tokens in the KV cache
  5187. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5188. cb(KQ_pos, "KQ_pos", -1);
  5189. for (int il = 0; il < n_layer; ++il) {
  5190. struct ggml_tensor * attn_norm;
  5191. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5192. model.layers[il].attn_norm,
  5193. NULL,
  5194. LLM_NORM, cb, il);
  5195. cb(attn_norm, "attn_norm", il);
  5196. // self-attention
  5197. {
  5198. cur = attn_norm;
  5199. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5200. cb(cur, "wqkv", il);
  5201. if (hparams.f_clamp_kqv > 0.0f) {
  5202. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5203. cb(cur, "wqkv_clamped", il);
  5204. }
  5205. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5206. 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)));
  5207. 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)));
  5208. cb(Qcur, "Qcur", il);
  5209. cb(Kcur, "Kcur", il);
  5210. cb(Vcur, "Vcur", il);
  5211. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5212. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5213. model.layers[il].wo, NULL,
  5214. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5215. cb(cur, "kqv_out", il);
  5216. }
  5217. // Add the input
  5218. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5219. cb(ffn_inp, "ffn_inp", il);
  5220. // feed forward
  5221. {
  5222. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5223. model.layers[il].ffn_norm,
  5224. NULL,
  5225. LLM_NORM, cb, il);
  5226. cb(cur, "ffn_norm", il);
  5227. cur = llm_build_ffn(ctx0, cur,
  5228. model.layers[il].ffn_up, NULL,
  5229. NULL, NULL,
  5230. model.layers[il].ffn_down, NULL,
  5231. model.layers[il].ffn_act,
  5232. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5233. cb(cur, "ffn_out", il);
  5234. }
  5235. cur = ggml_add(ctx0, cur, ffn_inp);
  5236. cb(cur, "l_out", il);
  5237. // input for next layer
  5238. inpL = cur;
  5239. }
  5240. cur = inpL;
  5241. cur = llm_build_norm(ctx0, cur, hparams,
  5242. model.output_norm,
  5243. NULL,
  5244. LLM_NORM, cb, -1);
  5245. cb(cur, "result_norm", -1);
  5246. cur = ggml_mul_mat(ctx0, model.output, cur);
  5247. cb(cur, "result_output", -1);
  5248. ggml_build_forward_expand(gf, cur);
  5249. return gf;
  5250. }
  5251. struct ggml_cgraph * build_stablelm() {
  5252. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5253. const int64_t n_embd_head = hparams.n_embd_head_v;
  5254. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5255. struct ggml_tensor * cur;
  5256. struct ggml_tensor * inpL;
  5257. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5258. cb(inpL, "inp_embd", -1);
  5259. // inp_pos - contains the positions
  5260. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5261. cb(inp_pos, "inp_pos", -1);
  5262. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5263. 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);
  5264. cb(KQ_mask, "KQ_mask", -1);
  5265. // shift the entire K-cache if needed
  5266. if (do_rope_shift) {
  5267. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5268. }
  5269. for (int il = 0; il < n_layer; ++il) {
  5270. struct ggml_tensor * inpSA = inpL;
  5271. // norm
  5272. cur = llm_build_norm(ctx0, inpL, hparams,
  5273. model.layers[il].attn_norm,
  5274. model.layers[il].attn_norm_b,
  5275. LLM_NORM, cb, il);
  5276. cb(cur, "attn_norm", il);
  5277. // self-attention
  5278. {
  5279. // compute Q and K and RoPE them
  5280. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5281. cb(Qcur, "Qcur", il);
  5282. if (model.layers[il].bq) {
  5283. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5284. cb(Qcur, "Qcur", il);
  5285. }
  5286. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5287. cb(Kcur, "Kcur", il);
  5288. if (model.layers[il].bk) {
  5289. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5290. cb(Kcur, "Kcur", il);
  5291. }
  5292. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5293. cb(Vcur, "Vcur", il);
  5294. if (model.layers[il].bv) {
  5295. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5296. cb(Vcur, "Vcur", il);
  5297. }
  5298. Qcur = ggml_rope_custom(
  5299. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5300. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5301. ext_factor, attn_factor, beta_fast, beta_slow
  5302. );
  5303. cb(Qcur, "Qcur", il);
  5304. Kcur = ggml_rope_custom(
  5305. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5306. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5307. ext_factor, attn_factor, beta_fast, beta_slow
  5308. );
  5309. cb(Kcur, "Kcur", il);
  5310. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5311. model.layers[il].wo, NULL,
  5312. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5313. cb(cur, "kqv_out", il);
  5314. }
  5315. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5316. cb(ffn_inp, "ffn_inp", il);
  5317. // feed-forward network
  5318. {
  5319. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5320. model.layers[il].ffn_norm,
  5321. model.layers[il].ffn_norm_b,
  5322. LLM_NORM, cb, il);
  5323. cb(cur, "ffn_norm", il);
  5324. cur = llm_build_ffn(ctx0, cur,
  5325. model.layers[il].ffn_up, NULL,
  5326. model.layers[il].ffn_gate, NULL,
  5327. model.layers[il].ffn_down, NULL,
  5328. NULL,
  5329. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5330. cb(cur, "ffn_out", il);
  5331. }
  5332. cur = ggml_add(ctx0, cur, ffn_inp);
  5333. cb(cur, "l_out", il);
  5334. // input for next layer
  5335. inpL = cur;
  5336. }
  5337. cur = inpL;
  5338. cur = llm_build_norm(ctx0, cur, hparams,
  5339. model.output_norm,
  5340. model.output_norm_b,
  5341. LLM_NORM, cb, -1);
  5342. cb(cur, "result_norm", -1);
  5343. // lm_head
  5344. cur = ggml_mul_mat(ctx0, model.output, cur);
  5345. cb(cur, "result_output", -1);
  5346. ggml_build_forward_expand(gf, cur);
  5347. return gf;
  5348. }
  5349. struct ggml_cgraph * build_qwen() {
  5350. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5351. const int64_t n_embd_head = hparams.n_embd_head_v;
  5352. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5353. struct ggml_tensor * cur;
  5354. struct ggml_tensor * inpL;
  5355. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5356. cb(inpL, "inp_embd", -1);
  5357. // inp_pos - contains the positions
  5358. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5359. cb(inp_pos, "inp_pos", -1);
  5360. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5361. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5362. cb(KQ_mask, "KQ_mask", -1);
  5363. // shift the entire K-cache if needed
  5364. if (do_rope_shift) {
  5365. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5366. }
  5367. for (int il = 0; il < n_layer; ++il) {
  5368. struct ggml_tensor * inpSA = inpL;
  5369. cur = llm_build_norm(ctx0, inpL, hparams,
  5370. model.layers[il].attn_norm, NULL,
  5371. LLM_NORM_RMS, cb, il);
  5372. cb(cur, "attn_norm", il);
  5373. // self-attention
  5374. {
  5375. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5376. cb(cur, "wqkv", il);
  5377. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5378. cb(cur, "bqkv", il);
  5379. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5380. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5381. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5382. cb(Qcur, "Qcur", il);
  5383. cb(Kcur, "Kcur", il);
  5384. cb(Vcur, "Vcur", il);
  5385. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5386. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5387. // using mode = 2 for neox mode
  5388. Qcur = ggml_rope_custom(
  5389. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5390. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5391. );
  5392. cb(Qcur, "Qcur", il);
  5393. Kcur = ggml_rope_custom(
  5394. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5395. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5396. );
  5397. cb(Kcur, "Kcur", il);
  5398. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5399. model.layers[il].wo, NULL,
  5400. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5401. cb(cur, "kqv_out", il);
  5402. }
  5403. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5404. cb(ffn_inp, "ffn_inp", il);
  5405. // feed-forward forward
  5406. {
  5407. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5408. model.layers[il].ffn_norm, NULL,
  5409. LLM_NORM_RMS, cb, il);
  5410. cb(cur, "ffn_norm", il);
  5411. cur = llm_build_ffn(ctx0, cur,
  5412. model.layers[il].ffn_up, NULL,
  5413. model.layers[il].ffn_gate, NULL,
  5414. model.layers[il].ffn_down, NULL,
  5415. NULL,
  5416. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5417. cb(cur, "ffn_out", il);
  5418. }
  5419. cur = ggml_add(ctx0, cur, ffn_inp);
  5420. cb(cur, "l_out", il);
  5421. // input for next layer
  5422. inpL = cur;
  5423. }
  5424. cur = inpL;
  5425. cur = llm_build_norm(ctx0, cur, hparams,
  5426. model.output_norm, NULL,
  5427. LLM_NORM_RMS, cb, -1);
  5428. cb(cur, "result_norm", -1);
  5429. // lm_head
  5430. cur = ggml_mul_mat(ctx0, model.output, cur);
  5431. cb(cur, "result_output", -1);
  5432. ggml_build_forward_expand(gf, cur);
  5433. return gf;
  5434. }
  5435. struct ggml_cgraph * build_qwen2() {
  5436. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5437. const int64_t n_embd_head = hparams.n_embd_head_v;
  5438. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5439. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5440. struct ggml_tensor * cur;
  5441. struct ggml_tensor * inpL;
  5442. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5443. cb(inpL, "inp_embd", -1);
  5444. // inp_pos - contains the positions
  5445. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5446. cb(inp_pos, "inp_pos", -1);
  5447. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5448. 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);
  5449. cb(KQ_mask, "KQ_mask", -1);
  5450. // shift the entire K-cache if needed
  5451. if (do_rope_shift) {
  5452. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5453. }
  5454. for (int il = 0; il < n_layer; ++il) {
  5455. struct ggml_tensor * inpSA = inpL;
  5456. // norm
  5457. cur = llm_build_norm(ctx0, inpL, hparams,
  5458. model.layers[il].attn_norm, NULL,
  5459. LLM_NORM_RMS, cb, il);
  5460. cb(cur, "attn_norm", il);
  5461. // self-attention
  5462. {
  5463. // compute Q and K and RoPE them
  5464. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5465. cb(Qcur, "Qcur", il);
  5466. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5467. cb(Qcur, "Qcur", il);
  5468. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5469. cb(Kcur, "Kcur", il);
  5470. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5471. cb(Kcur, "Kcur", il);
  5472. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5473. cb(Vcur, "Vcur", il);
  5474. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5475. cb(Vcur, "Vcur", il);
  5476. // these nodes are added to the graph together so that they are not reordered
  5477. // by doing so, the number of splits in the graph is reduced
  5478. ggml_build_forward_expand(gf, Qcur);
  5479. ggml_build_forward_expand(gf, Kcur);
  5480. ggml_build_forward_expand(gf, Vcur);
  5481. Qcur = ggml_rope_custom(
  5482. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5483. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5484. ext_factor, attn_factor, beta_fast, beta_slow
  5485. );
  5486. cb(Qcur, "Qcur", il);
  5487. Kcur = ggml_rope_custom(
  5488. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5489. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5490. ext_factor, attn_factor, beta_fast, beta_slow
  5491. );
  5492. cb(Kcur, "Kcur", il);
  5493. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5494. model.layers[il].wo, model.layers[il].bo,
  5495. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5496. cb(cur, "kqv_out", il);
  5497. }
  5498. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5499. cb(ffn_inp, "ffn_inp", il);
  5500. // feed-forward network
  5501. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5502. model.layers[il].ffn_norm, NULL,
  5503. LLM_NORM_RMS, cb, il);
  5504. cb(cur, "ffn_norm", il);
  5505. cur = llm_build_ffn(ctx0, cur,
  5506. model.layers[il].ffn_up, NULL,
  5507. model.layers[il].ffn_gate, NULL,
  5508. model.layers[il].ffn_down, NULL,
  5509. NULL,
  5510. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5511. cb(cur, "ffn_out", il);
  5512. cur = ggml_add(ctx0, cur, ffn_inp);
  5513. cb(cur, "l_out", il);
  5514. // input for next layer
  5515. inpL = cur;
  5516. }
  5517. cur = inpL;
  5518. cur = llm_build_norm(ctx0, cur, hparams,
  5519. model.output_norm, NULL,
  5520. LLM_NORM_RMS, cb, -1);
  5521. cb(cur, "result_norm", -1);
  5522. // lm_head
  5523. cur = ggml_mul_mat(ctx0, model.output, cur);
  5524. cb(cur, "result_output", -1);
  5525. ggml_build_forward_expand(gf, cur);
  5526. return gf;
  5527. }
  5528. struct ggml_cgraph * build_phi2() {
  5529. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5530. const int64_t n_embd_head = hparams.n_embd_head_v;
  5531. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5532. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5533. struct ggml_tensor * cur;
  5534. struct ggml_tensor * attn_norm_output;
  5535. struct ggml_tensor * ffn_output;
  5536. struct ggml_tensor * inpL;
  5537. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5538. cb(inpL, "inp_embd", -1);
  5539. // inp_pos - contains the positions
  5540. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5541. cb(inp_pos, "inp_pos", -1);
  5542. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5543. 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);
  5544. cb(KQ_mask, "KQ_mask", -1);
  5545. // shift the entire K-cache if needed
  5546. if (do_rope_shift) {
  5547. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5548. }
  5549. for (int il = 0; il < n_layer; ++il) {
  5550. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5551. model.layers[il].attn_norm,
  5552. model.layers[il].attn_norm_b,
  5553. LLM_NORM, cb, il);
  5554. cb(attn_norm_output, "attn_norm", il);
  5555. // self-attention
  5556. {
  5557. struct ggml_tensor * Qcur = nullptr;
  5558. struct ggml_tensor * Kcur = nullptr;
  5559. struct ggml_tensor * Vcur = nullptr;
  5560. if (model.layers[il].wqkv) {
  5561. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5562. cb(cur, "wqkv", il);
  5563. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5564. cb(cur, "bqkv", il);
  5565. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5566. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5567. 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)));
  5568. } else {
  5569. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5570. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5571. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5572. }
  5573. cb(Qcur, "Qcur", il);
  5574. cb(Kcur, "Kcur", il);
  5575. cb(Vcur, "Vcur", il);
  5576. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5577. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5578. Qcur = ggml_rope_custom(
  5579. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5580. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5581. );
  5582. cb(Qcur, "Qcur", il);
  5583. // with phi2, we scale the Q to avoid precision issues
  5584. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5585. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5586. cb(Qcur, "Qcur", il);
  5587. Kcur = ggml_rope_custom(
  5588. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5589. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5590. );
  5591. cb(Kcur, "Kcur", il);
  5592. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5593. model.layers[il].wo, model.layers[il].bo,
  5594. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5595. cb(cur, "kqv_out", il);
  5596. }
  5597. // FF
  5598. {
  5599. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5600. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5601. NULL, NULL,
  5602. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5603. NULL,
  5604. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5605. cb(ffn_output, "ffn_out", il);
  5606. }
  5607. cur = ggml_add(ctx0, cur, ffn_output);
  5608. cb(cur, "l_out", il);
  5609. cur = ggml_add(ctx0, cur, inpL);
  5610. cb(cur, "l_out", il);
  5611. inpL = cur;
  5612. }
  5613. cur = llm_build_norm(ctx0, inpL, hparams,
  5614. model.output_norm,
  5615. model.output_norm_b,
  5616. LLM_NORM, cb, -1);
  5617. cb(cur, "result_norm", -1);
  5618. cur = ggml_mul_mat(ctx0, model.output, cur);
  5619. cb(cur, "result_output_no_bias", -1);
  5620. cur = ggml_add(ctx0, cur, model.output_b);
  5621. cb(cur, "result_output", -1);
  5622. ggml_build_forward_expand(gf, cur);
  5623. return gf;
  5624. }
  5625. struct ggml_cgraph * build_plamo() {
  5626. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5627. const int64_t n_embd_head = hparams.n_embd_head_v;
  5628. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5629. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5630. struct ggml_tensor * cur;
  5631. struct ggml_tensor * inpL;
  5632. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5633. cb(inpL, "inp_embd", -1);
  5634. // inp_pos - contains the positions
  5635. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5636. cb(inp_pos, "inp_pos", -1);
  5637. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5638. 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);
  5639. cb(KQ_mask, "KQ_mask", -1);
  5640. // shift the entire K-cache if needed
  5641. if (do_rope_shift) {
  5642. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5643. }
  5644. for (int il = 0; il < n_layer; ++il) {
  5645. // norm
  5646. cur = llm_build_norm(ctx0, inpL, hparams,
  5647. model.layers[il].attn_norm, NULL,
  5648. LLM_NORM_RMS, cb, il);
  5649. cb(cur, "attn_norm", il);
  5650. struct ggml_tensor * attention_norm = cur;
  5651. // self-attention
  5652. {
  5653. // compute Q and K and RoPE them
  5654. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5655. cb(Qcur, "Qcur", il);
  5656. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5657. cb(Kcur, "Kcur", il);
  5658. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5659. cb(Vcur, "Vcur", il);
  5660. Qcur = ggml_rope_custom(
  5661. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5662. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5663. ext_factor, attn_factor, beta_fast, beta_slow);
  5664. cb(Qcur, "Qcur", il);
  5665. Kcur = ggml_rope_custom(
  5666. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5667. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5668. ext_factor, attn_factor, beta_fast, beta_slow);
  5669. cb(Kcur, "Kcur", il);
  5670. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5671. model.layers[il].wo, NULL,
  5672. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5673. cb(cur, "kqv_out", il);
  5674. }
  5675. struct ggml_tensor * sa_out = cur;
  5676. cur = attention_norm;
  5677. // feed-forward network
  5678. {
  5679. cur = llm_build_ffn(ctx0, cur,
  5680. model.layers[il].ffn_up, NULL,
  5681. model.layers[il].ffn_gate, NULL,
  5682. model.layers[il].ffn_down, NULL,
  5683. NULL,
  5684. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5685. cb(cur, "ffn_out", il);
  5686. }
  5687. cur = ggml_add(ctx0, cur, sa_out);
  5688. cb(cur, "l_out", il);
  5689. cur = ggml_add(ctx0, cur, inpL);
  5690. cb(cur, "l_out", il);
  5691. // input for next layer
  5692. inpL = cur;
  5693. }
  5694. cur = inpL;
  5695. cur = llm_build_norm(ctx0, cur, hparams,
  5696. model.output_norm, NULL,
  5697. LLM_NORM_RMS, cb, -1);
  5698. cb(cur, "result_norm", -1);
  5699. // lm_head
  5700. cur = ggml_mul_mat(ctx0, model.output, cur);
  5701. cb(cur, "result_output", -1);
  5702. ggml_build_forward_expand(gf, cur);
  5703. return gf;
  5704. }
  5705. struct ggml_cgraph * build_gpt2() {
  5706. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5707. const int64_t n_embd_head = hparams.n_embd_head_v;
  5708. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5709. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5710. struct ggml_tensor * cur;
  5711. struct ggml_tensor * pos;
  5712. struct ggml_tensor * inpL;
  5713. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5714. cb(inpL, "inp_embd", -1);
  5715. // inp_pos - contains the positions
  5716. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5717. cb(inp_pos, "inp_pos", -1);
  5718. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5719. 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);
  5720. cb(KQ_mask, "KQ_mask", -1);
  5721. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5722. cb(pos, "pos_embd", -1);
  5723. inpL = ggml_add(ctx0, inpL, pos);
  5724. cb(inpL, "inpL", -1);
  5725. for (int il = 0; il < n_layer; ++il) {
  5726. cur = llm_build_norm(ctx0, inpL, hparams,
  5727. model.layers[il].attn_norm,
  5728. model.layers[il].attn_norm_b,
  5729. LLM_NORM, cb, il);
  5730. cb(cur, "attn_norm", il);
  5731. // self-attention
  5732. {
  5733. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5734. cb(cur, "wqkv", il);
  5735. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5736. cb(cur, "bqkv", il);
  5737. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5738. 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)));
  5739. 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)));
  5740. cb(Qcur, "Qcur", il);
  5741. cb(Kcur, "Kcur", il);
  5742. cb(Vcur, "Vcur", il);
  5743. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5744. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5745. model.layers[il].wo, model.layers[il].bo,
  5746. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5747. cb(cur, "kqv_out", il);
  5748. }
  5749. // add the input
  5750. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5751. cb(ffn_inp, "ffn_inp", il);
  5752. // FF
  5753. {
  5754. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5755. model.layers[il].ffn_norm,
  5756. model.layers[il].ffn_norm_b,
  5757. LLM_NORM, cb, il);
  5758. cb(cur, "ffn_norm", il);
  5759. cur = llm_build_ffn(ctx0, cur,
  5760. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5761. NULL, NULL,
  5762. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5763. NULL,
  5764. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5765. cb(cur, "ffn_out", il);
  5766. }
  5767. inpL = ggml_add(ctx0, cur, ffn_inp);
  5768. cb(inpL, "l_out", il);
  5769. }
  5770. cur = llm_build_norm(ctx0, inpL, hparams,
  5771. model.output_norm,
  5772. model.output_norm_b,
  5773. LLM_NORM, cb, -1);
  5774. cb(cur, "result_norm", -1);
  5775. cur = ggml_mul_mat(ctx0, model.output, cur);
  5776. cb(cur, "result_output", -1);
  5777. ggml_build_forward_expand(gf, cur);
  5778. return gf;
  5779. }
  5780. struct ggml_cgraph * build_codeshell() {
  5781. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5782. const int64_t n_embd_head = hparams.n_embd_head_v;
  5783. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5784. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5785. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5786. struct ggml_tensor * cur;
  5787. struct ggml_tensor * inpL;
  5788. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5789. cb(inpL, "inp_embd", -1);
  5790. // inp_pos - contains the positions
  5791. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5792. cb(inp_pos, "inp_pos", -1);
  5793. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5794. 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);
  5795. cb(KQ_mask, "KQ_mask", -1);
  5796. // shift the entire K-cache if needed
  5797. if (do_rope_shift) {
  5798. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5799. }
  5800. for (int il = 0; il < n_layer; ++il) {
  5801. cur = llm_build_norm(ctx0, inpL, hparams,
  5802. model.layers[il].attn_norm,
  5803. model.layers[il].attn_norm_b,
  5804. LLM_NORM, cb, il);
  5805. cb(cur, "attn_norm", il);
  5806. // self-attention
  5807. {
  5808. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5809. cb(cur, "wqkv", il);
  5810. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5811. cb(cur, "bqkv", il);
  5812. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5813. 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)));
  5814. 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)));
  5815. cb(tmpq, "tmpq", il);
  5816. cb(tmpk, "tmpk", il);
  5817. cb(Vcur, "Vcur", il);
  5818. struct ggml_tensor * Qcur = ggml_rope_custom(
  5819. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5820. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5821. ext_factor, attn_factor, beta_fast, beta_slow
  5822. );
  5823. cb(Qcur, "Qcur", il);
  5824. struct ggml_tensor * Kcur = ggml_rope_custom(
  5825. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5826. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5827. ext_factor, attn_factor, beta_fast, beta_slow
  5828. );
  5829. cb(Kcur, "Kcur", il);
  5830. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5831. model.layers[il].wo, model.layers[il].bo,
  5832. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5833. cb(cur, "kqv_out", il);
  5834. }
  5835. // add the input
  5836. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5837. cb(ffn_inp, "ffn_inp", il);
  5838. // FF
  5839. {
  5840. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5841. model.layers[il].ffn_norm,
  5842. model.layers[il].ffn_norm_b,
  5843. LLM_NORM, cb, il);
  5844. cb(cur, "ffn_norm", il);
  5845. cur = llm_build_ffn(ctx0, cur,
  5846. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5847. NULL, NULL,
  5848. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5849. NULL,
  5850. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5851. cb(cur, "ffn_out", il);
  5852. }
  5853. inpL = ggml_add(ctx0, cur, ffn_inp);
  5854. cb(inpL, "l_out", il);
  5855. }
  5856. cur = llm_build_norm(ctx0, inpL, hparams,
  5857. model.output_norm,
  5858. model.output_norm_b,
  5859. LLM_NORM, cb, -1);
  5860. cb(cur, "result_norm", -1);
  5861. cur = ggml_mul_mat(ctx0, model.output, cur);
  5862. cb(cur, "result_output", -1);
  5863. ggml_build_forward_expand(gf, cur);
  5864. return gf;
  5865. }
  5866. struct ggml_cgraph * build_orion() {
  5867. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5868. const int64_t n_embd_head = hparams.n_embd_head_v;
  5869. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5870. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5871. struct ggml_tensor * cur;
  5872. struct ggml_tensor * inpL;
  5873. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5874. cb(inpL, "inp_embd", -1);
  5875. // inp_pos - contains the positions
  5876. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5877. cb(inp_pos, "inp_pos", -1);
  5878. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5879. 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);
  5880. cb(KQ_mask, "KQ_mask", -1);
  5881. // shift the entire K-cache if needed
  5882. if (do_rope_shift) {
  5883. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5884. }
  5885. for (int il = 0; il < n_layer; ++il) {
  5886. struct ggml_tensor * inpSA = inpL;
  5887. // norm
  5888. cur = llm_build_norm(ctx0, inpL, hparams,
  5889. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  5890. LLM_NORM, cb, il);
  5891. cb(cur, "attn_norm", il);
  5892. // self-attention
  5893. {
  5894. // compute Q and K and RoPE them
  5895. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5896. cb(Qcur, "Qcur", il);
  5897. // if (model.layers[il].bq) {
  5898. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5899. // cb(Qcur, "Qcur", il);
  5900. // }
  5901. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5902. cb(Kcur, "Kcur", il);
  5903. // if (model.layers[il].bk) {
  5904. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5905. // cb(Kcur, "Kcur", il);
  5906. // }
  5907. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5908. cb(Vcur, "Vcur", il);
  5909. // if (model.layers[il].bv) {
  5910. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5911. // cb(Vcur, "Vcur", il);
  5912. // }
  5913. Qcur = ggml_rope_custom(
  5914. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5915. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5916. ext_factor, attn_factor, beta_fast, beta_slow
  5917. );
  5918. cb(Qcur, "Qcur", il);
  5919. Kcur = ggml_rope_custom(
  5920. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5921. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5922. ext_factor, attn_factor, beta_fast, beta_slow
  5923. );
  5924. cb(Kcur, "Kcur", il);
  5925. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5926. model.layers[il].wo, NULL,
  5927. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5928. cb(cur, "kqv_out", il);
  5929. }
  5930. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5931. cb(ffn_inp, "ffn_inp", il);
  5932. // feed-forward network
  5933. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5934. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  5935. LLM_NORM, cb, il);
  5936. cb(cur, "ffn_norm", il);
  5937. cur = llm_build_ffn(ctx0, cur,
  5938. model.layers[il].ffn_up, NULL,
  5939. model.layers[il].ffn_gate, NULL,
  5940. model.layers[il].ffn_down, NULL,
  5941. NULL,
  5942. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5943. cb(cur, "ffn_out", il);
  5944. cur = ggml_add(ctx0, cur, ffn_inp);
  5945. cb(cur, "l_out", il);
  5946. // input for next layer
  5947. inpL = cur;
  5948. }
  5949. cur = inpL;
  5950. cur = llm_build_norm(ctx0, cur, hparams,
  5951. model.output_norm, model.output_norm_b,
  5952. LLM_NORM, cb, -1);
  5953. cb(cur, "result_norm", -1);
  5954. // lm_head
  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_internlm2() {
  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. // shift the entire K-cache if needed
  5976. if (do_rope_shift) {
  5977. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5978. }
  5979. for (int il = 0; il < n_layer; ++il) {
  5980. struct ggml_tensor * inpSA = inpL;
  5981. // norm
  5982. cur = llm_build_norm(ctx0, inpL, hparams,
  5983. model.layers[il].attn_norm, NULL,
  5984. LLM_NORM_RMS, cb, il);
  5985. cb(cur, "attn_norm", il);
  5986. // self-attention
  5987. {
  5988. // compute Q and K and RoPE them
  5989. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5990. cb(Qcur, "Qcur", il);
  5991. if (model.layers[il].bq) {
  5992. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5993. cb(Qcur, "Qcur", il);
  5994. }
  5995. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5996. cb(Kcur, "Kcur", il);
  5997. if (model.layers[il].bk) {
  5998. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5999. cb(Kcur, "Kcur", il);
  6000. }
  6001. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6002. cb(Vcur, "Vcur", il);
  6003. if (model.layers[il].bv) {
  6004. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6005. cb(Vcur, "Vcur", il);
  6006. }
  6007. Qcur = ggml_rope_custom(
  6008. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6009. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6010. ext_factor, attn_factor, beta_fast, beta_slow
  6011. );
  6012. cb(Qcur, "Qcur", il);
  6013. Kcur = ggml_rope_custom(
  6014. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6015. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6016. ext_factor, attn_factor, beta_fast, beta_slow
  6017. );
  6018. cb(Kcur, "Kcur", il);
  6019. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6020. model.layers[il].wo, model.layers[il].bo,
  6021. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6022. cb(cur, "kqv_out", il);
  6023. }
  6024. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6025. cb(ffn_inp, "ffn_inp", il);
  6026. // feed-forward network
  6027. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6028. model.layers[il].ffn_norm, NULL,
  6029. LLM_NORM_RMS, cb, il);
  6030. cb(cur, "ffn_norm", il);
  6031. cur = llm_build_ffn(ctx0, cur,
  6032. model.layers[il].ffn_up, NULL,
  6033. model.layers[il].ffn_gate, NULL,
  6034. model.layers[il].ffn_down, NULL,
  6035. NULL,
  6036. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6037. cb(cur, "ffn_out", il);
  6038. cur = ggml_add(ctx0, cur, ffn_inp);
  6039. cb(cur, "l_out", il);
  6040. // input for next layer
  6041. inpL = cur;
  6042. }
  6043. cur = inpL;
  6044. cur = llm_build_norm(ctx0, cur, hparams,
  6045. model.output_norm, NULL,
  6046. LLM_NORM_RMS, cb, -1);
  6047. cb(cur, "result_norm", -1);
  6048. // lm_head
  6049. cur = ggml_mul_mat(ctx0, model.output, cur);
  6050. cb(cur, "result_output", -1);
  6051. ggml_build_forward_expand(gf, cur);
  6052. return gf;
  6053. }
  6054. // ref: https://arxiv.org/abs/2203.03466
  6055. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6056. // based on the original build_llama() function
  6057. struct ggml_cgraph * build_minicpm() {
  6058. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6059. const int64_t n_embd_head = hparams.n_embd_head_v;
  6060. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6061. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6062. const int64_t n_embd = hparams.n_embd;
  6063. //TODO: if the model varies, these parameters need to be read from the model
  6064. const int64_t n_embd_base = 256;
  6065. const float scale_embd = 12.0f;
  6066. const float scale_depth = 1.4f;
  6067. struct ggml_tensor * cur;
  6068. struct ggml_tensor * inpL;
  6069. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6070. cb(inpL, "inp_embd", -1);
  6071. // scale the input embeddings
  6072. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6073. cb(inpL, "inp_scaled", -1);
  6074. // inp_pos - contains the positions
  6075. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6076. cb(inp_pos, "inp_pos", -1);
  6077. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6078. 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);
  6079. cb(KQ_mask, "KQ_mask", -1);
  6080. // shift the entire K-cache if needed
  6081. if (do_rope_shift) {
  6082. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  6083. }
  6084. for (int il = 0; il < n_layer; ++il) {
  6085. struct ggml_tensor * inpSA = inpL;
  6086. // norm
  6087. cur = llm_build_norm(ctx0, inpL, hparams,
  6088. model.layers[il].attn_norm, NULL,
  6089. LLM_NORM_RMS, cb, il);
  6090. cb(cur, "attn_norm", il);
  6091. // self-attention
  6092. {
  6093. // compute Q and K and RoPE them
  6094. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6095. cb(Qcur, "Qcur", il);
  6096. if (model.layers[il].bq) {
  6097. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6098. cb(Qcur, "Qcur", il);
  6099. }
  6100. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6101. cb(Kcur, "Kcur", il);
  6102. if (model.layers[il].bk) {
  6103. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6104. cb(Kcur, "Kcur", il);
  6105. }
  6106. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6107. cb(Vcur, "Vcur", il);
  6108. if (model.layers[il].bv) {
  6109. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6110. cb(Vcur, "Vcur", il);
  6111. }
  6112. Qcur = ggml_rope_custom(
  6113. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6114. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6115. ext_factor, attn_factor, beta_fast, beta_slow
  6116. );
  6117. cb(Qcur, "Qcur", il);
  6118. Kcur = ggml_rope_custom(
  6119. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6120. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6121. ext_factor, attn_factor, beta_fast, beta_slow
  6122. );
  6123. cb(Kcur, "Kcur", il);
  6124. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6125. model.layers[il].wo, model.layers[il].bo,
  6126. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6127. cb(cur, "kqv_out", il);
  6128. }
  6129. // scale_res - scale the hidden states for residual connection
  6130. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6131. cur = ggml_scale(ctx0, cur, scale_res);
  6132. cb(cur, "hidden_scaled", -1);
  6133. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6134. cb(ffn_inp, "ffn_inp", il);
  6135. // feed-forward network
  6136. {
  6137. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6138. model.layers[il].ffn_norm, NULL,
  6139. LLM_NORM_RMS, cb, il);
  6140. cb(cur, "ffn_norm", il);
  6141. cur = llm_build_ffn(ctx0, cur,
  6142. model.layers[il].ffn_up, NULL,
  6143. model.layers[il].ffn_gate, NULL,
  6144. model.layers[il].ffn_down, NULL,
  6145. NULL,
  6146. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6147. cb(cur, "ffn_out", il);
  6148. }
  6149. // scale the hidden states for residual connection
  6150. cur = ggml_scale(ctx0, cur, scale_res);
  6151. cb(cur, "hidden_scaled_ffn", -1);
  6152. cur = ggml_add(ctx0, cur, ffn_inp);
  6153. cb(cur, "l_out", il);
  6154. // input for next layer
  6155. inpL = cur;
  6156. }
  6157. cur = inpL;
  6158. cur = llm_build_norm(ctx0, cur, hparams,
  6159. model.output_norm, NULL,
  6160. LLM_NORM_RMS, cb, -1);
  6161. cb(cur, "result_norm", -1);
  6162. // lm_head scaling
  6163. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6164. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6165. cb(cur, "lmhead_scaling", -1);
  6166. // lm_head
  6167. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6168. cb(cur, "result_output", -1);
  6169. ggml_build_forward_expand(gf, cur);
  6170. return gf;
  6171. }
  6172. struct ggml_cgraph * build_gemma() {
  6173. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6174. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6175. struct ggml_tensor * cur;
  6176. struct ggml_tensor * inpL;
  6177. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6178. cb(inpL, "inp_embd", -1);
  6179. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6180. cb(inpL, "inp_scaled", -1);
  6181. // inp_pos - contains the positions
  6182. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6183. cb(inp_pos, "inp_pos", -1);
  6184. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6185. 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);
  6186. cb(KQ_mask, "KQ_mask", -1);
  6187. // shift the entire K-cache if needed
  6188. if (do_rope_shift) {
  6189. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  6190. }
  6191. for (int il = 0; il < n_layer; ++il) {
  6192. // norm
  6193. cur = llm_build_norm(ctx0, inpL, hparams,
  6194. model.layers[il].attn_norm, NULL,
  6195. LLM_NORM_RMS, cb, il);
  6196. cb(cur, "attn_norm", il);
  6197. // self-attention
  6198. {
  6199. // compute Q and K and RoPE them
  6200. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6201. cb(Qcur, "Qcur", il);
  6202. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6203. cb(Kcur, "Kcur", il);
  6204. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6205. cb(Vcur, "Vcur", il);
  6206. Qcur = ggml_rope_custom(
  6207. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6208. n_embd_head_k, 2, 0, n_orig_ctx, freq_base, freq_scale,
  6209. ext_factor, attn_factor, beta_fast, beta_slow);
  6210. cb(Qcur, "Qcur", il);
  6211. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6212. cb(Qcur, "Qcur_scaled", il);
  6213. Kcur = ggml_rope_custom(
  6214. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6215. n_embd_head_k, 2, 0, n_orig_ctx, freq_base, freq_scale,
  6216. ext_factor, attn_factor, beta_fast, beta_slow);
  6217. cb(Kcur, "Kcur", il);
  6218. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6219. model.layers[il].wo, NULL,
  6220. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6221. cb(cur, "kqv_out", il);
  6222. }
  6223. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6224. cb(sa_out, "sa_out", il);
  6225. cur = llm_build_norm(ctx0, sa_out, hparams,
  6226. model.layers[il].ffn_norm, NULL,
  6227. LLM_NORM_RMS, cb, il);
  6228. cb(cur, "ffn_norm", il);
  6229. // feed-forward network
  6230. {
  6231. cur = llm_build_ffn(ctx0, cur,
  6232. model.layers[il].ffn_up, NULL,
  6233. model.layers[il].ffn_gate, NULL,
  6234. model.layers[il].ffn_down, NULL,
  6235. NULL,
  6236. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6237. cb(cur, "ffn_out", il);
  6238. }
  6239. cur = ggml_add(ctx0, cur, sa_out);
  6240. cb(cur, "l_out", il);
  6241. // input for next layer
  6242. inpL = cur;
  6243. }
  6244. cur = inpL;
  6245. cur = llm_build_norm(ctx0, cur, hparams,
  6246. model.output_norm, NULL,
  6247. LLM_NORM_RMS, cb, -1);
  6248. cb(cur, "result_norm", -1);
  6249. // lm_head
  6250. cur = ggml_mul_mat(ctx0, model.output, cur);
  6251. cb(cur, "result_output", -1);
  6252. ggml_build_forward_expand(gf, cur);
  6253. return gf;
  6254. }
  6255. };
  6256. static struct ggml_cgraph * llama_build_graph(
  6257. llama_context & lctx,
  6258. const llama_batch & batch,
  6259. bool worst_case) {
  6260. const auto & model = lctx.model;
  6261. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6262. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6263. if (il >= 0) {
  6264. ggml_format_name(cur, "%s-%d", name, il);
  6265. } else {
  6266. ggml_set_name(cur, name);
  6267. }
  6268. if (!lctx.cparams.offload_kqv) {
  6269. if (strcmp(name, "kqv_merged_cont") == 0) {
  6270. // all nodes between the KV store and the attention output are run on the CPU
  6271. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  6272. }
  6273. }
  6274. };
  6275. struct ggml_cgraph * result = NULL;
  6276. struct llm_build_context llm(lctx, batch, cb, worst_case);
  6277. llm.init();
  6278. switch (model.arch) {
  6279. case LLM_ARCH_LLAMA:
  6280. {
  6281. result = llm.build_llama();
  6282. } break;
  6283. case LLM_ARCH_BAICHUAN:
  6284. {
  6285. result = llm.build_baichuan();
  6286. } break;
  6287. case LLM_ARCH_FALCON:
  6288. {
  6289. result = llm.build_falcon();
  6290. } break;
  6291. case LLM_ARCH_STARCODER:
  6292. {
  6293. result = llm.build_starcoder();
  6294. } break;
  6295. case LLM_ARCH_PERSIMMON:
  6296. {
  6297. result = llm.build_persimmon();
  6298. } break;
  6299. case LLM_ARCH_REFACT:
  6300. {
  6301. result = llm.build_refact();
  6302. } break;
  6303. case LLM_ARCH_BERT:
  6304. case LLM_ARCH_NOMIC_BERT:
  6305. {
  6306. result = llm.build_bert();
  6307. } break;
  6308. case LLM_ARCH_BLOOM:
  6309. {
  6310. result = llm.build_bloom();
  6311. } break;
  6312. case LLM_ARCH_MPT:
  6313. {
  6314. result = llm.build_mpt();
  6315. } break;
  6316. case LLM_ARCH_STABLELM:
  6317. {
  6318. result = llm.build_stablelm();
  6319. } break;
  6320. case LLM_ARCH_QWEN:
  6321. {
  6322. result = llm.build_qwen();
  6323. } break;
  6324. case LLM_ARCH_QWEN2:
  6325. {
  6326. result = llm.build_qwen2();
  6327. } break;
  6328. case LLM_ARCH_PHI2:
  6329. {
  6330. result = llm.build_phi2();
  6331. } break;
  6332. case LLM_ARCH_PLAMO:
  6333. {
  6334. result = llm.build_plamo();
  6335. } break;
  6336. case LLM_ARCH_GPT2:
  6337. {
  6338. result = llm.build_gpt2();
  6339. } break;
  6340. case LLM_ARCH_CODESHELL:
  6341. {
  6342. result = llm.build_codeshell();
  6343. } break;
  6344. case LLM_ARCH_ORION:
  6345. {
  6346. result = llm.build_orion();
  6347. } break;
  6348. case LLM_ARCH_INTERNLM2:
  6349. {
  6350. result = llm.build_internlm2();
  6351. } break;
  6352. case LLM_ARCH_MINICPM:
  6353. {
  6354. result = llm.build_minicpm();
  6355. } break;
  6356. case LLM_ARCH_GEMMA:
  6357. {
  6358. result = llm.build_gemma();
  6359. } break;
  6360. default:
  6361. GGML_ASSERT(false);
  6362. }
  6363. llm.free();
  6364. return result;
  6365. }
  6366. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  6367. //
  6368. // set input data
  6369. //
  6370. const auto & hparams = lctx.model.hparams;
  6371. const auto & cparams = lctx.cparams;
  6372. const auto & kv_self = lctx.kv_self;
  6373. if (batch.token) {
  6374. const int64_t n_tokens = batch.n_tokens;
  6375. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  6376. }
  6377. if (batch.embd) {
  6378. const int64_t n_embd = hparams.n_embd;
  6379. const int64_t n_tokens = batch.n_tokens;
  6380. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  6381. }
  6382. if (batch.pos) {
  6383. const int64_t n_tokens = batch.n_tokens;
  6384. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  6385. }
  6386. {
  6387. const int64_t n_kv = kv_self.n;
  6388. const int64_t n_tokens = batch.n_tokens;
  6389. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6390. float * data = (float *) lctx.inp_KQ_mask->data;
  6391. for (int h = 0; h < 1; ++h) {
  6392. for (int j = 0; j < n_tokens; ++j) {
  6393. const llama_pos pos = batch.pos[j];
  6394. const llama_seq_id seq_id = batch.seq_id[j][0];
  6395. for (int i = 0; i < n_kv; ++i) {
  6396. float f;
  6397. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) ||
  6398. (hparams.causal_attn && lctx.kv_self.cells[i].pos > pos)) {
  6399. f = -INFINITY;
  6400. } else {
  6401. f = 0;
  6402. }
  6403. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  6404. }
  6405. }
  6406. }
  6407. }
  6408. if (hparams.need_kq_pos) {
  6409. const int64_t n_kv = kv_self.n;
  6410. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  6411. float * data = (float *) lctx.inp_KQ_pos->data;
  6412. for (int i = 0; i < n_kv; ++i) {
  6413. data[i] = float(lctx.kv_self.cells[i].pos);
  6414. }
  6415. }
  6416. if (kv_self.has_shift) {
  6417. const int64_t n_ctx = cparams.n_ctx;
  6418. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  6419. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  6420. for (int i = 0; i < n_ctx; ++i) {
  6421. data[i] = lctx.kv_self.cells[i].delta;
  6422. }
  6423. }
  6424. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_MEAN) {
  6425. const int64_t n_tokens = batch.n_tokens;
  6426. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  6427. float * data = (float *) lctx.inp_mean->data;
  6428. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  6429. std::vector<uint64_t> sum(n_tokens, 0);
  6430. for (int i = 0; i < n_tokens; ++i) {
  6431. const llama_seq_id seq_id = batch.seq_id[i][0];
  6432. sum[seq_id] += 1;
  6433. }
  6434. std::vector<float> div(n_tokens, 0.0f);
  6435. for (int i = 0; i < n_tokens; ++i) {
  6436. const uint64_t s = sum[i];
  6437. if (s > 0) {
  6438. div[i] = 1.0f/float(s);
  6439. }
  6440. }
  6441. for (int i = 0; i < n_tokens; ++i) {
  6442. const llama_seq_id seq_id = batch.seq_id[i][0];
  6443. data[seq_id*n_tokens + i] = div[seq_id];
  6444. }
  6445. }
  6446. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_CLS) {
  6447. const int64_t n_tokens = batch.n_tokens;
  6448. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  6449. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  6450. for (int i = 0; i < n_tokens; ++i) {
  6451. const llama_seq_id seq_id = batch.seq_id[i][0];
  6452. const llama_pos pos = batch.pos[i];
  6453. if (pos == 0) {
  6454. data[seq_id] = i;
  6455. }
  6456. }
  6457. }
  6458. }
  6459. // decode a batch of tokens by evaluating the transformer
  6460. //
  6461. // - lctx: llama context
  6462. // - batch: batch to evaluate
  6463. //
  6464. // return 0 on success
  6465. // return positive int on warning
  6466. // return negative int on error
  6467. //
  6468. static int llama_decode_internal(
  6469. llama_context & lctx,
  6470. llama_batch batch) {
  6471. const uint32_t n_tokens = batch.n_tokens;
  6472. if (n_tokens == 0) {
  6473. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  6474. return -1;
  6475. }
  6476. const auto & model = lctx.model;
  6477. const auto & hparams = model.hparams;
  6478. const auto & cparams = lctx.cparams;
  6479. const auto n_batch = cparams.n_batch;
  6480. GGML_ASSERT(n_tokens <= n_batch);
  6481. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6482. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6483. const int64_t t_start_us = ggml_time_us();
  6484. #ifdef GGML_USE_MPI
  6485. // TODO: needs fix after #3228
  6486. GGML_ASSERT(false && "not implemented");
  6487. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  6488. #endif
  6489. GGML_ASSERT(n_threads > 0);
  6490. auto & kv_self = lctx.kv_self;
  6491. const int64_t n_embd = hparams.n_embd;
  6492. const int64_t n_vocab = hparams.n_vocab;
  6493. // helpers for smoother batch API transition
  6494. // after deprecating the llama_eval calls, these will be removed
  6495. std::vector<llama_pos> pos;
  6496. std::vector<int32_t> n_seq_id;
  6497. std::vector<llama_seq_id *> seq_id_arr;
  6498. std::vector<std::vector<llama_seq_id>> seq_id;
  6499. if (batch.pos == nullptr) {
  6500. pos.resize(n_tokens);
  6501. for (uint32_t i = 0; i < n_tokens; i++) {
  6502. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  6503. }
  6504. batch.pos = pos.data();
  6505. }
  6506. if (batch.seq_id == nullptr) {
  6507. n_seq_id.resize(n_tokens);
  6508. seq_id.resize(n_tokens);
  6509. seq_id_arr.resize(n_tokens);
  6510. for (uint32_t i = 0; i < n_tokens; i++) {
  6511. n_seq_id[i] = 1;
  6512. seq_id[i].resize(1);
  6513. seq_id[i][0] = batch.all_seq_id;
  6514. seq_id_arr[i] = seq_id[i].data();
  6515. }
  6516. batch.n_seq_id = n_seq_id.data();
  6517. batch.seq_id = seq_id_arr.data();
  6518. }
  6519. // if we have enough unused cells before the current head ->
  6520. // better to start searching from the beginning of the cache, hoping to fill it
  6521. if (kv_self.head > kv_self.used + 2*n_tokens) {
  6522. kv_self.head = 0;
  6523. }
  6524. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  6525. return 1;
  6526. }
  6527. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6528. // after enough generations, the benefit from this heuristic disappears
  6529. // if we start defragmenting the cache, the benefit from this will be more important
  6530. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  6531. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6532. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6533. ggml_backend_sched_reset(lctx.sched);
  6534. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6535. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  6536. // the output is always the last tensor in the graph
  6537. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  6538. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  6539. if (strcmp(res->name, "result_output") == 0) {
  6540. // the embeddings could be the second to last tensor, or the third to last tensor
  6541. if (strcmp(embeddings->name, "result_norm") != 0) {
  6542. embeddings = gf->nodes[gf->n_nodes - 3];
  6543. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  6544. }
  6545. } else if (strcmp(res->name, "result_embd") == 0) {
  6546. embeddings = res;
  6547. res = nullptr;
  6548. } else {
  6549. GGML_ASSERT(false);
  6550. }
  6551. // 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);
  6552. // for big prompts, if BLAS is enabled, it is better to use only one thread
  6553. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  6554. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  6555. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  6556. // with the BLAS calls. need a better solution
  6557. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  6558. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  6559. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  6560. n_threads = std::min(4, n_threads);
  6561. }
  6562. #ifdef GGML_USE_MPI
  6563. const int64_t n_layer = hparams.n_layer;
  6564. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  6565. #endif
  6566. #ifdef GGML_USE_METAL
  6567. if (ggml_backend_is_metal(lctx.backend_metal)) {
  6568. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  6569. }
  6570. #endif
  6571. if (lctx.backend_cpu != nullptr) {
  6572. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  6573. }
  6574. llama_set_inputs(lctx, batch);
  6575. ggml_backend_sched_graph_compute(lctx.sched, gf);
  6576. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6577. #ifdef GGML_USE_MPI
  6578. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  6579. #endif
  6580. // update the kv ring buffer
  6581. {
  6582. if (kv_self.has_shift) {
  6583. kv_self.has_shift = false;
  6584. for (uint32_t i = 0; i < kv_self.size; ++i) {
  6585. kv_self.cells[i].delta = 0;
  6586. }
  6587. }
  6588. kv_self.head += n_tokens;
  6589. // Ensure kv cache head points to a valid index.
  6590. if (kv_self.head >= kv_self.size) {
  6591. kv_self.head = 0;
  6592. }
  6593. }
  6594. #ifdef GGML_PERF
  6595. // print timing information per ggml operation (for debugging purposes)
  6596. // requires GGML_PERF to be defined
  6597. ggml_graph_print(gf);
  6598. #endif
  6599. // plot the computation graph in dot format (for debugging purposes)
  6600. //if (n_past%100 == 0) {
  6601. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6602. //}
  6603. // extract logits
  6604. // TODO: do not compute and extract logits if only embeddings are needed
  6605. // need to update the graphs to skip "result_output"
  6606. if (res) {
  6607. auto & logits_out = lctx.logits;
  6608. #ifndef NDEBUG
  6609. auto & logits_valid = lctx.logits_valid;
  6610. logits_valid.clear();
  6611. logits_valid.resize(n_tokens);
  6612. logits_out.clear();
  6613. #endif
  6614. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  6615. GGML_ASSERT(res_backend != nullptr);
  6616. if (batch.logits) {
  6617. logits_out.resize(n_vocab * n_tokens);
  6618. for (uint32_t i = 0; i < n_tokens; i++) {
  6619. if (batch.logits[i] == 0) {
  6620. continue;
  6621. }
  6622. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  6623. #ifndef NDEBUG
  6624. logits_valid[i] = true;
  6625. #endif
  6626. }
  6627. } else if (lctx.logits_all) {
  6628. logits_out.resize(n_vocab * n_tokens);
  6629. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  6630. #ifndef NDEBUG
  6631. std::fill(logits_valid.begin(), logits_valid.end(), true);
  6632. #endif
  6633. } else {
  6634. logits_out.resize(n_vocab);
  6635. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  6636. #ifndef NDEBUG
  6637. logits_valid[0] = true;
  6638. #endif
  6639. }
  6640. ggml_backend_synchronize(res_backend);
  6641. }
  6642. // extract embeddings
  6643. if (!lctx.embedding.empty()) {
  6644. auto & embedding_out = lctx.embedding;
  6645. const int64_t embd_pos = res ? n_embd * (n_tokens-1) : 0;
  6646. const int64_t embd_size = res ? n_embd : n_embd * n_tokens;
  6647. embedding_out.resize(embd_size);
  6648. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  6649. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), embd_pos*sizeof(float), embd_size*sizeof(float));
  6650. ggml_backend_synchronize(embeddings_backend);
  6651. }
  6652. // measure the performance only for the single-token evals
  6653. if (n_tokens == 1) {
  6654. lctx.t_eval_us += ggml_time_us() - t_start_us;
  6655. lctx.n_eval++;
  6656. }
  6657. else if (n_tokens > 1) {
  6658. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  6659. lctx.n_p_eval += n_tokens;
  6660. }
  6661. // get a more accurate load time, upon first eval
  6662. // TODO: fix this
  6663. if (!lctx.has_evaluated_once) {
  6664. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  6665. lctx.has_evaluated_once = true;
  6666. }
  6667. return 0;
  6668. }
  6669. //
  6670. // tokenizer
  6671. //
  6672. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  6673. return vocab.type;
  6674. }
  6675. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  6676. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  6677. }
  6678. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  6679. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  6680. }
  6681. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  6682. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  6683. }
  6684. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  6685. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  6686. }
  6687. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  6688. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  6689. }
  6690. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  6691. GGML_ASSERT(llama_is_byte_token(vocab, id));
  6692. const auto& token_data = vocab.id_to_token.at(id);
  6693. switch (llama_vocab_get_type(vocab)) {
  6694. case LLAMA_VOCAB_TYPE_SPM: {
  6695. auto buf = token_data.text.substr(3, 2);
  6696. return strtol(buf.c_str(), NULL, 16);
  6697. }
  6698. case LLAMA_VOCAB_TYPE_BPE: {
  6699. GGML_ASSERT(false);
  6700. return unicode_to_bytes_bpe(token_data.text);
  6701. }
  6702. case LLAMA_VOCAB_TYPE_WPM: {
  6703. GGML_ASSERT(false);
  6704. }
  6705. default:
  6706. GGML_ASSERT(false);
  6707. }
  6708. }
  6709. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  6710. static const char * hex = "0123456789ABCDEF";
  6711. switch (llama_vocab_get_type(vocab)) {
  6712. case LLAMA_VOCAB_TYPE_SPM: {
  6713. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  6714. auto token = vocab.token_to_id.find(buf);
  6715. if (token != vocab.token_to_id.end()) {
  6716. return (*token).second;
  6717. }
  6718. // Try to fall back to just the byte as a string
  6719. const char buf2[2] = { (char)ch, 0 };
  6720. return vocab.token_to_id.at(buf2);
  6721. }
  6722. case LLAMA_VOCAB_TYPE_WPM:
  6723. case LLAMA_VOCAB_TYPE_BPE: {
  6724. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  6725. }
  6726. default:
  6727. GGML_ASSERT(false);
  6728. }
  6729. }
  6730. static void llama_escape_whitespace(std::string & text) {
  6731. replace_all(text, " ", "\xe2\x96\x81");
  6732. }
  6733. static void llama_unescape_whitespace(std::string & word) {
  6734. replace_all(word, "\xe2\x96\x81", " ");
  6735. }
  6736. struct llm_symbol {
  6737. using index = int;
  6738. index prev;
  6739. index next;
  6740. const char * text;
  6741. size_t n;
  6742. };
  6743. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  6744. // SPM tokenizer
  6745. // original implementation:
  6746. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  6747. struct llm_bigram_spm {
  6748. struct comparator {
  6749. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  6750. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  6751. }
  6752. };
  6753. using queue_storage = std::vector<llm_bigram_spm>;
  6754. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  6755. llm_symbol::index left;
  6756. llm_symbol::index right;
  6757. float score;
  6758. size_t size;
  6759. };
  6760. struct llm_tokenizer_spm {
  6761. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  6762. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6763. // split string into utf8 chars
  6764. int index = 0;
  6765. size_t offs = 0;
  6766. while (offs < text.size()) {
  6767. llm_symbol sym;
  6768. size_t len = utf8_len(text[offs]);
  6769. sym.text = text.c_str() + offs;
  6770. sym.n = std::min(len, text.size() - offs);
  6771. offs += sym.n;
  6772. sym.prev = index - 1;
  6773. sym.next = offs == text.size() ? -1 : index + 1;
  6774. index++;
  6775. symbols.emplace_back(sym);
  6776. }
  6777. // seed the work queue with all possible 2-character tokens.
  6778. for (size_t i = 1; i < symbols.size(); ++i) {
  6779. try_add_bigram(i - 1, i);
  6780. }
  6781. // keep substituting the highest frequency pairs for as long as we can.
  6782. while (!work_queue.empty()) {
  6783. auto bigram = work_queue.top();
  6784. work_queue.pop();
  6785. auto & left_sym = symbols[bigram.left];
  6786. auto & right_sym = symbols[bigram.right];
  6787. // if one of the symbols already got merged, skip it.
  6788. if (left_sym.n == 0 || right_sym.n == 0 ||
  6789. left_sym.n + right_sym.n != bigram.size) {
  6790. continue;
  6791. }
  6792. // merge the right sym into the left one
  6793. left_sym.n += right_sym.n;
  6794. right_sym.n = 0;
  6795. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  6796. // remove the right sym from the chain
  6797. left_sym.next = right_sym.next;
  6798. if (right_sym.next >= 0) {
  6799. symbols[right_sym.next].prev = bigram.left;
  6800. }
  6801. // find more substitutions
  6802. try_add_bigram(left_sym.prev, bigram.left);
  6803. try_add_bigram(bigram.left, left_sym.next);
  6804. }
  6805. for (int i = 0; i != -1; i = symbols[i].next) {
  6806. auto & symbol = symbols[i];
  6807. resegment(symbol, output);
  6808. }
  6809. }
  6810. private:
  6811. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  6812. auto text = std::string(symbol.text, symbol.n);
  6813. auto token = vocab.token_to_id.find(text);
  6814. // Do we need to support is_unused?
  6815. if (token != vocab.token_to_id.end()) {
  6816. output.push_back((*token).second);
  6817. return;
  6818. }
  6819. const auto p = rev_merge.find(text);
  6820. if (p == rev_merge.end()) {
  6821. // output any symbols that did not form tokens as bytes.
  6822. output.reserve(output.size() + symbol.n);
  6823. for (int j = 0; j < (int)symbol.n; ++j) {
  6824. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  6825. output.push_back(token_id);
  6826. }
  6827. return;
  6828. }
  6829. resegment(symbols[p->second.first], output);
  6830. resegment(symbols[p->second.second], output);
  6831. }
  6832. void try_add_bigram(int left, int right) {
  6833. if (left == -1 || right == -1) {
  6834. return;
  6835. }
  6836. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  6837. auto token = vocab.token_to_id.find(text);
  6838. if (token == vocab.token_to_id.end()) {
  6839. return;
  6840. }
  6841. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  6842. return;
  6843. }
  6844. const auto & tok_data = vocab.id_to_token[(*token).second];
  6845. llm_bigram_spm bigram;
  6846. bigram.left = left;
  6847. bigram.right = right;
  6848. bigram.score = tok_data.score;
  6849. bigram.size = text.size();
  6850. work_queue.push(bigram);
  6851. // Do we need to support is_unused?
  6852. rev_merge[text] = std::make_pair(left, right);
  6853. }
  6854. const llama_vocab & vocab;
  6855. std::vector<llm_symbol> symbols;
  6856. llm_bigram_spm::queue work_queue;
  6857. std::map<std::string, std::pair<int, int>> rev_merge;
  6858. };
  6859. // BPE tokenizer
  6860. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  6861. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  6862. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  6863. struct llm_bigram_bpe {
  6864. struct comparator {
  6865. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  6866. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  6867. }
  6868. };
  6869. using queue_storage = std::vector<llm_bigram_bpe>;
  6870. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  6871. llm_symbol::index left;
  6872. llm_symbol::index right;
  6873. std::string text;
  6874. int rank;
  6875. size_t size;
  6876. };
  6877. struct llm_tokenizer_bpe {
  6878. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  6879. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6880. int final_prev_index = -1;
  6881. auto word_collection = bpe_gpt2_preprocess(text);
  6882. symbols_final.clear();
  6883. for (auto & word : word_collection) {
  6884. work_queue = llm_bigram_bpe::queue();
  6885. symbols.clear();
  6886. int index = 0;
  6887. size_t offset = 0;
  6888. while (offset < word.size()) {
  6889. llm_symbol sym;
  6890. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  6891. sym.text = word.c_str() + offset;
  6892. sym.n = char_len;
  6893. offset += sym.n;
  6894. sym.prev = index - 1;
  6895. sym.next = offset == word.size() ? -1 : index + 1;
  6896. index++;
  6897. symbols.emplace_back(sym);
  6898. }
  6899. for (size_t i = 1; i < symbols.size(); ++i) {
  6900. add_new_bigram(i - 1, i);
  6901. }
  6902. // build token(s)
  6903. while (!work_queue.empty()) {
  6904. auto bigram = work_queue.top();
  6905. work_queue.pop();
  6906. auto & left_symbol = symbols[bigram.left];
  6907. auto & right_symbol = symbols[bigram.right];
  6908. if (left_symbol.n == 0 || right_symbol.n == 0) {
  6909. continue;
  6910. }
  6911. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  6912. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  6913. if (left_token + right_token != bigram.text) {
  6914. continue; // Skip this bigram if it's outdated
  6915. }
  6916. // merge the right sym into the left one
  6917. left_symbol.n += right_symbol.n;
  6918. right_symbol.n = 0;
  6919. // remove the right sym from the chain
  6920. left_symbol.next = right_symbol.next;
  6921. if (right_symbol.next >= 0) {
  6922. symbols[right_symbol.next].prev = bigram.left;
  6923. }
  6924. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  6925. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  6926. }
  6927. // add the fnished tokens to the final list keeping correct order for next and prev
  6928. for (auto & sym : symbols) {
  6929. if (sym.n > 0) {
  6930. sym.prev = final_prev_index;
  6931. sym.next = -1;
  6932. if (final_prev_index != -1) {
  6933. symbols_final[final_prev_index].next = symbols_final.size();
  6934. }
  6935. symbols_final.emplace_back(sym);
  6936. final_prev_index = symbols_final.size() - 1;
  6937. }
  6938. }
  6939. }
  6940. symbols = symbols_final;
  6941. if (!symbols.empty()) {
  6942. for (int i = 0; i != -1; i = symbols[i].next) {
  6943. auto & symbol = symbols[i];
  6944. if (symbol.n == 0) {
  6945. continue;
  6946. }
  6947. const std::string str = std::string(symbol.text, symbol.n);
  6948. const auto token = vocab.token_to_id.find(str);
  6949. if (token == vocab.token_to_id.end()) {
  6950. for (auto j = str.begin(); j != str.end(); ++j) {
  6951. std::string byte_str(1, *j);
  6952. auto token_multibyte = vocab.token_to_id.find(byte_str);
  6953. if (token_multibyte == vocab.token_to_id.end()) {
  6954. throw std::runtime_error("ERROR: byte not found in vocab");
  6955. }
  6956. output.push_back((*token_multibyte).second);
  6957. }
  6958. } else {
  6959. output.push_back((*token).second);
  6960. }
  6961. }
  6962. }
  6963. }
  6964. private:
  6965. void add_new_bigram(int left, int right) {
  6966. if (left == -1 || right == -1) {
  6967. return;
  6968. }
  6969. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  6970. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  6971. int rank_found = -1;
  6972. rank_found = vocab.find_bpe_rank(left_token, right_token);
  6973. if (rank_found < 0) {
  6974. return;
  6975. }
  6976. llm_bigram_bpe bigram;
  6977. bigram.left = left;
  6978. bigram.right = right;
  6979. bigram.text = left_token + right_token;
  6980. bigram.size = left_token.size() + right_token.size();
  6981. bigram.rank = rank_found;
  6982. work_queue.push(bigram);
  6983. }
  6984. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  6985. std::vector<std::string> bpe_words;
  6986. std::vector<std::string> bpe_encoded_words;
  6987. std::string token = "";
  6988. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  6989. bool collecting_numeric = false;
  6990. bool collecting_letter = false;
  6991. bool collecting_special = false;
  6992. bool collecting_whitespace_lookahead = false;
  6993. bool collecting = false;
  6994. std::vector<std::string> text_utf;
  6995. text_utf.reserve(text.size());
  6996. bpe_words.reserve(text.size());
  6997. bpe_encoded_words.reserve(text.size());
  6998. auto cps = codepoints_from_utf8(text);
  6999. for (size_t i = 0; i < cps.size(); ++i)
  7000. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  7001. for (int i = 0; i < (int)text_utf.size(); i++) {
  7002. const std::string & utf_char = text_utf[i];
  7003. bool split_condition = false;
  7004. int bytes_remain = text_utf.size() - i;
  7005. // forward backward lookups
  7006. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  7007. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  7008. // handling contractions
  7009. if (!split_condition && bytes_remain >= 2) {
  7010. // 's|'t|'m|'d
  7011. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  7012. split_condition = true;
  7013. }
  7014. if (split_condition) {
  7015. if (token.size()) {
  7016. bpe_words.emplace_back(token); // push previous content as token
  7017. }
  7018. token = utf_char + utf_char_next;
  7019. bpe_words.emplace_back(token);
  7020. token = "";
  7021. i++;
  7022. continue;
  7023. }
  7024. }
  7025. if (!split_condition && bytes_remain >= 3) {
  7026. // 're|'ve|'ll
  7027. if (utf_char == "\'" && (
  7028. (utf_char_next == "r" && utf_char_next_next == "e") ||
  7029. (utf_char_next == "v" && utf_char_next_next == "e") ||
  7030. (utf_char_next == "l" && utf_char_next_next == "l"))
  7031. ) {
  7032. split_condition = true;
  7033. }
  7034. if (split_condition) {
  7035. // current token + next token can be defined
  7036. if (token.size()) {
  7037. bpe_words.emplace_back(token); // push previous content as token
  7038. }
  7039. token = utf_char + utf_char_next + utf_char_next_next;
  7040. bpe_words.emplace_back(token); // the contraction
  7041. token = "";
  7042. i += 2;
  7043. continue;
  7044. }
  7045. }
  7046. if (!split_condition && !collecting) {
  7047. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  7048. collecting_letter = true;
  7049. collecting = true;
  7050. }
  7051. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7052. collecting_numeric = true;
  7053. collecting = true;
  7054. }
  7055. else if (
  7056. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  7057. (!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)
  7058. ) {
  7059. collecting_special = true;
  7060. collecting = true;
  7061. }
  7062. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  7063. collecting_whitespace_lookahead = true;
  7064. collecting = true;
  7065. }
  7066. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  7067. split_condition = true;
  7068. }
  7069. }
  7070. else if (!split_condition && collecting) {
  7071. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  7072. split_condition = true;
  7073. }
  7074. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  7075. split_condition = true;
  7076. }
  7077. 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)) {
  7078. split_condition = true;
  7079. }
  7080. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7081. split_condition = true;
  7082. }
  7083. }
  7084. if (utf_char_next == "") {
  7085. split_condition = true; // final
  7086. token += utf_char;
  7087. }
  7088. if (split_condition) {
  7089. if (token.size()) {
  7090. bpe_words.emplace_back(token);
  7091. }
  7092. token = utf_char;
  7093. collecting = false;
  7094. collecting_letter = false;
  7095. collecting_numeric = false;
  7096. collecting_special = false;
  7097. collecting_whitespace_lookahead = false;
  7098. }
  7099. else {
  7100. token += utf_char;
  7101. }
  7102. }
  7103. for (std::string & word : bpe_words) {
  7104. std::string encoded_token = "";
  7105. for (char & c : word) {
  7106. encoded_token += bytes_to_unicode_bpe(c);
  7107. }
  7108. bpe_encoded_words.emplace_back(encoded_token);
  7109. }
  7110. return bpe_encoded_words;
  7111. }
  7112. const llama_vocab & vocab;
  7113. std::vector<llm_symbol> symbols;
  7114. std::vector<llm_symbol> symbols_final;
  7115. llm_bigram_bpe::queue work_queue;
  7116. };
  7117. struct llm_tokenizer_wpm {
  7118. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  7119. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7120. auto * token_map = &vocab.token_to_id;
  7121. // normalize and split by whitespace
  7122. std::vector<std::string> words = preprocess(text);
  7123. // bos token prepended already
  7124. // find the longest tokens that form the words
  7125. for (const std::string &word : words) {
  7126. // skip empty words
  7127. if (word.size() == 0) {
  7128. continue;
  7129. }
  7130. // prepend phantom space
  7131. std::string word1 = "\xe2\x96\x81" + word;
  7132. int n = word1.size();
  7133. // we're at the start of a new word
  7134. int i = 0;
  7135. bool match_any = false;
  7136. // move through character position in word
  7137. while (i < n) {
  7138. // loop through possible match length
  7139. bool match = false;
  7140. for (int j = n; j > i; j--) {
  7141. auto it = token_map->find(word1.substr(i, j - i));
  7142. if (it != token_map->end()) {
  7143. output.push_back(it->second);
  7144. match = true;
  7145. match_any = true;
  7146. i = j;
  7147. break;
  7148. }
  7149. }
  7150. // must be an unknown character
  7151. if (!match) {
  7152. i++;
  7153. }
  7154. }
  7155. // we didn't find any matches for this word
  7156. if (!match_any) {
  7157. output.push_back(vocab.special_unk_id);
  7158. }
  7159. }
  7160. // append eos token
  7161. output.push_back(vocab.special_eos_id);
  7162. }
  7163. std::vector<std::string> preprocess(const std::string & text) {
  7164. std::string ori_str = normalize(text);
  7165. uint64_t ori_size = ori_str.size();
  7166. // single punct / single symbol / single digit
  7167. // baseline: add whitespace on the left and right of punct and chinese characters
  7168. std::vector<std::string> words;
  7169. std::string new_str = "";
  7170. uint64_t i = 0;
  7171. while (i < ori_size) {
  7172. int utf_char_len = utf8_len(ori_str[i]);
  7173. if ((utf_char_len == 1) && ispunct(ori_str[i])) {
  7174. new_str += " ";
  7175. new_str += ori_str[i];
  7176. new_str += " ";
  7177. i += 1;
  7178. }
  7179. else if ((utf_char_len == 3) && is_chinese_char(ori_str.substr(i, 3))) {
  7180. new_str += " ";
  7181. new_str += ori_str.substr(i, 3);
  7182. new_str += " ";
  7183. i += 3;
  7184. }
  7185. else {
  7186. new_str += ori_str[i];
  7187. i += 1;
  7188. }
  7189. }
  7190. // split by whitespace
  7191. uint64_t l = 0;
  7192. uint64_t r = 0;
  7193. while (r < new_str.size()) {
  7194. // if is whitespace
  7195. if (isspace(new_str[r])) {
  7196. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  7197. l = r + 1;
  7198. r = l;
  7199. }
  7200. else {
  7201. r += 1;
  7202. }
  7203. }
  7204. if (r > l) {
  7205. words.push_back(new_str.substr(l, (r - l)));
  7206. }
  7207. return words;
  7208. }
  7209. std::string normalize(const std::string & text) {
  7210. // TODO: handle chinese characters? https://github.com/huggingface/tokenizers/blob/ef5f50605ddf9f8caef1598c0e4853862b9707a7/tokenizers/src/normalizers/bert.rs#L98
  7211. std::string text2 = strip_accents(text);
  7212. for (size_t i = 0; i < text2.size(); i += utf8_len(text2[i])) {
  7213. char c = text2[i];
  7214. if (c >= 'A' && c <= 'Z') {
  7215. text2[i] = c - 'A' + 'a';
  7216. }
  7217. }
  7218. return text2;
  7219. }
  7220. bool is_chinese_char(const std::string & str) {
  7221. int len = str.length();
  7222. unsigned int codepoint = 0;
  7223. int num_bytes = 0;
  7224. int i = 0;
  7225. unsigned char ch = static_cast<unsigned char>(str[i]);
  7226. if (ch <= 0x7f) {
  7227. codepoint = ch;
  7228. num_bytes = 1;
  7229. } else if ((ch >> 5) == 0x06) {
  7230. codepoint = ch & 0x1f;
  7231. num_bytes = 2;
  7232. } else if ((ch >> 4) == 0x0e) {
  7233. codepoint = ch & 0x0f;
  7234. num_bytes = 3;
  7235. } else if ((ch >> 3) == 0x1e) {
  7236. codepoint = ch & 0x07;
  7237. num_bytes = 4;
  7238. }
  7239. for (int j = 1; j < num_bytes; ++j) {
  7240. if (i + j >= len) {
  7241. return false; // incomplete UTF-8 character
  7242. }
  7243. unsigned char next_ch = static_cast<unsigned char>(str[i + j]);
  7244. if ((next_ch >> 6) != 0x02) {
  7245. return false; // invalid trailing byte
  7246. }
  7247. codepoint = (codepoint << 6) | (next_ch & 0x3f);
  7248. }
  7249. if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) ||
  7250. (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
  7251. (codepoint >= 0x20000 && codepoint <= 0x2A6DF) ||
  7252. (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
  7253. (codepoint >= 0x2B740 && codepoint <= 0x2B81F) ||
  7254. (codepoint >= 0x2B920 && codepoint <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  7255. (codepoint >= 0xF900 && codepoint <= 0xFAFF) ||
  7256. (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
  7257. (codepoint >= 0x3000 && codepoint <= 0x303F) ||
  7258. (codepoint >= 0xFF00 && codepoint <= 0xFFEF)) {
  7259. return true; // NOLINT
  7260. }
  7261. return false;
  7262. }
  7263. std::string strip_accents(const std::string & input_string) {
  7264. std::string resultString;
  7265. std::map<std::string, char> accent_map = {
  7266. {"À", 'A'}, {"Á", 'A'}, {"Â", 'A'}, {"Ã", 'A'}, {"Ä", 'A'}, {"Å", 'A'},
  7267. {"à", 'a'}, {"á", 'a'}, {"â", 'a'}, {"ã", 'a'}, {"ä", 'a'}, {"å", 'a'},
  7268. {"È", 'E'}, {"É", 'E'}, {"Ê", 'E'}, {"Ë", 'E'}, {"è", 'e'}, {"é", 'e'},
  7269. {"ê", 'e'}, {"ë", 'e'}, {"Ì", 'I'}, {"Í", 'I'}, {"Î", 'I'}, {"Ï", 'I'},
  7270. {"ì", 'i'}, {"í", 'i'}, {"î", 'i'}, {"ï", 'i'}, {"Ò", 'O'}, {"Ó", 'O'},
  7271. {"Ô", 'O'}, {"Õ", 'O'}, {"Ö", 'O'}, {"ò", 'o'}, {"ó", 'o'}, {"ô", 'o'},
  7272. {"õ", 'o'}, {"ö", 'o'}, {"Ù", 'U'}, {"Ú", 'U'}, {"Û", 'U'}, {"Ü", 'U'},
  7273. {"ù", 'u'}, {"ú", 'u'}, {"û", 'u'}, {"ü", 'u'}, {"Ý", 'Y'}, {"ý", 'y'},
  7274. {"Ç", 'C'}, {"ç", 'c'}, {"Ñ", 'N'}, {"ñ", 'n'},
  7275. };
  7276. for (size_t i = 0; i < input_string.length();) {
  7277. int len = utf8_len(input_string[i]);
  7278. std::string curChar = input_string.substr(i, len);
  7279. auto iter = accent_map.find(curChar);
  7280. if (iter != accent_map.end()) {
  7281. resultString += iter->second;
  7282. } else {
  7283. resultString += curChar;
  7284. }
  7285. i += len;
  7286. }
  7287. return resultString;
  7288. }
  7289. static size_t utf8_len(char src) {
  7290. const size_t lookup[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4};
  7291. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  7292. return lookup[highbits];
  7293. }
  7294. const llama_vocab & vocab;
  7295. };
  7296. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  7297. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  7298. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  7299. } FRAGMENT_BUFFER_VARIANT_TYPE;
  7300. struct fragment_buffer_variant {
  7301. fragment_buffer_variant(llama_vocab::id _token)
  7302. :
  7303. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  7304. token(_token),
  7305. raw_text(_dummy),
  7306. offset(0),
  7307. length(0) {}
  7308. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  7309. :
  7310. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  7311. token((llama_vocab::id) - 1),
  7312. raw_text(_raw_text),
  7313. offset(_offset),
  7314. length(_length){
  7315. GGML_ASSERT(_offset >= 0);
  7316. GGML_ASSERT(_length >= 1);
  7317. GGML_ASSERT(offset + length <= raw_text.length());
  7318. }
  7319. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  7320. const llama_vocab::id token;
  7321. const std::string _dummy;
  7322. const std::string & raw_text;
  7323. const uint64_t offset;
  7324. const uint64_t length;
  7325. };
  7326. // #define PRETOKENIZERDEBUG
  7327. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  7328. // for each special token
  7329. for (const auto & st: vocab.special_tokens_cache) {
  7330. const auto & special_token = st.first;
  7331. const auto & special_id = st.second;
  7332. // for each text fragment
  7333. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  7334. while (it != buffer.end()) {
  7335. auto & fragment = (*it);
  7336. // if a fragment is text ( not yet processed )
  7337. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7338. auto * raw_text = &(fragment.raw_text);
  7339. auto raw_text_base_offset = fragment.offset;
  7340. auto raw_text_base_length = fragment.length;
  7341. // loop over the text
  7342. while (true) {
  7343. // find the first occurrence of a given special token in this fragment
  7344. // passing offset argument only limit the "search area" but match coordinates
  7345. // are still relative to the source full raw_text
  7346. auto match = raw_text->find(special_token, raw_text_base_offset);
  7347. // no occurrences found, stop processing this fragment for a given special token
  7348. if (match == std::string::npos) break;
  7349. // check if match is within bounds of offset <-> length
  7350. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  7351. #ifdef PRETOKENIZERDEBUG
  7352. 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());
  7353. #endif
  7354. auto source = std::distance(buffer.begin(), it);
  7355. // if match is further than base offset
  7356. // then we have some text to the left of it
  7357. if (match > raw_text_base_offset) {
  7358. // left
  7359. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  7360. const int64_t left_reminder_length = match - raw_text_base_offset;
  7361. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  7362. #ifdef PRETOKENIZERDEBUG
  7363. 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());
  7364. #endif
  7365. it++;
  7366. }
  7367. // special token
  7368. buffer.emplace_after(it, special_id);
  7369. it++;
  7370. // right
  7371. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  7372. const int64_t right_reminder_offset = match + special_token.length();
  7373. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  7374. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  7375. #ifdef PRETOKENIZERDEBUG
  7376. 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());
  7377. #endif
  7378. it++;
  7379. if (source == 0) {
  7380. buffer.erase_after(buffer.before_begin());
  7381. } else {
  7382. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7383. }
  7384. // repeat for the right side
  7385. raw_text_base_offset = right_reminder_offset;
  7386. raw_text_base_length = right_reminder_length;
  7387. #ifdef PRETOKENIZERDEBUG
  7388. 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());
  7389. #endif
  7390. } else {
  7391. if (source == 0) {
  7392. buffer.erase_after(buffer.before_begin());
  7393. } else {
  7394. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7395. }
  7396. break;
  7397. }
  7398. }
  7399. }
  7400. it++;
  7401. }
  7402. }
  7403. }
  7404. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  7405. std::vector<llama_vocab::id> output;
  7406. // OG tokenizer behavior:
  7407. //
  7408. // tokenizer.encode('', add_bos=True) returns [1]
  7409. // tokenizer.encode('', add_bos=False) returns []
  7410. if (bos && vocab.special_bos_id != -1) {
  7411. output.push_back(vocab.special_bos_id);
  7412. }
  7413. if (raw_text.empty()) {
  7414. return output;
  7415. }
  7416. std::forward_list<fragment_buffer_variant> fragment_buffer;
  7417. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  7418. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  7419. switch (vocab.type) {
  7420. case LLAMA_VOCAB_TYPE_SPM:
  7421. {
  7422. for (const auto & fragment : fragment_buffer) {
  7423. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7424. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  7425. // TODO: It's likely possible to get rid of this string copy entirely
  7426. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  7427. // and passing 'add space prefix' as bool argument
  7428. //
  7429. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7430. if (&fragment == &fragment_buffer.front()) {
  7431. if (vocab.add_space_prefix) {
  7432. raw_text = " " + raw_text; // prefix with space if the first token is not special
  7433. }
  7434. }
  7435. #ifdef PRETOKENIZERDEBUG
  7436. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7437. #endif
  7438. llm_tokenizer_spm tokenizer(vocab);
  7439. llama_escape_whitespace(raw_text);
  7440. tokenizer.tokenize(raw_text, output);
  7441. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7442. output.push_back(fragment.token);
  7443. }
  7444. }
  7445. } break;
  7446. case LLAMA_VOCAB_TYPE_BPE:
  7447. {
  7448. for (const auto & fragment : fragment_buffer) {
  7449. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7450. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7451. #ifdef PRETOKENIZERDEBUG
  7452. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7453. #endif
  7454. llm_tokenizer_bpe tokenizer(vocab);
  7455. tokenizer.tokenize(raw_text, output);
  7456. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7457. output.push_back(fragment.token);
  7458. }
  7459. }
  7460. } break;
  7461. case LLAMA_VOCAB_TYPE_WPM:
  7462. {
  7463. for (const auto & fragment : fragment_buffer) {
  7464. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7465. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7466. #ifdef PRETOKENIZERDEBUG
  7467. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7468. #endif
  7469. llm_tokenizer_wpm tokenizer(vocab);
  7470. tokenizer.tokenize(raw_text, output);
  7471. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7472. output.push_back(fragment.token);
  7473. }
  7474. }
  7475. } break;
  7476. }
  7477. return output;
  7478. }
  7479. //
  7480. // grammar - internal
  7481. //
  7482. struct llama_partial_utf8 {
  7483. uint32_t value; // bit value so far (unshifted)
  7484. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  7485. };
  7486. struct llama_grammar {
  7487. const std::vector<std::vector<llama_grammar_element>> rules;
  7488. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7489. // buffer for partially generated UTF-8 sequence from accepted tokens
  7490. llama_partial_utf8 partial_utf8;
  7491. };
  7492. struct llama_grammar_candidate {
  7493. size_t index;
  7494. const uint32_t * code_points;
  7495. llama_partial_utf8 partial_utf8;
  7496. };
  7497. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  7498. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  7499. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  7500. const std::string & src,
  7501. llama_partial_utf8 partial_start) {
  7502. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  7503. const char * pos = src.c_str();
  7504. std::vector<uint32_t> code_points;
  7505. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  7506. code_points.reserve(src.size() + 1);
  7507. uint32_t value = partial_start.value;
  7508. int n_remain = partial_start.n_remain;
  7509. // continue previous decode, if applicable
  7510. while (*pos != 0 && n_remain > 0) {
  7511. uint8_t next_byte = static_cast<uint8_t>(*pos);
  7512. if ((next_byte >> 6) != 2) {
  7513. // invalid sequence, abort
  7514. code_points.push_back(0);
  7515. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  7516. }
  7517. value = (value << 6) + (next_byte & 0x3F);
  7518. ++pos;
  7519. --n_remain;
  7520. }
  7521. if (partial_start.n_remain > 0 && n_remain == 0) {
  7522. code_points.push_back(value);
  7523. }
  7524. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  7525. while (*pos != 0) {
  7526. uint8_t first_byte = static_cast<uint8_t>(*pos);
  7527. uint8_t highbits = first_byte >> 4;
  7528. n_remain = lookup[highbits] - 1;
  7529. if (n_remain < 0) {
  7530. // invalid sequence, abort
  7531. code_points.clear();
  7532. code_points.push_back(0);
  7533. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  7534. }
  7535. uint8_t mask = (1 << (7 - n_remain)) - 1;
  7536. value = first_byte & mask;
  7537. ++pos;
  7538. while (*pos != 0 && n_remain > 0) {
  7539. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  7540. ++pos;
  7541. --n_remain;
  7542. }
  7543. if (n_remain == 0) {
  7544. code_points.push_back(value);
  7545. }
  7546. }
  7547. code_points.push_back(0);
  7548. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  7549. }
  7550. // returns true iff pos points to the end of one of the definitions of a rule
  7551. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  7552. switch (pos->type) {
  7553. case LLAMA_GRETYPE_END: return true; // NOLINT
  7554. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  7555. default: return false;
  7556. }
  7557. }
  7558. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  7559. // asserts that pos is pointing to a char range element
  7560. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  7561. const llama_grammar_element * pos,
  7562. const uint32_t chr) {
  7563. bool found = false;
  7564. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7565. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  7566. do {
  7567. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7568. // inclusive range, e.g. [a-z]
  7569. found = found || (pos->value <= chr && chr <= pos[1].value);
  7570. pos += 2;
  7571. } else {
  7572. // exact char match, e.g. [a] or "a"
  7573. found = found || pos->value == chr;
  7574. pos += 1;
  7575. }
  7576. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7577. return std::make_pair(found == is_positive_char, pos);
  7578. }
  7579. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  7580. // range at pos (regular or inverse range)
  7581. // asserts that pos is pointing to a char range element
  7582. static bool llama_grammar_match_partial_char(
  7583. const llama_grammar_element * pos,
  7584. const llama_partial_utf8 partial_utf8) {
  7585. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7586. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  7587. uint32_t partial_value = partial_utf8.value;
  7588. int n_remain = partial_utf8.n_remain;
  7589. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  7590. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  7591. return false;
  7592. }
  7593. // range of possible code points this partial UTF-8 sequence could complete to
  7594. uint32_t low = partial_value << (n_remain * 6);
  7595. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  7596. if (low == 0) {
  7597. if (n_remain == 2) {
  7598. low = 1 << 11;
  7599. } else if (n_remain == 3) {
  7600. low = 1 << 16;
  7601. }
  7602. }
  7603. do {
  7604. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7605. // inclusive range, e.g. [a-z]
  7606. if (pos->value <= high && low <= pos[1].value) {
  7607. return is_positive_char;
  7608. }
  7609. pos += 2;
  7610. } else {
  7611. // exact char match, e.g. [a] or "a"
  7612. if (low <= pos->value && pos->value <= high) {
  7613. return is_positive_char;
  7614. }
  7615. pos += 1;
  7616. }
  7617. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7618. return !is_positive_char;
  7619. }
  7620. // transforms a grammar pushdown stack into N possible stacks, all ending
  7621. // at a character range (terminal element)
  7622. static void llama_grammar_advance_stack(
  7623. const std::vector<std::vector<llama_grammar_element>> & rules,
  7624. const std::vector<const llama_grammar_element *> & stack,
  7625. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  7626. if (stack.empty()) {
  7627. new_stacks.emplace_back(stack);
  7628. return;
  7629. }
  7630. const llama_grammar_element * pos = stack.back();
  7631. switch (pos->type) {
  7632. case LLAMA_GRETYPE_RULE_REF: {
  7633. const size_t rule_id = static_cast<size_t>(pos->value);
  7634. const llama_grammar_element * subpos = rules[rule_id].data();
  7635. do {
  7636. // init new stack without the top (pos)
  7637. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7638. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  7639. // if this rule ref is followed by another element, add that to stack
  7640. new_stack.push_back(pos + 1);
  7641. }
  7642. if (!llama_grammar_is_end_of_sequence(subpos)) {
  7643. // if alternate is nonempty, add to stack
  7644. new_stack.push_back(subpos);
  7645. }
  7646. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7647. while (!llama_grammar_is_end_of_sequence(subpos)) {
  7648. // scan to end of alternate def
  7649. subpos++;
  7650. }
  7651. if (subpos->type == LLAMA_GRETYPE_ALT) {
  7652. // there's another alternate def of this rule to process
  7653. subpos++;
  7654. } else {
  7655. break;
  7656. }
  7657. } while (true);
  7658. break;
  7659. }
  7660. case LLAMA_GRETYPE_CHAR:
  7661. case LLAMA_GRETYPE_CHAR_NOT:
  7662. new_stacks.emplace_back(stack);
  7663. break;
  7664. default:
  7665. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  7666. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  7667. // those
  7668. GGML_ASSERT(false);
  7669. }
  7670. }
  7671. // takes a set of possible pushdown stacks on a grammar, which are required to
  7672. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  7673. // produces the N possible stacks if the given char is accepted at those
  7674. // positions
  7675. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  7676. const std::vector<std::vector<llama_grammar_element>> & rules,
  7677. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7678. const uint32_t chr) {
  7679. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  7680. for (const auto & stack : stacks) {
  7681. if (stack.empty()) {
  7682. continue;
  7683. }
  7684. auto match = llama_grammar_match_char(stack.back(), chr);
  7685. if (match.first) {
  7686. const llama_grammar_element * pos = match.second;
  7687. // update top of stack to next element, if any
  7688. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7689. if (!llama_grammar_is_end_of_sequence(pos)) {
  7690. new_stack.push_back(pos);
  7691. }
  7692. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7693. }
  7694. }
  7695. return new_stacks;
  7696. }
  7697. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7698. const std::vector<std::vector<llama_grammar_element>> & rules,
  7699. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7700. const std::vector<llama_grammar_candidate> & candidates);
  7701. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  7702. const std::vector<std::vector<llama_grammar_element>> & rules,
  7703. const std::vector<const llama_grammar_element *> & stack,
  7704. const std::vector<llama_grammar_candidate> & candidates) {
  7705. std::vector<llama_grammar_candidate> rejects;
  7706. if (stack.empty()) {
  7707. for (const auto & tok : candidates) {
  7708. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  7709. rejects.push_back(tok);
  7710. }
  7711. }
  7712. return rejects;
  7713. }
  7714. const llama_grammar_element * stack_pos = stack.back();
  7715. std::vector<llama_grammar_candidate> next_candidates;
  7716. for (const auto & tok : candidates) {
  7717. if (*tok.code_points == 0) {
  7718. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  7719. // that cannot satisfy this position in grammar
  7720. if (tok.partial_utf8.n_remain != 0 &&
  7721. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  7722. rejects.push_back(tok);
  7723. }
  7724. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  7725. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  7726. } else {
  7727. rejects.push_back(tok);
  7728. }
  7729. }
  7730. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  7731. // update top of stack to next element, if any
  7732. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  7733. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  7734. stack_after.push_back(stack_pos_after);
  7735. }
  7736. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  7737. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  7738. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  7739. for (const auto & tok : next_rejects) {
  7740. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  7741. }
  7742. return rejects;
  7743. }
  7744. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7745. const std::vector<std::vector<llama_grammar_element>> & rules,
  7746. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7747. const std::vector<llama_grammar_candidate> & candidates) {
  7748. GGML_ASSERT(!stacks.empty()); // REVIEW
  7749. if (candidates.empty()) {
  7750. return std::vector<llama_grammar_candidate>();
  7751. }
  7752. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  7753. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  7754. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  7755. }
  7756. return rejects;
  7757. }
  7758. //
  7759. // grammar - external
  7760. //
  7761. struct llama_grammar * llama_grammar_init(
  7762. const llama_grammar_element ** rules,
  7763. size_t n_rules,
  7764. size_t start_rule_index) {
  7765. const llama_grammar_element * pos;
  7766. // copy rule definitions into vectors
  7767. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  7768. for (size_t i = 0; i < n_rules; i++) {
  7769. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  7770. vec_rules[i].push_back(*pos);
  7771. }
  7772. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  7773. }
  7774. // loop over alternates of start rule to build initial stacks
  7775. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7776. pos = rules[start_rule_index];
  7777. do {
  7778. std::vector<const llama_grammar_element *> stack;
  7779. if (!llama_grammar_is_end_of_sequence(pos)) {
  7780. // if alternate is nonempty, add to stack
  7781. stack.push_back(pos);
  7782. }
  7783. llama_grammar_advance_stack(vec_rules, stack, stacks);
  7784. while (!llama_grammar_is_end_of_sequence(pos)) {
  7785. // scan to end of alternate def
  7786. pos++;
  7787. }
  7788. if (pos->type == LLAMA_GRETYPE_ALT) {
  7789. // there's another alternate def of this rule to process
  7790. pos++;
  7791. } else {
  7792. break;
  7793. }
  7794. } while (true);
  7795. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  7796. }
  7797. void llama_grammar_free(struct llama_grammar * grammar) {
  7798. delete grammar;
  7799. }
  7800. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  7801. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  7802. // redirect elements in stacks to point to new rules
  7803. for (size_t is = 0; is < result->stacks.size(); is++) {
  7804. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  7805. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  7806. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  7807. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  7808. result->stacks[is][ie] = &result->rules[ir0][ir1];
  7809. }
  7810. }
  7811. }
  7812. }
  7813. }
  7814. return result;
  7815. }
  7816. //
  7817. // sampling
  7818. //
  7819. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  7820. if (seed == LLAMA_DEFAULT_SEED) {
  7821. seed = time(NULL);
  7822. }
  7823. ctx->rng.seed(seed);
  7824. }
  7825. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  7826. GGML_ASSERT(candidates->size > 0);
  7827. const int64_t t_start_sample_us = ggml_time_us();
  7828. // Sort the logits in descending order
  7829. if (!candidates->sorted) {
  7830. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7831. return a.logit > b.logit;
  7832. });
  7833. candidates->sorted = true;
  7834. }
  7835. float max_l = candidates->data[0].logit;
  7836. float cum_sum = 0.0f;
  7837. for (size_t i = 0; i < candidates->size; ++i) {
  7838. float p = expf(candidates->data[i].logit - max_l);
  7839. candidates->data[i].p = p;
  7840. cum_sum += p;
  7841. }
  7842. for (size_t i = 0; i < candidates->size; ++i) {
  7843. candidates->data[i].p /= cum_sum;
  7844. }
  7845. if (ctx) {
  7846. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7847. }
  7848. }
  7849. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  7850. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  7851. // if (k >= (int32_t)candidates->size) {
  7852. // return;
  7853. // }
  7854. const int64_t t_start_sample_us = ggml_time_us();
  7855. if (k <= 0) {
  7856. k = candidates->size;
  7857. }
  7858. k = std::max(k, (int) min_keep);
  7859. k = std::min(k, (int) candidates->size);
  7860. // Sort scores in descending order
  7861. if (!candidates->sorted) {
  7862. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  7863. return a.logit > b.logit;
  7864. };
  7865. if (k <= 128) {
  7866. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  7867. } else {
  7868. constexpr int nbuckets = 128;
  7869. constexpr float bucket_low = -10.0f;
  7870. constexpr float bucket_high = 10.0f;
  7871. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  7872. constexpr float bucker_inter = -bucket_low * bucket_scale;
  7873. std::vector<int> bucket_idx(candidates->size);
  7874. std::vector<int> histo(nbuckets, 0);
  7875. for (int i = 0; i < (int)candidates->size; ++i) {
  7876. const float val = candidates->data[i].logit;
  7877. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  7878. ib = std::max(0, std::min(nbuckets-1, ib));
  7879. bucket_idx[i] = ib;
  7880. ++histo[ib];
  7881. }
  7882. int nhave = 0;
  7883. int ib = nbuckets - 1;
  7884. for ( ; ib >= 0; --ib) {
  7885. nhave += histo[ib];
  7886. if (nhave >= k) break;
  7887. }
  7888. std::vector<llama_token_data> tmp_tokens(nhave);
  7889. auto ptr = tmp_tokens.data();
  7890. std::vector<llama_token_data*> bucket_ptrs;
  7891. bucket_ptrs.reserve(nbuckets - ib);
  7892. for (int j = nbuckets - 1; j >= ib; --j) {
  7893. bucket_ptrs.push_back(ptr);
  7894. ptr += histo[j];
  7895. }
  7896. for (int i = 0; i < (int)candidates->size; ++i) {
  7897. int j = bucket_idx[i];
  7898. if (j >= ib) {
  7899. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  7900. }
  7901. }
  7902. ptr = tmp_tokens.data();
  7903. int ndone = 0;
  7904. for (int j = nbuckets-1; j > ib; --j) {
  7905. std::sort(ptr, ptr + histo[j], comp);
  7906. ptr += histo[j];
  7907. ndone += histo[j];
  7908. }
  7909. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  7910. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  7911. }
  7912. candidates->sorted = true;
  7913. }
  7914. candidates->size = k;
  7915. if (ctx) {
  7916. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7917. }
  7918. }
  7919. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7920. if (p >= 1.0f) {
  7921. return;
  7922. }
  7923. llama_sample_softmax(ctx, candidates);
  7924. const int64_t t_start_sample_us = ggml_time_us();
  7925. // Compute the cumulative probabilities
  7926. float cum_sum = 0.0f;
  7927. size_t last_idx = candidates->size;
  7928. for (size_t i = 0; i < candidates->size; ++i) {
  7929. cum_sum += candidates->data[i].p;
  7930. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  7931. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  7932. if (cum_sum >= p && i + 1 >= min_keep) {
  7933. last_idx = i + 1;
  7934. break;
  7935. }
  7936. }
  7937. // Resize the output vector to keep only the top-p tokens
  7938. candidates->size = last_idx;
  7939. if (ctx) {
  7940. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7941. }
  7942. }
  7943. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7944. if (p <= 0.0f || !candidates->size) {
  7945. return;
  7946. }
  7947. const int64_t t_start_sample_us = ggml_time_us();
  7948. bool min_p_applied = false;
  7949. // if the candidates aren't sorted, try the unsorted implementation first
  7950. if (!candidates->sorted) {
  7951. std::vector<llama_token_data> filtered_tokens;
  7952. float max_logit = -FLT_MAX;
  7953. for (size_t i = 0; i < candidates->size; ++i) {
  7954. max_logit = std::max(max_logit, candidates->data[i].logit);
  7955. }
  7956. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  7957. for (size_t i = 0; i < candidates->size; ++i) {
  7958. if (candidates->data[i].logit >= min_logit) {
  7959. filtered_tokens.push_back(candidates->data[i]);
  7960. }
  7961. }
  7962. // if we have enough values the operation was a success
  7963. if (filtered_tokens.size() >= min_keep) {
  7964. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  7965. candidates->size = filtered_tokens.size();
  7966. min_p_applied = true;
  7967. }
  7968. }
  7969. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  7970. if (!min_p_applied) {
  7971. // Sort the logits in descending order
  7972. if (!candidates->sorted) {
  7973. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7974. return a.logit > b.logit;
  7975. });
  7976. candidates->sorted = true;
  7977. }
  7978. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  7979. size_t i = 1; // first token always matches
  7980. for (; i < candidates->size; ++i) {
  7981. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  7982. break; // prob too small
  7983. }
  7984. }
  7985. // Resize the output vector to keep only the matching tokens
  7986. candidates->size = i;
  7987. }
  7988. if (ctx) {
  7989. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7990. }
  7991. }
  7992. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  7993. if (z >= 1.0f || candidates->size <= 2) {
  7994. return;
  7995. }
  7996. llama_sample_softmax(nullptr, candidates);
  7997. const int64_t t_start_sample_us = ggml_time_us();
  7998. // Compute the first and second derivatives
  7999. std::vector<float> first_derivatives(candidates->size - 1);
  8000. std::vector<float> second_derivatives(candidates->size - 2);
  8001. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  8002. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  8003. }
  8004. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8005. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  8006. }
  8007. // Calculate absolute value of second derivatives
  8008. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8009. second_derivatives[i] = std::abs(second_derivatives[i]);
  8010. }
  8011. // Normalize the second derivatives
  8012. {
  8013. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  8014. if (second_derivatives_sum > 1e-6f) {
  8015. for (float & value : second_derivatives) {
  8016. value /= second_derivatives_sum;
  8017. }
  8018. } else {
  8019. for (float & value : second_derivatives) {
  8020. value = 1.0f / second_derivatives.size();
  8021. }
  8022. }
  8023. }
  8024. float cum_sum = 0.0f;
  8025. size_t last_idx = candidates->size;
  8026. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8027. cum_sum += second_derivatives[i];
  8028. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  8029. if (cum_sum > z && i >= min_keep) {
  8030. last_idx = i;
  8031. break;
  8032. }
  8033. }
  8034. // Resize the output vector to keep only the tokens above the tail location
  8035. candidates->size = last_idx;
  8036. if (ctx) {
  8037. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8038. }
  8039. }
  8040. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8041. // Reference implementation:
  8042. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  8043. if (p >= 1.0f) {
  8044. return;
  8045. }
  8046. // Compute the softmax of logits and calculate entropy
  8047. llama_sample_softmax(nullptr, candidates);
  8048. const int64_t t_start_sample_us = ggml_time_us();
  8049. float entropy = 0.0f;
  8050. for (size_t i = 0; i < candidates->size; ++i) {
  8051. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  8052. }
  8053. // Compute the absolute difference between negative log probability and entropy for each candidate
  8054. std::vector<float> shifted_scores;
  8055. for (size_t i = 0; i < candidates->size; ++i) {
  8056. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  8057. shifted_scores.push_back(shifted_score);
  8058. }
  8059. // Sort tokens based on the shifted_scores and their corresponding indices
  8060. std::vector<size_t> indices(candidates->size);
  8061. std::iota(indices.begin(), indices.end(), 0);
  8062. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  8063. return shifted_scores[a] < shifted_scores[b];
  8064. });
  8065. // Compute the cumulative probabilities
  8066. float cum_sum = 0.0f;
  8067. size_t last_idx = indices.size();
  8068. for (size_t i = 0; i < indices.size(); ++i) {
  8069. size_t idx = indices[i];
  8070. cum_sum += candidates->data[idx].p;
  8071. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  8072. if (cum_sum > p && i >= min_keep - 1) {
  8073. last_idx = i + 1;
  8074. break;
  8075. }
  8076. }
  8077. // Resize the output vector to keep only the locally typical tokens
  8078. std::vector<llama_token_data> new_candidates;
  8079. for (size_t i = 0; i < last_idx; ++i) {
  8080. size_t idx = indices[i];
  8081. new_candidates.push_back(candidates->data[idx]);
  8082. }
  8083. // Replace the data in candidates with the new_candidates data
  8084. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  8085. candidates->size = new_candidates.size();
  8086. candidates->sorted = false;
  8087. if (ctx) {
  8088. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8089. }
  8090. }
  8091. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  8092. const int64_t t_start_sample_us = ggml_time_us();
  8093. // no need to do anything if there is only one (or zero) candidates
  8094. if(candidates_p->size <= 1) {
  8095. return;
  8096. }
  8097. // Calculate maximum possible entropy
  8098. float max_entropy = -logf(1.0f / candidates_p->size);
  8099. llama_sample_softmax(nullptr, candidates_p);
  8100. // Calculate entropy of the softmax probabilities
  8101. float entropy = 0.0f;
  8102. for (size_t i = 0; i < candidates_p->size; ++i) {
  8103. float prob = candidates_p->data[i].p;
  8104. if (prob > 0.0f) { // Ensure no log(0)
  8105. entropy -= prob * logf(prob);
  8106. }
  8107. }
  8108. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  8109. float normalized_entropy = entropy / max_entropy;
  8110. // Map the normalized entropy to the desired temperature range using the power function
  8111. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  8112. #ifdef DEBUG
  8113. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  8114. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  8115. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  8116. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  8117. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  8118. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  8119. #endif
  8120. // Apply the dynamically calculated temperature scaling
  8121. for (size_t i = 0; i < candidates_p->size; ++i) {
  8122. candidates_p->data[i].logit /= dyn_temp;
  8123. }
  8124. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  8125. double max_l_double = candidates_p->data[0].logit;
  8126. double cum_sum_double = 0.0;
  8127. for (size_t i = 0; i < candidates_p->size; ++i) {
  8128. double p = exp(candidates_p->data[i].logit - max_l_double);
  8129. candidates_p->data[i].p = p; // Store the scaled probability
  8130. cum_sum_double += p;
  8131. }
  8132. for (size_t i = 0; i < candidates_p->size; ++i) {
  8133. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  8134. }
  8135. #ifdef DEBUG
  8136. // Print the updated top 25 probabilities after temperature scaling
  8137. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  8138. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  8139. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  8140. }
  8141. #endif
  8142. if (ctx) {
  8143. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8144. }
  8145. }
  8146. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8147. const int64_t t_start_sample_us = ggml_time_us();
  8148. for (size_t i = 0; i < candidates_p->size; ++i) {
  8149. candidates_p->data[i].logit /= temp;
  8150. }
  8151. if (ctx) {
  8152. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8153. }
  8154. }
  8155. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8156. llama_sample_temp(ctx, candidates_p, temp);
  8157. }
  8158. void llama_sample_repetition_penalties(
  8159. struct llama_context * ctx,
  8160. llama_token_data_array * candidates,
  8161. const llama_token * last_tokens,
  8162. size_t penalty_last_n,
  8163. float penalty_repeat,
  8164. float penalty_freq,
  8165. float penalty_present) {
  8166. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  8167. return;
  8168. }
  8169. const int64_t t_start_sample_us = ggml_time_us();
  8170. // Create a frequency map to count occurrences of each token in last_tokens
  8171. std::unordered_map<llama_token, int> token_count;
  8172. for (size_t i = 0; i < penalty_last_n; ++i) {
  8173. token_count[last_tokens[i]]++;
  8174. }
  8175. // Apply frequency and presence penalties to the candidates
  8176. for (size_t i = 0; i < candidates->size; ++i) {
  8177. const auto token_iter = token_count.find(candidates->data[i].id);
  8178. if (token_iter == token_count.end()) {
  8179. continue;
  8180. }
  8181. const int count = token_iter->second;
  8182. // 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.
  8183. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  8184. if (candidates->data[i].logit <= 0) {
  8185. candidates->data[i].logit *= penalty_repeat;
  8186. } else {
  8187. candidates->data[i].logit /= penalty_repeat;
  8188. }
  8189. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  8190. }
  8191. candidates->sorted = false;
  8192. if (ctx) {
  8193. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8194. }
  8195. }
  8196. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  8197. GGML_ASSERT(ctx);
  8198. const int64_t t_start_sample_us = ggml_time_us();
  8199. bool allow_eos = false;
  8200. for (const auto & stack : grammar->stacks) {
  8201. if (stack.empty()) {
  8202. allow_eos = true;
  8203. break;
  8204. }
  8205. }
  8206. const llama_token eos = llama_token_eos(&ctx->model);
  8207. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  8208. candidates_decoded.reserve(candidates->size);
  8209. std::vector<llama_grammar_candidate> candidates_grammar;
  8210. candidates_grammar.reserve(candidates->size);
  8211. for (size_t i = 0; i < candidates->size; ++i) {
  8212. const llama_token id = candidates->data[i].id;
  8213. const std::string piece = llama_token_to_piece(ctx, id);
  8214. if (id == eos) {
  8215. if (!allow_eos) {
  8216. candidates->data[i].logit = -INFINITY;
  8217. }
  8218. } else if (piece.empty() || piece[0] == 0) {
  8219. candidates->data[i].logit = -INFINITY;
  8220. } else {
  8221. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  8222. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  8223. }
  8224. }
  8225. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  8226. for (const auto & reject : rejects) {
  8227. candidates->data[reject.index].logit = -INFINITY;
  8228. }
  8229. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8230. }
  8231. static void llama_log_softmax(float * array, size_t size) {
  8232. float max_l = *std::max_element(array, array + size);
  8233. float sum = 0.f;
  8234. for (size_t i = 0; i < size; ++i) {
  8235. float p = expf(array[i] - max_l);
  8236. sum += p;
  8237. array[i] = p;
  8238. }
  8239. for (size_t i = 0; i < size; ++i) {
  8240. array[i] = logf(array[i] / sum);
  8241. }
  8242. }
  8243. void llama_sample_apply_guidance(
  8244. struct llama_context * ctx,
  8245. float * logits,
  8246. float * logits_guidance,
  8247. float scale) {
  8248. GGML_ASSERT(ctx);
  8249. const auto t_start_sample_us = ggml_time_us();
  8250. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  8251. llama_log_softmax(logits, n_vocab);
  8252. llama_log_softmax(logits_guidance, n_vocab);
  8253. for (int i = 0; i < n_vocab; ++i) {
  8254. auto & l = logits[i];
  8255. const auto & g = logits_guidance[i];
  8256. l = scale * (l - g) + g;
  8257. }
  8258. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8259. }
  8260. void llama_sample_classifier_free_guidance(
  8261. struct llama_context * ctx,
  8262. llama_token_data_array * candidates,
  8263. struct llama_context * guidance_ctx,
  8264. float scale) {
  8265. GGML_ASSERT(ctx);
  8266. int64_t t_start_sample_us;
  8267. t_start_sample_us = ggml_time_us();
  8268. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  8269. GGML_ASSERT(n_vocab == candidates->size);
  8270. GGML_ASSERT(!candidates->sorted);
  8271. std::vector<float> logits_base(n_vocab);
  8272. for (size_t i = 0; i < n_vocab; ++i) {
  8273. logits_base[i] = candidates->data[i].logit;
  8274. }
  8275. float * logits_guidance = llama_get_logits(guidance_ctx);
  8276. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8277. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  8278. t_start_sample_us = ggml_time_us();
  8279. for (size_t i = 0; i < n_vocab; ++i) {
  8280. candidates->data[i].logit = logits_base[i];
  8281. }
  8282. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8283. }
  8284. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  8285. GGML_ASSERT(ctx);
  8286. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  8287. int64_t t_start_sample_us;
  8288. t_start_sample_us = ggml_time_us();
  8289. llama_sample_softmax(nullptr, candidates);
  8290. // Estimate s_hat using the most probable m tokens
  8291. float s_hat = 0.0;
  8292. float sum_ti_bi = 0.0;
  8293. float sum_ti_sq = 0.0;
  8294. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  8295. float t_i = logf(float(i + 2) / float(i + 1));
  8296. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  8297. sum_ti_bi += t_i * b_i;
  8298. sum_ti_sq += t_i * t_i;
  8299. }
  8300. s_hat = sum_ti_bi / sum_ti_sq;
  8301. // Compute k from the estimated s_hat and target surprise value
  8302. float epsilon_hat = s_hat - 1;
  8303. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  8304. // Sample the next word X using top-k sampling
  8305. llama_sample_top_k(nullptr, candidates, int(k), 1);
  8306. if (ctx) {
  8307. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8308. }
  8309. llama_token X = llama_sample_token(ctx, candidates);
  8310. t_start_sample_us = ggml_time_us();
  8311. // Compute error as the difference between observed surprise and target surprise value
  8312. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8313. return candidate.id == X;
  8314. }));
  8315. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8316. float e = observed_surprise - tau;
  8317. // Update mu using the learning rate and error
  8318. *mu = *mu - eta * e;
  8319. if (ctx) {
  8320. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8321. }
  8322. return X;
  8323. }
  8324. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  8325. int64_t t_start_sample_us;
  8326. t_start_sample_us = ggml_time_us();
  8327. llama_sample_softmax(ctx, candidates);
  8328. // Truncate the words with surprise values greater than mu
  8329. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8330. return -log2f(candidate.p) > *mu;
  8331. }));
  8332. if (candidates->size == 0) {
  8333. candidates->size = 1;
  8334. }
  8335. if (ctx) {
  8336. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8337. }
  8338. // Normalize the probabilities of the remaining words
  8339. llama_sample_softmax(ctx, candidates);
  8340. // Sample the next word X from the remaining words
  8341. llama_token X = llama_sample_token(ctx, candidates);
  8342. t_start_sample_us = ggml_time_us();
  8343. // Compute error as the difference between observed surprise and target surprise value
  8344. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8345. return candidate.id == X;
  8346. }));
  8347. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8348. float e = observed_surprise - tau;
  8349. // Update mu using the learning rate and error
  8350. *mu = *mu - eta * e;
  8351. if (ctx) {
  8352. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8353. }
  8354. return X;
  8355. }
  8356. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  8357. const int64_t t_start_sample_us = ggml_time_us();
  8358. // Find max element
  8359. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8360. return a.logit < b.logit;
  8361. });
  8362. llama_token result = max_iter->id;
  8363. if (ctx) {
  8364. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8365. ctx->n_sample++;
  8366. }
  8367. return result;
  8368. }
  8369. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  8370. GGML_ASSERT(ctx);
  8371. const int64_t t_start_sample_us = ggml_time_us();
  8372. llama_sample_softmax(nullptr, candidates);
  8373. std::vector<float> probs;
  8374. probs.reserve(candidates->size);
  8375. for (size_t i = 0; i < candidates->size; ++i) {
  8376. probs.push_back(candidates->data[i].p);
  8377. }
  8378. std::discrete_distribution<> dist(probs.begin(), probs.end());
  8379. auto & rng = ctx->rng;
  8380. int idx = dist(rng);
  8381. llama_token result = candidates->data[idx].id;
  8382. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8383. ctx->n_sample++;
  8384. return result;
  8385. }
  8386. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  8387. const int64_t t_start_sample_us = ggml_time_us();
  8388. if (token == llama_token_eos(&ctx->model)) {
  8389. for (const auto & stack : grammar->stacks) {
  8390. if (stack.empty()) {
  8391. return;
  8392. }
  8393. }
  8394. GGML_ASSERT(false);
  8395. }
  8396. const std::string piece = llama_token_to_piece(ctx, token);
  8397. // Note terminating 0 in decoded string
  8398. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  8399. const auto & code_points = decoded.first;
  8400. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  8401. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  8402. }
  8403. grammar->partial_utf8 = decoded.second;
  8404. GGML_ASSERT(!grammar->stacks.empty());
  8405. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8406. }
  8407. //
  8408. // Beam search
  8409. //
  8410. struct llama_beam {
  8411. std::vector<llama_token> tokens;
  8412. float p; // Cumulative beam probability (renormalized relative to all beams)
  8413. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  8414. // Sort beams by probability. In case of ties, prefer beams at eob.
  8415. bool operator<(const llama_beam & rhs) const {
  8416. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  8417. }
  8418. // Shift off first n tokens and discard them.
  8419. void shift_tokens(const size_t n) {
  8420. if (n) {
  8421. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  8422. tokens.resize(tokens.size() - n);
  8423. }
  8424. }
  8425. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  8426. };
  8427. // A struct for calculating logit-related info.
  8428. struct llama_logit_info {
  8429. const float * const logits;
  8430. const int n_vocab;
  8431. const float max_l;
  8432. const float normalizer;
  8433. struct sum_exp {
  8434. float max_l;
  8435. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  8436. };
  8437. llama_logit_info(llama_context * ctx)
  8438. : logits(llama_get_logits(ctx))
  8439. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  8440. , max_l(*std::max_element(logits, logits + n_vocab))
  8441. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  8442. { }
  8443. llama_token_data get_token_data(const llama_token token_id) const {
  8444. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  8445. return {token_id, logits[token_id], p};
  8446. }
  8447. // Return top k token_data by logit.
  8448. std::vector<llama_token_data> top_k(size_t k) {
  8449. std::vector<llama_token_data> min_heap; // min-heap by logit
  8450. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  8451. min_heap.reserve(k_min);
  8452. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  8453. min_heap.push_back(get_token_data(token_id));
  8454. }
  8455. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  8456. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  8457. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  8458. if (min_heap.front().logit < logits[token_id]) {
  8459. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  8460. min_heap.back().id = token_id;
  8461. min_heap.back().logit = logits[token_id];
  8462. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  8463. }
  8464. }
  8465. return min_heap;
  8466. }
  8467. float probability_from_logit(float logit) const {
  8468. return normalizer * std::exp(logit - max_l);
  8469. }
  8470. };
  8471. struct llama_beam_search_data {
  8472. llama_context * ctx;
  8473. size_t n_beams;
  8474. int n_past;
  8475. int n_predict;
  8476. std::vector<llama_beam> beams;
  8477. std::vector<llama_beam> next_beams;
  8478. // Re-calculated on each loop iteration
  8479. size_t common_prefix_length;
  8480. // Used to communicate to/from callback on beams state.
  8481. std::vector<llama_beam_view> beam_views;
  8482. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  8483. : ctx(ctx)
  8484. , n_beams(n_beams)
  8485. , n_past(n_past)
  8486. , n_predict(n_predict)
  8487. , beam_views(n_beams) {
  8488. beams.reserve(n_beams);
  8489. next_beams.reserve(n_beams);
  8490. }
  8491. // Collapse beams to a single beam given by index.
  8492. void collapse_beams(const size_t beam_idx) {
  8493. if (0u < beam_idx) {
  8494. std::swap(beams[0], beams[beam_idx]);
  8495. }
  8496. beams.resize(1);
  8497. }
  8498. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  8499. // The repetitive patterns below reflect the 2 stages of heaps:
  8500. // * Gather elements until the vector is full, then call std::make_heap() on it.
  8501. // * If the heap is full and a new element is found that should be included, pop the
  8502. // least element to the back(), replace it with the new, then push it into the heap.
  8503. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  8504. // Min-heaps use a greater-than comparator.
  8505. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  8506. if (beam.eob) {
  8507. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  8508. if (next_beams.size() < n_beams) {
  8509. next_beams.push_back(std::move(beam));
  8510. if (next_beams.size() == n_beams) {
  8511. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8512. }
  8513. } else if (next_beams.front().p < beam.p) {
  8514. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8515. next_beams.back() = std::move(beam);
  8516. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8517. }
  8518. } else {
  8519. // beam is not at end-of-sentence, so branch with next top_k tokens.
  8520. if (!beam.tokens.empty()) {
  8521. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  8522. }
  8523. llama_logit_info logit_info(ctx);
  8524. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  8525. size_t i=0;
  8526. if (next_beams.size() < n_beams) {
  8527. for (; next_beams.size() < n_beams ; ++i) {
  8528. llama_beam next_beam = beam;
  8529. next_beam.tokens.push_back(next_tokens[i].id);
  8530. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8531. next_beams.push_back(std::move(next_beam));
  8532. }
  8533. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8534. } else {
  8535. for (; next_beams.front().p == 0.0f ; ++i) {
  8536. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8537. next_beams.back() = beam;
  8538. next_beams.back().tokens.push_back(next_tokens[i].id);
  8539. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8540. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8541. }
  8542. }
  8543. for (; i < n_beams ; ++i) {
  8544. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  8545. if (next_beams.front().p < next_p) {
  8546. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8547. next_beams.back() = beam;
  8548. next_beams.back().tokens.push_back(next_tokens[i].id);
  8549. next_beams.back().p = next_p;
  8550. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8551. }
  8552. }
  8553. }
  8554. }
  8555. // Find common_prefix_length based on beams.
  8556. // Requires beams is not empty.
  8557. size_t find_common_prefix_length() {
  8558. size_t common_prefix_length = beams[0].tokens.size();
  8559. for (size_t i = 1 ; i < beams.size() ; ++i) {
  8560. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  8561. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  8562. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  8563. common_prefix_length = j;
  8564. break;
  8565. }
  8566. }
  8567. }
  8568. return common_prefix_length;
  8569. }
  8570. // Construct beams_state to send back to caller via the callback function.
  8571. // Side effect: set common_prefix_length = find_common_prefix_length();
  8572. llama_beams_state get_beams_state(const bool last_call) {
  8573. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8574. beam_views[i] = beams[i].view();
  8575. }
  8576. common_prefix_length = find_common_prefix_length();
  8577. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  8578. }
  8579. // Loop:
  8580. // * while i < n_predict, AND
  8581. // * any of the beams have not yet reached end-of-beam (eob), AND
  8582. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  8583. // (since all other beam probabilities can only decrease)
  8584. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  8585. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  8586. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  8587. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  8588. !beams[top_beam_index()].eob ; ++i) {
  8589. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  8590. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  8591. if (common_prefix_length) {
  8592. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  8593. n_past += common_prefix_length;
  8594. }
  8595. // Zero-out next_beam probabilities to place them last in following min-heap.
  8596. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  8597. for (llama_beam & beam : beams) {
  8598. beam.shift_tokens(common_prefix_length);
  8599. fill_next_beams_by_top_probabilities(beam);
  8600. }
  8601. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  8602. beams.swap(next_beams);
  8603. renormalize_beam_probabilities(beams);
  8604. }
  8605. collapse_beams(top_beam_index());
  8606. callback(callback_data, get_beams_state(true));
  8607. }
  8608. // As beams grow, the cumulative probabilities decrease.
  8609. // Renormalize them to avoid floating point underflow.
  8610. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  8611. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  8612. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  8613. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  8614. }
  8615. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  8616. size_t top_beam_index() {
  8617. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  8618. }
  8619. // Copy (p,eob) for each beam which may have been changed by the callback.
  8620. void update_beams_from_beam_views() {
  8621. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8622. beams[i].p = beam_views[i].p;
  8623. beams[i].eob = beam_views[i].eob;
  8624. }
  8625. }
  8626. };
  8627. void llama_beam_search(llama_context * ctx,
  8628. llama_beam_search_callback_fn_t callback, void * callback_data,
  8629. size_t n_beams, int n_past, int n_predict) {
  8630. assert(ctx);
  8631. const int64_t t_start_sample_us = ggml_time_us();
  8632. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  8633. beam_search_data.loop(callback, callback_data);
  8634. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8635. ctx->n_sample++;
  8636. }
  8637. //
  8638. // quantization
  8639. //
  8640. struct quantize_state_internal {
  8641. const llama_model & model;
  8642. const llama_model_quantize_params * params;
  8643. int n_attention_wv = 0;
  8644. int n_ffn_down = 0;
  8645. int n_ffn_gate = 0;
  8646. int n_ffn_up = 0;
  8647. int i_attention_wv = 0;
  8648. int i_ffn_down = 0;
  8649. int i_ffn_gate = 0;
  8650. int i_ffn_up = 0;
  8651. int n_k_quantized = 0;
  8652. int n_fallback = 0;
  8653. bool has_imatrix = false;
  8654. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  8655. : model(model)
  8656. , params(params)
  8657. {}
  8658. };
  8659. static void llama_convert_tensor_internal(
  8660. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  8661. const size_t nelements, const int nthread
  8662. ) {
  8663. if (output.size() < nelements) {
  8664. output.resize(nelements);
  8665. }
  8666. float * f32_output = (float *) output.data();
  8667. ggml_type_traits_t qtype;
  8668. if (ggml_is_quantized(tensor->type)) {
  8669. qtype = ggml_internal_get_type_traits(tensor->type);
  8670. if (qtype.to_float == NULL) {
  8671. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  8672. }
  8673. } else if (tensor->type != GGML_TYPE_F16) {
  8674. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  8675. }
  8676. if (nthread < 2) {
  8677. if (tensor->type == GGML_TYPE_F16) {
  8678. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  8679. } else if (ggml_is_quantized(tensor->type)) {
  8680. qtype.to_float(tensor->data, f32_output, nelements);
  8681. } else {
  8682. GGML_ASSERT(false); // unreachable
  8683. }
  8684. return;
  8685. }
  8686. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  8687. size_t block_size_bytes = ggml_type_size(tensor->type);
  8688. GGML_ASSERT(nelements % block_size == 0);
  8689. size_t nblocks = nelements / block_size;
  8690. size_t blocks_per_thread = nblocks / nthread;
  8691. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  8692. size_t in_buff_offs = 0;
  8693. size_t out_buff_offs = 0;
  8694. for (int tnum = 0; tnum < nthread; tnum++) {
  8695. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  8696. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  8697. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  8698. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  8699. if (typ == GGML_TYPE_F16) {
  8700. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  8701. } else {
  8702. qtype.to_float(inbuf, outbuf, nels);
  8703. }
  8704. };
  8705. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  8706. in_buff_offs += thr_block_bytes;
  8707. out_buff_offs += thr_elems;
  8708. }
  8709. for (auto & w : workers) { w.join(); }
  8710. workers.clear();
  8711. }
  8712. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  8713. const std::string name = ggml_get_name(tensor);
  8714. // TODO: avoid hardcoded tensor names - use the TN_* constants
  8715. const llm_arch arch = qs.model.arch;
  8716. const auto tn = LLM_TN(arch);
  8717. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  8718. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  8719. };
  8720. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  8721. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  8722. if (n_expert > 1) {
  8723. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  8724. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  8725. // for getting the current layer as I initially thought, and we need to resort to parsing the
  8726. // tensor name.
  8727. n_layer /= n_expert;
  8728. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  8729. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  8730. }
  8731. if (i_layer < 0 || i_layer >= n_layer) {
  8732. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  8733. }
  8734. }
  8735. return std::make_pair(i_layer, n_layer);
  8736. };
  8737. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  8738. int nx = tensor->ne[0];
  8739. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  8740. new_type = GGML_TYPE_Q8_0;
  8741. }
  8742. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8743. new_type = GGML_TYPE_Q5_K;
  8744. }
  8745. else if (new_type != GGML_TYPE_Q8_0) {
  8746. new_type = GGML_TYPE_Q6_K;
  8747. }
  8748. } else if (name == "token_embd.weight") {
  8749. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8750. new_type = GGML_TYPE_Q2_K;
  8751. }
  8752. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8753. new_type = GGML_TYPE_Q4_K;
  8754. }
  8755. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8756. if (name.find("attn_v.weight") != std::string::npos) {
  8757. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  8758. else new_type = GGML_TYPE_Q2_K;
  8759. ++qs.i_attention_wv;
  8760. }
  8761. else if (name.find("ffn_down") != std::string::npos) {
  8762. if (qs.i_ffn_down < qs.n_ffn_down/8) new_type = GGML_TYPE_Q2_K;
  8763. ++qs.i_ffn_down;
  8764. }
  8765. else if (name.find("attn_output.weight") != std::string::npos) {
  8766. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  8767. }
  8768. } else if (name.find("attn_v.weight") != std::string::npos) {
  8769. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  8770. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8771. }
  8772. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  8773. new_type = GGML_TYPE_Q4_K;
  8774. }
  8775. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8776. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_Q3_K : GGML_TYPE_IQ3_XXS;
  8777. }
  8778. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8779. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8780. }
  8781. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  8782. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL && qs.model.hparams.n_gqa() >= 4) {
  8783. new_type = GGML_TYPE_Q5_K;
  8784. }
  8785. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  8786. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  8787. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  8788. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  8789. (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;
  8790. if (qs.model.type == MODEL_70B) {
  8791. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  8792. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  8793. // nearly negligible increase in model size by quantizing this tensor with more bits:
  8794. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  8795. }
  8796. if (qs.model.hparams.n_expert == 8) {
  8797. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8798. // TODO: explore better strategies
  8799. new_type = GGML_TYPE_Q8_0;
  8800. }
  8801. ++qs.i_attention_wv;
  8802. } else if (name.find("attn_k.weight") != std::string::npos) {
  8803. if (qs.model.hparams.n_expert == 8) {
  8804. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8805. // TODO: explore better strategies
  8806. new_type = GGML_TYPE_Q8_0;
  8807. }
  8808. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  8809. new_type = GGML_TYPE_Q2_K;
  8810. }
  8811. } else if (name.find("ffn_down") != std::string::npos) {
  8812. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  8813. int i_layer = info.first, n_layer = info.second;
  8814. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8815. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  8816. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  8817. }
  8818. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  8819. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8820. }
  8821. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8822. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  8823. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  8824. : GGML_TYPE_Q3_K;
  8825. }
  8826. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  8827. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  8828. }
  8829. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  8830. if (arch == LLM_ARCH_FALCON) {
  8831. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  8832. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8833. } else {
  8834. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  8835. }
  8836. }
  8837. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL && !qs.has_imatrix) {
  8838. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q5_K;
  8839. }
  8840. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  8841. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  8842. new_type = GGML_TYPE_Q5_K;
  8843. }
  8844. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  8845. && qs.has_imatrix && i_layer < n_layer/8) {
  8846. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  8847. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  8848. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  8849. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  8850. }
  8851. ++qs.i_ffn_down;
  8852. } else if (name.find("attn_output.weight") != std::string::npos) {
  8853. if (arch != LLM_ARCH_FALCON) {
  8854. if (qs.model.hparams.n_expert == 8) {
  8855. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  8856. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  8857. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  8858. new_type = GGML_TYPE_Q5_K;
  8859. }
  8860. } else {
  8861. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  8862. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_Q3_K;
  8863. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  8864. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  8865. }
  8866. } else {
  8867. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  8868. }
  8869. }
  8870. else if (name.find("attn_qkv.weight") != std::string::npos) {
  8871. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  8872. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  8873. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  8874. }
  8875. else if (name.find("ffn_gate") != std::string::npos) {
  8876. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  8877. int i_layer = info.first, n_layer = info.second;
  8878. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  8879. new_type = GGML_TYPE_Q2_K;
  8880. }
  8881. ++qs.i_ffn_gate;
  8882. }
  8883. else if (name.find("ffn_up") != std::string::npos) {
  8884. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  8885. int i_layer = info.first, n_layer = info.second;
  8886. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  8887. new_type = GGML_TYPE_Q2_K;
  8888. }
  8889. ++qs.i_ffn_up;
  8890. }
  8891. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8892. //}
  8893. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  8894. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  8895. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8896. //}
  8897. // This can be used to reduce the size of the Q5_K_S model.
  8898. // The associated PPL increase is fully in line with the size reduction
  8899. //else {
  8900. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  8901. //}
  8902. bool convert_incompatible_tensor = false;
  8903. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  8904. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  8905. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS ||
  8906. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8907. int nx = tensor->ne[0];
  8908. int ny = tensor->ne[1];
  8909. if (nx % QK_K != 0) {
  8910. 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));
  8911. convert_incompatible_tensor = true;
  8912. } else {
  8913. ++qs.n_k_quantized;
  8914. }
  8915. }
  8916. if (convert_incompatible_tensor) {
  8917. switch (new_type) {
  8918. case GGML_TYPE_IQ2_XXS:
  8919. case GGML_TYPE_IQ2_XS:
  8920. case GGML_TYPE_IQ3_XXS:
  8921. case GGML_TYPE_IQ1_S:
  8922. case GGML_TYPE_Q2_K:
  8923. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_IQ4_NL; break;
  8924. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  8925. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  8926. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  8927. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  8928. }
  8929. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  8930. ++qs.n_fallback;
  8931. }
  8932. return new_type;
  8933. }
  8934. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  8935. ggml_type quantized_type;
  8936. llama_ftype ftype = params->ftype;
  8937. switch (params->ftype) {
  8938. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  8939. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  8940. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  8941. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  8942. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  8943. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  8944. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  8945. // K-quants
  8946. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  8947. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  8948. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:
  8949. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  8950. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  8951. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  8952. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  8953. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  8954. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  8955. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  8956. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  8957. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: quantized_type = GGML_TYPE_IQ2_XXS; break;
  8958. case LLAMA_FTYPE_MOSTLY_IQ2_XS: quantized_type = GGML_TYPE_IQ2_XS; break;
  8959. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: quantized_type = GGML_TYPE_IQ3_XXS; break;
  8960. case LLAMA_FTYPE_MOSTLY_IQ1_S: quantized_type = GGML_TYPE_IQ1_S; break;
  8961. case LLAMA_FTYPE_MOSTLY_IQ4_NL: quantized_type = GGML_TYPE_IQ4_NL; break;
  8962. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  8963. }
  8964. int nthread = params->nthread;
  8965. if (nthread <= 0) {
  8966. nthread = std::thread::hardware_concurrency();
  8967. }
  8968. // mmap consistently increases speed Linux, and also increases speed on Windows with
  8969. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  8970. #if defined(__linux__) || defined(_WIN32)
  8971. constexpr bool use_mmap = true;
  8972. #else
  8973. constexpr bool use_mmap = false;
  8974. #endif
  8975. llama_model_loader ml(fname_inp, use_mmap, NULL);
  8976. ml.init_mapping(false); // no prefetching?
  8977. llama_model model;
  8978. llm_load_arch(ml, model);
  8979. llm_load_hparams(ml, model);
  8980. struct quantize_state_internal qs(model, params);
  8981. if (params->only_copy) {
  8982. ftype = model.ftype;
  8983. }
  8984. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  8985. if (params->imatrix) {
  8986. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  8987. if (imatrix_data) {
  8988. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  8989. qs.has_imatrix = true;
  8990. }
  8991. }
  8992. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  8993. struct gguf_context * ctx_out = gguf_init_empty();
  8994. // copy the KV pairs from the input file
  8995. gguf_set_kv (ctx_out, ml.ctx_gguf);
  8996. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  8997. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  8998. for (int i = 0; i < ml.n_tensors; ++i) {
  8999. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9000. const std::string name = ggml_get_name(meta);
  9001. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9002. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  9003. ++qs.n_attention_wv;
  9004. }
  9005. else if (name.find("ffn_down") != std::string::npos) {
  9006. ++qs.n_ffn_down;
  9007. }
  9008. else if (name.find("ffn_gate") != std::string::npos) {
  9009. ++qs.n_ffn_gate;
  9010. }
  9011. else if (name.find("ffn_up") != std::string::npos) {
  9012. ++qs.n_ffn_up;
  9013. }
  9014. }
  9015. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  9016. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  9017. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  9018. }
  9019. size_t total_size_org = 0;
  9020. size_t total_size_new = 0;
  9021. std::vector<int64_t> hist_all(1 << 4, 0);
  9022. std::vector<std::thread> workers;
  9023. workers.reserve(nthread);
  9024. std::mutex mutex;
  9025. int idx = 0;
  9026. std::vector<no_init<uint8_t>> read_data;
  9027. std::vector<no_init<uint8_t>> work;
  9028. std::vector<no_init<float>> f32_conv_buf;
  9029. // populate the original tensors so we get an initial meta data
  9030. for (int i = 0; i < ml.n_tensors; ++i) {
  9031. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9032. gguf_add_tensor(ctx_out, meta);
  9033. }
  9034. std::ofstream fout(fname_out, std::ios::binary);
  9035. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  9036. const size_t meta_size = gguf_get_meta_size(ctx_out);
  9037. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  9038. // placeholder for the meta data
  9039. ::zeros(fout, meta_size);
  9040. for (int i = 0; i < ml.n_tensors; ++i) {
  9041. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  9042. const std::string name = ggml_get_name(tensor);
  9043. if (!ml.use_mmap) {
  9044. if (read_data.size() < ggml_nbytes(tensor)) {
  9045. read_data.resize(ggml_nbytes(tensor));
  9046. }
  9047. tensor->data = read_data.data();
  9048. }
  9049. ml.load_data_for(tensor);
  9050. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  9051. ++idx, ml.n_tensors,
  9052. ggml_get_name(tensor),
  9053. llama_format_tensor_shape(tensor).c_str(),
  9054. ggml_type_name(tensor->type));
  9055. // This used to be a regex, but <regex> has an extreme cost to compile times.
  9056. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  9057. // quantize only 2D tensors
  9058. quantize &= (ggml_n_dims(tensor) == 2);
  9059. quantize &= params->quantize_output_tensor || name != "output.weight";
  9060. quantize &= !params->only_copy;
  9061. // do not quantize expert gating tensors
  9062. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_FFN_GATE_INP, "weight");
  9063. // do not quantize positional embeddings and token types (BERT)
  9064. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  9065. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  9066. enum ggml_type new_type;
  9067. void * new_data;
  9068. size_t new_size;
  9069. if (quantize) {
  9070. new_type = quantized_type;
  9071. if (!params->pure) {
  9072. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  9073. }
  9074. // If we've decided to quantize to the same type the tensor is already
  9075. // in then there's nothing to do.
  9076. quantize = tensor->type != new_type;
  9077. }
  9078. if (!quantize) {
  9079. new_type = tensor->type;
  9080. new_data = tensor->data;
  9081. new_size = ggml_nbytes(tensor);
  9082. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  9083. } else {
  9084. const size_t nelements = ggml_nelements(tensor);
  9085. const float * imatrix = nullptr;
  9086. if (imatrix_data) {
  9087. auto it = imatrix_data->find(tensor->name);
  9088. if (it == imatrix_data->end()) {
  9089. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  9090. } else {
  9091. if (it->second.size() == (size_t)tensor->ne[0]) {
  9092. imatrix = it->second.data();
  9093. } else {
  9094. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  9095. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  9096. }
  9097. }
  9098. }
  9099. if ((new_type == GGML_TYPE_IQ2_XXS ||
  9100. new_type == GGML_TYPE_IQ2_XS ||
  9101. new_type == GGML_TYPE_IQ1_S ||
  9102. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  9103. LLAMA_LOG_ERROR("\n\n============================================================\n");
  9104. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  9105. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  9106. LLAMA_LOG_ERROR("============================================================\n\n");
  9107. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  9108. }
  9109. float * f32_data;
  9110. if (tensor->type == GGML_TYPE_F32) {
  9111. f32_data = (float *) tensor->data;
  9112. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  9113. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  9114. } else {
  9115. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  9116. f32_data = (float *) f32_conv_buf.data();
  9117. }
  9118. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  9119. fflush(stdout);
  9120. if (work.size() < nelements * 4) {
  9121. work.resize(nelements * 4); // upper bound on size
  9122. }
  9123. new_data = work.data();
  9124. std::array<int64_t, 1 << 4> hist_cur = {};
  9125. const int n_per_row = tensor->ne[0];
  9126. const int nrows = nelements / n_per_row;
  9127. static const int min_chunk_size = 32 * 512;
  9128. 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);
  9129. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  9130. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  9131. if (nthread_use < 2) {
  9132. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  9133. } else {
  9134. int counter = 0;
  9135. new_size = 0;
  9136. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  9137. nrows, n_per_row, imatrix]() {
  9138. std::array<int64_t, 1 << 4> local_hist = {};
  9139. const int nrows_per_chunk = chunk_size / n_per_row;
  9140. size_t local_size = 0;
  9141. while (true) {
  9142. std::unique_lock<std::mutex> lock(mutex);
  9143. int first_row = counter; counter += nrows_per_chunk;
  9144. if (first_row >= nrows) {
  9145. if (local_size > 0) {
  9146. for (int j=0; j<int(local_hist.size()); ++j) {
  9147. hist_cur[j] += local_hist[j];
  9148. }
  9149. new_size += local_size;
  9150. }
  9151. break;
  9152. }
  9153. lock.unlock();
  9154. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  9155. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  9156. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  9157. }
  9158. };
  9159. for (int it = 0; it < nthread_use - 1; ++it) {
  9160. workers.emplace_back(compute);
  9161. }
  9162. compute();
  9163. for (auto & w : workers) { w.join(); }
  9164. workers.clear();
  9165. }
  9166. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  9167. int64_t tot_count = 0;
  9168. for (size_t i = 0; i < hist_cur.size(); i++) {
  9169. hist_all[i] += hist_cur[i];
  9170. tot_count += hist_cur[i];
  9171. }
  9172. if (tot_count > 0) {
  9173. LLAMA_LOG_INFO(" | hist: ");
  9174. for (size_t i = 0; i < hist_cur.size(); i++) {
  9175. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  9176. }
  9177. }
  9178. LLAMA_LOG_INFO("\n");
  9179. }
  9180. total_size_org += ggml_nbytes(tensor);
  9181. total_size_new += new_size;
  9182. // update the gguf meta data as we go
  9183. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  9184. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  9185. // write tensor data + padding
  9186. fout.write((const char *) new_data, new_size);
  9187. zeros(fout, GGML_PAD(new_size, align) - new_size);
  9188. }
  9189. // go back to beginning of file and write the updated meta data
  9190. {
  9191. fout.seekp(0);
  9192. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  9193. gguf_get_meta_data(ctx_out, data.data());
  9194. fout.write((const char *) data.data(), data.size());
  9195. }
  9196. fout.close();
  9197. gguf_free(ctx_out);
  9198. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  9199. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  9200. // print histogram for all tensors
  9201. {
  9202. int64_t sum_all = 0;
  9203. for (size_t i = 0; i < hist_all.size(); i++) {
  9204. sum_all += hist_all[i];
  9205. }
  9206. if (sum_all > 0) {
  9207. LLAMA_LOG_INFO("%s: hist: ", __func__);
  9208. for (size_t i = 0; i < hist_all.size(); i++) {
  9209. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  9210. }
  9211. LLAMA_LOG_INFO("\n");
  9212. }
  9213. }
  9214. if (qs.n_fallback > 0) {
  9215. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  9216. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  9217. }
  9218. }
  9219. static int llama_apply_lora_from_file_internal(
  9220. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  9221. ) {
  9222. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  9223. const int64_t t_start_lora_us = ggml_time_us();
  9224. llama_file fin(path_lora, "rb");
  9225. // verify magic and version
  9226. {
  9227. uint32_t magic = fin.read_u32();
  9228. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  9229. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  9230. return 1;
  9231. }
  9232. uint32_t format_version = fin.read_u32();
  9233. if (format_version != 1) {
  9234. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  9235. return 1;
  9236. }
  9237. }
  9238. int32_t lora_r = fin.read_u32();
  9239. int32_t lora_alpha = fin.read_u32();
  9240. float scaling = scale * (float)lora_alpha / (float)lora_r;
  9241. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  9242. // load base model
  9243. std::unique_ptr<llama_model_loader> ml;
  9244. if (path_base_model) {
  9245. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  9246. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  9247. ml->init_mapping(/*prefetch*/ false); // no prefetching
  9248. }
  9249. struct tensor_meta {
  9250. std::string name;
  9251. ggml_type type;
  9252. int32_t ne[2];
  9253. size_t offset;
  9254. };
  9255. std::map<std::string, tensor_meta> tensor_meta_map;
  9256. // load all tensor meta
  9257. while (true) {
  9258. if (fin.tell() == fin.size) {
  9259. // eof
  9260. break;
  9261. }
  9262. int32_t n_dims;
  9263. int32_t name_len;
  9264. int32_t ftype;
  9265. fin.read_raw(&n_dims, sizeof(n_dims));
  9266. fin.read_raw(&name_len, sizeof(name_len));
  9267. fin.read_raw(&ftype, sizeof(ftype));
  9268. if (n_dims != 1 && n_dims != 2) {
  9269. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  9270. return 1;
  9271. }
  9272. int32_t ne[2] = { 1, 1 };
  9273. for (int i = 0; i < n_dims; ++i) {
  9274. fin.read_raw(&ne[i], sizeof(ne[i]));
  9275. }
  9276. std::string name;
  9277. {
  9278. GGML_ASSERT(name_len < GGML_MAX_NAME);
  9279. char buf[GGML_MAX_NAME];
  9280. fin.read_raw(buf, name_len);
  9281. name = std::string(buf, name_len);
  9282. }
  9283. // check for lora suffix
  9284. std::string lora_suffix;
  9285. if (name.length() > 6) {
  9286. lora_suffix = name.substr(name.length() - 6);
  9287. }
  9288. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  9289. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  9290. return 1;
  9291. }
  9292. // tensor type
  9293. ggml_type wtype;
  9294. switch (ftype) {
  9295. case 0: wtype = GGML_TYPE_F32; break;
  9296. case 1: wtype = GGML_TYPE_F16; break;
  9297. default:
  9298. {
  9299. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  9300. __func__, ftype);
  9301. return 1;
  9302. }
  9303. }
  9304. // data offset
  9305. size_t offset = fin.tell();
  9306. offset = (offset + 31) & -32;
  9307. // skip tensor data
  9308. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  9309. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  9310. }
  9311. bool warned = false;
  9312. int n_tensors = 0;
  9313. // apply
  9314. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  9315. if (backend_cpu == nullptr) {
  9316. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  9317. return 1;
  9318. }
  9319. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  9320. std::vector<no_init<uint8_t>> read_buf;
  9321. for (const auto & it : model.tensors_by_name) {
  9322. const std::string & base_name = it.first;
  9323. ggml_tensor * model_t = it.second;
  9324. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  9325. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  9326. continue;
  9327. }
  9328. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  9329. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  9330. ggml_init_params lora_init_params = {
  9331. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  9332. /* .mem_buffer */ nullptr,
  9333. /* .no_alloc */ true,
  9334. };
  9335. ggml_context * lora_ctx = ggml_init(lora_init_params);
  9336. if (lora_ctx == nullptr) {
  9337. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  9338. ggml_backend_free(backend_cpu);
  9339. return 1;
  9340. }
  9341. // create tensors
  9342. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  9343. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  9344. ggml_set_name(loraA, metaA.name.c_str());
  9345. ggml_set_name(loraB, metaB.name.c_str());
  9346. ggml_tensor * base_t;
  9347. if (ml) {
  9348. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  9349. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  9350. return 1;
  9351. }
  9352. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  9353. } else {
  9354. base_t = ggml_dup_tensor(lora_ctx, model_t);
  9355. }
  9356. ggml_set_name(base_t, base_name.c_str());
  9357. // allocate in backend buffer
  9358. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9359. if (lora_buf == nullptr) {
  9360. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  9361. return 1;
  9362. }
  9363. // load tensor data
  9364. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  9365. read_buf.resize(ggml_nbytes(tensor));
  9366. fin.seek(tensor_meta.offset, SEEK_SET);
  9367. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  9368. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  9369. };
  9370. load_tensor(metaA, loraA);
  9371. load_tensor(metaB, loraB);
  9372. // load base model tensor data
  9373. if (ml) {
  9374. ml->load_data_for(base_t);
  9375. } else {
  9376. ggml_backend_tensor_copy(model_t, base_t);
  9377. }
  9378. if (ggml_is_quantized(base_t->type) && !warned) {
  9379. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  9380. "use a f16 or f32 base model with --lora-base\n", __func__);
  9381. warned = true;
  9382. }
  9383. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  9384. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  9385. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  9386. ggml_free(lora_ctx);
  9387. ggml_backend_buffer_free(lora_buf);
  9388. ggml_backend_free(backend_cpu);
  9389. return 1;
  9390. }
  9391. auto build_lora_graph = [&]() {
  9392. // w = w + BA*s
  9393. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  9394. ggml_set_name(BA, "BA");
  9395. if (scaling != 1.0f) {
  9396. BA = ggml_scale(lora_ctx, BA, scaling);
  9397. ggml_set_name(BA, "BA_scaled");
  9398. }
  9399. ggml_tensor * r;
  9400. r = ggml_add_inplace(lora_ctx, base_t, BA);
  9401. ggml_set_name(r, "r_add");
  9402. if (base_t->type != model_t->type) {
  9403. // convert the result to the model type
  9404. r = ggml_cast(lora_ctx, r, model_t->type);
  9405. ggml_set_name(r, "r_cast");
  9406. }
  9407. return r;
  9408. };
  9409. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  9410. ggml_tensor * r = build_lora_graph();
  9411. ggml_build_forward_expand(gf, r);
  9412. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9413. if (graph_buf == nullptr) {
  9414. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  9415. ggml_free(lora_ctx);
  9416. ggml_backend_buffer_free(lora_buf);
  9417. ggml_backend_free(backend_cpu);
  9418. return 1;
  9419. }
  9420. ggml_backend_graph_compute(backend_cpu, gf);
  9421. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  9422. #if 0
  9423. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  9424. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  9425. // sched compute
  9426. ggml_build_forward_expand(gf, build_graph());
  9427. ggml_backend_sched_init_measure(sched, gf);
  9428. // create the graph again, since the previous one was destroyed by the measure
  9429. ggml_graph_clear(gf);
  9430. ggml_build_forward_expand(gf, build_graph());
  9431. ggml_backend_sched_graph_compute(sched, gf);
  9432. ggml_backend_sched_free(sched);
  9433. #endif
  9434. ggml_backend_buffer_free(lora_buf);
  9435. ggml_backend_buffer_free(graph_buf);
  9436. ggml_free(lora_ctx);
  9437. n_tensors++;
  9438. if (n_tensors % 4 == 0) {
  9439. LLAMA_LOG_INFO(".");
  9440. }
  9441. }
  9442. ggml_backend_free(backend_cpu);
  9443. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  9444. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  9445. return 0;
  9446. }
  9447. //
  9448. // interface implementation
  9449. //
  9450. struct llama_model_params llama_model_default_params() {
  9451. struct llama_model_params result = {
  9452. /*.n_gpu_layers =*/ 0,
  9453. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  9454. /*.main_gpu =*/ 0,
  9455. /*.tensor_split =*/ nullptr,
  9456. /*.progress_callback =*/ nullptr,
  9457. /*.progress_callback_user_data =*/ nullptr,
  9458. /*.kv_overrides =*/ nullptr,
  9459. /*.vocab_only =*/ false,
  9460. /*.use_mmap =*/ true,
  9461. /*.use_mlock =*/ false,
  9462. };
  9463. #ifdef GGML_USE_METAL
  9464. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  9465. result.n_gpu_layers = 999;
  9466. #endif
  9467. return result;
  9468. }
  9469. struct llama_context_params llama_context_default_params() {
  9470. struct llama_context_params result = {
  9471. /*.seed =*/ LLAMA_DEFAULT_SEED,
  9472. /*.n_ctx =*/ 512,
  9473. /*.n_batch =*/ 512,
  9474. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  9475. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  9476. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  9477. /*.rope_freq_base =*/ 0.0f,
  9478. /*.rope_freq_scale =*/ 0.0f,
  9479. /*.yarn_ext_factor =*/ -1.0f,
  9480. /*.yarn_attn_factor =*/ 1.0f,
  9481. /*.yarn_beta_fast =*/ 32.0f,
  9482. /*.yarn_beta_slow =*/ 1.0f,
  9483. /*.yarn_orig_ctx =*/ 0,
  9484. /*.cb_eval =*/ nullptr,
  9485. /*.cb_eval_user_data =*/ nullptr,
  9486. /*.type_k =*/ GGML_TYPE_F16,
  9487. /*.type_v =*/ GGML_TYPE_F16,
  9488. /*.mul_mat_q =*/ true,
  9489. /*.logits_all =*/ false,
  9490. /*.embedding =*/ false,
  9491. /*.offload_kqv =*/ true,
  9492. /*.do_pooling =*/ true,
  9493. };
  9494. return result;
  9495. }
  9496. struct llama_model_quantize_params llama_model_quantize_default_params() {
  9497. struct llama_model_quantize_params result = {
  9498. /*.nthread =*/ 0,
  9499. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  9500. /*.allow_requantize =*/ false,
  9501. /*.quantize_output_tensor =*/ true,
  9502. /*.only_copy =*/ false,
  9503. /*.pure =*/ false,
  9504. /*.imatrix =*/ nullptr,
  9505. };
  9506. return result;
  9507. }
  9508. size_t llama_max_devices(void) {
  9509. #if defined(GGML_USE_METAL)
  9510. return 1;
  9511. #elif defined(GGML_USE_CUBLAS)
  9512. return GGML_CUDA_MAX_DEVICES;
  9513. #elif defined(GGML_USE_SYCL)
  9514. return GGML_SYCL_MAX_DEVICES;
  9515. #elif defined(GGML_USE_VULKAN)
  9516. return GGML_VK_MAX_DEVICES;
  9517. #else
  9518. return 1;
  9519. #endif
  9520. }
  9521. bool llama_supports_mmap(void) {
  9522. return llama_mmap::SUPPORTED;
  9523. }
  9524. bool llama_supports_mlock(void) {
  9525. return llama_mlock::SUPPORTED;
  9526. }
  9527. bool llama_supports_gpu_offload(void) {
  9528. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  9529. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  9530. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  9531. return true;
  9532. #else
  9533. return false;
  9534. #endif
  9535. }
  9536. // deprecated:
  9537. bool llama_mmap_supported(void) {
  9538. return llama_supports_mmap();
  9539. }
  9540. bool llama_mlock_supported(void) {
  9541. return llama_supports_mlock();
  9542. }
  9543. void llama_backend_init(void) {
  9544. ggml_time_init();
  9545. // needed to initialize f16 tables
  9546. {
  9547. struct ggml_init_params params = { 0, NULL, false };
  9548. struct ggml_context * ctx = ggml_init(params);
  9549. ggml_free(ctx);
  9550. }
  9551. #ifdef GGML_USE_MPI
  9552. ggml_mpi_backend_init();
  9553. #endif
  9554. }
  9555. void llama_numa_init(enum ggml_numa_strategy numa) {
  9556. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  9557. ggml_numa_init(numa);
  9558. }
  9559. }
  9560. void llama_backend_free(void) {
  9561. #ifdef GGML_USE_MPI
  9562. ggml_mpi_backend_free();
  9563. #endif
  9564. ggml_quantize_free();
  9565. }
  9566. int64_t llama_time_us(void) {
  9567. return ggml_time_us();
  9568. }
  9569. struct llama_model * llama_load_model_from_file(
  9570. const char * path_model,
  9571. struct llama_model_params params) {
  9572. ggml_time_init();
  9573. llama_model * model = new llama_model;
  9574. unsigned cur_percentage = 0;
  9575. if (params.progress_callback == NULL) {
  9576. params.progress_callback_user_data = &cur_percentage;
  9577. params.progress_callback = [](float progress, void * ctx) {
  9578. unsigned * cur_percentage_p = (unsigned *) ctx;
  9579. unsigned percentage = (unsigned) (100 * progress);
  9580. while (percentage > *cur_percentage_p) {
  9581. *cur_percentage_p = percentage;
  9582. LLAMA_LOG_INFO(".");
  9583. if (percentage >= 100) {
  9584. LLAMA_LOG_INFO("\n");
  9585. }
  9586. }
  9587. return true;
  9588. };
  9589. }
  9590. int status = llama_model_load(path_model, *model, params);
  9591. GGML_ASSERT(status <= 0);
  9592. if (status < 0) {
  9593. if (status == -1) {
  9594. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  9595. } else if (status == -2) {
  9596. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  9597. }
  9598. delete model;
  9599. return nullptr;
  9600. }
  9601. return model;
  9602. }
  9603. void llama_free_model(struct llama_model * model) {
  9604. delete model;
  9605. }
  9606. struct llama_context * llama_new_context_with_model(
  9607. struct llama_model * model,
  9608. struct llama_context_params params) {
  9609. if (!model) {
  9610. return nullptr;
  9611. }
  9612. llama_context * ctx = new llama_context(*model);
  9613. const auto & hparams = model->hparams;
  9614. auto & cparams = ctx->cparams;
  9615. cparams.n_batch = params.n_batch;
  9616. cparams.n_threads = params.n_threads;
  9617. cparams.n_threads_batch = params.n_threads_batch;
  9618. cparams.yarn_ext_factor = params.yarn_ext_factor;
  9619. cparams.yarn_attn_factor = params.yarn_attn_factor;
  9620. cparams.yarn_beta_fast = params.yarn_beta_fast;
  9621. cparams.yarn_beta_slow = params.yarn_beta_slow;
  9622. cparams.mul_mat_q = params.mul_mat_q;
  9623. cparams.offload_kqv = params.offload_kqv;
  9624. cparams.do_pooling = params.do_pooling;
  9625. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  9626. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  9627. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  9628. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  9629. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  9630. hparams.n_ctx_train;
  9631. cparams.cb_eval = params.cb_eval;
  9632. cparams.cb_eval_user_data = params.cb_eval_user_data;
  9633. auto rope_scaling_type = params.rope_scaling_type;
  9634. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  9635. rope_scaling_type = hparams.rope_scaling_type_train;
  9636. }
  9637. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  9638. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  9639. }
  9640. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  9641. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  9642. }
  9643. if (params.seed == LLAMA_DEFAULT_SEED) {
  9644. params.seed = time(NULL);
  9645. }
  9646. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  9647. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  9648. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  9649. ctx->rng = std::mt19937(params.seed);
  9650. ctx->logits_all = params.logits_all;
  9651. const ggml_type type_k = params.type_k;
  9652. const ggml_type type_v = params.type_v;
  9653. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  9654. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  9655. if (!hparams.vocab_only) {
  9656. // initialize backends
  9657. #ifdef GGML_USE_METAL
  9658. if (model->n_gpu_layers > 0) {
  9659. ctx->backend_metal = ggml_backend_metal_init();
  9660. if (ctx->backend_metal == nullptr) {
  9661. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  9662. llama_free(ctx);
  9663. return nullptr;
  9664. }
  9665. ctx->backends.push_back(ctx->backend_metal);
  9666. }
  9667. #elif defined(GGML_USE_CUBLAS)
  9668. if (model->n_gpu_layers > 0) {
  9669. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  9670. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  9671. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  9672. if (backend == nullptr) {
  9673. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  9674. llama_free(ctx);
  9675. return nullptr;
  9676. }
  9677. ctx->backends.push_back(backend);
  9678. } else {
  9679. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  9680. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  9681. ggml_backend_t backend = ggml_backend_cuda_init(device);
  9682. if (backend == nullptr) {
  9683. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  9684. llama_free(ctx);
  9685. return nullptr;
  9686. }
  9687. ctx->backends.push_back(backend);
  9688. }
  9689. }
  9690. }
  9691. #elif defined(GGML_USE_VULKAN)
  9692. if (model->n_gpu_layers > 0) {
  9693. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  9694. ggml_backend_t backend = ggml_backend_vk_init(device);
  9695. if (backend == nullptr) {
  9696. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  9697. llama_free(ctx);
  9698. return nullptr;
  9699. }
  9700. ctx->backends.push_back(backend);
  9701. }
  9702. }
  9703. #elif defined(GGML_USE_SYCL)
  9704. if (model->n_gpu_layers > 0) {
  9705. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  9706. if (backend == nullptr) {
  9707. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  9708. llama_free(ctx);
  9709. return nullptr;
  9710. }
  9711. ctx->backends.push_back(backend);
  9712. }
  9713. #elif defined(GGML_USE_KOMPUTE)
  9714. if (model->n_gpu_layers > 0) {
  9715. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  9716. if (backend == nullptr) {
  9717. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  9718. llama_free(ctx);
  9719. return nullptr;
  9720. }
  9721. ctx->backends.push_back(backend);
  9722. }
  9723. #endif
  9724. ctx->backend_cpu = ggml_backend_cpu_init();
  9725. if (ctx->backend_cpu == nullptr) {
  9726. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  9727. llama_free(ctx);
  9728. return nullptr;
  9729. }
  9730. ctx->backends.push_back(ctx->backend_cpu);
  9731. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  9732. cparams.n_ctx, cparams.offload_kqv)) {
  9733. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  9734. llama_free(ctx);
  9735. return nullptr;
  9736. }
  9737. {
  9738. size_t memory_size_k = 0;
  9739. size_t memory_size_v = 0;
  9740. for (auto & k : ctx->kv_self.k_l) {
  9741. memory_size_k += ggml_nbytes(k);
  9742. }
  9743. for (auto & v : ctx->kv_self.v_l) {
  9744. memory_size_v += ggml_nbytes(v);
  9745. }
  9746. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  9747. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  9748. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  9749. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  9750. }
  9751. // resized during inference, reserve maximum
  9752. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  9753. if (params.embedding) {
  9754. ctx->embedding.resize(hparams.n_embd);
  9755. }
  9756. // graph inputs
  9757. {
  9758. ggml_init_params init_params = {
  9759. /* .mem_size */ ggml_tensor_overhead()*8,
  9760. /* .mem_buffer */ nullptr,
  9761. /* .no_alloc */ true,
  9762. };
  9763. ctx->ctx_input = ggml_init(init_params);
  9764. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9765. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  9766. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9767. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  9768. ctx->inp_KQ_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx);
  9769. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  9770. ctx->inp_mean = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_batch, cparams.n_batch);
  9771. ctx->inp_cls = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9772. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  9773. ggml_set_name(ctx->inp_embd, "inp_embd");
  9774. ggml_set_name(ctx->inp_pos, "inp_pos");
  9775. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  9776. ggml_set_name(ctx->inp_KQ_pos, "inp_KQ_pos");
  9777. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  9778. ggml_set_name(ctx->inp_mean, "inp_mean");
  9779. ggml_set_name(ctx->inp_cls, "inp_cls");
  9780. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  9781. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  9782. ggml_backend_buffer_name(ctx->buf_input),
  9783. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  9784. }
  9785. // scheduler and compute buffers
  9786. {
  9787. // buffer types used for the compute buffer of each backend
  9788. std::vector<ggml_backend_buffer_type_t> backend_buft;
  9789. for (auto * backend : ctx->backends) {
  9790. if (ggml_backend_is_cpu(backend)) {
  9791. // use host buffers for the CPU backend compute buffer
  9792. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  9793. } else {
  9794. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  9795. }
  9796. }
  9797. // buffer used to store the computation graph and the tensor meta data
  9798. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  9799. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  9800. // build worst-case graph
  9801. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  9802. int n_past = cparams.n_ctx - n_tokens;
  9803. 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
  9804. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  9805. // initialize scheduler with the worst-case graph
  9806. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  9807. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  9808. llama_free(ctx);
  9809. return nullptr;
  9810. }
  9811. for (size_t i = 0; i < ctx->backends.size(); i++) {
  9812. ggml_backend_t backend = ctx->backends[i];
  9813. ggml_backend_buffer_type_t buft = backend_buft[i];
  9814. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  9815. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  9816. ggml_backend_buft_name(buft),
  9817. size / 1024.0 / 1024.0);
  9818. }
  9819. // note: the number of splits during measure is higher than during inference due to the kv shift
  9820. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  9821. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  9822. }
  9823. }
  9824. #ifdef GGML_USE_MPI
  9825. ctx->ctx_mpi = ggml_mpi_init();
  9826. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  9827. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  9828. // TODO: needs fix after #3228
  9829. GGML_ASSERT(false && "not implemented");
  9830. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  9831. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  9832. llama_backend_free();
  9833. exit(1);
  9834. }
  9835. #endif
  9836. return ctx;
  9837. }
  9838. void llama_free(struct llama_context * ctx) {
  9839. delete ctx;
  9840. }
  9841. const llama_model * llama_get_model(const struct llama_context * ctx) {
  9842. return &ctx->model;
  9843. }
  9844. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  9845. return ctx->cparams.n_ctx;
  9846. }
  9847. uint32_t llama_n_batch(const struct llama_context * ctx) {
  9848. return ctx->cparams.n_batch;
  9849. }
  9850. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  9851. return model->vocab.type;
  9852. }
  9853. int32_t llama_n_vocab(const struct llama_model * model) {
  9854. return model->vocab.id_to_token.size();
  9855. }
  9856. int32_t llama_n_ctx_train(const struct llama_model * model) {
  9857. return model->hparams.n_ctx_train;
  9858. }
  9859. int32_t llama_n_embd(const struct llama_model * model) {
  9860. return model->hparams.n_embd;
  9861. }
  9862. float llama_rope_freq_scale_train(const struct llama_model * model) {
  9863. return model->hparams.rope_freq_scale_train;
  9864. }
  9865. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  9866. const auto & it = model->gguf_kv.find(key);
  9867. if (it == model->gguf_kv.end()) {
  9868. if (buf_size > 0) {
  9869. buf[0] = '\0';
  9870. }
  9871. return -1;
  9872. }
  9873. return snprintf(buf, buf_size, "%s", it->second.c_str());
  9874. }
  9875. int32_t llama_model_meta_count(const struct llama_model * model) {
  9876. return (int)model->gguf_kv.size();
  9877. }
  9878. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  9879. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  9880. if (buf_size > 0) {
  9881. buf[0] = '\0';
  9882. }
  9883. return -1;
  9884. }
  9885. auto it = model->gguf_kv.begin();
  9886. std::advance(it, i);
  9887. return snprintf(buf, buf_size, "%s", it->first.c_str());
  9888. }
  9889. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  9890. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  9891. if (buf_size > 0) {
  9892. buf[0] = '\0';
  9893. }
  9894. return -1;
  9895. }
  9896. auto it = model->gguf_kv.begin();
  9897. std::advance(it, i);
  9898. return snprintf(buf, buf_size, "%s", it->second.c_str());
  9899. }
  9900. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  9901. return snprintf(buf, buf_size, "%s %s %s",
  9902. llama_model_arch_name(model->arch),
  9903. llama_model_type_name(model->type),
  9904. llama_model_ftype_name(model->ftype).c_str());
  9905. }
  9906. uint64_t llama_model_size(const struct llama_model * model) {
  9907. uint64_t size = 0;
  9908. for (const auto & it : model->tensors_by_name) {
  9909. size += ggml_nbytes(it.second);
  9910. }
  9911. return size;
  9912. }
  9913. uint64_t llama_model_n_params(const struct llama_model * model) {
  9914. uint64_t nparams = 0;
  9915. for (const auto & it : model->tensors_by_name) {
  9916. nparams += ggml_nelements(it.second);
  9917. }
  9918. return nparams;
  9919. }
  9920. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  9921. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  9922. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  9923. return it.first == name;
  9924. });
  9925. if (it == model->tensors_by_name.end()) {
  9926. return nullptr;
  9927. }
  9928. return it->second;
  9929. }
  9930. uint32_t llama_model_quantize(
  9931. const char * fname_inp,
  9932. const char * fname_out,
  9933. const llama_model_quantize_params * params) {
  9934. try {
  9935. llama_model_quantize_internal(fname_inp, fname_out, params);
  9936. return 0;
  9937. } catch (const std::exception & err) {
  9938. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  9939. return 1;
  9940. }
  9941. }
  9942. int32_t llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  9943. try {
  9944. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  9945. } catch (const std::exception & err) {
  9946. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9947. return 1;
  9948. }
  9949. }
  9950. 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) {
  9951. try {
  9952. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  9953. } catch (const std::exception & err) {
  9954. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9955. return 1;
  9956. }
  9957. }
  9958. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  9959. struct llama_kv_cache_view result = {
  9960. /*.n_cells = */ 0,
  9961. /*.n_max_seq = */ n_max_seq,
  9962. /*.token_count = */ 0,
  9963. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  9964. /*.max_contiguous = */ 0,
  9965. /*.max_contiguous_idx = */ -1,
  9966. /*.cells = */ nullptr,
  9967. /*.cells_sequences = */ nullptr,
  9968. };
  9969. return result;
  9970. }
  9971. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  9972. if (view->cells != nullptr) {
  9973. free(view->cells);
  9974. view->cells = nullptr;
  9975. }
  9976. if (view->cells_sequences != nullptr) {
  9977. free(view->cells_sequences);
  9978. view->cells_sequences = nullptr;
  9979. }
  9980. }
  9981. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  9982. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  9983. view->n_cells = int32_t(ctx->kv_self.size);
  9984. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  9985. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  9986. view->cells = (struct llama_kv_cache_view_cell *)p;
  9987. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  9988. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  9989. view->cells_sequences = (llama_seq_id *)p;
  9990. }
  9991. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  9992. llama_kv_cache_view_cell * c_curr = view->cells;
  9993. llama_seq_id * cs_curr = view->cells_sequences;
  9994. int32_t used_cells = 0;
  9995. int32_t token_count = 0;
  9996. int32_t curr_contig_idx = -1;
  9997. uint32_t max_contig = 0;
  9998. int32_t max_contig_idx = -1;
  9999. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  10000. const size_t curr_size = kv_cells[i].seq_id.size();
  10001. token_count += curr_size;
  10002. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  10003. if (curr_size > 0) {
  10004. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  10005. max_contig = i - curr_contig_idx;
  10006. max_contig_idx = curr_contig_idx;
  10007. }
  10008. curr_contig_idx = -1;
  10009. } else if (curr_contig_idx < 0) {
  10010. curr_contig_idx = i;
  10011. }
  10012. int seq_idx = 0;
  10013. for (const llama_seq_id it : kv_cells[i].seq_id) {
  10014. if (seq_idx >= view->n_max_seq) {
  10015. break;
  10016. }
  10017. cs_curr[seq_idx] = it;
  10018. seq_idx++;
  10019. }
  10020. if (seq_idx != 0) {
  10021. used_cells++;
  10022. }
  10023. for (; seq_idx < view->n_max_seq; seq_idx++) {
  10024. cs_curr[seq_idx] = -1;
  10025. }
  10026. }
  10027. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  10028. max_contig_idx = curr_contig_idx;
  10029. max_contig = kv_cells.size() - curr_contig_idx;
  10030. }
  10031. view->max_contiguous = max_contig;
  10032. view->max_contiguous_idx = max_contig_idx;
  10033. view->token_count = token_count;
  10034. view->used_cells = used_cells;
  10035. if (uint32_t(used_cells) != ctx->kv_self.used) {
  10036. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  10037. __func__, ctx->kv_self.used, used_cells);
  10038. }
  10039. }
  10040. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  10041. int result = 0;
  10042. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  10043. result += ctx->kv_self.cells[i].seq_id.size();
  10044. }
  10045. return result;
  10046. }
  10047. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  10048. return ctx->kv_self.used;
  10049. }
  10050. void llama_kv_cache_clear(struct llama_context * ctx) {
  10051. llama_kv_cache_clear(ctx->kv_self);
  10052. }
  10053. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  10054. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  10055. }
  10056. 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) {
  10057. if (seq_id_src == seq_id_dst) {
  10058. return;
  10059. }
  10060. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  10061. }
  10062. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  10063. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  10064. }
  10065. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  10066. if (delta == 0) {
  10067. return;
  10068. }
  10069. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  10070. }
  10071. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  10072. if (d == 1) {
  10073. return;
  10074. }
  10075. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  10076. }
  10077. // Returns the *maximum* size of the state
  10078. size_t llama_get_state_size(const struct llama_context * ctx) {
  10079. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  10080. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  10081. const size_t s_rng_size = sizeof(size_t);
  10082. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  10083. const size_t s_logits_size = sizeof(size_t);
  10084. // assume worst case for logits although only currently set ones are serialized
  10085. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  10086. const size_t s_embedding_size = sizeof(size_t);
  10087. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  10088. const size_t s_kv_size = sizeof(size_t);
  10089. const size_t s_kv_ntok = sizeof(int);
  10090. const size_t s_kv = ctx->kv_self.total_size();
  10091. const size_t s_total = (
  10092. + s_rng_size
  10093. + s_rng
  10094. + s_logits_size
  10095. + s_logits
  10096. + s_embedding_size
  10097. + s_embedding
  10098. + s_kv_size
  10099. + s_kv_ntok
  10100. + s_kv
  10101. );
  10102. return s_total;
  10103. }
  10104. // llama_context_data
  10105. struct llama_data_context {
  10106. virtual void write(const void * src, size_t size) = 0;
  10107. virtual size_t get_size_written() = 0;
  10108. virtual ~llama_data_context() = default;
  10109. };
  10110. struct llama_data_buffer_context : llama_data_context {
  10111. uint8_t * ptr;
  10112. size_t size_written = 0;
  10113. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  10114. void write(const void * src, size_t size) override {
  10115. memcpy(ptr, src, size);
  10116. ptr += size;
  10117. size_written += size;
  10118. }
  10119. size_t get_size_written() override {
  10120. return size_written;
  10121. }
  10122. };
  10123. struct llama_data_file_context : llama_data_context {
  10124. llama_file * file;
  10125. size_t size_written = 0;
  10126. llama_data_file_context(llama_file * f) : file(f) {}
  10127. void write(const void * src, size_t size) override {
  10128. file->write_raw(src, size);
  10129. size_written += size;
  10130. }
  10131. size_t get_size_written() override {
  10132. return size_written;
  10133. }
  10134. };
  10135. /** copy state data into either a buffer or file depending on the passed in context
  10136. *
  10137. * file context:
  10138. * llama_file file("/path", "wb");
  10139. * llama_data_file_context data_ctx(&file);
  10140. * llama_copy_state_data(ctx, &data_ctx);
  10141. *
  10142. * buffer context:
  10143. * std::vector<uint8_t> buf(max_size, 0);
  10144. * llama_data_buffer_context data_ctx(&buf.data());
  10145. * llama_copy_state_data(ctx, &data_ctx);
  10146. *
  10147. */
  10148. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  10149. // copy rng
  10150. {
  10151. std::ostringstream rng_ss;
  10152. rng_ss << ctx->rng;
  10153. const std::string & rng_str = rng_ss.str();
  10154. const size_t rng_size = rng_str.size();
  10155. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10156. data_ctx->write(&rng_size, sizeof(rng_size));
  10157. data_ctx->write(rng_str.data(), rng_size);
  10158. }
  10159. // copy logits
  10160. {
  10161. const size_t logits_size = ctx->logits.size();
  10162. data_ctx->write(&logits_size, sizeof(logits_size));
  10163. if (logits_size) {
  10164. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  10165. }
  10166. }
  10167. // copy embeddings
  10168. {
  10169. const size_t embedding_size = ctx->embedding.size();
  10170. data_ctx->write(&embedding_size, sizeof(embedding_size));
  10171. if (embedding_size) {
  10172. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  10173. }
  10174. }
  10175. // copy kv cache
  10176. {
  10177. const auto & kv_self = ctx->kv_self;
  10178. const auto & hparams = ctx->model.hparams;
  10179. const auto & cparams = ctx->cparams;
  10180. const auto n_layer = hparams.n_layer;
  10181. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  10182. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  10183. const auto n_ctx = cparams.n_ctx;
  10184. const size_t kv_buf_size = kv_self.total_size();
  10185. const uint32_t kv_head = kv_self.head;
  10186. const uint32_t kv_size = kv_self.size;
  10187. const uint32_t kv_used = kv_self.used;
  10188. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  10189. data_ctx->write(&kv_head, sizeof(kv_head));
  10190. data_ctx->write(&kv_size, sizeof(kv_size));
  10191. data_ctx->write(&kv_used, sizeof(kv_used));
  10192. if (kv_buf_size) {
  10193. std::vector<uint8_t> tmp_buf;
  10194. for (int il = 0; il < (int) n_layer; ++il) {
  10195. size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10196. tmp_buf.resize(k_size);
  10197. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  10198. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10199. // v is not contiguous, copy row by row
  10200. size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10201. size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10202. tmp_buf.resize(v_row_size);
  10203. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10204. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  10205. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10206. }
  10207. }
  10208. }
  10209. for (uint32_t i = 0; i < kv_size; ++i) {
  10210. const auto & cell = kv_self.cells[i];
  10211. const llama_pos pos = cell.pos;
  10212. const size_t seq_id_size = cell.seq_id.size();
  10213. data_ctx->write(&pos, sizeof(pos));
  10214. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  10215. for (auto seq_id : cell.seq_id) {
  10216. data_ctx->write(&seq_id, sizeof(seq_id));
  10217. }
  10218. }
  10219. }
  10220. }
  10221. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  10222. llama_data_buffer_context data_ctx(dst);
  10223. llama_copy_state_data_internal(ctx, &data_ctx);
  10224. return data_ctx.get_size_written();
  10225. }
  10226. // Sets the state reading from the specified source address
  10227. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  10228. uint8_t * inp = src;
  10229. // set rng
  10230. {
  10231. size_t rng_size;
  10232. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  10233. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10234. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  10235. std::istringstream rng_ss(rng_str);
  10236. rng_ss >> ctx->rng;
  10237. GGML_ASSERT(!rng_ss.fail());
  10238. }
  10239. // set logits
  10240. {
  10241. size_t logits_size;
  10242. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  10243. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  10244. if (logits_size) {
  10245. ctx->logits.resize(logits_size);
  10246. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  10247. inp += logits_size * sizeof(float);
  10248. }
  10249. }
  10250. // set embeddings
  10251. {
  10252. size_t embedding_size;
  10253. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  10254. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  10255. if (embedding_size) {
  10256. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  10257. inp += embedding_size * sizeof(float);
  10258. }
  10259. }
  10260. // set kv cache
  10261. {
  10262. const auto & kv_self = ctx->kv_self;
  10263. const auto & hparams = ctx->model.hparams;
  10264. const auto & cparams = ctx->cparams;
  10265. const int n_layer = hparams.n_layer;
  10266. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  10267. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  10268. const int n_ctx = cparams.n_ctx;
  10269. size_t kv_buf_size;
  10270. uint32_t kv_head;
  10271. uint32_t kv_size;
  10272. uint32_t kv_used;
  10273. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  10274. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  10275. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  10276. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  10277. if (kv_buf_size) {
  10278. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  10279. for (int il = 0; il < (int) n_layer; ++il) {
  10280. size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10281. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  10282. inp += k_size;
  10283. // v is not contiguous, copy row by row
  10284. size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10285. size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10286. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10287. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  10288. inp += v_row_size;
  10289. }
  10290. }
  10291. }
  10292. ctx->kv_self.head = kv_head;
  10293. ctx->kv_self.size = kv_size;
  10294. ctx->kv_self.used = kv_used;
  10295. ctx->kv_self.cells.resize(kv_size);
  10296. for (uint32_t i = 0; i < kv_size; ++i) {
  10297. llama_pos pos;
  10298. size_t seq_id_size;
  10299. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  10300. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  10301. ctx->kv_self.cells[i].pos = pos;
  10302. llama_seq_id seq_id;
  10303. for (size_t j = 0; j < seq_id_size; ++j) {
  10304. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  10305. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  10306. }
  10307. }
  10308. }
  10309. const size_t nread = inp - src;
  10310. const size_t max_size = llama_get_state_size(ctx);
  10311. GGML_ASSERT(nread <= max_size);
  10312. return nread;
  10313. }
  10314. 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) {
  10315. llama_file file(path_session, "rb");
  10316. // sanity checks
  10317. {
  10318. const uint32_t magic = file.read_u32();
  10319. const uint32_t version = file.read_u32();
  10320. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  10321. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  10322. return false;
  10323. }
  10324. llama_hparams session_hparams;
  10325. file.read_raw(&session_hparams, sizeof(llama_hparams));
  10326. if (session_hparams != ctx->model.hparams) {
  10327. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  10328. return false;
  10329. }
  10330. }
  10331. // load the prompt
  10332. {
  10333. const uint32_t n_token_count = file.read_u32();
  10334. if (n_token_count > n_token_capacity) {
  10335. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  10336. return false;
  10337. }
  10338. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  10339. *n_token_count_out = n_token_count;
  10340. }
  10341. // restore the context state
  10342. {
  10343. const size_t n_state_size_cur = file.size - file.tell();
  10344. const size_t n_state_size_max = llama_get_state_size(ctx);
  10345. if (n_state_size_cur > n_state_size_max) {
  10346. 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);
  10347. return false;
  10348. }
  10349. std::vector<uint8_t> state_data(n_state_size_max);
  10350. file.read_raw(state_data.data(), n_state_size_cur);
  10351. llama_set_state_data(ctx, state_data.data());
  10352. }
  10353. return true;
  10354. }
  10355. 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) {
  10356. try {
  10357. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  10358. } catch (const std::exception & err) {
  10359. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  10360. return false;
  10361. }
  10362. }
  10363. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  10364. llama_file file(path_session, "wb");
  10365. file.write_u32(LLAMA_SESSION_MAGIC);
  10366. file.write_u32(LLAMA_SESSION_VERSION);
  10367. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  10368. // save the prompt
  10369. file.write_u32((uint32_t) n_token_count);
  10370. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  10371. // save the context state using stream saving
  10372. llama_data_file_context data_ctx(&file);
  10373. llama_copy_state_data_internal(ctx, &data_ctx);
  10374. return true;
  10375. }
  10376. int llama_eval(
  10377. struct llama_context * ctx,
  10378. llama_token * tokens,
  10379. int32_t n_tokens,
  10380. int32_t n_past) {
  10381. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10382. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  10383. if (ret < 0) {
  10384. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10385. }
  10386. return ret;
  10387. }
  10388. int llama_eval_embd(
  10389. struct llama_context * ctx,
  10390. float * embd,
  10391. int32_t n_tokens,
  10392. int32_t n_past) {
  10393. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10394. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  10395. const int ret = llama_decode_internal(*ctx, batch);
  10396. if (ret < 0) {
  10397. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10398. }
  10399. return ret;
  10400. }
  10401. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  10402. ctx->cparams.n_threads = n_threads;
  10403. ctx->cparams.n_threads_batch = n_threads_batch;
  10404. }
  10405. struct llama_batch llama_batch_get_one(
  10406. llama_token * tokens,
  10407. int32_t n_tokens,
  10408. llama_pos pos_0,
  10409. llama_seq_id seq_id) {
  10410. return {
  10411. /*n_tokens =*/ n_tokens,
  10412. /*tokens =*/ tokens,
  10413. /*embd =*/ nullptr,
  10414. /*pos =*/ nullptr,
  10415. /*n_seq_id =*/ nullptr,
  10416. /*seq_id =*/ nullptr,
  10417. /*logits =*/ nullptr,
  10418. /*all_pos_0 =*/ pos_0,
  10419. /*all_pos_1 =*/ 1,
  10420. /*all_seq_id =*/ seq_id,
  10421. };
  10422. }
  10423. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  10424. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  10425. if (embd) {
  10426. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  10427. } else {
  10428. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  10429. }
  10430. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  10431. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  10432. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  10433. for (int i = 0; i < n_tokens_alloc; ++i) {
  10434. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  10435. }
  10436. batch.seq_id[n_tokens_alloc] = nullptr;
  10437. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  10438. return batch;
  10439. }
  10440. void llama_batch_free(struct llama_batch batch) {
  10441. if (batch.token) free(batch.token);
  10442. if (batch.embd) free(batch.embd);
  10443. if (batch.pos) free(batch.pos);
  10444. if (batch.n_seq_id) free(batch.n_seq_id);
  10445. if (batch.seq_id) {
  10446. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  10447. free(batch.seq_id[i]);
  10448. }
  10449. free(batch.seq_id);
  10450. }
  10451. if (batch.logits) free(batch.logits);
  10452. }
  10453. int32_t llama_decode(
  10454. struct llama_context * ctx,
  10455. struct llama_batch batch) {
  10456. const int ret = llama_decode_internal(*ctx, batch);
  10457. if (ret < 0) {
  10458. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10459. }
  10460. return ret;
  10461. }
  10462. float * llama_get_logits(struct llama_context * ctx) {
  10463. return ctx->logits.data();
  10464. }
  10465. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  10466. assert(ctx->logits_valid.at(i));
  10467. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  10468. }
  10469. float * llama_get_embeddings(struct llama_context * ctx) {
  10470. return ctx->embedding.data();
  10471. }
  10472. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  10473. return ctx->embedding.data() + i*ctx->model.hparams.n_embd;
  10474. }
  10475. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  10476. return model->vocab.id_to_token[token].text.c_str();
  10477. }
  10478. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  10479. return model->vocab.id_to_token[token].score;
  10480. }
  10481. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  10482. return model->vocab.id_to_token[token].type;
  10483. }
  10484. llama_token llama_token_bos(const struct llama_model * model) {
  10485. return model->vocab.special_bos_id;
  10486. }
  10487. llama_token llama_token_eos(const struct llama_model * model) {
  10488. return model->vocab.special_eos_id;
  10489. }
  10490. llama_token llama_token_nl(const struct llama_model * model) {
  10491. return model->vocab.linefeed_id;
  10492. }
  10493. int32_t llama_add_bos_token(const struct llama_model * model) {
  10494. return model->vocab.special_add_bos;
  10495. }
  10496. int32_t llama_add_eos_token(const struct llama_model * model) {
  10497. return model->vocab.special_add_eos;
  10498. }
  10499. llama_token llama_token_prefix(const struct llama_model * model) {
  10500. return model->vocab.special_prefix_id;
  10501. }
  10502. llama_token llama_token_middle(const struct llama_model * model) {
  10503. return model->vocab.special_middle_id;
  10504. }
  10505. llama_token llama_token_suffix(const struct llama_model * model) {
  10506. return model->vocab.special_suffix_id;
  10507. }
  10508. llama_token llama_token_eot(const struct llama_model * model) {
  10509. return model->vocab.special_eot_id;
  10510. }
  10511. int32_t llama_tokenize(
  10512. const struct llama_model * model,
  10513. const char * text,
  10514. int32_t text_len,
  10515. llama_token * tokens,
  10516. int32_t n_max_tokens,
  10517. bool add_bos,
  10518. bool special) {
  10519. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  10520. if (n_max_tokens < (int) res.size()) {
  10521. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  10522. return -((int) res.size());
  10523. }
  10524. for (size_t i = 0; i < res.size(); i++) {
  10525. tokens[i] = res[i];
  10526. }
  10527. return res.size();
  10528. }
  10529. static std::string llama_decode_text(const std::string & text) {
  10530. std::string decoded_text;
  10531. auto unicode_sequences = codepoints_from_utf8(text);
  10532. for (auto& unicode_sequence : unicode_sequences) {
  10533. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  10534. }
  10535. return decoded_text;
  10536. }
  10537. // does not write null-terminator to buf
  10538. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  10539. if (0 <= token && token < llama_n_vocab(model)) {
  10540. switch (llama_vocab_get_type(model->vocab)) {
  10541. case LLAMA_VOCAB_TYPE_WPM:
  10542. case LLAMA_VOCAB_TYPE_SPM: {
  10543. // NOTE: we accept all unsupported token types,
  10544. // suppressing them like CONTROL tokens.
  10545. if (llama_is_normal_token(model->vocab, token)) {
  10546. std::string result = model->vocab.id_to_token[token].text;
  10547. llama_unescape_whitespace(result);
  10548. if (length < (int) result.length()) {
  10549. return -(int) result.length();
  10550. }
  10551. memcpy(buf, result.c_str(), result.length());
  10552. return result.length();
  10553. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10554. std::string result = model->vocab.id_to_token[token].text;
  10555. if (length < (int) result.length()) {
  10556. return -result.length();
  10557. }
  10558. memcpy(buf, result.c_str(), result.length());
  10559. return result.length();
  10560. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  10561. if (length < 3) {
  10562. return -3;
  10563. }
  10564. memcpy(buf, "\xe2\x96\x85", 3);
  10565. return 3;
  10566. } else if (llama_is_control_token(model->vocab, token)) {
  10567. ;
  10568. } else if (llama_is_byte_token(model->vocab, token)) {
  10569. if (length < 1) {
  10570. return -1;
  10571. }
  10572. buf[0] = llama_token_to_byte(model->vocab, token);
  10573. return 1;
  10574. }
  10575. break;
  10576. }
  10577. case LLAMA_VOCAB_TYPE_BPE: {
  10578. // NOTE: we accept all unsupported token types,
  10579. // suppressing them like CONTROL tokens.
  10580. if (llama_is_normal_token(model->vocab, token)) {
  10581. std::string result = model->vocab.id_to_token[token].text;
  10582. result = llama_decode_text(result);
  10583. if (length < (int) result.length()) {
  10584. return -(int) result.length();
  10585. }
  10586. memcpy(buf, result.c_str(), result.length());
  10587. return result.length();
  10588. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10589. std::string result = model->vocab.id_to_token[token].text;
  10590. if (length < (int) result.length()) {
  10591. return -result.length();
  10592. }
  10593. memcpy(buf, result.c_str(), result.length());
  10594. return result.length();
  10595. } else if (llama_is_control_token(model->vocab, token)) {
  10596. ;
  10597. }
  10598. break;
  10599. }
  10600. default:
  10601. GGML_ASSERT(false);
  10602. }
  10603. }
  10604. return 0;
  10605. }
  10606. // trim whitespace from the beginning and end of a string
  10607. static std::string trim(const std::string & str) {
  10608. size_t start = 0;
  10609. size_t end = str.size();
  10610. while (start < end && isspace(str[start])) {
  10611. start += 1;
  10612. }
  10613. while (end > start && isspace(str[end - 1])) {
  10614. end -= 1;
  10615. }
  10616. return str.substr(start, end - start);
  10617. }
  10618. // Simple version of "llama_apply_chat_template" that only works with strings
  10619. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  10620. static int32_t llama_chat_apply_template_internal(
  10621. const std::string & tmpl,
  10622. const std::vector<const llama_chat_message *> & chat,
  10623. std::string & dest, bool add_ass) {
  10624. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  10625. std::stringstream ss;
  10626. if (tmpl.find("<|im_start|>") != std::string::npos) {
  10627. // chatml template
  10628. for (auto message : chat) {
  10629. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  10630. }
  10631. if (add_ass) {
  10632. ss << "<|im_start|>assistant\n";
  10633. }
  10634. } else if (tmpl.find("[INST]") != std::string::npos) {
  10635. // llama2 template and its variants
  10636. // [variant] support system message
  10637. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  10638. // [variant] space before + after response
  10639. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  10640. // [variant] add BOS inside history
  10641. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  10642. // [variant] trim spaces from the input message
  10643. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  10644. // construct the prompt
  10645. bool is_inside_turn = true; // skip BOS at the beginning
  10646. ss << "[INST] ";
  10647. for (auto message : chat) {
  10648. std::string content = strip_message ? trim(message->content) : message->content;
  10649. std::string role(message->role);
  10650. if (!is_inside_turn) {
  10651. is_inside_turn = true;
  10652. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  10653. }
  10654. if (role == "system") {
  10655. if (support_system_message) {
  10656. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  10657. } else {
  10658. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  10659. ss << content << "\n";
  10660. }
  10661. } else if (role == "user") {
  10662. ss << content << " [/INST]";
  10663. } else {
  10664. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  10665. is_inside_turn = false;
  10666. }
  10667. }
  10668. // llama2 templates seem to not care about "add_generation_prompt"
  10669. } else if (tmpl.find("<|user|>") != std::string::npos) {
  10670. // zephyr template
  10671. for (auto message : chat) {
  10672. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  10673. }
  10674. if (add_ass) {
  10675. ss << "<|assistant|>\n";
  10676. }
  10677. } else {
  10678. // template not supported
  10679. return -1;
  10680. }
  10681. dest = ss.str();
  10682. return dest.size();
  10683. }
  10684. LLAMA_API int32_t llama_chat_apply_template(
  10685. const struct llama_model * model,
  10686. const char * tmpl,
  10687. const struct llama_chat_message * chat,
  10688. size_t n_msg,
  10689. bool add_ass,
  10690. char * buf,
  10691. int32_t length) {
  10692. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  10693. if (tmpl == nullptr) {
  10694. GGML_ASSERT(model != nullptr);
  10695. // load template from model
  10696. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  10697. std::string template_key = "tokenizer.chat_template";
  10698. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  10699. if (res < 0) {
  10700. // worst case: there is no information about template, we will use chatml by default
  10701. curr_tmpl = "<|im_start|>"; // see llama_chat_apply_template_internal
  10702. } else {
  10703. curr_tmpl = std::string(model_template.data(), model_template.size());
  10704. }
  10705. }
  10706. // format the chat to string
  10707. std::vector<const llama_chat_message *> chat_vec;
  10708. chat_vec.resize(n_msg);
  10709. for (size_t i = 0; i < n_msg; i++) {
  10710. chat_vec[i] = &chat[i];
  10711. }
  10712. std::string formatted_chat;
  10713. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  10714. if (res < 0) {
  10715. return res;
  10716. }
  10717. strncpy(buf, formatted_chat.c_str(), length);
  10718. return res;
  10719. }
  10720. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  10721. struct llama_timings result = {
  10722. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  10723. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  10724. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  10725. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  10726. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  10727. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  10728. /*.n_sample =*/ std::max(1, ctx->n_sample),
  10729. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  10730. /*.n_eval =*/ std::max(1, ctx->n_eval),
  10731. };
  10732. return result;
  10733. }
  10734. void llama_print_timings(struct llama_context * ctx) {
  10735. const llama_timings timings = llama_get_timings(ctx);
  10736. LLAMA_LOG_INFO("\n");
  10737. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  10738. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10739. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  10740. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  10741. __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);
  10742. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10743. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  10744. 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));
  10745. }
  10746. void llama_reset_timings(struct llama_context * ctx) {
  10747. ctx->t_start_us = ggml_time_us();
  10748. ctx->t_sample_us = ctx->n_sample = 0;
  10749. ctx->t_eval_us = ctx->n_eval = 0;
  10750. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  10751. }
  10752. const char * llama_print_system_info(void) {
  10753. static std::string s;
  10754. s = "";
  10755. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  10756. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  10757. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  10758. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  10759. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  10760. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  10761. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  10762. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  10763. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  10764. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  10765. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  10766. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  10767. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  10768. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  10769. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  10770. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  10771. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  10772. return s.c_str();
  10773. }
  10774. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  10775. fprintf(stream, "\n");
  10776. fprintf(stream, "###########\n");
  10777. fprintf(stream, "# Timings #\n");
  10778. fprintf(stream, "###########\n");
  10779. fprintf(stream, "\n");
  10780. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  10781. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  10782. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  10783. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  10784. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  10785. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  10786. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  10787. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  10788. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  10789. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  10790. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  10791. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  10792. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  10793. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  10794. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  10795. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  10796. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  10797. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  10798. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  10799. }
  10800. // For internal test use
  10801. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  10802. struct llama_context * ctx
  10803. ) {
  10804. return ctx->model.tensors_by_name;
  10805. }
  10806. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  10807. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  10808. g_state.log_callback_user_data = user_data;
  10809. #ifdef GGML_USE_METAL
  10810. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  10811. #endif
  10812. }
  10813. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  10814. va_list args_copy;
  10815. va_copy(args_copy, args);
  10816. char buffer[128];
  10817. int len = vsnprintf(buffer, 128, format, args);
  10818. if (len < 128) {
  10819. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  10820. } else {
  10821. char* buffer2 = new char[len+1];
  10822. vsnprintf(buffer2, len+1, format, args_copy);
  10823. buffer2[len] = 0;
  10824. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  10825. delete[] buffer2;
  10826. }
  10827. va_end(args_copy);
  10828. }
  10829. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  10830. va_list args;
  10831. va_start(args, format);
  10832. llama_log_internal_v(level, format, args);
  10833. va_end(args);
  10834. }
  10835. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  10836. (void) level;
  10837. (void) user_data;
  10838. fputs(text, stderr);
  10839. fflush(stderr);
  10840. }