llama.cpp 508 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019
  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_ATTN_NORM, "blk.%d.attn_norm" },
  473. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  474. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  475. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  476. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  477. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  478. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  479. },
  480. },
  481. {
  482. LLM_ARCH_STARCODER,
  483. {
  484. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  485. { LLM_TENSOR_POS_EMBD, "position_embd" },
  486. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  487. { LLM_TENSOR_OUTPUT, "output" },
  488. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  489. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  490. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  491. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  492. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  493. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  494. },
  495. },
  496. {
  497. LLM_ARCH_REFACT,
  498. {
  499. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  500. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  501. { LLM_TENSOR_OUTPUT, "output" },
  502. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  503. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  504. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  505. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  506. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  507. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  508. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  509. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  510. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  511. },
  512. },
  513. {
  514. LLM_ARCH_BERT,
  515. {
  516. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  517. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  518. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  519. { LLM_TENSOR_POS_EMBD, "position_embd" },
  520. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  521. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  522. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  523. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  524. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  525. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  526. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  527. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  528. },
  529. },
  530. {
  531. LLM_ARCH_NOMIC_BERT,
  532. {
  533. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  534. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  535. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  536. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  537. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  538. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  539. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  540. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  541. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  542. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  543. },
  544. },
  545. {
  546. LLM_ARCH_BLOOM,
  547. {
  548. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  549. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  550. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  551. { LLM_TENSOR_OUTPUT, "output" },
  552. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  553. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  554. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  555. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  556. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  557. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  558. },
  559. },
  560. {
  561. LLM_ARCH_STABLELM,
  562. {
  563. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  564. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  565. { LLM_TENSOR_OUTPUT, "output" },
  566. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  567. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  568. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  569. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  570. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  571. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  572. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  573. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  574. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  575. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  576. },
  577. },
  578. {
  579. LLM_ARCH_QWEN,
  580. {
  581. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  582. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  583. { LLM_TENSOR_OUTPUT, "output" },
  584. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  585. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  586. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  587. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  588. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  589. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  590. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  591. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  592. },
  593. },
  594. {
  595. LLM_ARCH_QWEN2,
  596. {
  597. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  598. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  599. { LLM_TENSOR_OUTPUT, "output" },
  600. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  601. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  602. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  603. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  604. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  605. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  606. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  607. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  608. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  609. },
  610. },
  611. {
  612. LLM_ARCH_PHI2,
  613. {
  614. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  615. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  616. { LLM_TENSOR_OUTPUT, "output" },
  617. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  618. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  619. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  620. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  621. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  622. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  623. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  624. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  625. },
  626. },
  627. {
  628. LLM_ARCH_PLAMO,
  629. {
  630. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  631. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  632. { LLM_TENSOR_OUTPUT, "output" },
  633. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  634. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  635. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  636. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  637. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  638. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  639. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  640. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  641. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  642. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  643. },
  644. },
  645. {
  646. LLM_ARCH_CODESHELL,
  647. {
  648. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  649. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  650. { LLM_TENSOR_OUTPUT, "output" },
  651. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  652. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  653. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  654. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  655. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  656. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  657. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  658. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  659. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  660. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  661. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  662. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  663. },
  664. },
  665. {
  666. LLM_ARCH_ORION,
  667. {
  668. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  669. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  670. { LLM_TENSOR_OUTPUT, "output" },
  671. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  672. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  673. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  674. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  675. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  676. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  677. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  678. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  679. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  680. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  681. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  682. },
  683. },
  684. {
  685. LLM_ARCH_INTERNLM2,
  686. {
  687. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  688. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  689. { LLM_TENSOR_OUTPUT, "output" },
  690. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  691. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  692. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  693. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  694. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  695. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  696. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  697. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  698. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  699. },
  700. },
  701. {
  702. LLM_ARCH_MINICPM,
  703. {
  704. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  705. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  706. { LLM_TENSOR_OUTPUT, "output" },
  707. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  708. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  709. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  710. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  711. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  712. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  713. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  714. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  715. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  716. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  717. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  718. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  719. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  720. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  721. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  722. },
  723. },
  724. {
  725. LLM_ARCH_GEMMA,
  726. {
  727. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  728. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  729. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  730. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  731. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  732. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  733. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  734. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  735. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  736. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  737. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  738. },
  739. },
  740. {
  741. LLM_ARCH_UNKNOWN,
  742. {
  743. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  744. },
  745. },
  746. };
  747. static llm_arch llm_arch_from_string(const std::string & name) {
  748. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  749. if (kv.second == name) {
  750. return kv.first;
  751. }
  752. }
  753. return LLM_ARCH_UNKNOWN;
  754. }
  755. // helper to handle gguf constants
  756. // usage:
  757. //
  758. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  759. //
  760. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  761. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  762. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  763. //
  764. struct LLM_TN {
  765. LLM_TN(llm_arch arch) : arch(arch) {}
  766. llm_arch arch;
  767. std::string operator()(llm_tensor tensor) const {
  768. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  769. return "__missing__";
  770. }
  771. return LLM_TENSOR_NAMES[arch].at(tensor);
  772. }
  773. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  774. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  775. return "__missing__";
  776. }
  777. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  778. }
  779. std::string operator()(llm_tensor tensor, int bid) const {
  780. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  781. return "__missing__";
  782. }
  783. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  784. }
  785. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  786. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  787. return "__missing__";
  788. }
  789. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  790. }
  791. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  792. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  793. return "__missing__";
  794. }
  795. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  796. }
  797. };
  798. //
  799. // gguf helpers
  800. //
  801. static std::map<int32_t, const char *> LLAMA_ROPE_SCALING_TYPES = {
  802. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  803. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  804. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  805. };
  806. static int32_t llama_rope_scaling_type_from_string(const std::string & name) {
  807. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  808. if (kv.second == name) {
  809. return kv.first;
  810. }
  811. }
  812. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  813. }
  814. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  815. switch (type) {
  816. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  817. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  818. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  819. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  820. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  821. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  822. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  823. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  824. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  825. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  826. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  827. default: return format("unknown type %d", type);
  828. }
  829. }
  830. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  831. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  832. switch (type) {
  833. case GGUF_TYPE_STRING:
  834. return gguf_get_val_str(ctx_gguf, i);
  835. case GGUF_TYPE_ARRAY:
  836. {
  837. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  838. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  839. const void * data = gguf_get_arr_data(ctx_gguf, i);
  840. std::stringstream ss;
  841. ss << "[";
  842. for (int j = 0; j < arr_n; j++) {
  843. if (arr_type == GGUF_TYPE_STRING) {
  844. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  845. // escape quotes
  846. replace_all(val, "\\", "\\\\");
  847. replace_all(val, "\"", "\\\"");
  848. ss << '"' << val << '"';
  849. } else if (arr_type == GGUF_TYPE_ARRAY) {
  850. ss << "???";
  851. } else {
  852. ss << gguf_data_to_str(arr_type, data, j);
  853. }
  854. if (j < arr_n - 1) {
  855. ss << ", ";
  856. }
  857. }
  858. ss << "]";
  859. return ss.str();
  860. }
  861. default:
  862. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  863. }
  864. }
  865. //
  866. // ggml helpers
  867. //
  868. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  869. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  870. if (plan.work_size > 0) {
  871. buf.resize(plan.work_size);
  872. plan.work_data = buf.data();
  873. }
  874. ggml_graph_compute(graph, &plan);
  875. }
  876. //
  877. // llama helpers
  878. //
  879. #if defined(_WIN32)
  880. static std::string llama_format_win_err(DWORD err) {
  881. LPSTR buf;
  882. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  883. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  884. if (!size) {
  885. return "FormatMessageA failed";
  886. }
  887. std::string ret(buf, size);
  888. LocalFree(buf);
  889. return ret;
  890. }
  891. #endif
  892. template <typename T>
  893. struct no_init {
  894. T value;
  895. no_init() { /* do nothing */ }
  896. };
  897. struct llama_file {
  898. // use FILE * so we don't have to re-open the file to mmap
  899. FILE * fp;
  900. size_t size;
  901. llama_file(const char * fname, const char * mode) {
  902. fp = std::fopen(fname, mode);
  903. if (fp == NULL) {
  904. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  905. }
  906. seek(0, SEEK_END);
  907. size = tell();
  908. seek(0, SEEK_SET);
  909. }
  910. size_t tell() const {
  911. #ifdef _WIN32
  912. __int64 ret = _ftelli64(fp);
  913. #else
  914. long ret = std::ftell(fp);
  915. #endif
  916. GGML_ASSERT(ret != -1); // this really shouldn't fail
  917. return (size_t) ret;
  918. }
  919. void seek(size_t offset, int whence) const {
  920. #ifdef _WIN32
  921. int ret = _fseeki64(fp, (__int64) offset, whence);
  922. #else
  923. int ret = std::fseek(fp, (long) offset, whence);
  924. #endif
  925. GGML_ASSERT(ret == 0); // same
  926. }
  927. void read_raw(void * ptr, size_t len) const {
  928. if (len == 0) {
  929. return;
  930. }
  931. errno = 0;
  932. std::size_t ret = std::fread(ptr, len, 1, fp);
  933. if (ferror(fp)) {
  934. throw std::runtime_error(format("read error: %s", strerror(errno)));
  935. }
  936. if (ret != 1) {
  937. throw std::runtime_error("unexpectedly reached end of file");
  938. }
  939. }
  940. uint32_t read_u32() const {
  941. uint32_t ret;
  942. read_raw(&ret, sizeof(ret));
  943. return ret;
  944. }
  945. void write_raw(const void * ptr, size_t len) const {
  946. if (len == 0) {
  947. return;
  948. }
  949. errno = 0;
  950. size_t ret = std::fwrite(ptr, len, 1, fp);
  951. if (ret != 1) {
  952. throw std::runtime_error(format("write error: %s", strerror(errno)));
  953. }
  954. }
  955. void write_u32(std::uint32_t val) const {
  956. write_raw(&val, sizeof(val));
  957. }
  958. ~llama_file() {
  959. if (fp) {
  960. std::fclose(fp);
  961. }
  962. }
  963. };
  964. struct llama_mmap {
  965. void * addr;
  966. size_t size;
  967. llama_mmap(const llama_mmap &) = delete;
  968. #ifdef _POSIX_MAPPED_FILES
  969. static constexpr bool SUPPORTED = true;
  970. // list of mapped fragments (first_offset, last_offset)
  971. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  972. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  973. size = file->size;
  974. int fd = fileno(file->fp);
  975. int flags = MAP_SHARED;
  976. // prefetch/readahead impairs performance on NUMA systems
  977. if (numa) { prefetch = 0; }
  978. #ifdef __linux__
  979. // advise the kernel to read the file sequentially (increases readahead)
  980. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  981. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  982. strerror(errno));
  983. }
  984. if (prefetch) { flags |= MAP_POPULATE; }
  985. #endif
  986. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  987. if (addr == MAP_FAILED) { // NOLINT
  988. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  989. }
  990. if (prefetch > 0) {
  991. // advise the kernel to preload the mapped memory
  992. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  993. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  994. strerror(errno));
  995. }
  996. }
  997. if (numa) {
  998. // advise the kernel not to use readahead
  999. // (because the next page might not belong on the same node)
  1000. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1001. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1002. strerror(errno));
  1003. }
  1004. }
  1005. // initialize list of mapped_fragments
  1006. mapped_fragments.emplace_back(0, file->size);
  1007. }
  1008. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1009. // align first to the next page
  1010. size_t offset_in_page = *first & (page_size - 1);
  1011. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1012. *first += offset_to_page;
  1013. // align last to the previous page
  1014. *last = *last & ~(page_size - 1);
  1015. if (*last <= *first) {
  1016. *last = *first;
  1017. }
  1018. }
  1019. // partially unmap the file in the range [first, last)
  1020. void unmap_fragment(size_t first, size_t last) {
  1021. // note: this function must not be called multiple times with overlapping ranges
  1022. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1023. int page_size = sysconf(_SC_PAGESIZE);
  1024. align_range(&first, &last, page_size);
  1025. size_t len = last - first;
  1026. if (len == 0) {
  1027. return;
  1028. }
  1029. GGML_ASSERT(first % page_size == 0);
  1030. GGML_ASSERT(last % page_size == 0);
  1031. GGML_ASSERT(last > first);
  1032. void * next_page_start = (uint8_t *) addr + first;
  1033. // unmap the range
  1034. if (munmap(next_page_start, len)) {
  1035. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1036. }
  1037. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1038. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1039. for (const auto & frag : mapped_fragments) {
  1040. if (frag.first < first && frag.second > last) {
  1041. // the range is in the middle of the fragment, split it
  1042. new_mapped_fragments.emplace_back(frag.first, first);
  1043. new_mapped_fragments.emplace_back(last, frag.second);
  1044. } else if (frag.first < first && frag.second > first) {
  1045. // the range starts in the middle of the fragment
  1046. new_mapped_fragments.emplace_back(frag.first, first);
  1047. } else if (frag.first < last && frag.second > last) {
  1048. // the range ends in the middle of the fragment
  1049. new_mapped_fragments.emplace_back(last, frag.second);
  1050. } else if (frag.first >= first && frag.second <= last) {
  1051. // the range covers the entire fragment
  1052. } else {
  1053. // the range is outside the fragment
  1054. new_mapped_fragments.push_back(frag);
  1055. }
  1056. }
  1057. mapped_fragments = std::move(new_mapped_fragments);
  1058. }
  1059. ~llama_mmap() {
  1060. for (const auto & frag : mapped_fragments) {
  1061. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1062. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1063. }
  1064. }
  1065. }
  1066. #elif defined(_WIN32)
  1067. static constexpr bool SUPPORTED = true;
  1068. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1069. GGML_UNUSED(numa);
  1070. size = file->size;
  1071. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1072. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1073. if (hMapping == NULL) {
  1074. DWORD error = GetLastError();
  1075. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1076. }
  1077. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1078. DWORD error = GetLastError();
  1079. CloseHandle(hMapping);
  1080. if (addr == NULL) {
  1081. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1082. }
  1083. if (prefetch > 0) {
  1084. #if _WIN32_WINNT >= 0x602
  1085. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1086. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1087. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1088. // may fail on pre-Windows 8 systems
  1089. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1090. if (pPrefetchVirtualMemory) {
  1091. // advise the kernel to preload the mapped memory
  1092. WIN32_MEMORY_RANGE_ENTRY range;
  1093. range.VirtualAddress = addr;
  1094. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1095. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1096. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1097. llama_format_win_err(GetLastError()).c_str());
  1098. }
  1099. }
  1100. #else
  1101. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1102. #endif
  1103. }
  1104. }
  1105. void unmap_fragment(size_t first, size_t last) {
  1106. // not supported
  1107. GGML_UNUSED(first);
  1108. GGML_UNUSED(last);
  1109. }
  1110. ~llama_mmap() {
  1111. if (!UnmapViewOfFile(addr)) {
  1112. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1113. llama_format_win_err(GetLastError()).c_str());
  1114. }
  1115. }
  1116. #else
  1117. static constexpr bool SUPPORTED = false;
  1118. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1119. GGML_UNUSED(file);
  1120. GGML_UNUSED(prefetch);
  1121. GGML_UNUSED(numa);
  1122. throw std::runtime_error("mmap not supported");
  1123. }
  1124. void unmap_fragment(size_t first, size_t last) {
  1125. GGML_UNUSED(first);
  1126. GGML_UNUSED(last);
  1127. throw std::runtime_error("mmap not supported");
  1128. }
  1129. #endif
  1130. };
  1131. // Represents some region of memory being locked using mlock or VirtualLock;
  1132. // will automatically unlock on destruction.
  1133. struct llama_mlock {
  1134. void * addr = NULL;
  1135. size_t size = 0;
  1136. bool failed_already = false;
  1137. llama_mlock() {}
  1138. llama_mlock(const llama_mlock &) = delete;
  1139. ~llama_mlock() {
  1140. if (size) {
  1141. raw_unlock(addr, size);
  1142. }
  1143. }
  1144. void init(void * ptr) {
  1145. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1146. addr = ptr;
  1147. }
  1148. void grow_to(size_t target_size) {
  1149. GGML_ASSERT(addr);
  1150. if (failed_already) {
  1151. return;
  1152. }
  1153. size_t granularity = lock_granularity();
  1154. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1155. if (target_size > size) {
  1156. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1157. size = target_size;
  1158. } else {
  1159. failed_already = true;
  1160. }
  1161. }
  1162. }
  1163. #ifdef _POSIX_MEMLOCK_RANGE
  1164. static constexpr bool SUPPORTED = true;
  1165. static size_t lock_granularity() {
  1166. return (size_t) sysconf(_SC_PAGESIZE);
  1167. }
  1168. #ifdef __APPLE__
  1169. #define MLOCK_SUGGESTION \
  1170. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1171. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1172. #else
  1173. #define MLOCK_SUGGESTION \
  1174. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1175. #endif
  1176. bool raw_lock(const void * addr, size_t size) const {
  1177. if (!mlock(addr, size)) {
  1178. return true;
  1179. }
  1180. char* errmsg = std::strerror(errno);
  1181. bool suggest = (errno == ENOMEM);
  1182. // Check if the resource limit is fine after all
  1183. struct rlimit lock_limit;
  1184. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1185. suggest = false;
  1186. }
  1187. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1188. suggest = false;
  1189. }
  1190. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1191. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1192. return false;
  1193. }
  1194. #undef MLOCK_SUGGESTION
  1195. static void raw_unlock(void * addr, size_t size) {
  1196. if (munlock(addr, size)) {
  1197. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1198. }
  1199. }
  1200. #elif defined(_WIN32)
  1201. static constexpr bool SUPPORTED = true;
  1202. static size_t lock_granularity() {
  1203. SYSTEM_INFO si;
  1204. GetSystemInfo(&si);
  1205. return (size_t) si.dwPageSize;
  1206. }
  1207. bool raw_lock(void * ptr, size_t len) const {
  1208. for (int tries = 1; ; tries++) {
  1209. if (VirtualLock(ptr, len)) {
  1210. return true;
  1211. }
  1212. if (tries == 2) {
  1213. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1214. len, size, llama_format_win_err(GetLastError()).c_str());
  1215. return false;
  1216. }
  1217. // It failed but this was only the first try; increase the working
  1218. // set size and try again.
  1219. SIZE_T min_ws_size, max_ws_size;
  1220. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1221. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1222. llama_format_win_err(GetLastError()).c_str());
  1223. return false;
  1224. }
  1225. // Per MSDN: "The maximum number of pages that a process can lock
  1226. // is equal to the number of pages in its minimum working set minus
  1227. // a small overhead."
  1228. // Hopefully a megabyte is enough overhead:
  1229. size_t increment = len + 1048576;
  1230. // The minimum must be <= the maximum, so we need to increase both:
  1231. min_ws_size += increment;
  1232. max_ws_size += increment;
  1233. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1234. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1235. llama_format_win_err(GetLastError()).c_str());
  1236. return false;
  1237. }
  1238. }
  1239. }
  1240. static void raw_unlock(void * ptr, size_t len) {
  1241. if (!VirtualUnlock(ptr, len)) {
  1242. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1243. llama_format_win_err(GetLastError()).c_str());
  1244. }
  1245. }
  1246. #else
  1247. static constexpr bool SUPPORTED = false;
  1248. static size_t lock_granularity() {
  1249. return (size_t) 65536;
  1250. }
  1251. bool raw_lock(const void * addr, size_t len) const {
  1252. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1253. return false;
  1254. }
  1255. static void raw_unlock(const void * addr, size_t len) {}
  1256. #endif
  1257. };
  1258. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1259. std::vector<char> result(8, 0);
  1260. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1261. if (n_tokens < 0) {
  1262. result.resize(-n_tokens);
  1263. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1264. GGML_ASSERT(check == -n_tokens);
  1265. }
  1266. else {
  1267. result.resize(n_tokens);
  1268. }
  1269. return std::string(result.data(), result.size());
  1270. }
  1271. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1272. ggml_backend_buffer_type_t buft = nullptr;
  1273. #if defined(GGML_USE_CUBLAS)
  1274. // host buffers should only be used when data is expected to be copied to/from the GPU
  1275. if (host_buffer) {
  1276. buft = ggml_backend_cuda_host_buffer_type();
  1277. }
  1278. #elif defined(GGML_USE_SYCL)
  1279. buft = ggml_backend_sycl_host_buffer_type();
  1280. #elif defined(GGML_USE_CPU_HBM)
  1281. buft = ggml_backend_cpu_hbm_buffer_type();
  1282. #elif defined(GGML_USE_VULKAN)
  1283. if (host_buffer) {
  1284. buft = ggml_backend_vk_host_buffer_type();
  1285. }
  1286. #endif
  1287. if (buft == nullptr) {
  1288. buft = ggml_backend_cpu_buffer_type();
  1289. }
  1290. return buft;
  1291. GGML_UNUSED(host_buffer);
  1292. }
  1293. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1294. ggml_backend_buffer_type_t buft = nullptr;
  1295. #ifdef GGML_USE_METAL
  1296. buft = ggml_backend_metal_buffer_type();
  1297. #elif defined(GGML_USE_CUBLAS)
  1298. buft = ggml_backend_cuda_buffer_type(gpu);
  1299. #elif defined(GGML_USE_VULKAN)
  1300. buft = ggml_backend_vk_buffer_type(gpu);
  1301. #elif defined(GGML_USE_SYCL)
  1302. buft = ggml_backend_sycl_buffer_type(gpu);
  1303. #elif defined(GGML_USE_CLBLAST)
  1304. buft = ggml_backend_opencl_buffer_type();
  1305. #elif defined(GGML_USE_KOMPUTE)
  1306. buft = ggml_backend_kompute_buffer_type(gpu);
  1307. if (buft == nullptr) {
  1308. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1309. }
  1310. #endif
  1311. if (buft == nullptr) {
  1312. buft = llama_default_buffer_type_cpu(true);
  1313. }
  1314. return buft;
  1315. GGML_UNUSED(gpu);
  1316. }
  1317. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1318. ggml_backend_buffer_type_t buft = nullptr;
  1319. #ifdef GGML_USE_CUBLAS
  1320. if (ggml_backend_cuda_get_device_count() > 1) {
  1321. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1322. }
  1323. #endif
  1324. if (buft == nullptr) {
  1325. buft = llama_default_buffer_type_offload(fallback_gpu);
  1326. }
  1327. return buft;
  1328. GGML_UNUSED(tensor_split);
  1329. }
  1330. static size_t llama_get_device_count() {
  1331. #if defined(GGML_USE_CUBLAS)
  1332. return ggml_backend_cuda_get_device_count();
  1333. #elif defined(GGML_USE_VULKAN)
  1334. return ggml_backend_vk_get_device_count();
  1335. #else
  1336. return 1;
  1337. #endif
  1338. }
  1339. static size_t llama_get_device_memory(int device) {
  1340. #if defined(GGML_USE_CUBLAS)
  1341. size_t total;
  1342. size_t free;
  1343. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1344. return free;
  1345. #elif defined(GGML_USE_VULKAN)
  1346. size_t total;
  1347. size_t free;
  1348. ggml_backend_vk_get_device_memory(device, &total, &free);
  1349. return free;
  1350. #else
  1351. return 1;
  1352. GGML_UNUSED(device);
  1353. #endif
  1354. }
  1355. //
  1356. // globals
  1357. //
  1358. struct llama_state {
  1359. llama_state() {
  1360. #ifdef GGML_USE_METAL
  1361. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1362. #endif
  1363. }
  1364. // We save the log callback globally
  1365. ggml_log_callback log_callback = llama_log_callback_default;
  1366. void * log_callback_user_data = nullptr;
  1367. };
  1368. static llama_state g_state;
  1369. // available llama models
  1370. enum e_model {
  1371. MODEL_UNKNOWN,
  1372. MODEL_17M,
  1373. MODEL_22M,
  1374. MODEL_33M,
  1375. MODEL_109M,
  1376. MODEL_137M,
  1377. MODEL_335M,
  1378. MODEL_0_5B,
  1379. MODEL_1B,
  1380. MODEL_2B,
  1381. MODEL_3B,
  1382. MODEL_4B,
  1383. MODEL_7B,
  1384. MODEL_8B,
  1385. MODEL_13B,
  1386. MODEL_14B,
  1387. MODEL_15B,
  1388. MODEL_20B,
  1389. MODEL_30B,
  1390. MODEL_34B,
  1391. MODEL_40B,
  1392. MODEL_65B,
  1393. MODEL_70B,
  1394. MODEL_SMALL,
  1395. MODEL_MEDIUM,
  1396. MODEL_LARGE,
  1397. MODEL_XL,
  1398. };
  1399. static const size_t kiB = 1024;
  1400. static const size_t MiB = 1024*kiB;
  1401. static const size_t GiB = 1024*MiB;
  1402. struct llama_hparams {
  1403. bool vocab_only;
  1404. bool rope_finetuned;
  1405. uint32_t n_vocab;
  1406. uint32_t n_ctx_train; // context size the model was trained on
  1407. uint32_t n_embd;
  1408. uint32_t n_head;
  1409. uint32_t n_head_kv;
  1410. uint32_t n_layer;
  1411. uint32_t n_rot;
  1412. 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
  1413. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1414. uint32_t n_ff;
  1415. uint32_t n_expert = 0;
  1416. uint32_t n_expert_used = 0;
  1417. uint32_t n_vocab_type = 0; // for BERT-style token types
  1418. float f_norm_eps;
  1419. float f_norm_rms_eps;
  1420. float rope_freq_base_train;
  1421. float rope_freq_scale_train;
  1422. uint32_t n_yarn_orig_ctx;
  1423. int32_t rope_scaling_type_train;
  1424. float f_clamp_kqv = 0.0f;
  1425. float f_max_alibi_bias = 0.0f;
  1426. bool causal_attn = true;
  1427. bool need_kq_pos = false;
  1428. uint32_t pooling_type = LLAMA_POOLING_TYPE_NONE;
  1429. bool operator!=(const llama_hparams & other) const {
  1430. if (this->vocab_only != other.vocab_only) return true;
  1431. if (this->n_vocab != other.n_vocab) return true;
  1432. if (this->n_ctx_train != other.n_ctx_train) return true;
  1433. if (this->n_embd != other.n_embd) return true;
  1434. if (this->n_head != other.n_head) return true;
  1435. if (this->n_head_kv != other.n_head_kv) return true;
  1436. if (this->n_layer != other.n_layer) return true;
  1437. if (this->n_rot != other.n_rot) return true;
  1438. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1439. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1440. if (this->n_ff != other.n_ff) return true;
  1441. if (this->n_expert != other.n_expert) return true;
  1442. if (this->n_expert_used != other.n_expert_used) return true;
  1443. if (this->rope_finetuned != other.rope_finetuned) return true;
  1444. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1445. const float EPSILON = 1e-9f;
  1446. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1447. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1448. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1449. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1450. return false;
  1451. }
  1452. uint32_t n_gqa() const {
  1453. return n_head/n_head_kv;
  1454. }
  1455. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1456. return n_embd_head_k * n_head_kv;
  1457. }
  1458. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1459. return n_embd_head_v * n_head_kv;
  1460. }
  1461. };
  1462. struct llama_cparams {
  1463. uint32_t n_ctx; // context size used during inference
  1464. uint32_t n_batch;
  1465. uint32_t n_threads; // number of threads to use for generation
  1466. uint32_t n_threads_batch; // number of threads to use for batch processing
  1467. float rope_freq_base;
  1468. float rope_freq_scale;
  1469. uint32_t n_yarn_orig_ctx;
  1470. // These hyperparameters are not exposed in GGUF, because all
  1471. // existing YaRN models use the same values for them.
  1472. float yarn_ext_factor;
  1473. float yarn_attn_factor;
  1474. float yarn_beta_fast;
  1475. float yarn_beta_slow;
  1476. bool mul_mat_q;
  1477. bool offload_kqv;
  1478. bool do_pooling;
  1479. ggml_backend_sched_eval_callback cb_eval;
  1480. void * cb_eval_user_data;
  1481. };
  1482. struct llama_layer {
  1483. // normalization
  1484. struct ggml_tensor * attn_norm;
  1485. struct ggml_tensor * attn_norm_b;
  1486. struct ggml_tensor * attn_norm_2;
  1487. struct ggml_tensor * attn_norm_2_b;
  1488. struct ggml_tensor * attn_q_norm;
  1489. struct ggml_tensor * attn_q_norm_b;
  1490. struct ggml_tensor * attn_k_norm;
  1491. struct ggml_tensor * attn_k_norm_b;
  1492. struct ggml_tensor * attn_out_norm;
  1493. struct ggml_tensor * attn_out_norm_b;
  1494. // attention
  1495. struct ggml_tensor * wq;
  1496. struct ggml_tensor * wk;
  1497. struct ggml_tensor * wv;
  1498. struct ggml_tensor * wo;
  1499. struct ggml_tensor * wqkv;
  1500. // attention bias
  1501. struct ggml_tensor * bq;
  1502. struct ggml_tensor * bk;
  1503. struct ggml_tensor * bv;
  1504. struct ggml_tensor * bo;
  1505. struct ggml_tensor * bqkv;
  1506. // normalization
  1507. struct ggml_tensor * ffn_norm;
  1508. struct ggml_tensor * ffn_norm_b;
  1509. struct ggml_tensor * layer_out_norm;
  1510. struct ggml_tensor * layer_out_norm_b;
  1511. // ff
  1512. struct ggml_tensor * ffn_gate; // w1
  1513. struct ggml_tensor * ffn_down; // w2
  1514. struct ggml_tensor * ffn_up; // w3
  1515. // ff MoE
  1516. struct ggml_tensor * ffn_gate_inp;
  1517. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1518. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1519. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1520. // ff bias
  1521. struct ggml_tensor * ffn_down_b; // b2
  1522. struct ggml_tensor * ffn_up_b; // b3
  1523. struct ggml_tensor * ffn_act;
  1524. };
  1525. struct llama_kv_cell {
  1526. llama_pos pos = -1;
  1527. llama_pos delta = 0;
  1528. std::set<llama_seq_id> seq_id;
  1529. bool has_seq_id(const llama_seq_id & id) const {
  1530. return seq_id.find(id) != seq_id.end();
  1531. }
  1532. };
  1533. // ring-buffer of cached KV data
  1534. struct llama_kv_cache {
  1535. bool has_shift = false;
  1536. // Note: The value of head isn't only used to optimize searching
  1537. // for a free KV slot. llama_decode_internal also uses it, so it
  1538. // cannot be freely changed after a slot has been allocated.
  1539. uint32_t head = 0;
  1540. uint32_t size = 0;
  1541. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1542. // computed before each graph build
  1543. uint32_t n = 0;
  1544. std::vector<llama_kv_cell> cells;
  1545. std::vector<struct ggml_tensor *> k_l; // per layer
  1546. std::vector<struct ggml_tensor *> v_l;
  1547. std::vector<struct ggml_context *> ctxs;
  1548. std::vector<ggml_backend_buffer_t> bufs;
  1549. size_t total_size() const {
  1550. size_t size = 0;
  1551. for (ggml_backend_buffer_t buf : bufs) {
  1552. size += ggml_backend_buffer_get_size(buf);
  1553. }
  1554. return size;
  1555. }
  1556. ~llama_kv_cache() {
  1557. for (struct ggml_context * ctx : ctxs) {
  1558. ggml_free(ctx);
  1559. }
  1560. for (ggml_backend_buffer_t buf : bufs) {
  1561. ggml_backend_buffer_free(buf);
  1562. }
  1563. }
  1564. };
  1565. struct llama_vocab {
  1566. using id = int32_t;
  1567. using token = std::string;
  1568. using ttype = llama_token_type;
  1569. struct token_data {
  1570. token text;
  1571. float score;
  1572. ttype type;
  1573. };
  1574. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1575. std::unordered_map<token, id> token_to_id;
  1576. std::vector<token_data> id_to_token;
  1577. std::unordered_map<token, id> special_tokens_cache;
  1578. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1579. // default LLaMA special tokens
  1580. id special_bos_id = 1;
  1581. id special_eos_id = 2;
  1582. id special_unk_id = 0;
  1583. id special_sep_id = -1;
  1584. id special_pad_id = -1;
  1585. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1586. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1587. id linefeed_id = 13;
  1588. id special_prefix_id = 32007;
  1589. id special_middle_id = 32009;
  1590. id special_suffix_id = 32008;
  1591. id special_eot_id = 32010;
  1592. bool add_space_prefix = true;
  1593. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1594. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1595. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1596. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1597. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1598. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1599. if (it == bpe_ranks.end()) {
  1600. return -1;
  1601. }
  1602. return it->second;
  1603. }
  1604. };
  1605. struct llama_model {
  1606. e_model type = MODEL_UNKNOWN;
  1607. llm_arch arch = LLM_ARCH_UNKNOWN;
  1608. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1609. std::string name = "n/a";
  1610. llama_hparams hparams = {};
  1611. llama_vocab vocab;
  1612. struct ggml_tensor * tok_embd;
  1613. struct ggml_tensor * type_embd;
  1614. struct ggml_tensor * pos_embd;
  1615. struct ggml_tensor * tok_norm;
  1616. struct ggml_tensor * tok_norm_b;
  1617. struct ggml_tensor * output_norm;
  1618. struct ggml_tensor * output_norm_b;
  1619. struct ggml_tensor * output;
  1620. struct ggml_tensor * output_b;
  1621. std::vector<llama_layer> layers;
  1622. llama_split_mode split_mode;
  1623. int main_gpu;
  1624. int n_gpu_layers;
  1625. // gguf metadata
  1626. std::unordered_map<std::string, std::string> gguf_kv;
  1627. // layer -> buffer type mapping
  1628. struct layer_buft {
  1629. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1630. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1631. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1632. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1633. ggml_backend_buffer_type_t buft; // everything else
  1634. };
  1635. layer_buft buft_input;
  1636. layer_buft buft_output;
  1637. std::vector<layer_buft> buft_layer;
  1638. // contexts where the model tensors metadata is stored
  1639. std::vector<struct ggml_context *> ctxs;
  1640. // the model memory buffers for the tensor data
  1641. std::vector<ggml_backend_buffer_t> bufs;
  1642. // model memory mapped file
  1643. std::unique_ptr<llama_mmap> mapping;
  1644. // objects representing data potentially being locked in memory
  1645. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1646. llama_mlock mlock_mmap;
  1647. // for quantize-stats only
  1648. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1649. int64_t t_load_us = 0;
  1650. int64_t t_start_us = 0;
  1651. ~llama_model() {
  1652. for (struct ggml_context * ctx : ctxs) {
  1653. ggml_free(ctx);
  1654. }
  1655. for (ggml_backend_buffer_t buf : bufs) {
  1656. ggml_backend_buffer_free(buf);
  1657. }
  1658. }
  1659. };
  1660. struct llama_context {
  1661. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1662. ~llama_context() {
  1663. ggml_backend_sched_free(sched);
  1664. for (ggml_backend_t backend : backends) {
  1665. ggml_backend_free(backend);
  1666. }
  1667. #ifdef GGML_USE_VULKAN
  1668. ggml_vk_free_cpu_assist();
  1669. #endif
  1670. ggml_backend_buffer_free(buf_input);
  1671. ggml_free(ctx_input);
  1672. }
  1673. llama_cparams cparams;
  1674. std::vector<ggml_backend_t> backends;
  1675. #ifdef GGML_USE_METAL
  1676. ggml_backend_t backend_metal = nullptr;
  1677. #endif
  1678. ggml_backend_t backend_cpu = nullptr;
  1679. const llama_model & model;
  1680. // key + value cache for the self attention
  1681. struct llama_kv_cache kv_self;
  1682. std::mt19937 rng;
  1683. bool has_evaluated_once = false;
  1684. int64_t t_start_us;
  1685. int64_t t_load_us;
  1686. int64_t t_sample_us = 0;
  1687. int64_t t_p_eval_us = 0;
  1688. int64_t t_eval_us = 0;
  1689. int32_t n_sample = 0; // number of tokens sampled
  1690. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1691. int32_t n_eval = 0; // number of eval calls
  1692. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1693. std::vector<float> logits;
  1694. #ifndef NDEBUG
  1695. // guard against access to unset logits
  1696. std::vector<bool> logits_valid;
  1697. #endif
  1698. bool logits_all = false;
  1699. // input embedding (1-dimensional array: [n_embd])
  1700. std::vector<float> embedding;
  1701. // memory buffers used to evaluate the model
  1702. std::vector<uint8_t> buf_compute_meta;
  1703. ggml_backend_sched_t sched = nullptr;
  1704. // input tensors
  1705. ggml_backend_buffer_t buf_input = nullptr;
  1706. ggml_context * ctx_input = nullptr;
  1707. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1708. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1709. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1710. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1711. struct ggml_tensor * inp_KQ_pos; // F32 [n_ctx]
  1712. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1713. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1714. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1715. #ifdef GGML_USE_MPI
  1716. ggml_mpi_context * ctx_mpi = NULL;
  1717. #endif
  1718. };
  1719. //
  1720. // kv cache helpers
  1721. //
  1722. static bool llama_kv_cache_init(
  1723. struct llama_kv_cache & cache,
  1724. const llama_model & model,
  1725. ggml_type ktype,
  1726. ggml_type vtype,
  1727. uint32_t n_ctx,
  1728. bool offload) {
  1729. const struct llama_hparams & hparams = model.hparams;
  1730. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1731. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1732. const int64_t n_layer = hparams.n_layer;
  1733. cache.has_shift = false;
  1734. cache.head = 0;
  1735. cache.size = n_ctx;
  1736. cache.used = 0;
  1737. cache.cells.clear();
  1738. cache.cells.resize(n_ctx);
  1739. #ifdef GGML_USE_CLBLAST
  1740. offload = false;
  1741. #endif
  1742. // count used buffer types
  1743. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1744. if (offload) {
  1745. for (int64_t i = 0; i < n_layer; ++i) {
  1746. buft_layer_count[model.buft_layer[i].buft]++;
  1747. }
  1748. } else {
  1749. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1750. }
  1751. // create a context for each buffer type
  1752. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1753. for (auto & it : buft_layer_count) {
  1754. int n_layers = it.second;
  1755. struct ggml_init_params params = {
  1756. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1757. /*.mem_buffer =*/ NULL,
  1758. /*.no_alloc =*/ true,
  1759. };
  1760. ggml_context * ctx = ggml_init(params);
  1761. if (!ctx) {
  1762. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1763. return false;
  1764. }
  1765. ctx_map[it.first] = ctx;
  1766. cache.ctxs.push_back(ctx);
  1767. }
  1768. cache.k_l.reserve(n_layer);
  1769. cache.v_l.reserve(n_layer);
  1770. for (int i = 0; i < (int) n_layer; i++) {
  1771. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1772. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1773. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1774. ggml_format_name(k, "cache_k_l%d", i);
  1775. ggml_format_name(v, "cache_v_l%d", i);
  1776. cache.k_l.push_back(k);
  1777. cache.v_l.push_back(v);
  1778. }
  1779. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1780. for (auto it : ctx_map) {
  1781. ggml_backend_buffer_type_t buft = it.first;
  1782. ggml_context * ctx = it.second;
  1783. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1784. if (!buf) {
  1785. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1786. return false;
  1787. }
  1788. ggml_backend_buffer_clear(buf, 0);
  1789. 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);
  1790. cache.bufs.push_back(buf);
  1791. }
  1792. return true;
  1793. }
  1794. // find an empty slot of size "n_tokens" in the cache
  1795. // updates the cache head
  1796. // Note: On success, it's important that cache.head points
  1797. // to the first cell of the slot.
  1798. static bool llama_kv_cache_find_slot(
  1799. struct llama_kv_cache & cache,
  1800. const struct llama_batch & batch) {
  1801. const uint32_t n_ctx = cache.size;
  1802. const uint32_t n_tokens = batch.n_tokens;
  1803. if (n_tokens > n_ctx) {
  1804. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1805. return false;
  1806. }
  1807. uint32_t n_tested = 0;
  1808. while (true) {
  1809. if (cache.head + n_tokens > n_ctx) {
  1810. n_tested += n_ctx - cache.head;
  1811. cache.head = 0;
  1812. continue;
  1813. }
  1814. bool found = true;
  1815. for (uint32_t i = 0; i < n_tokens; i++) {
  1816. if (cache.cells[cache.head + i].pos >= 0) {
  1817. found = false;
  1818. cache.head += i + 1;
  1819. n_tested += i + 1;
  1820. break;
  1821. }
  1822. }
  1823. if (found) {
  1824. break;
  1825. }
  1826. if (n_tested >= n_ctx) {
  1827. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1828. return false;
  1829. }
  1830. }
  1831. for (uint32_t i = 0; i < n_tokens; i++) {
  1832. cache.cells[cache.head + i].pos = batch.pos[i];
  1833. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1834. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1835. }
  1836. }
  1837. cache.used += n_tokens;
  1838. return true;
  1839. }
  1840. // find how many cells are currently in use
  1841. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1842. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1843. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1844. return i + 1;
  1845. }
  1846. }
  1847. return 0;
  1848. }
  1849. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1850. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1851. cache.cells[i].pos = -1;
  1852. cache.cells[i].seq_id.clear();
  1853. }
  1854. cache.head = 0;
  1855. cache.used = 0;
  1856. }
  1857. static void llama_kv_cache_seq_rm(
  1858. struct llama_kv_cache & cache,
  1859. llama_seq_id seq_id,
  1860. llama_pos p0,
  1861. llama_pos p1) {
  1862. uint32_t new_head = cache.size;
  1863. if (p0 < 0) p0 = 0;
  1864. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1865. for (uint32_t i = 0; i < cache.size; ++i) {
  1866. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1867. if (seq_id < 0) {
  1868. cache.cells[i].seq_id.clear();
  1869. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1870. cache.cells[i].seq_id.erase(seq_id);
  1871. } else {
  1872. continue;
  1873. }
  1874. if (cache.cells[i].seq_id.empty()) {
  1875. // keep count of the number of used cells
  1876. if (cache.cells[i].pos >= 0) cache.used--;
  1877. cache.cells[i].pos = -1;
  1878. if (new_head == cache.size) new_head = i;
  1879. }
  1880. }
  1881. }
  1882. // If we freed up a slot, set head to it so searching can start there.
  1883. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1884. }
  1885. static void llama_kv_cache_seq_cp(
  1886. struct llama_kv_cache & cache,
  1887. llama_seq_id seq_id_src,
  1888. llama_seq_id seq_id_dst,
  1889. llama_pos p0,
  1890. llama_pos p1) {
  1891. if (p0 < 0) p0 = 0;
  1892. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1893. cache.head = 0;
  1894. for (uint32_t i = 0; i < cache.size; ++i) {
  1895. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1896. cache.cells[i].seq_id.insert(seq_id_dst);
  1897. }
  1898. }
  1899. }
  1900. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1901. uint32_t new_head = cache.size;
  1902. for (uint32_t i = 0; i < cache.size; ++i) {
  1903. if (!cache.cells[i].has_seq_id(seq_id)) {
  1904. if (cache.cells[i].pos >= 0) cache.used--;
  1905. cache.cells[i].pos = -1;
  1906. cache.cells[i].seq_id.clear();
  1907. if (new_head == cache.size) new_head = i;
  1908. } else {
  1909. cache.cells[i].seq_id.clear();
  1910. cache.cells[i].seq_id.insert(seq_id);
  1911. }
  1912. }
  1913. // If we freed up a slot, set head to it so searching can start there.
  1914. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1915. }
  1916. static void llama_kv_cache_seq_shift(
  1917. struct llama_kv_cache & cache,
  1918. llama_seq_id seq_id,
  1919. llama_pos p0,
  1920. llama_pos p1,
  1921. llama_pos delta) {
  1922. uint32_t new_head = cache.size;
  1923. if (p0 < 0) p0 = 0;
  1924. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1925. for (uint32_t i = 0; i < cache.size; ++i) {
  1926. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1927. cache.has_shift = true;
  1928. cache.cells[i].pos += delta;
  1929. cache.cells[i].delta += delta;
  1930. if (cache.cells[i].pos < 0) {
  1931. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1932. cache.cells[i].pos = -1;
  1933. cache.cells[i].seq_id.clear();
  1934. if (new_head == cache.size) new_head = i;
  1935. }
  1936. }
  1937. }
  1938. // If we freed up a slot, set head to it so searching can start there.
  1939. // Otherwise we just start the next search from the beginning.
  1940. cache.head = new_head != cache.size ? new_head : 0;
  1941. }
  1942. static void llama_kv_cache_seq_div(
  1943. struct llama_kv_cache & cache,
  1944. llama_seq_id seq_id,
  1945. llama_pos p0,
  1946. llama_pos p1,
  1947. int d) {
  1948. if (p0 < 0) p0 = 0;
  1949. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1950. for (uint32_t i = 0; i < cache.size; ++i) {
  1951. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1952. cache.has_shift = true;
  1953. {
  1954. llama_pos p_old = cache.cells[i].pos;
  1955. cache.cells[i].pos /= d;
  1956. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1957. }
  1958. }
  1959. }
  1960. }
  1961. //
  1962. // model loading and saving
  1963. //
  1964. enum llama_fver {
  1965. GGUF_FILE_VERSION_V1 = 1,
  1966. GGUF_FILE_VERSION_V2 = 2,
  1967. GGUF_FILE_VERSION_V3 = 3,
  1968. };
  1969. static const char * llama_file_version_name(llama_fver version) {
  1970. switch (version) {
  1971. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1972. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1973. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1974. }
  1975. return "unknown";
  1976. }
  1977. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1978. char buf[256];
  1979. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1980. for (size_t i = 1; i < ne.size(); i++) {
  1981. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1982. }
  1983. return buf;
  1984. }
  1985. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1986. char buf[256];
  1987. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1988. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1989. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1990. }
  1991. return buf;
  1992. }
  1993. namespace GGUFMeta {
  1994. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1995. struct GKV_Base_Type {
  1996. static constexpr gguf_type gt = gt_;
  1997. static T getter(const gguf_context * ctx, const int kid) {
  1998. return gfun(ctx, kid);
  1999. }
  2000. };
  2001. template<typename T> struct GKV_Base;
  2002. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2003. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2004. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2005. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2006. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2007. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2008. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2009. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2010. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2011. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2012. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2013. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2014. template<> struct GKV_Base<std::string> {
  2015. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2016. static std::string getter(const gguf_context * ctx, const int kid) {
  2017. return gguf_get_val_str(ctx, kid);
  2018. }
  2019. };
  2020. struct ArrayInfo{
  2021. const gguf_type gt;
  2022. const size_t length;
  2023. const void * data;
  2024. };
  2025. template<> struct GKV_Base<ArrayInfo> {
  2026. public:
  2027. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2028. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2029. return ArrayInfo {
  2030. gguf_get_arr_type(ctx, k),
  2031. size_t(gguf_get_arr_n(ctx, k)),
  2032. gguf_get_arr_data(ctx, k),
  2033. };
  2034. }
  2035. };
  2036. template<typename T>
  2037. class GKV: public GKV_Base<T> {
  2038. GKV() = delete;
  2039. public:
  2040. static T get_kv(const gguf_context * ctx, const int k) {
  2041. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2042. if (kt != GKV::gt) {
  2043. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2044. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2045. }
  2046. return GKV::getter(ctx, k);
  2047. }
  2048. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2049. switch (ty) {
  2050. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2051. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2052. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2053. }
  2054. return "unknown";
  2055. }
  2056. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  2057. if (!override) { return false; }
  2058. if (override->tag == expected_type) {
  2059. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2060. __func__, override_type_to_str(override->tag), override->key);
  2061. switch (override->tag) {
  2062. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2063. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  2064. } break;
  2065. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2066. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  2067. } break;
  2068. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2069. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  2070. } break;
  2071. default:
  2072. // Shouldn't be possible to end up here, but just in case...
  2073. throw std::runtime_error(
  2074. format("Unsupported attempt to override %s type for metadata key %s\n",
  2075. override_type_to_str(override->tag), override->key));
  2076. }
  2077. return true;
  2078. }
  2079. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2080. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  2081. return false;
  2082. }
  2083. template<typename OT>
  2084. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2085. try_override(OT & target, const struct llama_model_kv_override *override) {
  2086. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, override)) {
  2087. target = override->bool_value;
  2088. return true;
  2089. }
  2090. return false;
  2091. }
  2092. template<typename OT>
  2093. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2094. try_override(OT & target, const struct llama_model_kv_override *override) {
  2095. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, override)) {
  2096. target = override->int_value;
  2097. return true;
  2098. }
  2099. return false;
  2100. }
  2101. template<typename OT>
  2102. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2103. try_override(T & target, const struct llama_model_kv_override *override) {
  2104. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, override)) {
  2105. target = override->float_value;
  2106. return true;
  2107. }
  2108. return false;
  2109. }
  2110. template<typename OT>
  2111. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2112. try_override(T & target, const struct llama_model_kv_override *override) {
  2113. (void)target;
  2114. (void)override;
  2115. if (!override) { return false; }
  2116. // Currently, we should never end up here so it would be a bug if we do.
  2117. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2118. override ? override->key : "NULL"));
  2119. }
  2120. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  2121. if (try_override<T>(target, override)) {
  2122. return true;
  2123. }
  2124. if (k < 0) { return false; }
  2125. target = get_kv(ctx, k);
  2126. return true;
  2127. }
  2128. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  2129. return set(ctx, gguf_find_key(ctx, key), target, override);
  2130. }
  2131. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  2132. return set(ctx, key.c_str(), target, override);
  2133. }
  2134. };
  2135. }
  2136. struct llama_model_loader {
  2137. int n_kv = 0;
  2138. int n_tensors = 0;
  2139. int n_created = 0;
  2140. int64_t n_elements = 0;
  2141. size_t n_bytes = 0;
  2142. bool use_mmap = false;
  2143. llama_file file;
  2144. llama_ftype ftype;
  2145. llama_fver fver;
  2146. std::unique_ptr<llama_mmap> mapping;
  2147. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2148. struct gguf_context * ctx_gguf = NULL;
  2149. struct ggml_context * ctx_meta = NULL;
  2150. std::string arch_name;
  2151. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2152. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2153. int trace = 0;
  2154. if (getenv("LLAMA_TRACE")) {
  2155. trace = atoi(getenv("LLAMA_TRACE"));
  2156. }
  2157. struct gguf_init_params params = {
  2158. /*.no_alloc = */ true,
  2159. /*.ctx = */ &ctx_meta,
  2160. };
  2161. if (param_overrides_p != nullptr) {
  2162. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2163. kv_overrides.insert({std::string(p->key), *p});
  2164. }
  2165. }
  2166. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2167. if (!ctx_gguf) {
  2168. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2169. }
  2170. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2171. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2172. n_kv = gguf_get_n_kv(ctx_gguf);
  2173. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2174. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2175. for (int i = 0; i < n_tensors; i++) {
  2176. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2177. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2178. n_elements += ggml_nelements(t);
  2179. n_bytes += ggml_nbytes(t);
  2180. }
  2181. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2182. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2183. // determine file type based on the number of tensors for each quantization and print meta data
  2184. // TODO: make optional
  2185. {
  2186. std::map<enum ggml_type, uint32_t> n_type;
  2187. uint32_t n_type_max = 0;
  2188. enum ggml_type type_max = GGML_TYPE_F32;
  2189. for (int i = 0; i < n_tensors; i++) {
  2190. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2191. n_type[type]++;
  2192. if (n_type_max < n_type[type]) {
  2193. n_type_max = n_type[type];
  2194. type_max = type;
  2195. }
  2196. if (trace > 0) {
  2197. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2198. 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());
  2199. }
  2200. }
  2201. switch (type_max) {
  2202. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2203. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2204. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2205. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2206. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2207. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2208. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2209. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2210. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2211. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2212. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2213. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2214. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2215. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2216. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2217. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2218. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2219. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; 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 (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2417. if (progress_callback) {
  2418. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2419. return false;
  2420. }
  2421. }
  2422. const size_t offs = file_offset(ggml_get_name(cur));
  2423. if (use_mmap && mapping) {
  2424. if (buf_mmap && cur->data == nullptr) {
  2425. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2426. if (lmlock) {
  2427. lmlock->grow_to(offs + ggml_nbytes(cur));
  2428. }
  2429. mmap_used_first = std::min(mmap_used_first, offs);
  2430. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2431. } else {
  2432. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2433. }
  2434. } else {
  2435. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2436. file.seek(offs, SEEK_SET);
  2437. file.read_raw(cur->data, ggml_nbytes(cur));
  2438. } else {
  2439. read_buf.resize(ggml_nbytes(cur));
  2440. file.seek(offs, SEEK_SET);
  2441. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2442. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2443. }
  2444. }
  2445. size_done += ggml_nbytes(cur);
  2446. }
  2447. // check if this is the last call and do final cleanup
  2448. if (size_done >= size_data) {
  2449. // unmap offloaded tensors and metadata
  2450. if (use_mmap && mapping) {
  2451. mapping->unmap_fragment(0, mmap_used_first);
  2452. if (mmap_used_last != 0) {
  2453. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2454. }
  2455. }
  2456. if (progress_callback) {
  2457. // Even though the model is done loading, we still honor
  2458. // cancellation since we need to free allocations.
  2459. return progress_callback(1.0f, progress_callback_user_data);
  2460. }
  2461. }
  2462. return true;
  2463. }
  2464. };
  2465. //
  2466. // load LLaMA models
  2467. //
  2468. static const char * llama_model_arch_name(llm_arch arch) {
  2469. auto it = LLM_ARCH_NAMES.find(arch);
  2470. if (it == LLM_ARCH_NAMES.end()) {
  2471. return "unknown";
  2472. }
  2473. return it->second;
  2474. }
  2475. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2476. if (ftype & LLAMA_FTYPE_GUESSED) {
  2477. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2478. }
  2479. switch (ftype) {
  2480. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2481. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2482. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2483. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2484. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2485. return "Q4_1, some F16";
  2486. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2487. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2488. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2489. // K-quants
  2490. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2491. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2492. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2493. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2494. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2495. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2496. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2497. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2498. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2499. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2500. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2501. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2502. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:return "Q3_K - Extra small";
  2503. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2504. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2505. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2506. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2507. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2508. default: return "unknown, may not work";
  2509. }
  2510. }
  2511. static const char * llama_model_type_name(e_model type) {
  2512. switch (type) {
  2513. case MODEL_22M: return "22M";
  2514. case MODEL_33M: return "33M";
  2515. case MODEL_109M: return "109M";
  2516. case MODEL_137M: return "137M";
  2517. case MODEL_0_5B: return "0.5B";
  2518. case MODEL_1B: return "1B";
  2519. case MODEL_2B: return "2B";
  2520. case MODEL_3B: return "3B";
  2521. case MODEL_7B: return "7B";
  2522. case MODEL_8B: return "8B";
  2523. case MODEL_13B: return "13B";
  2524. case MODEL_14B: return "14B";
  2525. case MODEL_15B: return "15B";
  2526. case MODEL_20B: return "20B";
  2527. case MODEL_30B: return "30B";
  2528. case MODEL_34B: return "34B";
  2529. case MODEL_40B: return "40B";
  2530. case MODEL_65B: return "65B";
  2531. case MODEL_70B: return "70B";
  2532. case MODEL_SMALL: return "0.1B";
  2533. case MODEL_MEDIUM: return "0.4B";
  2534. case MODEL_LARGE: return "0.8B";
  2535. case MODEL_XL: return "1.5B";
  2536. default: return "?B";
  2537. }
  2538. }
  2539. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2540. switch (type) {
  2541. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2542. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2543. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2544. default: return "unknown";
  2545. }
  2546. }
  2547. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2548. model.arch = ml.get_arch();
  2549. if (model.arch == LLM_ARCH_UNKNOWN) {
  2550. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2551. }
  2552. }
  2553. static void llm_load_hparams(
  2554. llama_model_loader & ml,
  2555. llama_model & model) {
  2556. auto & hparams = model.hparams;
  2557. const gguf_context * ctx = ml.ctx_gguf;
  2558. // get metadata as string
  2559. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2560. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2561. if (type == GGUF_TYPE_ARRAY) {
  2562. continue;
  2563. }
  2564. const char * name = gguf_get_key(ctx, i);
  2565. const std::string value = gguf_kv_to_str(ctx, i);
  2566. model.gguf_kv.emplace(name, value);
  2567. }
  2568. // get general kv
  2569. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2570. // get hparams kv
  2571. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2572. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2573. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2574. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2575. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2576. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2577. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2578. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2579. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2580. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2581. if (hparams.n_expert > 0) {
  2582. GGML_ASSERT(hparams.n_expert_used > 0);
  2583. } else {
  2584. GGML_ASSERT(hparams.n_expert_used == 0);
  2585. }
  2586. // n_head_kv is optional, default to n_head
  2587. hparams.n_head_kv = hparams.n_head;
  2588. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2589. bool rope_finetuned = false;
  2590. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2591. hparams.rope_finetuned = rope_finetuned;
  2592. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2593. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2594. // rope_freq_base (optional)
  2595. hparams.rope_freq_base_train = 10000.0f;
  2596. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2597. std::string rope_scaling("linear");
  2598. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2599. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2600. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  2601. // rope_freq_scale (inverse of the kv) is optional
  2602. float ropescale = 0.0f;
  2603. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2604. // try the old key name
  2605. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2606. }
  2607. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2608. // sanity check for n_rot (optional)
  2609. {
  2610. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2611. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2612. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2613. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2614. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2615. }
  2616. }
  2617. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2618. // gpt-j n_rot = rotary_dim
  2619. }
  2620. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2621. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2622. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2623. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2624. // arch-specific KVs
  2625. switch (model.arch) {
  2626. case LLM_ARCH_LLAMA:
  2627. {
  2628. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2629. switch (hparams.n_layer) {
  2630. case 22: model.type = e_model::MODEL_1B; break;
  2631. case 26: model.type = e_model::MODEL_3B; break;
  2632. case 32: model.type = e_model::MODEL_7B; break;
  2633. case 40: model.type = e_model::MODEL_13B; break;
  2634. case 48: model.type = e_model::MODEL_34B; break;
  2635. case 60: model.type = e_model::MODEL_30B; break;
  2636. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2637. default: model.type = e_model::MODEL_UNKNOWN;
  2638. }
  2639. } break;
  2640. case LLM_ARCH_MINICPM:
  2641. {
  2642. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2643. switch (hparams.n_layer) {
  2644. case 40: model.type = e_model::MODEL_2B; break;
  2645. default: model.type = e_model::MODEL_UNKNOWN;
  2646. }
  2647. } break;
  2648. case LLM_ARCH_FALCON:
  2649. {
  2650. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2651. switch (hparams.n_layer) {
  2652. case 32: model.type = e_model::MODEL_7B; break;
  2653. case 60: model.type = e_model::MODEL_40B; break;
  2654. default: model.type = e_model::MODEL_UNKNOWN;
  2655. }
  2656. } break;
  2657. case LLM_ARCH_BAICHUAN:
  2658. {
  2659. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2660. switch (hparams.n_layer) {
  2661. case 32: model.type = e_model::MODEL_7B; break;
  2662. case 40: model.type = e_model::MODEL_13B; break;
  2663. default: model.type = e_model::MODEL_UNKNOWN;
  2664. }
  2665. if (model.type == e_model::MODEL_13B) {
  2666. // TODO: become GGUF KV parameter
  2667. hparams.f_max_alibi_bias = 8.0f;
  2668. }
  2669. } break;
  2670. case LLM_ARCH_STARCODER:
  2671. {
  2672. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2673. switch (hparams.n_layer) {
  2674. case 24: model.type = e_model::MODEL_1B; break;
  2675. case 36: model.type = e_model::MODEL_3B; break;
  2676. case 42: model.type = e_model::MODEL_7B; break;
  2677. case 40: model.type = e_model::MODEL_15B; break;
  2678. default: model.type = e_model::MODEL_UNKNOWN;
  2679. }
  2680. } break;
  2681. case LLM_ARCH_PERSIMMON:
  2682. {
  2683. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2684. switch (hparams.n_layer) {
  2685. case 36: model.type = e_model::MODEL_8B; break;
  2686. default: model.type = e_model::MODEL_UNKNOWN;
  2687. }
  2688. } break;
  2689. case LLM_ARCH_REFACT:
  2690. {
  2691. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2692. switch (hparams.n_layer) {
  2693. case 32: model.type = e_model::MODEL_1B; break;
  2694. default: model.type = e_model::MODEL_UNKNOWN;
  2695. }
  2696. // TODO: become GGUF KV parameter
  2697. hparams.f_max_alibi_bias = 8.0f;
  2698. } break;
  2699. case LLM_ARCH_BERT:
  2700. {
  2701. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2702. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2703. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2704. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2705. switch (hparams.n_layer) {
  2706. case 3:
  2707. model.type = e_model::MODEL_17M; break; // bge-micro
  2708. case 6:
  2709. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2710. case 12:
  2711. switch (hparams.n_embd) {
  2712. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2713. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2714. } break;
  2715. case 24:
  2716. model.type = e_model::MODEL_335M; break; // bge-large
  2717. }
  2718. } break;
  2719. case LLM_ARCH_NOMIC_BERT:
  2720. {
  2721. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2722. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2723. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2724. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2725. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  2726. model.type = e_model::MODEL_137M;
  2727. }
  2728. } break;
  2729. case LLM_ARCH_BLOOM:
  2730. {
  2731. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2732. switch (hparams.n_layer) {
  2733. case 24: model.type = e_model::MODEL_1B; break;
  2734. case 30:
  2735. switch (hparams.n_embd) {
  2736. case 2560: model.type = e_model::MODEL_3B; break;
  2737. case 4096: model.type = e_model::MODEL_7B; break;
  2738. } break;
  2739. }
  2740. // TODO: become GGUF KV parameter
  2741. hparams.f_max_alibi_bias = 8.0f;
  2742. } break;
  2743. case LLM_ARCH_MPT:
  2744. {
  2745. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2746. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2747. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2748. switch (hparams.n_layer) {
  2749. case 32: model.type = e_model::MODEL_7B; break;
  2750. case 48: model.type = e_model::MODEL_30B; break;
  2751. default: model.type = e_model::MODEL_UNKNOWN;
  2752. }
  2753. } break;
  2754. case LLM_ARCH_STABLELM:
  2755. {
  2756. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2757. switch (hparams.n_layer) {
  2758. case 24: model.type = e_model::MODEL_1B; break;
  2759. case 32: model.type = e_model::MODEL_3B; break;
  2760. default: model.type = e_model::MODEL_UNKNOWN;
  2761. }
  2762. } break;
  2763. case LLM_ARCH_QWEN:
  2764. {
  2765. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2766. switch (hparams.n_layer) {
  2767. case 32: model.type = e_model::MODEL_7B; break;
  2768. case 40: model.type = e_model::MODEL_13B; break;
  2769. default: model.type = e_model::MODEL_UNKNOWN;
  2770. }
  2771. } break;
  2772. case LLM_ARCH_QWEN2:
  2773. {
  2774. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2775. switch (hparams.n_layer) {
  2776. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2777. case 32: model.type = e_model::MODEL_7B; break;
  2778. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2779. case 80: model.type = e_model::MODEL_70B; break;
  2780. default: model.type = e_model::MODEL_UNKNOWN;
  2781. }
  2782. } break;
  2783. case LLM_ARCH_PHI2:
  2784. {
  2785. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2786. switch (hparams.n_layer) {
  2787. case 24: model.type = e_model::MODEL_1B; break;
  2788. case 32: model.type = e_model::MODEL_3B; break;
  2789. default: model.type = e_model::MODEL_UNKNOWN;
  2790. }
  2791. } break;
  2792. case LLM_ARCH_PLAMO:
  2793. {
  2794. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2795. switch (hparams.n_layer) {
  2796. case 40: model.type = e_model::MODEL_13B; break;
  2797. default: model.type = e_model::MODEL_UNKNOWN;
  2798. }
  2799. } break;
  2800. case LLM_ARCH_GPT2:
  2801. {
  2802. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2803. switch (hparams.n_layer) {
  2804. case 12: model.type = e_model::MODEL_SMALL; break;
  2805. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2806. case 36: model.type = e_model::MODEL_LARGE; break;
  2807. case 48: model.type = e_model::MODEL_XL; break;
  2808. default: model.type = e_model::MODEL_UNKNOWN;
  2809. }
  2810. } break;
  2811. case LLM_ARCH_CODESHELL:
  2812. {
  2813. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2814. switch (hparams.n_layer) {
  2815. case 42: model.type = e_model::MODEL_SMALL; break;
  2816. default: model.type = e_model::MODEL_UNKNOWN;
  2817. }
  2818. } break;
  2819. case LLM_ARCH_ORION:
  2820. {
  2821. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2822. switch (hparams.n_layer) {
  2823. case 40: model.type = e_model::MODEL_14B; break;
  2824. default: model.type = e_model::MODEL_UNKNOWN;
  2825. }
  2826. } break;
  2827. case LLM_ARCH_INTERNLM2:
  2828. {
  2829. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2830. switch (hparams.n_layer) {
  2831. case 32: model.type = e_model::MODEL_7B; break;
  2832. case 48: model.type = e_model::MODEL_20B; break;
  2833. default: model.type = e_model::MODEL_UNKNOWN;
  2834. }
  2835. } break;
  2836. case LLM_ARCH_GEMMA:
  2837. {
  2838. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2839. switch (hparams.n_layer) {
  2840. case 18: model.type = e_model::MODEL_2B; break;
  2841. case 28: model.type = e_model::MODEL_7B; break;
  2842. default: model.type = e_model::MODEL_UNKNOWN;
  2843. }
  2844. } break;
  2845. default: (void)0;
  2846. }
  2847. model.ftype = ml.ftype;
  2848. if (hparams.f_max_alibi_bias > 0.0f) {
  2849. hparams.need_kq_pos = true;
  2850. }
  2851. }
  2852. // TODO: This should probably be in llama.h
  2853. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2854. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2855. static void llm_load_vocab(
  2856. llama_model_loader & ml,
  2857. llama_model & model) {
  2858. auto & vocab = model.vocab;
  2859. struct gguf_context * ctx = ml.ctx_gguf;
  2860. const auto kv = LLM_KV(model.arch);
  2861. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2862. if (token_idx == -1) {
  2863. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2864. }
  2865. const float * scores = nullptr;
  2866. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2867. if (score_idx != -1) {
  2868. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2869. }
  2870. const int * toktypes = nullptr;
  2871. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2872. if (toktype_idx != -1) {
  2873. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2874. }
  2875. // determine vocab type
  2876. {
  2877. std::string tokenizer_name;
  2878. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2879. if (tokenizer_name == "llama") {
  2880. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2881. // default special tokens
  2882. vocab.special_bos_id = 1;
  2883. vocab.special_eos_id = 2;
  2884. vocab.special_unk_id = 0;
  2885. vocab.special_sep_id = -1;
  2886. vocab.special_pad_id = -1;
  2887. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2888. if (add_space_prefix_keyidx != -1) {
  2889. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2890. } // The default value of add_space_prefix is true.
  2891. } else if (tokenizer_name == "gpt2") {
  2892. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2893. // read bpe merges and populate bpe ranks
  2894. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2895. if (merges_keyidx == -1) {
  2896. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2897. }
  2898. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2899. for (int i = 0; i < n_merges; i++) {
  2900. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2901. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2902. std::string first;
  2903. std::string second;
  2904. const size_t pos = word.find(' ', 1);
  2905. if (pos != std::string::npos) {
  2906. first = word.substr(0, pos);
  2907. second = word.substr(pos + 1);
  2908. }
  2909. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2910. }
  2911. // default special tokens
  2912. vocab.special_bos_id = 11;
  2913. vocab.special_eos_id = 11;
  2914. vocab.special_unk_id = -1;
  2915. vocab.special_sep_id = -1;
  2916. vocab.special_pad_id = -1;
  2917. } else if (tokenizer_name == "bert") {
  2918. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  2919. // default special tokens
  2920. vocab.special_bos_id = 101;
  2921. vocab.special_eos_id = 102;
  2922. vocab.special_unk_id = 100;
  2923. vocab.special_sep_id = -1;
  2924. vocab.special_pad_id = -1;
  2925. vocab.add_space_prefix = false;
  2926. } else {
  2927. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2928. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2929. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2930. }
  2931. }
  2932. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2933. vocab.id_to_token.resize(n_vocab);
  2934. for (uint32_t i = 0; i < n_vocab; i++) {
  2935. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2936. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2937. vocab.token_to_id[word] = i;
  2938. auto & token_data = vocab.id_to_token[i];
  2939. token_data.text = std::move(word);
  2940. token_data.score = scores ? scores[i] : 0.0f;
  2941. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2942. }
  2943. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2944. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2945. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2946. try {
  2947. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2948. } catch (const std::exception & e) {
  2949. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  2950. vocab.linefeed_id = vocab.special_pad_id;
  2951. }
  2952. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  2953. vocab.linefeed_id = vocab.special_pad_id;
  2954. } else {
  2955. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2956. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2957. vocab.linefeed_id = ids[0];
  2958. }
  2959. // special tokens
  2960. {
  2961. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2962. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2963. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2964. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2965. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2966. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2967. };
  2968. for (const auto & it : special_token_types) {
  2969. const std::string & key = kv(std::get<0>(it));
  2970. int32_t & id = std::get<1>(it);
  2971. uint32_t new_id;
  2972. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2973. continue;
  2974. }
  2975. if (new_id >= vocab.id_to_token.size()) {
  2976. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2977. __func__, key.c_str(), new_id, id);
  2978. } else {
  2979. id = new_id;
  2980. }
  2981. }
  2982. // Handle add_bos_token and add_eos_token
  2983. {
  2984. bool temp = true;
  2985. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2986. vocab.special_add_bos = int(temp);
  2987. }
  2988. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2989. vocab.special_add_eos = int(temp);
  2990. }
  2991. }
  2992. }
  2993. // build special tokens cache
  2994. {
  2995. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2996. // and will always be correctly labeled in 'added_tokens.json' etc.
  2997. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2998. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2999. // are special tokens.
  3000. // From testing, this appears to correlate 1:1 with special tokens.
  3001. //
  3002. // Counting special tokens and verifying in only one direction
  3003. // is sufficient to detect difference in those two sets.
  3004. //
  3005. uint32_t special_tokens_count_by_type = 0;
  3006. uint32_t special_tokens_count_from_verification = 0;
  3007. bool special_tokens_definition_mismatch = false;
  3008. for (const auto & t : vocab.token_to_id) {
  3009. const auto & token = t.first;
  3010. const auto & id = t.second;
  3011. // Count all non-normal tokens in the vocab while iterating
  3012. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3013. special_tokens_count_by_type++;
  3014. }
  3015. // Skip single character tokens
  3016. if (token.length() > 1) {
  3017. bool is_tokenizable = false;
  3018. // Split token string representation in two, in all possible ways
  3019. // and check if both halves can be matched to a valid token
  3020. for (unsigned i = 1; i < token.length();) {
  3021. const auto left = token.substr(0, i);
  3022. const auto right = token.substr(i);
  3023. // check if we didnt partition in the middle of a utf sequence
  3024. auto utf = utf8_len(left.at(left.length() - 1));
  3025. if (utf == 1) {
  3026. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3027. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3028. is_tokenizable = true;
  3029. break;
  3030. }
  3031. i++;
  3032. } else {
  3033. // skip over the rest of multibyte utf sequence
  3034. i += utf - 1;
  3035. }
  3036. }
  3037. if (!is_tokenizable) {
  3038. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3039. // it's faster to re-filter them here, since there are way less candidates now
  3040. // Calculate a total "utf" length of a token string representation
  3041. size_t utf8_str_len = 0;
  3042. for (unsigned i = 0; i < token.length();) {
  3043. utf8_str_len++;
  3044. i += utf8_len(token.at(i));
  3045. }
  3046. // And skip the ones which are one character
  3047. if (utf8_str_len > 1) {
  3048. // At this point what we have left are special tokens only
  3049. vocab.special_tokens_cache[token] = id;
  3050. // Count manually found special tokens
  3051. special_tokens_count_from_verification++;
  3052. // If this manually found special token is not marked as such, flag a mismatch
  3053. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3054. special_tokens_definition_mismatch = true;
  3055. }
  3056. }
  3057. }
  3058. }
  3059. }
  3060. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3061. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3062. __func__,
  3063. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3064. special_tokens_count_by_type, vocab.id_to_token.size()
  3065. );
  3066. } else {
  3067. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3068. __func__,
  3069. special_tokens_count_from_verification, vocab.id_to_token.size()
  3070. );
  3071. }
  3072. }
  3073. }
  3074. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3075. const auto & hparams = model.hparams;
  3076. const auto & vocab = model.vocab;
  3077. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3078. // hparams
  3079. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3080. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3081. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3082. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3083. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3084. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3085. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3086. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3087. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3088. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3089. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3090. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3091. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3092. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3093. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3094. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3095. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3096. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3097. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3098. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3099. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3100. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3101. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3102. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3103. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3104. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3105. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3106. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3107. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3108. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3109. if (ml.n_elements >= 1e12) {
  3110. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3111. } else if (ml.n_elements >= 1e9) {
  3112. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3113. } else if (ml.n_elements >= 1e6) {
  3114. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3115. } else {
  3116. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3117. }
  3118. if (ml.n_bytes < GiB) {
  3119. 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);
  3120. } else {
  3121. 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);
  3122. }
  3123. // general kv
  3124. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3125. // special tokens
  3126. 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() ); }
  3127. 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() ); }
  3128. 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() ); }
  3129. 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() ); }
  3130. 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() ); }
  3131. 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() ); }
  3132. }
  3133. // Returns false if cancelled by progress_callback
  3134. static bool llm_load_tensors(
  3135. llama_model_loader & ml,
  3136. llama_model & model,
  3137. int n_gpu_layers,
  3138. enum llama_split_mode split_mode,
  3139. int main_gpu,
  3140. const float * tensor_split,
  3141. bool use_mlock,
  3142. llama_progress_callback progress_callback,
  3143. void * progress_callback_user_data) {
  3144. model.t_start_us = ggml_time_us();
  3145. auto & hparams = model.hparams;
  3146. model.split_mode = split_mode;
  3147. model.main_gpu = main_gpu;
  3148. model.n_gpu_layers = n_gpu_layers;
  3149. const int64_t n_layer = hparams.n_layer;
  3150. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3151. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3152. model.buft_input = llama_default_buffer_type_cpu(true);
  3153. model.buft_layer.resize(n_layer);
  3154. // assign cpu layers
  3155. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3156. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3157. }
  3158. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3159. // calculate the split points
  3160. int device_count = llama_get_device_count();
  3161. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3162. std::vector<float> splits(device_count);
  3163. if (all_zero) {
  3164. // default split, by free memory
  3165. for (int i = 0; i < device_count; ++i) {
  3166. splits[i] = llama_get_device_memory(i);
  3167. }
  3168. } else {
  3169. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3170. }
  3171. // sum and normalize the splits to get the split points
  3172. float split_sum = 0.0f;
  3173. for (int i = 0; i < device_count; ++i) {
  3174. split_sum += splits[i];
  3175. splits[i] = split_sum;
  3176. }
  3177. for (int i = 0; i < device_count; ++i) {
  3178. splits[i] /= split_sum;
  3179. }
  3180. // assign the repeating layers to the devices according to the splits
  3181. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3182. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3183. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3184. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3185. }
  3186. // assign the output layer
  3187. if (n_gpu_layers > n_layer) {
  3188. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3189. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3190. } else {
  3191. model.buft_output = llama_default_buffer_type_cpu(true);
  3192. }
  3193. } else {
  3194. ggml_backend_buffer_type_t split_buft;
  3195. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3196. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3197. } else {
  3198. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3199. split_buft = llama_default_buffer_type_offload(main_gpu);
  3200. }
  3201. // assign the repeating layers
  3202. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3203. model.buft_layer[i] = {
  3204. split_buft,
  3205. llama_default_buffer_type_offload(main_gpu)
  3206. };
  3207. }
  3208. // assign the output layer
  3209. if (n_gpu_layers > n_layer) {
  3210. model.buft_output = {
  3211. split_buft,
  3212. llama_default_buffer_type_offload(main_gpu)
  3213. };
  3214. } else {
  3215. model.buft_output = llama_default_buffer_type_cpu(true);
  3216. }
  3217. }
  3218. // count used buffer types
  3219. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3220. buft_layer_count[model.buft_input.buft]++;
  3221. buft_layer_count[model.buft_input.buft_matrix]++;
  3222. buft_layer_count[model.buft_output.buft]++;
  3223. buft_layer_count[model.buft_output.buft_matrix]++;
  3224. for (int64_t i = 0; i < n_layer; ++i) {
  3225. buft_layer_count[model.buft_layer[i].buft]++;
  3226. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3227. }
  3228. // create one context per buffer type
  3229. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3230. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3231. for (auto & it : buft_layer_count) {
  3232. struct ggml_init_params params = {
  3233. /*.mem_size =*/ ctx_size,
  3234. /*.mem_buffer =*/ NULL,
  3235. /*.no_alloc =*/ true,
  3236. };
  3237. ggml_context * ctx = ggml_init(params);
  3238. if (!ctx) {
  3239. throw std::runtime_error(format("failed to create context"));
  3240. }
  3241. ctx_map[it.first] = ctx;
  3242. model.ctxs.push_back(ctx);
  3243. }
  3244. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3245. // create tensors for the weights
  3246. {
  3247. const int64_t n_embd = hparams.n_embd;
  3248. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3249. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3250. const int64_t n_embd_gqa = n_embd_v_gqa;
  3251. const int64_t n_vocab = hparams.n_vocab;
  3252. const int64_t n_vocab_type = hparams.n_vocab_type;
  3253. const int64_t n_ff = hparams.n_ff;
  3254. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3255. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3256. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3257. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3258. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3259. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3260. model.layers.resize(n_layer);
  3261. const auto tn = LLM_TN(model.arch);
  3262. switch (model.arch) {
  3263. case LLM_ARCH_LLAMA:
  3264. case LLM_ARCH_REFACT:
  3265. case LLM_ARCH_MINICPM:
  3266. {
  3267. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3268. // output
  3269. {
  3270. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3271. if (model.arch != LLM_ARCH_MINICPM){
  3272. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3273. }
  3274. }
  3275. for (int i = 0; i < n_layer; ++i) {
  3276. ggml_context * ctx_layer = ctx_for_layer(i);
  3277. ggml_context * ctx_split = ctx_for_layer_split(i);
  3278. auto & layer = model.layers[i];
  3279. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3280. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3281. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3282. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3283. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3284. // optional bias tensors
  3285. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3286. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3287. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3288. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3289. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3290. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3291. if (layer.ffn_gate_inp == nullptr) {
  3292. GGML_ASSERT(hparams.n_expert == 0);
  3293. GGML_ASSERT(hparams.n_expert_used == 0);
  3294. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3295. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3296. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3297. } else {
  3298. GGML_ASSERT(hparams.n_expert > 0);
  3299. GGML_ASSERT(hparams.n_expert_used > 0);
  3300. // MoE branch
  3301. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3302. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3303. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3304. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3305. }
  3306. }
  3307. }
  3308. } break;
  3309. case LLM_ARCH_BAICHUAN:
  3310. {
  3311. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3312. {
  3313. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3314. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3315. }
  3316. for (int i = 0; i < n_layer; ++i) {
  3317. ggml_context * ctx_layer = ctx_for_layer(i);
  3318. ggml_context * ctx_split = ctx_for_layer_split(i);
  3319. auto & layer = model.layers[i];
  3320. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3321. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3322. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3323. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3324. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3325. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3326. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3327. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3328. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3329. }
  3330. } break;
  3331. case LLM_ARCH_FALCON:
  3332. {
  3333. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3334. // output
  3335. {
  3336. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3337. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3338. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3339. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3340. } else {
  3341. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3342. ml.n_created--; // artificial tensor
  3343. ml.size_data += ggml_nbytes(model.output);
  3344. }
  3345. }
  3346. for (int i = 0; i < n_layer; ++i) {
  3347. ggml_context * ctx_layer = ctx_for_layer(i);
  3348. ggml_context * ctx_split = ctx_for_layer_split(i);
  3349. auto & layer = model.layers[i];
  3350. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3351. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3352. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3353. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3354. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3355. }
  3356. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3357. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3358. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3359. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3360. }
  3361. } break;
  3362. case LLM_ARCH_STARCODER:
  3363. {
  3364. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3365. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3366. // output
  3367. {
  3368. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3369. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3370. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3371. }
  3372. for (int i = 0; i < n_layer; ++i) {
  3373. ggml_context * ctx_layer = ctx_for_layer(i);
  3374. ggml_context * ctx_split = ctx_for_layer_split(i);
  3375. auto & layer = model.layers[i];
  3376. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3377. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3378. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3379. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3380. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3381. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3382. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3383. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3384. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3385. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3386. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3387. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3388. }
  3389. } break;
  3390. case LLM_ARCH_PERSIMMON:
  3391. {
  3392. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3393. {
  3394. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3395. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3396. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3397. }
  3398. for (int i = 0; i < n_layer; ++i) {
  3399. ggml_context * ctx_layer = ctx_for_layer(i);
  3400. ggml_context * ctx_split = ctx_for_layer_split(i);
  3401. auto & layer = model.layers[i];
  3402. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3403. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3404. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3405. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3406. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3407. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3408. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3409. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3410. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3411. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3412. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3413. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3414. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3415. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3416. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3417. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3418. }
  3419. } break;
  3420. case LLM_ARCH_BERT:
  3421. case LLM_ARCH_NOMIC_BERT:
  3422. {
  3423. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3424. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3425. if (model.arch == LLM_ARCH_BERT) {
  3426. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3427. }
  3428. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3429. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3430. for (int i = 0; i < n_layer; ++i) {
  3431. ggml_context * ctx_layer = ctx_for_layer(i);
  3432. ggml_context * ctx_split = ctx_for_layer_split(i);
  3433. auto & layer = model.layers[i];
  3434. if (model.arch == LLM_ARCH_BERT) {
  3435. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3436. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3437. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3438. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3439. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3440. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3441. } else {
  3442. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3443. }
  3444. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3445. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3446. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3447. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3448. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3449. if (model.arch == LLM_ARCH_BERT) {
  3450. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3451. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3452. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3453. } else {
  3454. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3455. }
  3456. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3457. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3458. }
  3459. } break;
  3460. case LLM_ARCH_BLOOM:
  3461. {
  3462. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3463. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3464. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3465. // output
  3466. {
  3467. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3468. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3469. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3470. }
  3471. for (int i = 0; i < n_layer; ++i) {
  3472. ggml_context * ctx_layer = ctx_for_layer(i);
  3473. ggml_context * ctx_split = ctx_for_layer_split(i);
  3474. auto & layer = model.layers[i];
  3475. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3476. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3477. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3478. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3479. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3480. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3481. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3482. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3483. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3484. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3485. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3486. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3487. }
  3488. } break;
  3489. case LLM_ARCH_MPT:
  3490. {
  3491. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3492. // output
  3493. {
  3494. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3495. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  3496. // same as tok_embd, duplicated to allow offloading
  3497. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3498. ml.n_created--; // artificial tensor
  3499. ml.size_data += ggml_nbytes(model.output);
  3500. }
  3501. for (int i = 0; i < n_layer; ++i) {
  3502. ggml_context * ctx_layer = ctx_for_layer(i);
  3503. ggml_context * ctx_split = ctx_for_layer_split(i);
  3504. auto & layer = model.layers[i];
  3505. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3506. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  3507. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3508. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3509. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3510. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3511. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3512. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  3513. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3514. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  3515. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3516. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  3517. // AWQ ScaleActivation layer
  3518. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3519. }
  3520. } break;
  3521. case LLM_ARCH_STABLELM:
  3522. {
  3523. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3524. // output
  3525. {
  3526. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3527. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3528. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3529. }
  3530. for (int i = 0; i < n_layer; ++i) {
  3531. ggml_context * ctx_layer = ctx_for_layer(i);
  3532. ggml_context * ctx_split = ctx_for_layer_split(i);
  3533. auto & layer = model.layers[i];
  3534. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3535. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3536. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3537. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3538. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3539. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3540. // optional bias tensors, present in Stable LM 2 1.6B
  3541. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3542. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3543. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3544. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3545. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3546. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3547. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3548. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3549. }
  3550. } break;
  3551. case LLM_ARCH_QWEN:
  3552. {
  3553. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3554. // output
  3555. {
  3556. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3557. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3558. }
  3559. for (int i = 0; i < n_layer; ++i) {
  3560. ggml_context * ctx_layer = ctx_for_layer(i);
  3561. ggml_context * ctx_split = ctx_for_layer_split(i);
  3562. auto & layer = model.layers[i];
  3563. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3564. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3565. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3566. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3567. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3568. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3569. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3570. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3571. }
  3572. } break;
  3573. case LLM_ARCH_QWEN2:
  3574. {
  3575. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3576. // output
  3577. {
  3578. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3579. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3580. }
  3581. for (int i = 0; i < n_layer; ++i) {
  3582. ggml_context * ctx_layer = ctx_for_layer(i);
  3583. ggml_context * ctx_split = ctx_for_layer_split(i);
  3584. auto & layer = model.layers[i];
  3585. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3586. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3587. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3588. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3589. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3590. // optional bias tensors
  3591. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3592. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3593. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3594. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3595. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3596. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3597. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3598. }
  3599. } break;
  3600. case LLM_ARCH_PHI2:
  3601. {
  3602. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3603. // output
  3604. {
  3605. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3606. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3607. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3608. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3609. }
  3610. for (int i = 0; i < n_layer; ++i) {
  3611. ggml_context * ctx_layer = ctx_for_layer(i);
  3612. ggml_context * ctx_split = ctx_for_layer_split(i);
  3613. auto & layer = model.layers[i];
  3614. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3615. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3616. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3617. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3618. if (layer.wqkv == nullptr) {
  3619. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3620. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3621. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3622. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3623. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3624. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3625. }
  3626. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3627. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3628. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3629. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3630. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3631. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3632. }
  3633. } break;
  3634. case LLM_ARCH_PLAMO:
  3635. {
  3636. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3637. // output
  3638. {
  3639. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3640. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3641. }
  3642. for (int i = 0; i < n_layer; ++i) {
  3643. ggml_context * ctx_layer = ctx_for_layer(i);
  3644. ggml_context * ctx_split = ctx_for_layer_split(i);
  3645. auto & layer = model.layers[i];
  3646. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3647. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3648. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3649. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3650. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3651. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3652. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3653. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3654. }
  3655. } break;
  3656. case LLM_ARCH_GPT2:
  3657. {
  3658. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3659. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3660. // output
  3661. {
  3662. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3663. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3664. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3665. }
  3666. for (int i = 0; i < n_layer; ++i) {
  3667. ggml_context * ctx_layer = ctx_for_layer(i);
  3668. ggml_context * ctx_split = ctx_for_layer_split(i);
  3669. auto & layer = model.layers[i];
  3670. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3671. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3672. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3673. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3674. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3675. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3676. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3677. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3678. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3679. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3680. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3681. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3682. }
  3683. } break;
  3684. case LLM_ARCH_CODESHELL:
  3685. {
  3686. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3687. // output
  3688. {
  3689. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3690. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3691. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3692. }
  3693. for (int i = 0; i < n_layer; ++i) {
  3694. ggml_context * ctx_layer = ctx_for_layer(i);
  3695. ggml_context * ctx_split = ctx_for_layer_split(i);
  3696. auto & layer = model.layers[i];
  3697. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3698. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3699. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3700. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3701. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3702. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3703. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3704. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3705. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3706. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3707. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3708. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3709. }
  3710. } break;
  3711. case LLM_ARCH_ORION:
  3712. {
  3713. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3714. {
  3715. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3716. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3717. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3718. }
  3719. for (int i = 0; i < n_layer; ++i) {
  3720. ggml_context * ctx_layer = ctx_for_layer(i);
  3721. ggml_context * ctx_split = ctx_for_layer_split(i);
  3722. auto & layer = model.layers[i];
  3723. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3724. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3725. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3726. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3727. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3728. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3729. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3730. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3731. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3732. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3733. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3734. }
  3735. } break;
  3736. case LLM_ARCH_INTERNLM2:
  3737. {
  3738. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3739. // output
  3740. {
  3741. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3742. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3743. }
  3744. for (int i = 0; i < n_layer; ++i) {
  3745. ggml_context * ctx_layer = ctx_for_layer(i);
  3746. ggml_context * ctx_split = ctx_for_layer_split(i);
  3747. auto & layer = model.layers[i];
  3748. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3749. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3750. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3751. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3752. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3753. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3754. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3755. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3756. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3757. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3758. }
  3759. } break;
  3760. case LLM_ARCH_GEMMA:
  3761. {
  3762. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3763. // output
  3764. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3765. 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
  3766. ml.n_created--; // artificial tensor
  3767. ml.size_data += ggml_nbytes(model.output);
  3768. const int64_t n_ff = hparams.n_ff;
  3769. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3770. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3771. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3772. for (uint32_t i = 0; i < n_layer; ++i) {
  3773. ggml_context * ctx_layer = ctx_for_layer(i);
  3774. ggml_context * ctx_split = ctx_for_layer_split(i);
  3775. auto & layer = model.layers[i];
  3776. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3777. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  3778. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  3779. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  3780. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  3781. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3782. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3783. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3784. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3785. }
  3786. } break;
  3787. default:
  3788. throw std::runtime_error("unknown architecture");
  3789. }
  3790. }
  3791. ml.done_getting_tensors();
  3792. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3793. // create the backend buffers
  3794. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3795. for (auto & it : ctx_map) {
  3796. ggml_backend_buffer_type_t buft = it.first;
  3797. ggml_context * ctx = it.second;
  3798. ggml_backend_buffer_t buf = nullptr;
  3799. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3800. // 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
  3801. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3802. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3803. size_t first, last;
  3804. ml.get_mapping_range(&first, &last, ctx);
  3805. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3806. }
  3807. #ifdef GGML_USE_METAL
  3808. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3809. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3810. size_t first, last;
  3811. ml.get_mapping_range(&first, &last, ctx);
  3812. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3813. }
  3814. #endif
  3815. else {
  3816. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3817. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3818. model.mlock_bufs.emplace_back(new llama_mlock);
  3819. auto & mlock_buf = model.mlock_bufs.back();
  3820. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3821. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3822. }
  3823. }
  3824. if (buf == nullptr) {
  3825. throw std::runtime_error("failed to allocate buffer");
  3826. }
  3827. // indicate that this buffer contains weights
  3828. // 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
  3829. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3830. model.bufs.push_back(buf);
  3831. ctx_bufs.emplace_back(ctx, buf);
  3832. }
  3833. if (llama_supports_gpu_offload()) {
  3834. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3835. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3836. if (n_gpu_layers > (int) hparams.n_layer) {
  3837. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3838. }
  3839. const int max_backend_supported_layers = hparams.n_layer + 1;
  3840. const int max_offloadable_layers = hparams.n_layer + 1;
  3841. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3842. }
  3843. // print memory requirements
  3844. for (ggml_backend_buffer_t buf : model.bufs) {
  3845. 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);
  3846. }
  3847. // populate tensors_by_name
  3848. for (ggml_context * ctx : model.ctxs) {
  3849. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3850. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3851. }
  3852. }
  3853. // load tensor data
  3854. for (auto & it : ctx_bufs) {
  3855. ggml_context * ctx = it.first;
  3856. ggml_backend_buffer_t buf = it.second;
  3857. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3858. return false;
  3859. }
  3860. }
  3861. model.mapping = std::move(ml.mapping);
  3862. // loading time will be recalculate after the first eval, so
  3863. // we take page faults deferred by mmap() into consideration
  3864. model.t_load_us = ggml_time_us() - model.t_start_us;
  3865. return true;
  3866. }
  3867. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3868. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  3869. try {
  3870. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3871. model.hparams.vocab_only = params.vocab_only;
  3872. try {
  3873. llm_load_arch(ml, model);
  3874. } catch(const std::exception & e) {
  3875. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  3876. }
  3877. try {
  3878. llm_load_hparams(ml, model);
  3879. } catch(const std::exception & e) {
  3880. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  3881. }
  3882. try {
  3883. llm_load_vocab(ml, model);
  3884. } catch(const std::exception & e) {
  3885. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  3886. }
  3887. llm_load_print_meta(ml, model);
  3888. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3889. throw std::runtime_error("vocab size mismatch");
  3890. }
  3891. if (params.vocab_only) {
  3892. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3893. return 0;
  3894. }
  3895. #ifdef GGML_USE_KOMPUTE
  3896. if (params.n_gpu_layers > 0 && (
  3897. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  3898. || !(
  3899. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  3900. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  3901. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  3902. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  3903. )
  3904. )) {
  3905. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  3906. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  3907. params.n_gpu_layers = 0;
  3908. }
  3909. #endif
  3910. if (!llm_load_tensors(
  3911. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3912. params.progress_callback, params.progress_callback_user_data
  3913. )) {
  3914. return -2;
  3915. }
  3916. } catch (const std::exception & err) {
  3917. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3918. return -1;
  3919. }
  3920. return 0;
  3921. }
  3922. //
  3923. // llm_build
  3924. //
  3925. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3926. enum llm_rope_type {
  3927. LLM_ROPE,
  3928. LLM_ROPE_NEOX,
  3929. LLM_ROPE_GLM,
  3930. };
  3931. enum llm_ffn_op_type {
  3932. LLM_FFN_SILU,
  3933. LLM_FFN_GELU,
  3934. LLM_FFN_RELU,
  3935. LLM_FFN_RELU_SQR,
  3936. };
  3937. enum llm_ffn_gate_type {
  3938. LLM_FFN_SEQ,
  3939. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3940. };
  3941. enum llm_norm_type {
  3942. LLM_NORM,
  3943. LLM_NORM_RMS,
  3944. };
  3945. static struct ggml_tensor * llm_build_inp_embd(
  3946. struct ggml_context * ctx,
  3947. const llama_hparams & hparams,
  3948. const llama_batch & batch,
  3949. struct ggml_tensor * tok_embd,
  3950. struct ggml_tensor * inp_tokens,
  3951. struct ggml_tensor * inp_embd,
  3952. const llm_build_cb & cb) {
  3953. const int64_t n_embd = hparams.n_embd;
  3954. struct ggml_tensor * inpL;
  3955. if (batch.token) {
  3956. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3957. cb(inp_tokens, "inp_tokens", -1);
  3958. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  3959. } else {
  3960. #ifdef GGML_USE_MPI
  3961. GGML_ASSERT(false && "not implemented");
  3962. #endif
  3963. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  3964. }
  3965. return inpL;
  3966. }
  3967. // Persimmon: n_rot = n_embd_head_k/2
  3968. // Other: n_rot = n_embd_head_k
  3969. static void llm_build_k_shift(
  3970. struct ggml_context * ctx,
  3971. const llama_hparams & hparams,
  3972. const llama_cparams & cparams,
  3973. const llama_kv_cache & kv,
  3974. struct ggml_cgraph * graph,
  3975. struct ggml_tensor * K_shift,
  3976. llm_rope_type type,
  3977. int64_t n_ctx,
  3978. float freq_base,
  3979. float freq_scale,
  3980. const llm_build_cb & cb) {
  3981. const int64_t n_layer = hparams.n_layer;
  3982. const int64_t n_head_kv = hparams.n_head_kv;
  3983. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3984. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3985. const int32_t n_rot = hparams.n_rot;
  3986. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3987. const float ext_factor = cparams.yarn_ext_factor;
  3988. const float attn_factor = cparams.yarn_attn_factor;
  3989. const float beta_fast = cparams.yarn_beta_fast;
  3990. const float beta_slow = cparams.yarn_beta_slow;
  3991. int rope_type = 0;
  3992. switch (type) {
  3993. case LLM_ROPE: rope_type = 0; break;
  3994. case LLM_ROPE_NEOX: rope_type = 2; break;
  3995. case LLM_ROPE_GLM: rope_type = 4; break;
  3996. }
  3997. for (int il = 0; il < n_layer; ++il) {
  3998. struct ggml_tensor * tmp =
  3999. // we rotate only the first n_rot dimensions
  4000. ggml_rope_custom_inplace(ctx,
  4001. ggml_view_3d(ctx, kv.k_l[il],
  4002. n_embd_head_k, n_head_kv, n_ctx,
  4003. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4004. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4005. 0),
  4006. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4007. ext_factor, attn_factor, beta_fast, beta_slow);
  4008. cb(tmp, "K_shifted", il);
  4009. ggml_build_forward_expand(graph, tmp);
  4010. }
  4011. }
  4012. static void llm_build_kv_store(
  4013. struct ggml_context * ctx,
  4014. const llama_hparams & hparams,
  4015. const llama_kv_cache & kv,
  4016. struct ggml_cgraph * graph,
  4017. struct ggml_tensor * k_cur,
  4018. struct ggml_tensor * v_cur,
  4019. int64_t n_ctx,
  4020. int32_t n_tokens,
  4021. int32_t kv_head,
  4022. const llm_build_cb & cb,
  4023. int64_t il) {
  4024. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4025. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4026. // compute the transposed [n_tokens, n_embd] V matrix
  4027. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4028. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4029. cb(v_cur_t, "v_cur_t", il);
  4030. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4031. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4032. cb(k_cache_view, "k_cache_view", il);
  4033. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4034. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4035. (kv_head)*ggml_element_size(kv.v_l[il]));
  4036. cb(v_cache_view, "v_cache_view", il);
  4037. // important: storing RoPE-ed version of K in the KV cache!
  4038. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4039. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4040. }
  4041. static struct ggml_tensor * llm_build_norm(
  4042. struct ggml_context * ctx,
  4043. struct ggml_tensor * cur,
  4044. const llama_hparams & hparams,
  4045. struct ggml_tensor * mw,
  4046. struct ggml_tensor * mb,
  4047. llm_norm_type type,
  4048. const llm_build_cb & cb,
  4049. int il) {
  4050. switch (type) {
  4051. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4052. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4053. }
  4054. if (mw || mb) {
  4055. cb(cur, "norm", il);
  4056. }
  4057. if (mw) {
  4058. cur = ggml_mul(ctx, cur, mw);
  4059. if (mb) {
  4060. cb(cur, "norm_w", il);
  4061. }
  4062. }
  4063. if (mb) {
  4064. cur = ggml_add(ctx, cur, mb);
  4065. }
  4066. return cur;
  4067. }
  4068. static struct ggml_tensor * llm_build_ffn(
  4069. struct ggml_context * ctx,
  4070. struct ggml_tensor * cur,
  4071. struct ggml_tensor * up,
  4072. struct ggml_tensor * up_b,
  4073. struct ggml_tensor * gate,
  4074. struct ggml_tensor * gate_b,
  4075. struct ggml_tensor * down,
  4076. struct ggml_tensor * down_b,
  4077. struct ggml_tensor * act_scales,
  4078. llm_ffn_op_type type_op,
  4079. llm_ffn_gate_type type_gate,
  4080. const llm_build_cb & cb,
  4081. int il) {
  4082. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4083. cb(tmp, "ffn_up", il);
  4084. if (up_b) {
  4085. tmp = ggml_add(ctx, tmp, up_b);
  4086. cb(tmp, "ffn_up_b", il);
  4087. }
  4088. if (gate) {
  4089. switch (type_gate) {
  4090. case LLM_FFN_SEQ:
  4091. {
  4092. cur = ggml_mul_mat(ctx, gate, tmp);
  4093. cb(cur, "ffn_gate", il);
  4094. } break;
  4095. case LLM_FFN_PAR:
  4096. {
  4097. cur = ggml_mul_mat(ctx, gate, cur);
  4098. cb(cur, "ffn_gate", il);
  4099. } break;
  4100. }
  4101. if (gate_b) {
  4102. cur = ggml_add(ctx, cur, gate_b);
  4103. cb(cur, "ffn_gate_b", il);
  4104. }
  4105. } else {
  4106. cur = tmp;
  4107. }
  4108. switch (type_op) {
  4109. case LLM_FFN_SILU:
  4110. {
  4111. cur = ggml_silu(ctx, cur);
  4112. cb(cur, "ffn_silu", il);
  4113. } break;
  4114. case LLM_FFN_GELU:
  4115. {
  4116. cur = ggml_gelu(ctx, cur);
  4117. cb(cur, "ffn_gelu", il);
  4118. if (act_scales != NULL) {
  4119. cur = ggml_div(ctx, cur, act_scales);
  4120. cb(cur, "ffn_act", il);
  4121. }
  4122. } break;
  4123. case LLM_FFN_RELU:
  4124. {
  4125. cur = ggml_relu(ctx, cur);
  4126. cb(cur, "ffn_relu", il);
  4127. } break;
  4128. case LLM_FFN_RELU_SQR:
  4129. {
  4130. cur = ggml_relu(ctx, cur);
  4131. cb(cur, "ffn_relu", il);
  4132. cur = ggml_sqr(ctx, cur);
  4133. cb(cur, "ffn_sqr(relu)", il);
  4134. } break;
  4135. }
  4136. if (type_gate == LLM_FFN_PAR) {
  4137. cur = ggml_mul(ctx, cur, tmp);
  4138. cb(cur, "ffn_gate_par", il);
  4139. }
  4140. cur = ggml_mul_mat(ctx, down, cur);
  4141. if (down_b) {
  4142. cb(cur, "ffn_down", il);
  4143. }
  4144. if (down_b) {
  4145. cur = ggml_add(ctx, cur, down_b);
  4146. }
  4147. return cur;
  4148. }
  4149. // if max_alibi_bias > 0 then apply ALiBi
  4150. static struct ggml_tensor * llm_build_kqv(
  4151. struct ggml_context * ctx,
  4152. const llama_model & model,
  4153. const llama_hparams & hparams,
  4154. const llama_kv_cache & kv,
  4155. struct ggml_cgraph * graph,
  4156. struct ggml_tensor * wo,
  4157. struct ggml_tensor * wo_b,
  4158. struct ggml_tensor * q_cur,
  4159. struct ggml_tensor * kq_mask,
  4160. struct ggml_tensor * kq_pos,
  4161. int64_t n_ctx,
  4162. int32_t n_tokens,
  4163. int32_t n_kv,
  4164. float kq_scale,
  4165. const llm_build_cb & cb,
  4166. int il) {
  4167. const int64_t n_head = hparams.n_head;
  4168. const int64_t n_head_kv = hparams.n_head_kv;
  4169. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4170. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4171. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4172. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4173. cb(q, "q", il);
  4174. struct ggml_tensor * k =
  4175. ggml_view_3d(ctx, kv.k_l[il],
  4176. n_embd_head_k, n_kv, n_head_kv,
  4177. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4178. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4179. 0);
  4180. cb(k, "k", il);
  4181. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4182. cb(kq, "kq", il);
  4183. if (model.arch == LLM_ARCH_PHI2) {
  4184. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4185. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4186. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4187. }
  4188. #if defined(GGML_USE_VULKAN) || defined(GGML_USE_KOMPUTE) || defined(GGML_USE_SYCL)
  4189. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Vulkan, Kompute, and SYCL")
  4190. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4191. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4192. if (hparams.f_max_alibi_bias > 0.0f) {
  4193. kq = ggml_scale(ctx, kq, kq_scale);
  4194. cb(kq, "kq_scaled", il);
  4195. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4196. cb(kq, "kq_scaled_alibi", il);
  4197. kq = ggml_add(ctx, kq, kq_mask);
  4198. cb(kq, "kq_masked", il);
  4199. kq = ggml_soft_max(ctx, kq);
  4200. cb(kq, "kq_soft_max", il);
  4201. } else
  4202. #endif
  4203. {
  4204. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4205. cb(kq, "kq_soft_max_ext", il);
  4206. }
  4207. // split cached v into n_head heads
  4208. struct ggml_tensor * v =
  4209. ggml_view_3d(ctx, kv.v_l[il],
  4210. n_kv, n_embd_head_v, n_head_kv,
  4211. ggml_element_size(kv.v_l[il])*n_ctx,
  4212. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4213. 0);
  4214. cb(v, "v", il);
  4215. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4216. cb(kqv, "kqv", il);
  4217. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4218. cb(kqv_merged, "kqv_merged", il);
  4219. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4220. cb(cur, "kqv_merged_cont", il);
  4221. ggml_build_forward_expand(graph, cur);
  4222. cur = ggml_mul_mat(ctx, wo, cur);
  4223. if (wo_b) {
  4224. cb(cur, "kqv_wo", il);
  4225. }
  4226. if (wo_b) {
  4227. cur = ggml_add(ctx, cur, wo_b);
  4228. }
  4229. return cur;
  4230. }
  4231. static struct ggml_tensor * llm_build_kv(
  4232. struct ggml_context * ctx,
  4233. const llama_model & model,
  4234. const llama_hparams & hparams,
  4235. const llama_kv_cache & kv,
  4236. struct ggml_cgraph * graph,
  4237. struct ggml_tensor * wo,
  4238. struct ggml_tensor * wo_b,
  4239. struct ggml_tensor * k_cur,
  4240. struct ggml_tensor * v_cur,
  4241. struct ggml_tensor * q_cur,
  4242. struct ggml_tensor * kq_mask,
  4243. struct ggml_tensor * kq_pos,
  4244. int64_t n_ctx,
  4245. int32_t n_tokens,
  4246. int32_t kv_head,
  4247. int32_t n_kv,
  4248. float kq_scale,
  4249. const llm_build_cb & cb,
  4250. int il) {
  4251. // these nodes are added to the graph together so that they are not reordered
  4252. // by doing so, the number of splits in the graph is reduced
  4253. ggml_build_forward_expand(graph, q_cur);
  4254. ggml_build_forward_expand(graph, k_cur);
  4255. ggml_build_forward_expand(graph, v_cur);
  4256. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4257. struct ggml_tensor * cur;
  4258. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4259. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4260. cb(cur, "kqv_out", il);
  4261. return cur;
  4262. }
  4263. struct llm_build_context {
  4264. const llama_model & model;
  4265. const llama_context & lctx;
  4266. const llama_hparams & hparams;
  4267. const llama_cparams & cparams;
  4268. const llama_batch & batch;
  4269. const llama_kv_cache & kv_self;
  4270. const int64_t n_embd;
  4271. const int64_t n_layer;
  4272. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4273. const int64_t n_head;
  4274. const int64_t n_head_kv;
  4275. const int64_t n_embd_head_k;
  4276. const int64_t n_embd_k_gqa;
  4277. const int64_t n_embd_head_v;
  4278. const int64_t n_embd_v_gqa;
  4279. const int64_t n_expert;
  4280. const int64_t n_expert_used;
  4281. const float freq_base;
  4282. const float freq_scale;
  4283. const float ext_factor;
  4284. const float attn_factor;
  4285. const float beta_fast;
  4286. const float beta_slow;
  4287. const float norm_eps;
  4288. const float norm_rms_eps;
  4289. const int32_t n_tokens;
  4290. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4291. const int32_t kv_head; // index of where we store new KV data in the cache
  4292. const int32_t n_orig_ctx;
  4293. const bool do_rope_shift;
  4294. const uint32_t pooling_type;
  4295. const llm_build_cb & cb;
  4296. std::vector<uint8_t> & buf_compute_meta;
  4297. struct ggml_context * ctx0 = nullptr;
  4298. // TODO: consider making the entire interface noexcept
  4299. llm_build_context(
  4300. llama_context & lctx,
  4301. const llama_batch & batch,
  4302. const llm_build_cb & cb,
  4303. bool worst_case) :
  4304. model (lctx.model),
  4305. lctx (lctx),
  4306. hparams (model.hparams),
  4307. cparams (lctx.cparams),
  4308. batch (batch),
  4309. kv_self (lctx.kv_self),
  4310. n_embd (hparams.n_embd),
  4311. n_layer (hparams.n_layer),
  4312. n_ctx (cparams.n_ctx),
  4313. n_head (hparams.n_head),
  4314. n_head_kv (hparams.n_head_kv),
  4315. n_embd_head_k (hparams.n_embd_head_k),
  4316. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4317. n_embd_head_v (hparams.n_embd_head_v),
  4318. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4319. n_expert (hparams.n_expert),
  4320. n_expert_used (hparams.n_expert_used),
  4321. freq_base (cparams.rope_freq_base),
  4322. freq_scale (cparams.rope_freq_scale),
  4323. ext_factor (cparams.yarn_ext_factor),
  4324. attn_factor (cparams.yarn_attn_factor),
  4325. beta_fast (cparams.yarn_beta_fast),
  4326. beta_slow (cparams.yarn_beta_slow),
  4327. norm_eps (hparams.f_norm_eps),
  4328. norm_rms_eps (hparams.f_norm_rms_eps),
  4329. n_tokens (batch.n_tokens),
  4330. n_kv (worst_case ? n_ctx : kv_self.n),
  4331. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4332. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4333. do_rope_shift (worst_case || kv_self.has_shift),
  4334. pooling_type (cparams.do_pooling ? hparams.pooling_type : (uint32_t)LLAMA_POOLING_TYPE_NONE),
  4335. cb (cb),
  4336. buf_compute_meta (lctx.buf_compute_meta) {
  4337. // all initializations should be done in init()
  4338. }
  4339. void init() {
  4340. struct ggml_init_params params = {
  4341. /*.mem_size =*/ buf_compute_meta.size(),
  4342. /*.mem_buffer =*/ buf_compute_meta.data(),
  4343. /*.no_alloc =*/ true,
  4344. };
  4345. ctx0 = ggml_init(params);
  4346. }
  4347. void free() {
  4348. if (ctx0) {
  4349. ggml_free(ctx0);
  4350. ctx0 = nullptr;
  4351. }
  4352. }
  4353. struct ggml_cgraph * build_llama() {
  4354. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4355. const int64_t n_embd_head = hparams.n_embd_head_v;
  4356. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4357. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4358. struct ggml_tensor * cur;
  4359. struct ggml_tensor * inpL;
  4360. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4361. cb(inpL, "inp_embd", -1);
  4362. // inp_pos - contains the positions
  4363. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4364. cb(inp_pos, "inp_pos", -1);
  4365. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4366. 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);
  4367. cb(KQ_mask, "KQ_mask", -1);
  4368. // shift the entire K-cache if needed
  4369. if (do_rope_shift) {
  4370. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4371. }
  4372. for (int il = 0; il < n_layer; ++il) {
  4373. struct ggml_tensor * inpSA = inpL;
  4374. // norm
  4375. cur = llm_build_norm(ctx0, inpL, hparams,
  4376. model.layers[il].attn_norm, NULL,
  4377. LLM_NORM_RMS, cb, il);
  4378. cb(cur, "attn_norm", il);
  4379. // self-attention
  4380. {
  4381. // compute Q and K and RoPE them
  4382. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4383. cb(Qcur, "Qcur", il);
  4384. if (model.layers[il].bq) {
  4385. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4386. cb(Qcur, "Qcur", il);
  4387. }
  4388. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4389. cb(Kcur, "Kcur", il);
  4390. if (model.layers[il].bk) {
  4391. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4392. cb(Kcur, "Kcur", il);
  4393. }
  4394. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4395. cb(Vcur, "Vcur", il);
  4396. if (model.layers[il].bv) {
  4397. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4398. cb(Vcur, "Vcur", il);
  4399. }
  4400. Qcur = ggml_rope_custom(
  4401. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4402. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4403. ext_factor, attn_factor, beta_fast, beta_slow
  4404. );
  4405. cb(Qcur, "Qcur", il);
  4406. Kcur = ggml_rope_custom(
  4407. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4408. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4409. ext_factor, attn_factor, beta_fast, beta_slow
  4410. );
  4411. cb(Kcur, "Kcur", il);
  4412. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4413. model.layers[il].wo, model.layers[il].bo,
  4414. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4415. cb(cur, "kqv_out", il);
  4416. }
  4417. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4418. cb(ffn_inp, "ffn_inp", il);
  4419. // feed-forward network
  4420. if (model.layers[il].ffn_gate_inp == nullptr) {
  4421. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4422. model.layers[il].ffn_norm, NULL,
  4423. LLM_NORM_RMS, cb, il);
  4424. cb(cur, "ffn_norm", il);
  4425. cur = llm_build_ffn(ctx0, cur,
  4426. model.layers[il].ffn_up, NULL,
  4427. model.layers[il].ffn_gate, NULL,
  4428. model.layers[il].ffn_down, NULL,
  4429. NULL,
  4430. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4431. cb(cur, "ffn_out", il);
  4432. } else {
  4433. // MoE branch
  4434. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4435. model.layers[il].ffn_norm, NULL,
  4436. LLM_NORM_RMS, cb, il);
  4437. cb(cur, "ffn_norm", il);
  4438. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4439. cb(logits, "ffn_moe_logits", il);
  4440. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4441. cb(probs, "ffn_moe_probs", il);
  4442. // select experts
  4443. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4444. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4445. ggml_tensor * weights = ggml_get_rows(ctx0,
  4446. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4447. cb(weights, "ffn_moe_weights", il);
  4448. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4449. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4450. cb(weights_sum, "ffn_moe_weights_sum", il);
  4451. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4452. cb(weights, "ffn_moe_weights_norm", il);
  4453. // compute expert outputs
  4454. ggml_tensor * moe_out = nullptr;
  4455. for (int i = 0; i < n_expert_used; ++i) {
  4456. ggml_tensor * cur_expert;
  4457. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4458. cb(cur_up, "ffn_moe_up", il);
  4459. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4460. cb(cur_gate, "ffn_moe_gate", il);
  4461. cur_gate = ggml_silu(ctx0, cur_gate);
  4462. cb(cur_gate, "ffn_moe_silu", il);
  4463. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4464. cb(cur_expert, "ffn_moe_gate_par", il);
  4465. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4466. cb(cur_expert, "ffn_moe_down", il);
  4467. cur_expert = ggml_mul(ctx0, cur_expert,
  4468. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4469. cb(cur_expert, "ffn_moe_weighted", il);
  4470. if (i == 0) {
  4471. moe_out = cur_expert;
  4472. } else {
  4473. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4474. cb(moe_out, "ffn_moe_out", il);
  4475. }
  4476. }
  4477. cur = moe_out;
  4478. }
  4479. cur = ggml_add(ctx0, cur, ffn_inp);
  4480. cb(cur, "l_out", il);
  4481. // input for next layer
  4482. inpL = cur;
  4483. }
  4484. cur = inpL;
  4485. cur = llm_build_norm(ctx0, cur, hparams,
  4486. model.output_norm, NULL,
  4487. LLM_NORM_RMS, cb, -1);
  4488. cb(cur, "result_norm", -1);
  4489. // lm_head
  4490. cur = ggml_mul_mat(ctx0, model.output, cur);
  4491. cb(cur, "result_output", -1);
  4492. ggml_build_forward_expand(gf, cur);
  4493. return gf;
  4494. }
  4495. struct ggml_cgraph * build_baichuan() {
  4496. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4497. const int64_t n_embd_head = hparams.n_embd_head_v;
  4498. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4499. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4500. struct ggml_tensor * cur;
  4501. struct ggml_tensor * inpL;
  4502. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4503. cb(inpL, "inp_embd", -1);
  4504. // inp_pos - contains the positions
  4505. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4506. cb(inp_pos, "inp_pos", -1);
  4507. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4508. 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);
  4509. cb(KQ_mask, "KQ_mask", -1);
  4510. // positions of the tokens in the KV cache
  4511. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4512. cb(KQ_pos, "KQ_pos", -1);
  4513. // shift the entire K-cache if needed
  4514. if (do_rope_shift) {
  4515. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4516. }
  4517. for (int il = 0; il < n_layer; ++il) {
  4518. struct ggml_tensor * inpSA = inpL;
  4519. cur = llm_build_norm(ctx0, inpL, hparams,
  4520. model.layers[il].attn_norm, NULL,
  4521. LLM_NORM_RMS, cb, il);
  4522. cb(cur, "attn_norm", il);
  4523. // self-attention
  4524. {
  4525. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4526. cb(Qcur, "Qcur", il);
  4527. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4528. cb(Kcur, "Kcur", il);
  4529. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4530. cb(Vcur, "Vcur", il);
  4531. switch (model.type) {
  4532. case MODEL_7B:
  4533. Qcur = ggml_rope_custom(
  4534. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4535. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4536. ext_factor, attn_factor, beta_fast, beta_slow
  4537. );
  4538. Kcur = ggml_rope_custom(
  4539. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4540. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4541. ext_factor, attn_factor, beta_fast, beta_slow
  4542. );
  4543. break;
  4544. case MODEL_13B:
  4545. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4546. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4547. break;
  4548. default:
  4549. GGML_ASSERT(false);
  4550. }
  4551. cb(Qcur, "Qcur", il);
  4552. cb(Kcur, "Kcur", il);
  4553. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4554. model.layers[il].wo, NULL,
  4555. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4556. cb(cur, "kqv_out", il);
  4557. }
  4558. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4559. cb(ffn_inp, "ffn_inp", il);
  4560. // feed-forward network
  4561. {
  4562. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4563. model.layers[il].ffn_norm, NULL,
  4564. LLM_NORM_RMS, cb, il);
  4565. cb(cur, "ffn_norm", il);
  4566. cur = llm_build_ffn(ctx0, cur,
  4567. model.layers[il].ffn_up, NULL,
  4568. model.layers[il].ffn_gate, NULL,
  4569. model.layers[il].ffn_down, NULL,
  4570. NULL,
  4571. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4572. cb(cur, "ffn_out", il);
  4573. }
  4574. cur = ggml_add(ctx0, cur, ffn_inp);
  4575. cb(cur, "l_out", il);
  4576. // input for next layer
  4577. inpL = cur;
  4578. }
  4579. cur = inpL;
  4580. cur = llm_build_norm(ctx0, cur, hparams,
  4581. model.output_norm, NULL,
  4582. LLM_NORM_RMS, cb, -1);
  4583. cb(cur, "result_norm", -1);
  4584. // lm_head
  4585. cur = ggml_mul_mat(ctx0, model.output, cur);
  4586. cb(cur, "result_output", -1);
  4587. ggml_build_forward_expand(gf, cur);
  4588. return gf;
  4589. }
  4590. struct ggml_cgraph * build_falcon() {
  4591. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4592. const int64_t n_embd_head = hparams.n_embd_head_v;
  4593. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4594. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4595. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4596. struct ggml_tensor * cur;
  4597. struct ggml_tensor * inpL;
  4598. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4599. cb(inpL, "inp_embd", -1);
  4600. // inp_pos - contains the positions
  4601. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4602. cb(inp_pos, "inp_pos", -1);
  4603. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4604. 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);
  4605. cb(KQ_mask, "KQ_mask", -1);
  4606. // shift the entire K-cache if needed
  4607. if (do_rope_shift) {
  4608. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4609. }
  4610. for (int il = 0; il < n_layer; ++il) {
  4611. struct ggml_tensor * attn_norm;
  4612. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4613. model.layers[il].attn_norm,
  4614. model.layers[il].attn_norm_b,
  4615. LLM_NORM, cb, il);
  4616. cb(attn_norm, "attn_norm", il);
  4617. // self-attention
  4618. {
  4619. if (model.layers[il].attn_norm_2) {
  4620. // Falcon-40B
  4621. cur = llm_build_norm(ctx0, inpL, hparams,
  4622. model.layers[il].attn_norm_2,
  4623. model.layers[il].attn_norm_2_b,
  4624. LLM_NORM, cb, il);
  4625. cb(cur, "attn_norm_2", il);
  4626. } else {
  4627. cur = attn_norm;
  4628. }
  4629. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4630. cb(cur, "wqkv", il);
  4631. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4632. 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)));
  4633. 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)));
  4634. cb(Qcur, "Qcur", il);
  4635. cb(Kcur, "Kcur", il);
  4636. cb(Vcur, "Vcur", il);
  4637. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4638. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4639. // using mode = 2 for neox mode
  4640. Qcur = ggml_rope_custom(
  4641. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4642. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4643. );
  4644. cb(Qcur, "Qcur", il);
  4645. Kcur = ggml_rope_custom(
  4646. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4647. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4648. );
  4649. cb(Kcur, "Kcur", il);
  4650. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4651. model.layers[il].wo, NULL,
  4652. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4653. cb(cur, "kqv_out", il);
  4654. }
  4655. struct ggml_tensor * ffn_inp = cur;
  4656. // feed forward
  4657. {
  4658. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4659. model.layers[il].ffn_up, NULL,
  4660. NULL, NULL,
  4661. model.layers[il].ffn_down, NULL,
  4662. NULL,
  4663. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4664. cb(cur, "ffn_out", il);
  4665. }
  4666. cur = ggml_add(ctx0, cur, ffn_inp);
  4667. cb(cur, "l_out", il);
  4668. cur = ggml_add(ctx0, cur, inpL);
  4669. cb(cur, "l_out", il);
  4670. // input for next layer
  4671. inpL = cur;
  4672. }
  4673. cur = inpL;
  4674. // norm
  4675. cur = llm_build_norm(ctx0, cur, hparams,
  4676. model.output_norm,
  4677. model.output_norm_b,
  4678. LLM_NORM, cb, -1);
  4679. cb(cur, "result_norm", -1);
  4680. cur = ggml_mul_mat(ctx0, model.output, cur);
  4681. cb(cur, "result_output", -1);
  4682. ggml_build_forward_expand(gf, cur);
  4683. return gf;
  4684. }
  4685. struct ggml_cgraph * build_starcoder() {
  4686. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4687. const int64_t n_embd_head = hparams.n_embd_head_v;
  4688. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4689. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4690. struct ggml_tensor * cur;
  4691. struct ggml_tensor * pos;
  4692. struct ggml_tensor * inpL;
  4693. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4694. cb(inpL, "inp_embd", -1);
  4695. // inp_pos - contains the positions
  4696. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4697. cb(inp_pos, "inp_pos", -1);
  4698. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4699. 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);
  4700. cb(KQ_mask, "KQ_mask", -1);
  4701. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4702. cb(pos, "pos_embd", -1);
  4703. inpL = ggml_add(ctx0, inpL, pos);
  4704. cb(inpL, "inpL", -1);
  4705. for (int il = 0; il < n_layer; ++il) {
  4706. cur = llm_build_norm(ctx0, inpL, hparams,
  4707. model.layers[il].attn_norm,
  4708. model.layers[il].attn_norm_b,
  4709. LLM_NORM, cb, il);
  4710. cb(cur, "attn_norm", il);
  4711. // self-attention
  4712. {
  4713. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4714. cb(cur, "wqkv", il);
  4715. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4716. cb(cur, "bqkv", il);
  4717. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4718. 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)));
  4719. 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)));
  4720. cb(Qcur, "Qcur", il);
  4721. cb(Kcur, "Kcur", il);
  4722. cb(Vcur, "Vcur", il);
  4723. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4724. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4725. model.layers[il].wo, model.layers[il].bo,
  4726. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4727. cb(cur, "kqv_out", il);
  4728. }
  4729. // add the input
  4730. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4731. cb(ffn_inp, "ffn_inp", il);
  4732. // FF
  4733. {
  4734. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4735. model.layers[il].ffn_norm,
  4736. model.layers[il].ffn_norm_b,
  4737. LLM_NORM, cb, il);
  4738. cb(cur, "ffn_norm", il);
  4739. cur = llm_build_ffn(ctx0, cur,
  4740. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4741. NULL, NULL,
  4742. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4743. NULL,
  4744. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4745. cb(cur, "ffn_out", il);
  4746. }
  4747. inpL = ggml_add(ctx0, cur, ffn_inp);
  4748. cb(inpL, "l_out", il);
  4749. }
  4750. cur = llm_build_norm(ctx0, inpL, hparams,
  4751. model.output_norm,
  4752. model.output_norm_b,
  4753. LLM_NORM, cb, -1);
  4754. cb(cur, "result_norm", -1);
  4755. cur = ggml_mul_mat(ctx0, model.output, cur);
  4756. cb(cur, "result_output", -1);
  4757. ggml_build_forward_expand(gf, cur);
  4758. return gf;
  4759. }
  4760. struct ggml_cgraph * build_persimmon() {
  4761. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4762. const int64_t n_embd_head = hparams.n_embd_head_v;
  4763. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4764. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4765. struct ggml_tensor * cur;
  4766. struct ggml_tensor * inpL;
  4767. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4768. cb(inpL, "inp_embd", -1);
  4769. // inp_pos - contains the positions
  4770. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4771. cb(inp_pos, "inp_pos", -1);
  4772. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4773. 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);
  4774. cb(KQ_mask, "KQ_mask", -1);
  4775. if (do_rope_shift) {
  4776. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4777. }
  4778. for (int il = 0; il < n_layer; ++il) {
  4779. struct ggml_tensor * residual = inpL;
  4780. cur = llm_build_norm(ctx0, inpL, hparams,
  4781. model.layers[il].attn_norm,
  4782. model.layers[il].attn_norm_b,
  4783. LLM_NORM, cb, il);
  4784. cb(cur, "attn_norm", il);
  4785. // self attention
  4786. {
  4787. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4788. cb(cur, "wqkv", il);
  4789. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4790. cb(cur, "bqkv", il);
  4791. // split qkv
  4792. GGML_ASSERT(n_head_kv == n_head);
  4793. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4794. cb(tmpqkv, "tmpqkv", il);
  4795. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4796. cb(tmpqkv_perm, "tmpqkv", il);
  4797. struct ggml_tensor * tmpq = ggml_view_3d(
  4798. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4799. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4800. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4801. 0
  4802. );
  4803. cb(tmpq, "tmpq", il);
  4804. struct ggml_tensor * tmpk = ggml_view_3d(
  4805. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4806. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4807. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4808. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4809. );
  4810. cb(tmpk, "tmpk", il);
  4811. // Q/K Layernorm
  4812. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4813. model.layers[il].attn_q_norm,
  4814. model.layers[il].attn_q_norm_b,
  4815. LLM_NORM, cb, il);
  4816. cb(tmpq, "tmpq", il);
  4817. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4818. model.layers[il].attn_k_norm,
  4819. model.layers[il].attn_k_norm_b,
  4820. LLM_NORM, cb, il);
  4821. cb(tmpk, "tmpk", il);
  4822. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4823. struct ggml_tensor * qrot = ggml_view_3d(
  4824. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4825. ggml_element_size(tmpq) * n_embd_head,
  4826. ggml_element_size(tmpq) * n_embd_head * n_head,
  4827. 0
  4828. );
  4829. cb(qrot, "qrot", il);
  4830. struct ggml_tensor * krot = ggml_view_3d(
  4831. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4832. ggml_element_size(tmpk) * n_embd_head,
  4833. ggml_element_size(tmpk) * n_embd_head * n_head,
  4834. 0
  4835. );
  4836. cb(krot, "krot", il);
  4837. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4838. struct ggml_tensor * qpass = ggml_view_3d(
  4839. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4840. ggml_element_size(tmpq) * n_embd_head,
  4841. ggml_element_size(tmpq) * n_embd_head * n_head,
  4842. ggml_element_size(tmpq) * hparams.n_rot
  4843. );
  4844. cb(qpass, "qpass", il);
  4845. struct ggml_tensor * kpass = ggml_view_3d(
  4846. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4847. ggml_element_size(tmpk) * n_embd_head,
  4848. ggml_element_size(tmpk) * n_embd_head * n_head,
  4849. ggml_element_size(tmpk) * hparams.n_rot
  4850. );
  4851. cb(kpass, "kpass", il);
  4852. struct ggml_tensor * qrotated = ggml_rope_custom(
  4853. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4854. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4855. );
  4856. cb(qrotated, "qrotated", il);
  4857. struct ggml_tensor * krotated = ggml_rope_custom(
  4858. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4859. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4860. );
  4861. cb(krotated, "krotated", il);
  4862. // ggml currently only supports concatenation on dim=2
  4863. // so we need to permute qrot, qpass, concat, then permute back.
  4864. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4865. cb(qrotated, "qrotated", il);
  4866. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4867. cb(krotated, "krotated", il);
  4868. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4869. cb(qpass, "qpass", il);
  4870. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4871. cb(kpass, "kpass", il);
  4872. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4873. cb(Qcur, "Qcur", il);
  4874. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4875. cb(Kcur, "Kcur", il);
  4876. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4877. cb(Q, "Q", il);
  4878. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4879. cb(Kcur, "Kcur", il);
  4880. struct ggml_tensor * Vcur = ggml_view_3d(
  4881. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4882. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4883. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4884. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4885. );
  4886. cb(Vcur, "Vcur", il);
  4887. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4888. model.layers[il].wo, model.layers[il].bo,
  4889. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4890. cb(cur, "kqv_out", il);
  4891. }
  4892. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4893. cb(ffn_inp, "ffn_inp", il);
  4894. // feed-forward network
  4895. {
  4896. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4897. model.layers[il].ffn_norm,
  4898. model.layers[il].ffn_norm_b,
  4899. LLM_NORM, cb, il);
  4900. cb(cur, "ffn_norm", il);
  4901. cur = llm_build_ffn(ctx0, cur,
  4902. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4903. NULL, NULL,
  4904. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4905. NULL,
  4906. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4907. cb(cur, "ffn_out", il);
  4908. }
  4909. cur = ggml_add(ctx0, cur, ffn_inp);
  4910. cb(cur, "l_out", il);
  4911. inpL = cur;
  4912. }
  4913. cur = inpL;
  4914. cur = llm_build_norm(ctx0, cur, hparams,
  4915. model.output_norm,
  4916. model.output_norm_b,
  4917. LLM_NORM, cb, -1);
  4918. cb(cur, "result_norm", -1);
  4919. cur = ggml_mul_mat(ctx0, model.output, cur);
  4920. cb(cur, "result_output", -1);
  4921. ggml_build_forward_expand(gf, cur);
  4922. return gf;
  4923. }
  4924. struct ggml_cgraph * build_refact() {
  4925. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4926. const int64_t n_embd_head = hparams.n_embd_head_v;
  4927. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4928. struct ggml_tensor * cur;
  4929. struct ggml_tensor * inpL;
  4930. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4931. cb(inpL, "inp_embd", -1);
  4932. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4933. 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);
  4934. cb(KQ_mask, "KQ_mask", -1);
  4935. // positions of the tokens in the KV cache
  4936. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4937. cb(KQ_pos, "KQ_pos", -1);
  4938. for (int il = 0; il < n_layer; ++il) {
  4939. struct ggml_tensor * inpSA = inpL;
  4940. cur = llm_build_norm(ctx0, inpL, hparams,
  4941. model.layers[il].attn_norm, NULL,
  4942. LLM_NORM_RMS, cb, il);
  4943. cb(cur, "attn_norm", il);
  4944. // self-attention
  4945. {
  4946. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4947. cb(Qcur, "Qcur", il);
  4948. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4949. cb(Kcur, "Kcur", il);
  4950. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4951. cb(Vcur, "Vcur", il);
  4952. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4953. cb(Kcur, "Kcur", il);
  4954. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4955. cb(Qcur, "Qcur", il);
  4956. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4957. model.layers[il].wo, NULL,
  4958. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4959. cb(cur, "kqv_out", il);
  4960. }
  4961. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4962. cb(ffn_inp, "ffn_inp", il);
  4963. // feed-forward network
  4964. {
  4965. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4966. model.layers[il].ffn_norm, NULL,
  4967. LLM_NORM_RMS, cb, il);
  4968. cb(cur, "ffn_norm", il);
  4969. cur = llm_build_ffn(ctx0, cur,
  4970. model.layers[il].ffn_up, NULL,
  4971. model.layers[il].ffn_gate, NULL,
  4972. model.layers[il].ffn_down, NULL,
  4973. NULL,
  4974. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4975. cb(cur, "ffn_out", il);
  4976. }
  4977. cur = ggml_add(ctx0, cur, ffn_inp);
  4978. cb(cur, "l_out", il);
  4979. // input for next layer
  4980. inpL = cur;
  4981. }
  4982. cur = inpL;
  4983. cur = llm_build_norm(ctx0, cur, hparams,
  4984. model.output_norm, NULL,
  4985. LLM_NORM_RMS, cb, -1);
  4986. cb(cur, "result_norm", -1);
  4987. // lm_head
  4988. cur = ggml_mul_mat(ctx0, model.output, cur);
  4989. cb(cur, "result_output", -1);
  4990. ggml_build_forward_expand(gf, cur);
  4991. return gf;
  4992. }
  4993. struct ggml_cgraph * build_bert() {
  4994. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4995. const int64_t n_embd_head = hparams.n_embd_head_v;
  4996. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4997. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4998. struct ggml_tensor * cur;
  4999. struct ggml_tensor * inpL;
  5000. // get input vectors with right size
  5001. const size_t stride1 = n_tokens * ggml_type_size(lctx.inp_tokens->type);
  5002. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5003. struct ggml_tensor * inp_mean = ggml_view_2d(ctx0, lctx.inp_mean, n_tokens, n_tokens, stride1, 0);
  5004. struct ggml_tensor * inp_cls = ggml_view_1d(ctx0, lctx.inp_cls, n_tokens, 0);
  5005. // construct input embeddings (token, type, position)
  5006. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5007. // token types are hardcoded to zero ("Sentence A")
  5008. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5009. inpL = ggml_add(ctx0, inpL, type_row0);
  5010. if (model.arch == LLM_ARCH_BERT) {
  5011. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5012. }
  5013. cb(inpL, "inp_embd", -1);
  5014. // embed layer norm
  5015. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5016. cb(inpL, "inp_norm", -1);
  5017. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5018. 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);
  5019. cb(KQ_mask, "KQ_mask", -1); // [n_kv, n_tokens]
  5020. // iterate layers
  5021. for (int il = 0; il < n_layer; ++il) {
  5022. struct ggml_tensor * cur = inpL;
  5023. // self-attention
  5024. if (model.arch == LLM_ARCH_BERT) {
  5025. struct ggml_tensor * Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5026. cb(Qcur, "Qcur", il);
  5027. struct ggml_tensor * Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5028. cb(Kcur, "Kcur", il);
  5029. struct ggml_tensor * Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5030. cb(Vcur, "Vcur", il);
  5031. // seems like we just need to do this for Q?
  5032. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5033. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5034. model.layers[il].wo, model.layers[il].bo,
  5035. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5036. cb(cur, "kqv_out", il);
  5037. } else {
  5038. // compute Q and K and RoPE them
  5039. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5040. cb(cur, "wqkv", il);
  5041. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5042. 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)));
  5043. 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)));
  5044. cb(Qcur, "Qcur", il);
  5045. cb(Kcur, "Kcur", il);
  5046. cb(Vcur, "Vcur", il);
  5047. Qcur = ggml_rope_custom(
  5048. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5049. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5050. ext_factor, attn_factor, beta_fast, beta_slow
  5051. );
  5052. cb(Qcur, "Qcur", il);
  5053. Kcur = ggml_rope_custom(
  5054. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5055. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5056. ext_factor, attn_factor, beta_fast, beta_slow
  5057. );
  5058. cb(Kcur, "Kcur", il);
  5059. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5060. model.layers[il].wo, model.layers[il].bo,
  5061. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5062. cb(cur, "kqv_out", il);
  5063. }
  5064. // re-add the layer input
  5065. cur = ggml_add(ctx0, cur, inpL);
  5066. // attention layer norm
  5067. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5068. struct ggml_tensor * ffn_inp = cur;
  5069. cb(ffn_inp, "ffn_inp", il);
  5070. // feed-forward network
  5071. if (model.arch == LLM_ARCH_BERT) {
  5072. cur = llm_build_ffn(ctx0, cur,
  5073. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5074. NULL, NULL,
  5075. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5076. NULL,
  5077. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5078. } else {
  5079. cur = llm_build_ffn(ctx0, cur,
  5080. model.layers[il].ffn_up, NULL,
  5081. model.layers[il].ffn_gate, NULL,
  5082. model.layers[il].ffn_down, NULL,
  5083. NULL,
  5084. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5085. }
  5086. cb(cur, "ffn_out", il);
  5087. // attentions bypass the intermediate layer
  5088. cur = ggml_add(ctx0, cur, ffn_inp);
  5089. // output layer norm
  5090. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5091. // input for next layer
  5092. inpL = cur;
  5093. }
  5094. // final output
  5095. cur = inpL;
  5096. // pooling layer
  5097. if (pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  5098. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5099. } else if (pooling_type == LLAMA_POOLING_TYPE_CLS) {
  5100. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5101. } else {
  5102. GGML_ASSERT(pooling_type == LLAMA_POOLING_TYPE_NONE && "Invalid pooling type");
  5103. }
  5104. cb(cur, "result_embd", -1);
  5105. ggml_build_forward_expand(gf, cur);
  5106. return gf;
  5107. }
  5108. struct ggml_cgraph * build_bloom() {
  5109. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5110. const int64_t n_embd_head = hparams.n_embd_head_v;
  5111. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5112. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5113. struct ggml_tensor * cur;
  5114. struct ggml_tensor * inpL;
  5115. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5116. cb(inpL, "inp_embd", -1);
  5117. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5118. 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);
  5119. cb(KQ_mask, "KQ_mask", -1);
  5120. // positions of the tokens in the KV cache
  5121. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5122. cb(KQ_pos, "KQ_pos", -1);
  5123. inpL = llm_build_norm(ctx0, inpL, hparams,
  5124. model.tok_norm,
  5125. model.tok_norm_b,
  5126. LLM_NORM, cb, -1);
  5127. cb(inpL, "inp_norm", -1);
  5128. for (int il = 0; il < n_layer; ++il) {
  5129. cur = llm_build_norm(ctx0, inpL, hparams,
  5130. model.layers[il].attn_norm,
  5131. model.layers[il].attn_norm_b,
  5132. LLM_NORM, cb, il);
  5133. cb(cur, "attn_norm", il);
  5134. // self-attention
  5135. {
  5136. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5137. cb(cur, "wqkv", il);
  5138. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5139. cb(cur, "bqkv", il);
  5140. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5141. 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)));
  5142. 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)));
  5143. cb(Qcur, "Qcur", il);
  5144. cb(Kcur, "Kcur", il);
  5145. cb(Vcur, "Vcur", il);
  5146. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5147. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5148. model.layers[il].wo, model.layers[il].bo,
  5149. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5150. cb(cur, "kqv_out", il);
  5151. }
  5152. // Add the input
  5153. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5154. cb(ffn_inp, "ffn_inp", il);
  5155. // FF
  5156. {
  5157. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5158. model.layers[il].ffn_norm,
  5159. model.layers[il].ffn_norm_b,
  5160. LLM_NORM, cb, il);
  5161. cb(cur, "ffn_norm", il);
  5162. cur = llm_build_ffn(ctx0, cur,
  5163. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5164. NULL, NULL,
  5165. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5166. NULL,
  5167. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5168. cb(cur, "ffn_out", il);
  5169. }
  5170. inpL = ggml_add(ctx0, cur, ffn_inp);
  5171. cb(inpL, "l_out", il);
  5172. }
  5173. cur = llm_build_norm(ctx0, inpL, hparams,
  5174. model.output_norm,
  5175. model.output_norm_b,
  5176. LLM_NORM, cb, -1);
  5177. cb(cur, "result_norm", -1);
  5178. cur = ggml_mul_mat(ctx0, model.output, cur);
  5179. cb(cur, "result_output", -1);
  5180. ggml_build_forward_expand(gf, cur);
  5181. return gf;
  5182. }
  5183. struct ggml_cgraph * build_mpt() {
  5184. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5185. const int64_t n_embd_head = hparams.n_embd_head_v;
  5186. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5187. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5188. struct ggml_tensor * cur;
  5189. struct ggml_tensor * inpL;
  5190. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5191. cb(inpL, "inp_embd", -1);
  5192. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5193. 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);
  5194. cb(KQ_mask, "KQ_mask", -1);
  5195. // positions of the tokens in the KV cache
  5196. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5197. cb(KQ_pos, "KQ_pos", -1);
  5198. for (int il = 0; il < n_layer; ++il) {
  5199. struct ggml_tensor * attn_norm;
  5200. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5201. model.layers[il].attn_norm,
  5202. model.layers[il].attn_norm_b,
  5203. LLM_NORM, cb, il);
  5204. cb(attn_norm, "attn_norm", il);
  5205. // self-attention
  5206. {
  5207. cur = attn_norm;
  5208. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5209. cb(cur, "wqkv", il);
  5210. if (model.layers[il].bqkv){
  5211. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5212. cb(cur, "bqkv", il);
  5213. }
  5214. if (hparams.f_clamp_kqv > 0.0f) {
  5215. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5216. cb(cur, "wqkv_clamped", il);
  5217. }
  5218. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5219. 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)));
  5220. 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)));
  5221. cb(Qcur, "Qcur", il);
  5222. cb(Kcur, "Kcur", il);
  5223. cb(Vcur, "Vcur", il);
  5224. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5225. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5226. model.layers[il].wo, model.layers[il].bo,
  5227. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5228. cb(cur, "kqv_out", il);
  5229. }
  5230. // Add the input
  5231. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5232. cb(ffn_inp, "ffn_inp", il);
  5233. // feed forward
  5234. {
  5235. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5236. model.layers[il].ffn_norm,
  5237. model.layers[il].ffn_norm_b,
  5238. LLM_NORM, cb, il);
  5239. cb(cur, "ffn_norm", il);
  5240. cur = llm_build_ffn(ctx0, cur,
  5241. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5242. NULL, NULL,
  5243. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5244. model.layers[il].ffn_act,
  5245. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5246. cb(cur, "ffn_out", il);
  5247. }
  5248. cur = ggml_add(ctx0, cur, ffn_inp);
  5249. cb(cur, "l_out", il);
  5250. // input for next layer
  5251. inpL = cur;
  5252. }
  5253. cur = inpL;
  5254. cur = llm_build_norm(ctx0, cur, hparams,
  5255. model.output_norm,
  5256. model.output_norm_b,
  5257. LLM_NORM, cb, -1);
  5258. cb(cur, "result_norm", -1);
  5259. cur = ggml_mul_mat(ctx0, model.output, cur);
  5260. cb(cur, "result_output", -1);
  5261. ggml_build_forward_expand(gf, cur);
  5262. return gf;
  5263. }
  5264. struct ggml_cgraph * build_stablelm() {
  5265. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5266. const int64_t n_embd_head = hparams.n_embd_head_v;
  5267. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5268. struct ggml_tensor * cur;
  5269. struct ggml_tensor * inpL;
  5270. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5271. cb(inpL, "inp_embd", -1);
  5272. // inp_pos - contains the positions
  5273. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5274. cb(inp_pos, "inp_pos", -1);
  5275. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5276. 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);
  5277. cb(KQ_mask, "KQ_mask", -1);
  5278. // shift the entire K-cache if needed
  5279. if (do_rope_shift) {
  5280. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5281. }
  5282. for (int il = 0; il < n_layer; ++il) {
  5283. struct ggml_tensor * inpSA = inpL;
  5284. // norm
  5285. cur = llm_build_norm(ctx0, inpL, hparams,
  5286. model.layers[il].attn_norm,
  5287. model.layers[il].attn_norm_b,
  5288. LLM_NORM, cb, il);
  5289. cb(cur, "attn_norm", il);
  5290. // self-attention
  5291. {
  5292. // compute Q and K and RoPE them
  5293. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5294. cb(Qcur, "Qcur", il);
  5295. if (model.layers[il].bq) {
  5296. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5297. cb(Qcur, "Qcur", il);
  5298. }
  5299. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5300. cb(Kcur, "Kcur", il);
  5301. if (model.layers[il].bk) {
  5302. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5303. cb(Kcur, "Kcur", il);
  5304. }
  5305. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5306. cb(Vcur, "Vcur", il);
  5307. if (model.layers[il].bv) {
  5308. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5309. cb(Vcur, "Vcur", il);
  5310. }
  5311. Qcur = ggml_rope_custom(
  5312. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5313. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5314. ext_factor, attn_factor, beta_fast, beta_slow
  5315. );
  5316. cb(Qcur, "Qcur", il);
  5317. Kcur = ggml_rope_custom(
  5318. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5319. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5320. ext_factor, attn_factor, beta_fast, beta_slow
  5321. );
  5322. cb(Kcur, "Kcur", il);
  5323. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5324. model.layers[il].wo, NULL,
  5325. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5326. cb(cur, "kqv_out", il);
  5327. }
  5328. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5329. cb(ffn_inp, "ffn_inp", il);
  5330. // feed-forward network
  5331. {
  5332. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5333. model.layers[il].ffn_norm,
  5334. model.layers[il].ffn_norm_b,
  5335. LLM_NORM, cb, il);
  5336. cb(cur, "ffn_norm", il);
  5337. cur = llm_build_ffn(ctx0, cur,
  5338. model.layers[il].ffn_up, NULL,
  5339. model.layers[il].ffn_gate, NULL,
  5340. model.layers[il].ffn_down, NULL,
  5341. NULL,
  5342. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5343. cb(cur, "ffn_out", il);
  5344. }
  5345. cur = ggml_add(ctx0, cur, ffn_inp);
  5346. cb(cur, "l_out", il);
  5347. // input for next layer
  5348. inpL = cur;
  5349. }
  5350. cur = inpL;
  5351. cur = llm_build_norm(ctx0, cur, hparams,
  5352. model.output_norm,
  5353. model.output_norm_b,
  5354. LLM_NORM, cb, -1);
  5355. cb(cur, "result_norm", -1);
  5356. // lm_head
  5357. cur = ggml_mul_mat(ctx0, model.output, cur);
  5358. cb(cur, "result_output", -1);
  5359. ggml_build_forward_expand(gf, cur);
  5360. return gf;
  5361. }
  5362. struct ggml_cgraph * build_qwen() {
  5363. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5364. const int64_t n_embd_head = hparams.n_embd_head_v;
  5365. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5366. struct ggml_tensor * cur;
  5367. struct ggml_tensor * inpL;
  5368. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5369. cb(inpL, "inp_embd", -1);
  5370. // inp_pos - contains the positions
  5371. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5372. cb(inp_pos, "inp_pos", -1);
  5373. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5374. 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);
  5375. cb(KQ_mask, "KQ_mask", -1);
  5376. // shift the entire K-cache if needed
  5377. if (do_rope_shift) {
  5378. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5379. }
  5380. for (int il = 0; il < n_layer; ++il) {
  5381. struct ggml_tensor * inpSA = inpL;
  5382. cur = llm_build_norm(ctx0, inpL, hparams,
  5383. model.layers[il].attn_norm, NULL,
  5384. LLM_NORM_RMS, cb, il);
  5385. cb(cur, "attn_norm", il);
  5386. // self-attention
  5387. {
  5388. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5389. cb(cur, "wqkv", il);
  5390. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5391. cb(cur, "bqkv", il);
  5392. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5393. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5394. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5395. cb(Qcur, "Qcur", il);
  5396. cb(Kcur, "Kcur", il);
  5397. cb(Vcur, "Vcur", il);
  5398. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5399. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5400. // using mode = 2 for neox mode
  5401. Qcur = ggml_rope_custom(
  5402. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5403. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5404. );
  5405. cb(Qcur, "Qcur", il);
  5406. Kcur = ggml_rope_custom(
  5407. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5408. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5409. );
  5410. cb(Kcur, "Kcur", il);
  5411. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5412. model.layers[il].wo, NULL,
  5413. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5414. cb(cur, "kqv_out", il);
  5415. }
  5416. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5417. cb(ffn_inp, "ffn_inp", il);
  5418. // feed-forward forward
  5419. {
  5420. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5421. model.layers[il].ffn_norm, NULL,
  5422. LLM_NORM_RMS, cb, il);
  5423. cb(cur, "ffn_norm", il);
  5424. cur = llm_build_ffn(ctx0, cur,
  5425. model.layers[il].ffn_up, NULL,
  5426. model.layers[il].ffn_gate, NULL,
  5427. model.layers[il].ffn_down, NULL,
  5428. NULL,
  5429. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5430. cb(cur, "ffn_out", il);
  5431. }
  5432. cur = ggml_add(ctx0, cur, ffn_inp);
  5433. cb(cur, "l_out", il);
  5434. // input for next layer
  5435. inpL = cur;
  5436. }
  5437. cur = inpL;
  5438. cur = llm_build_norm(ctx0, cur, hparams,
  5439. model.output_norm, NULL,
  5440. LLM_NORM_RMS, cb, -1);
  5441. cb(cur, "result_norm", -1);
  5442. // lm_head
  5443. cur = ggml_mul_mat(ctx0, model.output, cur);
  5444. cb(cur, "result_output", -1);
  5445. ggml_build_forward_expand(gf, cur);
  5446. return gf;
  5447. }
  5448. struct ggml_cgraph * build_qwen2() {
  5449. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5450. const int64_t n_embd_head = hparams.n_embd_head_v;
  5451. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5452. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5453. struct ggml_tensor * cur;
  5454. struct ggml_tensor * inpL;
  5455. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5456. cb(inpL, "inp_embd", -1);
  5457. // inp_pos - contains the positions
  5458. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5459. cb(inp_pos, "inp_pos", -1);
  5460. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5461. 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);
  5462. cb(KQ_mask, "KQ_mask", -1);
  5463. // shift the entire K-cache if needed
  5464. if (do_rope_shift) {
  5465. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5466. }
  5467. for (int il = 0; il < n_layer; ++il) {
  5468. struct ggml_tensor * inpSA = inpL;
  5469. // norm
  5470. cur = llm_build_norm(ctx0, inpL, hparams,
  5471. model.layers[il].attn_norm, NULL,
  5472. LLM_NORM_RMS, cb, il);
  5473. cb(cur, "attn_norm", il);
  5474. // self-attention
  5475. {
  5476. // compute Q and K and RoPE them
  5477. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5478. cb(Qcur, "Qcur", il);
  5479. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5480. cb(Qcur, "Qcur", il);
  5481. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5482. cb(Kcur, "Kcur", il);
  5483. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5484. cb(Kcur, "Kcur", il);
  5485. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5486. cb(Vcur, "Vcur", il);
  5487. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5488. cb(Vcur, "Vcur", il);
  5489. // these nodes are added to the graph together so that they are not reordered
  5490. // by doing so, the number of splits in the graph is reduced
  5491. ggml_build_forward_expand(gf, Qcur);
  5492. ggml_build_forward_expand(gf, Kcur);
  5493. ggml_build_forward_expand(gf, Vcur);
  5494. Qcur = ggml_rope_custom(
  5495. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5496. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5497. ext_factor, attn_factor, beta_fast, beta_slow
  5498. );
  5499. cb(Qcur, "Qcur", il);
  5500. Kcur = ggml_rope_custom(
  5501. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5502. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5503. ext_factor, attn_factor, beta_fast, beta_slow
  5504. );
  5505. cb(Kcur, "Kcur", il);
  5506. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5507. model.layers[il].wo, model.layers[il].bo,
  5508. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5509. cb(cur, "kqv_out", il);
  5510. }
  5511. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5512. cb(ffn_inp, "ffn_inp", il);
  5513. // feed-forward network
  5514. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5515. model.layers[il].ffn_norm, NULL,
  5516. LLM_NORM_RMS, cb, il);
  5517. cb(cur, "ffn_norm", il);
  5518. cur = llm_build_ffn(ctx0, cur,
  5519. model.layers[il].ffn_up, NULL,
  5520. model.layers[il].ffn_gate, NULL,
  5521. model.layers[il].ffn_down, NULL,
  5522. NULL,
  5523. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5524. cb(cur, "ffn_out", il);
  5525. cur = ggml_add(ctx0, cur, ffn_inp);
  5526. cb(cur, "l_out", il);
  5527. // input for next layer
  5528. inpL = cur;
  5529. }
  5530. cur = inpL;
  5531. cur = llm_build_norm(ctx0, cur, hparams,
  5532. model.output_norm, NULL,
  5533. LLM_NORM_RMS, cb, -1);
  5534. cb(cur, "result_norm", -1);
  5535. // lm_head
  5536. cur = ggml_mul_mat(ctx0, model.output, cur);
  5537. cb(cur, "result_output", -1);
  5538. ggml_build_forward_expand(gf, cur);
  5539. return gf;
  5540. }
  5541. struct ggml_cgraph * build_phi2() {
  5542. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5543. const int64_t n_embd_head = hparams.n_embd_head_v;
  5544. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5545. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5546. struct ggml_tensor * cur;
  5547. struct ggml_tensor * attn_norm_output;
  5548. struct ggml_tensor * ffn_output;
  5549. struct ggml_tensor * inpL;
  5550. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5551. cb(inpL, "inp_embd", -1);
  5552. // inp_pos - contains the positions
  5553. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5554. cb(inp_pos, "inp_pos", -1);
  5555. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5556. 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);
  5557. cb(KQ_mask, "KQ_mask", -1);
  5558. // shift the entire K-cache if needed
  5559. if (do_rope_shift) {
  5560. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5561. }
  5562. for (int il = 0; il < n_layer; ++il) {
  5563. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5564. model.layers[il].attn_norm,
  5565. model.layers[il].attn_norm_b,
  5566. LLM_NORM, cb, il);
  5567. cb(attn_norm_output, "attn_norm", il);
  5568. // self-attention
  5569. {
  5570. struct ggml_tensor * Qcur = nullptr;
  5571. struct ggml_tensor * Kcur = nullptr;
  5572. struct ggml_tensor * Vcur = nullptr;
  5573. if (model.layers[il].wqkv) {
  5574. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5575. cb(cur, "wqkv", il);
  5576. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5577. cb(cur, "bqkv", il);
  5578. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5579. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5580. 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)));
  5581. } else {
  5582. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5583. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5584. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5585. }
  5586. cb(Qcur, "Qcur", il);
  5587. cb(Kcur, "Kcur", il);
  5588. cb(Vcur, "Vcur", il);
  5589. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5590. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5591. Qcur = ggml_rope_custom(
  5592. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5593. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5594. );
  5595. cb(Qcur, "Qcur", il);
  5596. // with phi2, we scale the Q to avoid precision issues
  5597. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5598. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5599. cb(Qcur, "Qcur", il);
  5600. Kcur = ggml_rope_custom(
  5601. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5602. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5603. );
  5604. cb(Kcur, "Kcur", il);
  5605. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5606. model.layers[il].wo, model.layers[il].bo,
  5607. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5608. cb(cur, "kqv_out", il);
  5609. }
  5610. // FF
  5611. {
  5612. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5613. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5614. NULL, NULL,
  5615. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5616. NULL,
  5617. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5618. cb(ffn_output, "ffn_out", il);
  5619. }
  5620. cur = ggml_add(ctx0, cur, ffn_output);
  5621. cb(cur, "l_out", il);
  5622. cur = ggml_add(ctx0, cur, inpL);
  5623. cb(cur, "l_out", il);
  5624. inpL = cur;
  5625. }
  5626. cur = llm_build_norm(ctx0, inpL, hparams,
  5627. model.output_norm,
  5628. model.output_norm_b,
  5629. LLM_NORM, cb, -1);
  5630. cb(cur, "result_norm", -1);
  5631. cur = ggml_mul_mat(ctx0, model.output, cur);
  5632. cb(cur, "result_output_no_bias", -1);
  5633. cur = ggml_add(ctx0, cur, model.output_b);
  5634. cb(cur, "result_output", -1);
  5635. ggml_build_forward_expand(gf, cur);
  5636. return gf;
  5637. }
  5638. struct ggml_cgraph * build_plamo() {
  5639. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5640. const int64_t n_embd_head = hparams.n_embd_head_v;
  5641. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5642. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5643. struct ggml_tensor * cur;
  5644. struct ggml_tensor * inpL;
  5645. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5646. cb(inpL, "inp_embd", -1);
  5647. // inp_pos - contains the positions
  5648. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5649. cb(inp_pos, "inp_pos", -1);
  5650. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5651. 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);
  5652. cb(KQ_mask, "KQ_mask", -1);
  5653. // shift the entire K-cache if needed
  5654. if (do_rope_shift) {
  5655. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5656. }
  5657. for (int il = 0; il < n_layer; ++il) {
  5658. // norm
  5659. cur = llm_build_norm(ctx0, inpL, hparams,
  5660. model.layers[il].attn_norm, NULL,
  5661. LLM_NORM_RMS, cb, il);
  5662. cb(cur, "attn_norm", il);
  5663. struct ggml_tensor * attention_norm = cur;
  5664. // self-attention
  5665. {
  5666. // compute Q and K and RoPE them
  5667. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5668. cb(Qcur, "Qcur", il);
  5669. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5670. cb(Kcur, "Kcur", il);
  5671. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5672. cb(Vcur, "Vcur", il);
  5673. Qcur = ggml_rope_custom(
  5674. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5675. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5676. ext_factor, attn_factor, beta_fast, beta_slow);
  5677. cb(Qcur, "Qcur", il);
  5678. Kcur = ggml_rope_custom(
  5679. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5680. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5681. ext_factor, attn_factor, beta_fast, beta_slow);
  5682. cb(Kcur, "Kcur", il);
  5683. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5684. model.layers[il].wo, NULL,
  5685. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5686. cb(cur, "kqv_out", il);
  5687. }
  5688. struct ggml_tensor * sa_out = cur;
  5689. cur = attention_norm;
  5690. // feed-forward network
  5691. {
  5692. cur = llm_build_ffn(ctx0, cur,
  5693. model.layers[il].ffn_up, NULL,
  5694. model.layers[il].ffn_gate, NULL,
  5695. model.layers[il].ffn_down, NULL,
  5696. NULL,
  5697. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5698. cb(cur, "ffn_out", il);
  5699. }
  5700. cur = ggml_add(ctx0, cur, sa_out);
  5701. cb(cur, "l_out", il);
  5702. cur = ggml_add(ctx0, cur, inpL);
  5703. cb(cur, "l_out", il);
  5704. // input for next layer
  5705. inpL = cur;
  5706. }
  5707. cur = inpL;
  5708. cur = llm_build_norm(ctx0, cur, hparams,
  5709. model.output_norm, NULL,
  5710. LLM_NORM_RMS, cb, -1);
  5711. cb(cur, "result_norm", -1);
  5712. // lm_head
  5713. cur = ggml_mul_mat(ctx0, model.output, cur);
  5714. cb(cur, "result_output", -1);
  5715. ggml_build_forward_expand(gf, cur);
  5716. return gf;
  5717. }
  5718. struct ggml_cgraph * build_gpt2() {
  5719. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5720. const int64_t n_embd_head = hparams.n_embd_head_v;
  5721. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5722. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5723. struct ggml_tensor * cur;
  5724. struct ggml_tensor * pos;
  5725. struct ggml_tensor * inpL;
  5726. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5727. cb(inpL, "inp_embd", -1);
  5728. // inp_pos - contains the positions
  5729. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5730. cb(inp_pos, "inp_pos", -1);
  5731. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5732. 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);
  5733. cb(KQ_mask, "KQ_mask", -1);
  5734. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5735. cb(pos, "pos_embd", -1);
  5736. inpL = ggml_add(ctx0, inpL, pos);
  5737. cb(inpL, "inpL", -1);
  5738. for (int il = 0; il < n_layer; ++il) {
  5739. cur = llm_build_norm(ctx0, inpL, hparams,
  5740. model.layers[il].attn_norm,
  5741. model.layers[il].attn_norm_b,
  5742. LLM_NORM, cb, il);
  5743. cb(cur, "attn_norm", il);
  5744. // self-attention
  5745. {
  5746. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5747. cb(cur, "wqkv", il);
  5748. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5749. cb(cur, "bqkv", il);
  5750. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5751. 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)));
  5752. 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)));
  5753. cb(Qcur, "Qcur", il);
  5754. cb(Kcur, "Kcur", il);
  5755. cb(Vcur, "Vcur", il);
  5756. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5757. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5758. model.layers[il].wo, model.layers[il].bo,
  5759. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5760. cb(cur, "kqv_out", il);
  5761. }
  5762. // add the input
  5763. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5764. cb(ffn_inp, "ffn_inp", il);
  5765. // FF
  5766. {
  5767. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5768. model.layers[il].ffn_norm,
  5769. model.layers[il].ffn_norm_b,
  5770. LLM_NORM, cb, il);
  5771. cb(cur, "ffn_norm", il);
  5772. cur = llm_build_ffn(ctx0, cur,
  5773. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5774. NULL, NULL,
  5775. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5776. NULL,
  5777. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5778. cb(cur, "ffn_out", il);
  5779. }
  5780. inpL = ggml_add(ctx0, cur, ffn_inp);
  5781. cb(inpL, "l_out", il);
  5782. }
  5783. cur = llm_build_norm(ctx0, inpL, hparams,
  5784. model.output_norm,
  5785. model.output_norm_b,
  5786. LLM_NORM, cb, -1);
  5787. cb(cur, "result_norm", -1);
  5788. cur = ggml_mul_mat(ctx0, model.output, cur);
  5789. cb(cur, "result_output", -1);
  5790. ggml_build_forward_expand(gf, cur);
  5791. return gf;
  5792. }
  5793. struct ggml_cgraph * build_codeshell() {
  5794. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5795. const int64_t n_embd_head = hparams.n_embd_head_v;
  5796. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5797. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5798. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5799. struct ggml_tensor * cur;
  5800. struct ggml_tensor * inpL;
  5801. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5802. cb(inpL, "inp_embd", -1);
  5803. // inp_pos - contains the positions
  5804. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5805. cb(inp_pos, "inp_pos", -1);
  5806. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5807. 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);
  5808. cb(KQ_mask, "KQ_mask", -1);
  5809. // shift the entire K-cache if needed
  5810. if (do_rope_shift) {
  5811. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5812. }
  5813. for (int il = 0; il < n_layer; ++il) {
  5814. cur = llm_build_norm(ctx0, inpL, hparams,
  5815. model.layers[il].attn_norm,
  5816. model.layers[il].attn_norm_b,
  5817. LLM_NORM, cb, il);
  5818. cb(cur, "attn_norm", il);
  5819. // self-attention
  5820. {
  5821. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5822. cb(cur, "wqkv", il);
  5823. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5824. cb(cur, "bqkv", il);
  5825. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5826. 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)));
  5827. 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)));
  5828. cb(tmpq, "tmpq", il);
  5829. cb(tmpk, "tmpk", il);
  5830. cb(Vcur, "Vcur", il);
  5831. struct ggml_tensor * Qcur = ggml_rope_custom(
  5832. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5833. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5834. ext_factor, attn_factor, beta_fast, beta_slow
  5835. );
  5836. cb(Qcur, "Qcur", il);
  5837. struct ggml_tensor * Kcur = ggml_rope_custom(
  5838. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5839. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5840. ext_factor, attn_factor, beta_fast, beta_slow
  5841. );
  5842. cb(Kcur, "Kcur", il);
  5843. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5844. model.layers[il].wo, model.layers[il].bo,
  5845. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5846. cb(cur, "kqv_out", il);
  5847. }
  5848. // add the input
  5849. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5850. cb(ffn_inp, "ffn_inp", il);
  5851. // FF
  5852. {
  5853. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5854. model.layers[il].ffn_norm,
  5855. model.layers[il].ffn_norm_b,
  5856. LLM_NORM, cb, il);
  5857. cb(cur, "ffn_norm", il);
  5858. cur = llm_build_ffn(ctx0, cur,
  5859. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5860. NULL, NULL,
  5861. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5862. NULL,
  5863. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5864. cb(cur, "ffn_out", il);
  5865. }
  5866. inpL = ggml_add(ctx0, cur, ffn_inp);
  5867. cb(inpL, "l_out", il);
  5868. }
  5869. cur = llm_build_norm(ctx0, inpL, hparams,
  5870. model.output_norm,
  5871. model.output_norm_b,
  5872. LLM_NORM, cb, -1);
  5873. cb(cur, "result_norm", -1);
  5874. cur = ggml_mul_mat(ctx0, model.output, cur);
  5875. cb(cur, "result_output", -1);
  5876. ggml_build_forward_expand(gf, cur);
  5877. return gf;
  5878. }
  5879. struct ggml_cgraph * build_orion() {
  5880. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5881. const int64_t n_embd_head = hparams.n_embd_head_v;
  5882. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5883. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5884. struct ggml_tensor * cur;
  5885. struct ggml_tensor * inpL;
  5886. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5887. cb(inpL, "inp_embd", -1);
  5888. // inp_pos - contains the positions
  5889. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5890. cb(inp_pos, "inp_pos", -1);
  5891. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5892. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5893. cb(KQ_mask, "KQ_mask", -1);
  5894. // shift the entire K-cache if needed
  5895. if (do_rope_shift) {
  5896. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5897. }
  5898. for (int il = 0; il < n_layer; ++il) {
  5899. struct ggml_tensor * inpSA = inpL;
  5900. // norm
  5901. cur = llm_build_norm(ctx0, inpL, hparams,
  5902. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  5903. LLM_NORM, cb, il);
  5904. cb(cur, "attn_norm", il);
  5905. // self-attention
  5906. {
  5907. // compute Q and K and RoPE them
  5908. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5909. cb(Qcur, "Qcur", il);
  5910. // if (model.layers[il].bq) {
  5911. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5912. // cb(Qcur, "Qcur", il);
  5913. // }
  5914. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5915. cb(Kcur, "Kcur", il);
  5916. // if (model.layers[il].bk) {
  5917. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5918. // cb(Kcur, "Kcur", il);
  5919. // }
  5920. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5921. cb(Vcur, "Vcur", il);
  5922. // if (model.layers[il].bv) {
  5923. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5924. // cb(Vcur, "Vcur", il);
  5925. // }
  5926. Qcur = ggml_rope_custom(
  5927. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5928. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5929. ext_factor, attn_factor, beta_fast, beta_slow
  5930. );
  5931. cb(Qcur, "Qcur", il);
  5932. Kcur = ggml_rope_custom(
  5933. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5934. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5935. ext_factor, attn_factor, beta_fast, beta_slow
  5936. );
  5937. cb(Kcur, "Kcur", il);
  5938. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5939. model.layers[il].wo, NULL,
  5940. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5941. cb(cur, "kqv_out", il);
  5942. }
  5943. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5944. cb(ffn_inp, "ffn_inp", il);
  5945. // feed-forward network
  5946. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5947. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  5948. LLM_NORM, cb, il);
  5949. cb(cur, "ffn_norm", il);
  5950. cur = llm_build_ffn(ctx0, cur,
  5951. model.layers[il].ffn_up, NULL,
  5952. model.layers[il].ffn_gate, NULL,
  5953. model.layers[il].ffn_down, NULL,
  5954. NULL,
  5955. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5956. cb(cur, "ffn_out", il);
  5957. cur = ggml_add(ctx0, cur, ffn_inp);
  5958. cb(cur, "l_out", il);
  5959. // input for next layer
  5960. inpL = cur;
  5961. }
  5962. cur = inpL;
  5963. cur = llm_build_norm(ctx0, cur, hparams,
  5964. model.output_norm, model.output_norm_b,
  5965. LLM_NORM, cb, -1);
  5966. cb(cur, "result_norm", -1);
  5967. // lm_head
  5968. cur = ggml_mul_mat(ctx0, model.output, cur);
  5969. cb(cur, "result_output", -1);
  5970. ggml_build_forward_expand(gf, cur);
  5971. return gf;
  5972. }
  5973. struct ggml_cgraph * build_internlm2() {
  5974. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5975. const int64_t n_embd_head = hparams.n_embd_head_v;
  5976. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5977. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5978. struct ggml_tensor * cur;
  5979. struct ggml_tensor * inpL;
  5980. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5981. cb(inpL, "inp_embd", -1);
  5982. // inp_pos - contains the positions
  5983. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5984. cb(inp_pos, "inp_pos", -1);
  5985. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5986. 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);
  5987. cb(KQ_mask, "KQ_mask", -1);
  5988. // shift the entire K-cache if needed
  5989. if (do_rope_shift) {
  5990. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5991. }
  5992. for (int il = 0; il < n_layer; ++il) {
  5993. struct ggml_tensor * inpSA = inpL;
  5994. // norm
  5995. cur = llm_build_norm(ctx0, inpL, hparams,
  5996. model.layers[il].attn_norm, NULL,
  5997. LLM_NORM_RMS, cb, il);
  5998. cb(cur, "attn_norm", il);
  5999. // self-attention
  6000. {
  6001. // compute Q and K and RoPE them
  6002. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6003. cb(Qcur, "Qcur", il);
  6004. if (model.layers[il].bq) {
  6005. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6006. cb(Qcur, "Qcur", il);
  6007. }
  6008. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6009. cb(Kcur, "Kcur", il);
  6010. if (model.layers[il].bk) {
  6011. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6012. cb(Kcur, "Kcur", il);
  6013. }
  6014. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6015. cb(Vcur, "Vcur", il);
  6016. if (model.layers[il].bv) {
  6017. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6018. cb(Vcur, "Vcur", il);
  6019. }
  6020. Qcur = ggml_rope_custom(
  6021. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6022. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6023. ext_factor, attn_factor, beta_fast, beta_slow
  6024. );
  6025. cb(Qcur, "Qcur", il);
  6026. Kcur = ggml_rope_custom(
  6027. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6028. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6029. ext_factor, attn_factor, beta_fast, beta_slow
  6030. );
  6031. cb(Kcur, "Kcur", il);
  6032. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6033. model.layers[il].wo, model.layers[il].bo,
  6034. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6035. cb(cur, "kqv_out", il);
  6036. }
  6037. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6038. cb(ffn_inp, "ffn_inp", il);
  6039. // feed-forward network
  6040. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6041. model.layers[il].ffn_norm, NULL,
  6042. LLM_NORM_RMS, cb, il);
  6043. cb(cur, "ffn_norm", il);
  6044. cur = llm_build_ffn(ctx0, cur,
  6045. model.layers[il].ffn_up, NULL,
  6046. model.layers[il].ffn_gate, NULL,
  6047. model.layers[il].ffn_down, NULL,
  6048. NULL,
  6049. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6050. cb(cur, "ffn_out", il);
  6051. cur = ggml_add(ctx0, cur, ffn_inp);
  6052. cb(cur, "l_out", il);
  6053. // input for next layer
  6054. inpL = cur;
  6055. }
  6056. cur = inpL;
  6057. cur = llm_build_norm(ctx0, cur, hparams,
  6058. model.output_norm, NULL,
  6059. LLM_NORM_RMS, cb, -1);
  6060. cb(cur, "result_norm", -1);
  6061. // lm_head
  6062. cur = ggml_mul_mat(ctx0, model.output, cur);
  6063. cb(cur, "result_output", -1);
  6064. ggml_build_forward_expand(gf, cur);
  6065. return gf;
  6066. }
  6067. // ref: https://arxiv.org/abs/2203.03466
  6068. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6069. // based on the original build_llama() function
  6070. struct ggml_cgraph * build_minicpm() {
  6071. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6072. const int64_t n_embd_head = hparams.n_embd_head_v;
  6073. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6074. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6075. const int64_t n_embd = hparams.n_embd;
  6076. //TODO: if the model varies, these parameters need to be read from the model
  6077. const int64_t n_embd_base = 256;
  6078. const float scale_embd = 12.0f;
  6079. const float scale_depth = 1.4f;
  6080. struct ggml_tensor * cur;
  6081. struct ggml_tensor * inpL;
  6082. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6083. cb(inpL, "inp_embd", -1);
  6084. // scale the input embeddings
  6085. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6086. cb(inpL, "inp_scaled", -1);
  6087. // inp_pos - contains the positions
  6088. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6089. cb(inp_pos, "inp_pos", -1);
  6090. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6091. 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);
  6092. cb(KQ_mask, "KQ_mask", -1);
  6093. // shift the entire K-cache if needed
  6094. if (do_rope_shift) {
  6095. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  6096. }
  6097. for (int il = 0; il < n_layer; ++il) {
  6098. struct ggml_tensor * inpSA = inpL;
  6099. // norm
  6100. cur = llm_build_norm(ctx0, inpL, hparams,
  6101. model.layers[il].attn_norm, NULL,
  6102. LLM_NORM_RMS, cb, il);
  6103. cb(cur, "attn_norm", il);
  6104. // self-attention
  6105. {
  6106. // compute Q and K and RoPE them
  6107. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6108. cb(Qcur, "Qcur", il);
  6109. if (model.layers[il].bq) {
  6110. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6111. cb(Qcur, "Qcur", il);
  6112. }
  6113. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6114. cb(Kcur, "Kcur", il);
  6115. if (model.layers[il].bk) {
  6116. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6117. cb(Kcur, "Kcur", il);
  6118. }
  6119. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6120. cb(Vcur, "Vcur", il);
  6121. if (model.layers[il].bv) {
  6122. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6123. cb(Vcur, "Vcur", il);
  6124. }
  6125. Qcur = ggml_rope_custom(
  6126. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6127. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6128. ext_factor, attn_factor, beta_fast, beta_slow
  6129. );
  6130. cb(Qcur, "Qcur", il);
  6131. Kcur = ggml_rope_custom(
  6132. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6133. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  6134. ext_factor, attn_factor, beta_fast, beta_slow
  6135. );
  6136. cb(Kcur, "Kcur", il);
  6137. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6138. model.layers[il].wo, model.layers[il].bo,
  6139. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6140. cb(cur, "kqv_out", il);
  6141. }
  6142. // scale_res - scale the hidden states for residual connection
  6143. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6144. cur = ggml_scale(ctx0, cur, scale_res);
  6145. cb(cur, "hidden_scaled", -1);
  6146. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6147. cb(ffn_inp, "ffn_inp", il);
  6148. // feed-forward network
  6149. {
  6150. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6151. model.layers[il].ffn_norm, NULL,
  6152. LLM_NORM_RMS, cb, il);
  6153. cb(cur, "ffn_norm", il);
  6154. cur = llm_build_ffn(ctx0, cur,
  6155. model.layers[il].ffn_up, NULL,
  6156. model.layers[il].ffn_gate, NULL,
  6157. model.layers[il].ffn_down, NULL,
  6158. NULL,
  6159. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6160. cb(cur, "ffn_out", il);
  6161. }
  6162. // scale the hidden states for residual connection
  6163. cur = ggml_scale(ctx0, cur, scale_res);
  6164. cb(cur, "hidden_scaled_ffn", -1);
  6165. cur = ggml_add(ctx0, cur, ffn_inp);
  6166. cb(cur, "l_out", il);
  6167. // input for next layer
  6168. inpL = cur;
  6169. }
  6170. cur = inpL;
  6171. cur = llm_build_norm(ctx0, cur, hparams,
  6172. model.output_norm, NULL,
  6173. LLM_NORM_RMS, cb, -1);
  6174. cb(cur, "result_norm", -1);
  6175. // lm_head scaling
  6176. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6177. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6178. cb(cur, "lmhead_scaling", -1);
  6179. // lm_head
  6180. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6181. cb(cur, "result_output", -1);
  6182. ggml_build_forward_expand(gf, cur);
  6183. return gf;
  6184. }
  6185. struct ggml_cgraph * build_gemma() {
  6186. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6187. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6188. struct ggml_tensor * cur;
  6189. struct ggml_tensor * inpL;
  6190. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6191. cb(inpL, "inp_embd", -1);
  6192. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6193. cb(inpL, "inp_scaled", -1);
  6194. // inp_pos - contains the positions
  6195. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6196. cb(inp_pos, "inp_pos", -1);
  6197. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6198. 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);
  6199. cb(KQ_mask, "KQ_mask", -1);
  6200. // shift the entire K-cache if needed
  6201. if (do_rope_shift) {
  6202. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  6203. }
  6204. for (int il = 0; il < n_layer; ++il) {
  6205. // norm
  6206. cur = llm_build_norm(ctx0, inpL, hparams,
  6207. model.layers[il].attn_norm, NULL,
  6208. LLM_NORM_RMS, cb, il);
  6209. cb(cur, "attn_norm", il);
  6210. // self-attention
  6211. {
  6212. // compute Q and K and RoPE them
  6213. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6214. cb(Qcur, "Qcur", il);
  6215. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6216. cb(Kcur, "Kcur", il);
  6217. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6218. cb(Vcur, "Vcur", il);
  6219. Qcur = ggml_rope_custom(
  6220. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6221. n_embd_head_k, 2, 0, n_orig_ctx, freq_base, freq_scale,
  6222. ext_factor, attn_factor, beta_fast, beta_slow);
  6223. cb(Qcur, "Qcur", il);
  6224. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6225. cb(Qcur, "Qcur_scaled", il);
  6226. Kcur = ggml_rope_custom(
  6227. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6228. n_embd_head_k, 2, 0, n_orig_ctx, freq_base, freq_scale,
  6229. ext_factor, attn_factor, beta_fast, beta_slow);
  6230. cb(Kcur, "Kcur", il);
  6231. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6232. model.layers[il].wo, NULL,
  6233. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6234. cb(cur, "kqv_out", il);
  6235. }
  6236. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6237. cb(sa_out, "sa_out", il);
  6238. cur = llm_build_norm(ctx0, sa_out, hparams,
  6239. model.layers[il].ffn_norm, NULL,
  6240. LLM_NORM_RMS, cb, il);
  6241. cb(cur, "ffn_norm", il);
  6242. // feed-forward network
  6243. {
  6244. cur = llm_build_ffn(ctx0, cur,
  6245. model.layers[il].ffn_up, NULL,
  6246. model.layers[il].ffn_gate, NULL,
  6247. model.layers[il].ffn_down, NULL,
  6248. NULL,
  6249. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6250. cb(cur, "ffn_out", il);
  6251. }
  6252. cur = ggml_add(ctx0, cur, sa_out);
  6253. cb(cur, "l_out", il);
  6254. // input for next layer
  6255. inpL = cur;
  6256. }
  6257. cur = inpL;
  6258. cur = llm_build_norm(ctx0, cur, hparams,
  6259. model.output_norm, NULL,
  6260. LLM_NORM_RMS, cb, -1);
  6261. cb(cur, "result_norm", -1);
  6262. // lm_head
  6263. cur = ggml_mul_mat(ctx0, model.output, cur);
  6264. cb(cur, "result_output", -1);
  6265. ggml_build_forward_expand(gf, cur);
  6266. return gf;
  6267. }
  6268. };
  6269. static struct ggml_cgraph * llama_build_graph(
  6270. llama_context & lctx,
  6271. const llama_batch & batch,
  6272. bool worst_case) {
  6273. const auto & model = lctx.model;
  6274. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6275. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6276. if (il >= 0) {
  6277. ggml_format_name(cur, "%s-%d", name, il);
  6278. } else {
  6279. ggml_set_name(cur, name);
  6280. }
  6281. if (!lctx.cparams.offload_kqv) {
  6282. if (strcmp(name, "kqv_merged_cont") == 0) {
  6283. // all nodes between the KV store and the attention output are run on the CPU
  6284. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  6285. }
  6286. }
  6287. };
  6288. struct ggml_cgraph * result = NULL;
  6289. struct llm_build_context llm(lctx, batch, cb, worst_case);
  6290. llm.init();
  6291. switch (model.arch) {
  6292. case LLM_ARCH_LLAMA:
  6293. {
  6294. result = llm.build_llama();
  6295. } break;
  6296. case LLM_ARCH_BAICHUAN:
  6297. {
  6298. result = llm.build_baichuan();
  6299. } break;
  6300. case LLM_ARCH_FALCON:
  6301. {
  6302. result = llm.build_falcon();
  6303. } break;
  6304. case LLM_ARCH_STARCODER:
  6305. {
  6306. result = llm.build_starcoder();
  6307. } break;
  6308. case LLM_ARCH_PERSIMMON:
  6309. {
  6310. result = llm.build_persimmon();
  6311. } break;
  6312. case LLM_ARCH_REFACT:
  6313. {
  6314. result = llm.build_refact();
  6315. } break;
  6316. case LLM_ARCH_BERT:
  6317. case LLM_ARCH_NOMIC_BERT:
  6318. {
  6319. result = llm.build_bert();
  6320. } break;
  6321. case LLM_ARCH_BLOOM:
  6322. {
  6323. result = llm.build_bloom();
  6324. } break;
  6325. case LLM_ARCH_MPT:
  6326. {
  6327. result = llm.build_mpt();
  6328. } break;
  6329. case LLM_ARCH_STABLELM:
  6330. {
  6331. result = llm.build_stablelm();
  6332. } break;
  6333. case LLM_ARCH_QWEN:
  6334. {
  6335. result = llm.build_qwen();
  6336. } break;
  6337. case LLM_ARCH_QWEN2:
  6338. {
  6339. result = llm.build_qwen2();
  6340. } break;
  6341. case LLM_ARCH_PHI2:
  6342. {
  6343. result = llm.build_phi2();
  6344. } break;
  6345. case LLM_ARCH_PLAMO:
  6346. {
  6347. result = llm.build_plamo();
  6348. } break;
  6349. case LLM_ARCH_GPT2:
  6350. {
  6351. result = llm.build_gpt2();
  6352. } break;
  6353. case LLM_ARCH_CODESHELL:
  6354. {
  6355. result = llm.build_codeshell();
  6356. } break;
  6357. case LLM_ARCH_ORION:
  6358. {
  6359. result = llm.build_orion();
  6360. } break;
  6361. case LLM_ARCH_INTERNLM2:
  6362. {
  6363. result = llm.build_internlm2();
  6364. } break;
  6365. case LLM_ARCH_MINICPM:
  6366. {
  6367. result = llm.build_minicpm();
  6368. } break;
  6369. case LLM_ARCH_GEMMA:
  6370. {
  6371. result = llm.build_gemma();
  6372. } break;
  6373. default:
  6374. GGML_ASSERT(false);
  6375. }
  6376. llm.free();
  6377. return result;
  6378. }
  6379. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  6380. //
  6381. // set input data
  6382. //
  6383. const auto & hparams = lctx.model.hparams;
  6384. const auto & cparams = lctx.cparams;
  6385. const auto & kv_self = lctx.kv_self;
  6386. if (batch.token) {
  6387. const int64_t n_tokens = batch.n_tokens;
  6388. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  6389. }
  6390. if (batch.embd) {
  6391. const int64_t n_embd = hparams.n_embd;
  6392. const int64_t n_tokens = batch.n_tokens;
  6393. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  6394. }
  6395. if (batch.pos) {
  6396. const int64_t n_tokens = batch.n_tokens;
  6397. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  6398. }
  6399. {
  6400. const int64_t n_kv = kv_self.n;
  6401. const int64_t n_tokens = batch.n_tokens;
  6402. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6403. float * data = (float *) lctx.inp_KQ_mask->data;
  6404. for (int h = 0; h < 1; ++h) {
  6405. for (int j = 0; j < n_tokens; ++j) {
  6406. const llama_pos pos = batch.pos[j];
  6407. const llama_seq_id seq_id = batch.seq_id[j][0];
  6408. for (int i = 0; i < n_kv; ++i) {
  6409. float f;
  6410. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) ||
  6411. (hparams.causal_attn && lctx.kv_self.cells[i].pos > pos)) {
  6412. f = -INFINITY;
  6413. } else {
  6414. f = 0;
  6415. }
  6416. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  6417. }
  6418. }
  6419. }
  6420. }
  6421. if (hparams.need_kq_pos) {
  6422. const int64_t n_kv = kv_self.n;
  6423. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  6424. float * data = (float *) lctx.inp_KQ_pos->data;
  6425. for (int i = 0; i < n_kv; ++i) {
  6426. data[i] = float(lctx.kv_self.cells[i].pos);
  6427. }
  6428. }
  6429. if (kv_self.has_shift) {
  6430. const int64_t n_ctx = cparams.n_ctx;
  6431. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  6432. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  6433. for (int i = 0; i < n_ctx; ++i) {
  6434. data[i] = lctx.kv_self.cells[i].delta;
  6435. }
  6436. }
  6437. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  6438. const int64_t n_tokens = batch.n_tokens;
  6439. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  6440. float * data = (float *) lctx.inp_mean->data;
  6441. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  6442. std::vector<uint64_t> sum(n_tokens, 0);
  6443. for (int i = 0; i < n_tokens; ++i) {
  6444. const llama_seq_id seq_id = batch.seq_id[i][0];
  6445. sum[seq_id] += 1;
  6446. }
  6447. std::vector<float> div(n_tokens, 0.0f);
  6448. for (int i = 0; i < n_tokens; ++i) {
  6449. const uint64_t s = sum[i];
  6450. if (s > 0) {
  6451. div[i] = 1.0f/float(s);
  6452. }
  6453. }
  6454. for (int i = 0; i < n_tokens; ++i) {
  6455. const llama_seq_id seq_id = batch.seq_id[i][0];
  6456. data[seq_id*n_tokens + i] = div[seq_id];
  6457. }
  6458. }
  6459. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  6460. const int64_t n_tokens = batch.n_tokens;
  6461. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  6462. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  6463. for (int i = 0; i < n_tokens; ++i) {
  6464. const llama_seq_id seq_id = batch.seq_id[i][0];
  6465. const llama_pos pos = batch.pos[i];
  6466. if (pos == 0) {
  6467. data[seq_id] = i;
  6468. }
  6469. }
  6470. }
  6471. }
  6472. // decode a batch of tokens by evaluating the transformer
  6473. //
  6474. // - lctx: llama context
  6475. // - batch: batch to evaluate
  6476. //
  6477. // return 0 on success
  6478. // return positive int on warning
  6479. // return negative int on error
  6480. //
  6481. static int llama_decode_internal(
  6482. llama_context & lctx,
  6483. llama_batch batch) {
  6484. const uint32_t n_tokens = batch.n_tokens;
  6485. if (n_tokens == 0) {
  6486. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  6487. return -1;
  6488. }
  6489. const auto & model = lctx.model;
  6490. const auto & hparams = model.hparams;
  6491. const auto & cparams = lctx.cparams;
  6492. const auto n_batch = cparams.n_batch;
  6493. GGML_ASSERT(n_tokens <= n_batch);
  6494. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6495. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6496. const int64_t t_start_us = ggml_time_us();
  6497. #ifdef GGML_USE_MPI
  6498. // TODO: needs fix after #3228
  6499. GGML_ASSERT(false && "not implemented");
  6500. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  6501. #endif
  6502. GGML_ASSERT(n_threads > 0);
  6503. auto & kv_self = lctx.kv_self;
  6504. const int64_t n_embd = hparams.n_embd;
  6505. const int64_t n_vocab = hparams.n_vocab;
  6506. // helpers for smoother batch API transition
  6507. // after deprecating the llama_eval calls, these will be removed
  6508. std::vector<llama_pos> pos;
  6509. std::vector<int32_t> n_seq_id;
  6510. std::vector<llama_seq_id *> seq_id_arr;
  6511. std::vector<std::vector<llama_seq_id>> seq_id;
  6512. if (batch.pos == nullptr) {
  6513. pos.resize(n_tokens);
  6514. for (uint32_t i = 0; i < n_tokens; i++) {
  6515. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  6516. }
  6517. batch.pos = pos.data();
  6518. }
  6519. if (batch.seq_id == nullptr) {
  6520. n_seq_id.resize(n_tokens);
  6521. seq_id.resize(n_tokens);
  6522. seq_id_arr.resize(n_tokens);
  6523. for (uint32_t i = 0; i < n_tokens; i++) {
  6524. n_seq_id[i] = 1;
  6525. seq_id[i].resize(1);
  6526. seq_id[i][0] = batch.all_seq_id;
  6527. seq_id_arr[i] = seq_id[i].data();
  6528. }
  6529. batch.n_seq_id = n_seq_id.data();
  6530. batch.seq_id = seq_id_arr.data();
  6531. }
  6532. // if we have enough unused cells before the current head ->
  6533. // better to start searching from the beginning of the cache, hoping to fill it
  6534. if (kv_self.head > kv_self.used + 2*n_tokens) {
  6535. kv_self.head = 0;
  6536. }
  6537. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  6538. return 1;
  6539. }
  6540. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6541. // after enough generations, the benefit from this heuristic disappears
  6542. // if we start defragmenting the cache, the benefit from this will be more important
  6543. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  6544. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6545. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6546. ggml_backend_sched_reset(lctx.sched);
  6547. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6548. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  6549. // the output is always the last tensor in the graph
  6550. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  6551. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  6552. if (strcmp(res->name, "result_output") == 0) {
  6553. // the embeddings could be the second to last tensor, or the third to last tensor
  6554. if (strcmp(embeddings->name, "result_norm") != 0) {
  6555. embeddings = gf->nodes[gf->n_nodes - 3];
  6556. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  6557. }
  6558. } else if (strcmp(res->name, "result_embd") == 0) {
  6559. embeddings = res;
  6560. res = nullptr;
  6561. } else {
  6562. GGML_ASSERT(false);
  6563. }
  6564. // 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);
  6565. // for big prompts, if BLAS is enabled, it is better to use only one thread
  6566. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  6567. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  6568. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  6569. // with the BLAS calls. need a better solution
  6570. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  6571. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  6572. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  6573. n_threads = std::min(4, n_threads);
  6574. }
  6575. #ifdef GGML_USE_MPI
  6576. const int64_t n_layer = hparams.n_layer;
  6577. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  6578. #endif
  6579. #ifdef GGML_USE_METAL
  6580. if (ggml_backend_is_metal(lctx.backend_metal)) {
  6581. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  6582. }
  6583. #endif
  6584. if (lctx.backend_cpu != nullptr) {
  6585. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  6586. }
  6587. llama_set_inputs(lctx, batch);
  6588. ggml_backend_sched_graph_compute(lctx.sched, gf);
  6589. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6590. #ifdef GGML_USE_MPI
  6591. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  6592. #endif
  6593. // update the kv ring buffer
  6594. {
  6595. if (kv_self.has_shift) {
  6596. kv_self.has_shift = false;
  6597. for (uint32_t i = 0; i < kv_self.size; ++i) {
  6598. kv_self.cells[i].delta = 0;
  6599. }
  6600. }
  6601. kv_self.head += n_tokens;
  6602. // Ensure kv cache head points to a valid index.
  6603. if (kv_self.head >= kv_self.size) {
  6604. kv_self.head = 0;
  6605. }
  6606. }
  6607. #ifdef GGML_PERF
  6608. // print timing information per ggml operation (for debugging purposes)
  6609. // requires GGML_PERF to be defined
  6610. ggml_graph_print(gf);
  6611. #endif
  6612. // plot the computation graph in dot format (for debugging purposes)
  6613. //if (n_past%100 == 0) {
  6614. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6615. //}
  6616. // extract logits
  6617. // TODO: do not compute and extract logits if only embeddings are needed
  6618. // need to update the graphs to skip "result_output"
  6619. if (res) {
  6620. auto & logits_out = lctx.logits;
  6621. #ifndef NDEBUG
  6622. auto & logits_valid = lctx.logits_valid;
  6623. logits_valid.clear();
  6624. logits_valid.resize(n_tokens);
  6625. logits_out.clear();
  6626. #endif
  6627. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  6628. GGML_ASSERT(res_backend != nullptr);
  6629. if (batch.logits) {
  6630. logits_out.resize(n_vocab * n_tokens);
  6631. for (uint32_t i = 0; i < n_tokens; i++) {
  6632. if (batch.logits[i] == 0) {
  6633. continue;
  6634. }
  6635. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  6636. #ifndef NDEBUG
  6637. logits_valid[i] = true;
  6638. #endif
  6639. }
  6640. } else if (lctx.logits_all) {
  6641. logits_out.resize(n_vocab * n_tokens);
  6642. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  6643. #ifndef NDEBUG
  6644. std::fill(logits_valid.begin(), logits_valid.end(), true);
  6645. #endif
  6646. } else {
  6647. logits_out.resize(n_vocab);
  6648. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  6649. #ifndef NDEBUG
  6650. logits_valid[0] = true;
  6651. #endif
  6652. }
  6653. ggml_backend_synchronize(res_backend);
  6654. }
  6655. // extract embeddings
  6656. if (!lctx.embedding.empty()) {
  6657. auto & embedding_out = lctx.embedding;
  6658. const int64_t embd_pos = res ? n_embd * (n_tokens-1) : 0;
  6659. const int64_t embd_size = res ? n_embd : n_embd * n_tokens;
  6660. embedding_out.resize(embd_size);
  6661. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  6662. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), embd_pos*sizeof(float), embd_size*sizeof(float));
  6663. ggml_backend_synchronize(embeddings_backend);
  6664. }
  6665. // measure the performance only for the single-token evals
  6666. if (n_tokens == 1) {
  6667. lctx.t_eval_us += ggml_time_us() - t_start_us;
  6668. lctx.n_eval++;
  6669. }
  6670. else if (n_tokens > 1) {
  6671. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  6672. lctx.n_p_eval += n_tokens;
  6673. }
  6674. // get a more accurate load time, upon first eval
  6675. // TODO: fix this
  6676. if (!lctx.has_evaluated_once) {
  6677. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  6678. lctx.has_evaluated_once = true;
  6679. }
  6680. return 0;
  6681. }
  6682. //
  6683. // tokenizer
  6684. //
  6685. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  6686. return vocab.type;
  6687. }
  6688. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  6689. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  6690. }
  6691. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  6692. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  6693. }
  6694. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  6695. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  6696. }
  6697. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  6698. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  6699. }
  6700. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  6701. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  6702. }
  6703. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  6704. GGML_ASSERT(llama_is_byte_token(vocab, id));
  6705. const auto& token_data = vocab.id_to_token.at(id);
  6706. switch (llama_vocab_get_type(vocab)) {
  6707. case LLAMA_VOCAB_TYPE_SPM: {
  6708. auto buf = token_data.text.substr(3, 2);
  6709. return strtol(buf.c_str(), NULL, 16);
  6710. }
  6711. case LLAMA_VOCAB_TYPE_BPE: {
  6712. GGML_ASSERT(false);
  6713. return unicode_to_bytes_bpe(token_data.text);
  6714. }
  6715. case LLAMA_VOCAB_TYPE_WPM: {
  6716. GGML_ASSERT(false);
  6717. }
  6718. default:
  6719. GGML_ASSERT(false);
  6720. }
  6721. }
  6722. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  6723. static const char * hex = "0123456789ABCDEF";
  6724. switch (llama_vocab_get_type(vocab)) {
  6725. case LLAMA_VOCAB_TYPE_SPM: {
  6726. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  6727. auto token = vocab.token_to_id.find(buf);
  6728. if (token != vocab.token_to_id.end()) {
  6729. return (*token).second;
  6730. }
  6731. // Try to fall back to just the byte as a string
  6732. const char buf2[2] = { (char)ch, 0 };
  6733. return vocab.token_to_id.at(buf2);
  6734. }
  6735. case LLAMA_VOCAB_TYPE_WPM:
  6736. case LLAMA_VOCAB_TYPE_BPE: {
  6737. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  6738. }
  6739. default:
  6740. GGML_ASSERT(false);
  6741. }
  6742. }
  6743. static void llama_escape_whitespace(std::string & text) {
  6744. replace_all(text, " ", "\xe2\x96\x81");
  6745. }
  6746. static void llama_unescape_whitespace(std::string & word) {
  6747. replace_all(word, "\xe2\x96\x81", " ");
  6748. }
  6749. struct llm_symbol {
  6750. using index = int;
  6751. index prev;
  6752. index next;
  6753. const char * text;
  6754. size_t n;
  6755. };
  6756. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  6757. // SPM tokenizer
  6758. // original implementation:
  6759. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  6760. struct llm_bigram_spm {
  6761. struct comparator {
  6762. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  6763. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  6764. }
  6765. };
  6766. using queue_storage = std::vector<llm_bigram_spm>;
  6767. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  6768. llm_symbol::index left;
  6769. llm_symbol::index right;
  6770. float score;
  6771. size_t size;
  6772. };
  6773. struct llm_tokenizer_spm {
  6774. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  6775. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6776. // split string into utf8 chars
  6777. int index = 0;
  6778. size_t offs = 0;
  6779. while (offs < text.size()) {
  6780. llm_symbol sym;
  6781. size_t len = utf8_len(text[offs]);
  6782. sym.text = text.c_str() + offs;
  6783. sym.n = std::min(len, text.size() - offs);
  6784. offs += sym.n;
  6785. sym.prev = index - 1;
  6786. sym.next = offs == text.size() ? -1 : index + 1;
  6787. index++;
  6788. symbols.emplace_back(sym);
  6789. }
  6790. // seed the work queue with all possible 2-character tokens.
  6791. for (size_t i = 1; i < symbols.size(); ++i) {
  6792. try_add_bigram(i - 1, i);
  6793. }
  6794. // keep substituting the highest frequency pairs for as long as we can.
  6795. while (!work_queue.empty()) {
  6796. auto bigram = work_queue.top();
  6797. work_queue.pop();
  6798. auto & left_sym = symbols[bigram.left];
  6799. auto & right_sym = symbols[bigram.right];
  6800. // if one of the symbols already got merged, skip it.
  6801. if (left_sym.n == 0 || right_sym.n == 0 ||
  6802. left_sym.n + right_sym.n != bigram.size) {
  6803. continue;
  6804. }
  6805. // merge the right sym into the left one
  6806. left_sym.n += right_sym.n;
  6807. right_sym.n = 0;
  6808. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  6809. // remove the right sym from the chain
  6810. left_sym.next = right_sym.next;
  6811. if (right_sym.next >= 0) {
  6812. symbols[right_sym.next].prev = bigram.left;
  6813. }
  6814. // find more substitutions
  6815. try_add_bigram(left_sym.prev, bigram.left);
  6816. try_add_bigram(bigram.left, left_sym.next);
  6817. }
  6818. for (int i = 0; i != -1; i = symbols[i].next) {
  6819. auto & symbol = symbols[i];
  6820. resegment(symbol, output);
  6821. }
  6822. }
  6823. private:
  6824. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  6825. auto text = std::string(symbol.text, symbol.n);
  6826. auto token = vocab.token_to_id.find(text);
  6827. // Do we need to support is_unused?
  6828. if (token != vocab.token_to_id.end()) {
  6829. output.push_back((*token).second);
  6830. return;
  6831. }
  6832. const auto p = rev_merge.find(text);
  6833. if (p == rev_merge.end()) {
  6834. // output any symbols that did not form tokens as bytes.
  6835. output.reserve(output.size() + symbol.n);
  6836. for (int j = 0; j < (int)symbol.n; ++j) {
  6837. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  6838. output.push_back(token_id);
  6839. }
  6840. return;
  6841. }
  6842. resegment(symbols[p->second.first], output);
  6843. resegment(symbols[p->second.second], output);
  6844. }
  6845. void try_add_bigram(int left, int right) {
  6846. if (left == -1 || right == -1) {
  6847. return;
  6848. }
  6849. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  6850. auto token = vocab.token_to_id.find(text);
  6851. if (token == vocab.token_to_id.end()) {
  6852. return;
  6853. }
  6854. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  6855. return;
  6856. }
  6857. const auto & tok_data = vocab.id_to_token[(*token).second];
  6858. llm_bigram_spm bigram;
  6859. bigram.left = left;
  6860. bigram.right = right;
  6861. bigram.score = tok_data.score;
  6862. bigram.size = text.size();
  6863. work_queue.push(bigram);
  6864. // Do we need to support is_unused?
  6865. rev_merge[text] = std::make_pair(left, right);
  6866. }
  6867. const llama_vocab & vocab;
  6868. std::vector<llm_symbol> symbols;
  6869. llm_bigram_spm::queue work_queue;
  6870. std::map<std::string, std::pair<int, int>> rev_merge;
  6871. };
  6872. // BPE tokenizer
  6873. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  6874. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  6875. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  6876. struct llm_bigram_bpe {
  6877. struct comparator {
  6878. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  6879. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  6880. }
  6881. };
  6882. using queue_storage = std::vector<llm_bigram_bpe>;
  6883. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  6884. llm_symbol::index left;
  6885. llm_symbol::index right;
  6886. std::string text;
  6887. int rank;
  6888. size_t size;
  6889. };
  6890. struct llm_tokenizer_bpe {
  6891. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  6892. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6893. int final_prev_index = -1;
  6894. auto word_collection = bpe_gpt2_preprocess(text);
  6895. symbols_final.clear();
  6896. for (auto & word : word_collection) {
  6897. work_queue = llm_bigram_bpe::queue();
  6898. symbols.clear();
  6899. int index = 0;
  6900. size_t offset = 0;
  6901. while (offset < word.size()) {
  6902. llm_symbol sym;
  6903. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  6904. sym.text = word.c_str() + offset;
  6905. sym.n = char_len;
  6906. offset += sym.n;
  6907. sym.prev = index - 1;
  6908. sym.next = offset == word.size() ? -1 : index + 1;
  6909. index++;
  6910. symbols.emplace_back(sym);
  6911. }
  6912. for (size_t i = 1; i < symbols.size(); ++i) {
  6913. add_new_bigram(i - 1, i);
  6914. }
  6915. // build token(s)
  6916. while (!work_queue.empty()) {
  6917. auto bigram = work_queue.top();
  6918. work_queue.pop();
  6919. auto & left_symbol = symbols[bigram.left];
  6920. auto & right_symbol = symbols[bigram.right];
  6921. if (left_symbol.n == 0 || right_symbol.n == 0) {
  6922. continue;
  6923. }
  6924. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  6925. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  6926. if (left_token + right_token != bigram.text) {
  6927. continue; // Skip this bigram if it's outdated
  6928. }
  6929. // merge the right sym into the left one
  6930. left_symbol.n += right_symbol.n;
  6931. right_symbol.n = 0;
  6932. // remove the right sym from the chain
  6933. left_symbol.next = right_symbol.next;
  6934. if (right_symbol.next >= 0) {
  6935. symbols[right_symbol.next].prev = bigram.left;
  6936. }
  6937. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  6938. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  6939. }
  6940. // add the fnished tokens to the final list keeping correct order for next and prev
  6941. for (auto & sym : symbols) {
  6942. if (sym.n > 0) {
  6943. sym.prev = final_prev_index;
  6944. sym.next = -1;
  6945. if (final_prev_index != -1) {
  6946. symbols_final[final_prev_index].next = symbols_final.size();
  6947. }
  6948. symbols_final.emplace_back(sym);
  6949. final_prev_index = symbols_final.size() - 1;
  6950. }
  6951. }
  6952. }
  6953. symbols = symbols_final;
  6954. if (!symbols.empty()) {
  6955. for (int i = 0; i != -1; i = symbols[i].next) {
  6956. auto & symbol = symbols[i];
  6957. if (symbol.n == 0) {
  6958. continue;
  6959. }
  6960. const std::string str = std::string(symbol.text, symbol.n);
  6961. const auto token = vocab.token_to_id.find(str);
  6962. if (token == vocab.token_to_id.end()) {
  6963. for (auto j = str.begin(); j != str.end(); ++j) {
  6964. std::string byte_str(1, *j);
  6965. auto token_multibyte = vocab.token_to_id.find(byte_str);
  6966. if (token_multibyte == vocab.token_to_id.end()) {
  6967. throw std::runtime_error("ERROR: byte not found in vocab");
  6968. }
  6969. output.push_back((*token_multibyte).second);
  6970. }
  6971. } else {
  6972. output.push_back((*token).second);
  6973. }
  6974. }
  6975. }
  6976. }
  6977. private:
  6978. void add_new_bigram(int left, int right) {
  6979. if (left == -1 || right == -1) {
  6980. return;
  6981. }
  6982. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  6983. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  6984. int rank_found = -1;
  6985. rank_found = vocab.find_bpe_rank(left_token, right_token);
  6986. if (rank_found < 0) {
  6987. return;
  6988. }
  6989. llm_bigram_bpe bigram;
  6990. bigram.left = left;
  6991. bigram.right = right;
  6992. bigram.text = left_token + right_token;
  6993. bigram.size = left_token.size() + right_token.size();
  6994. bigram.rank = rank_found;
  6995. work_queue.push(bigram);
  6996. }
  6997. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  6998. std::vector<std::string> bpe_words;
  6999. std::vector<std::string> bpe_encoded_words;
  7000. std::string token = "";
  7001. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  7002. bool collecting_numeric = false;
  7003. bool collecting_letter = false;
  7004. bool collecting_special = false;
  7005. bool collecting_whitespace_lookahead = false;
  7006. bool collecting = false;
  7007. std::vector<std::string> text_utf;
  7008. text_utf.reserve(text.size());
  7009. bpe_words.reserve(text.size());
  7010. bpe_encoded_words.reserve(text.size());
  7011. auto cps = codepoints_from_utf8(text);
  7012. for (size_t i = 0; i < cps.size(); ++i)
  7013. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  7014. for (int i = 0; i < (int)text_utf.size(); i++) {
  7015. const std::string & utf_char = text_utf[i];
  7016. bool split_condition = false;
  7017. int bytes_remain = text_utf.size() - i;
  7018. // forward backward lookups
  7019. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  7020. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  7021. // handling contractions
  7022. if (!split_condition && bytes_remain >= 2) {
  7023. // 's|'t|'m|'d
  7024. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  7025. split_condition = true;
  7026. }
  7027. if (split_condition) {
  7028. if (token.size()) {
  7029. bpe_words.emplace_back(token); // push previous content as token
  7030. }
  7031. token = utf_char + utf_char_next;
  7032. bpe_words.emplace_back(token);
  7033. token = "";
  7034. i++;
  7035. continue;
  7036. }
  7037. }
  7038. if (!split_condition && bytes_remain >= 3) {
  7039. // 're|'ve|'ll
  7040. if (utf_char == "\'" && (
  7041. (utf_char_next == "r" && utf_char_next_next == "e") ||
  7042. (utf_char_next == "v" && utf_char_next_next == "e") ||
  7043. (utf_char_next == "l" && utf_char_next_next == "l"))
  7044. ) {
  7045. split_condition = true;
  7046. }
  7047. if (split_condition) {
  7048. // current token + next token can be defined
  7049. if (token.size()) {
  7050. bpe_words.emplace_back(token); // push previous content as token
  7051. }
  7052. token = utf_char + utf_char_next + utf_char_next_next;
  7053. bpe_words.emplace_back(token); // the contraction
  7054. token = "";
  7055. i += 2;
  7056. continue;
  7057. }
  7058. }
  7059. if (!split_condition && !collecting) {
  7060. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  7061. collecting_letter = true;
  7062. collecting = true;
  7063. }
  7064. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7065. collecting_numeric = true;
  7066. collecting = true;
  7067. }
  7068. else if (
  7069. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  7070. (!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)
  7071. ) {
  7072. collecting_special = true;
  7073. collecting = true;
  7074. }
  7075. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  7076. collecting_whitespace_lookahead = true;
  7077. collecting = true;
  7078. }
  7079. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  7080. split_condition = true;
  7081. }
  7082. }
  7083. else if (!split_condition && collecting) {
  7084. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  7085. split_condition = true;
  7086. }
  7087. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  7088. split_condition = true;
  7089. }
  7090. 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)) {
  7091. split_condition = true;
  7092. }
  7093. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7094. split_condition = true;
  7095. }
  7096. }
  7097. if (utf_char_next == "") {
  7098. split_condition = true; // final
  7099. token += utf_char;
  7100. }
  7101. if (split_condition) {
  7102. if (token.size()) {
  7103. bpe_words.emplace_back(token);
  7104. }
  7105. token = utf_char;
  7106. collecting = false;
  7107. collecting_letter = false;
  7108. collecting_numeric = false;
  7109. collecting_special = false;
  7110. collecting_whitespace_lookahead = false;
  7111. }
  7112. else {
  7113. token += utf_char;
  7114. }
  7115. }
  7116. for (std::string & word : bpe_words) {
  7117. std::string encoded_token = "";
  7118. for (char & c : word) {
  7119. encoded_token += bytes_to_unicode_bpe(c);
  7120. }
  7121. bpe_encoded_words.emplace_back(encoded_token);
  7122. }
  7123. return bpe_encoded_words;
  7124. }
  7125. const llama_vocab & vocab;
  7126. std::vector<llm_symbol> symbols;
  7127. std::vector<llm_symbol> symbols_final;
  7128. llm_bigram_bpe::queue work_queue;
  7129. };
  7130. struct llm_tokenizer_wpm {
  7131. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  7132. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7133. auto * token_map = &vocab.token_to_id;
  7134. // normalize and split by whitespace
  7135. std::vector<std::string> words = preprocess(text);
  7136. // bos token prepended already
  7137. // find the longest tokens that form the words
  7138. for (const std::string &word : words) {
  7139. // skip empty words
  7140. if (word.size() == 0) {
  7141. continue;
  7142. }
  7143. // prepend phantom space
  7144. std::string word1 = "\xe2\x96\x81" + word;
  7145. int n = word1.size();
  7146. // we're at the start of a new word
  7147. int i = 0;
  7148. bool match_any = false;
  7149. // move through character position in word
  7150. while (i < n) {
  7151. // loop through possible match length
  7152. bool match = false;
  7153. for (int j = n; j > i; j--) {
  7154. auto it = token_map->find(word1.substr(i, j - i));
  7155. if (it != token_map->end()) {
  7156. output.push_back(it->second);
  7157. match = true;
  7158. match_any = true;
  7159. i = j;
  7160. break;
  7161. }
  7162. }
  7163. // must be an unknown character
  7164. if (!match) {
  7165. i++;
  7166. }
  7167. }
  7168. // we didn't find any matches for this word
  7169. if (!match_any) {
  7170. output.push_back(vocab.special_unk_id);
  7171. }
  7172. }
  7173. // append eos token
  7174. output.push_back(vocab.special_eos_id);
  7175. }
  7176. std::vector<std::string> preprocess(const std::string & text) {
  7177. std::string ori_str = normalize(text);
  7178. uint64_t ori_size = ori_str.size();
  7179. // single punct / single symbol / single digit
  7180. // baseline: add whitespace on the left and right of punct and chinese characters
  7181. std::vector<std::string> words;
  7182. std::string new_str = "";
  7183. uint64_t i = 0;
  7184. while (i < ori_size) {
  7185. int utf_char_len = utf8_len(ori_str[i]);
  7186. if ((utf_char_len == 1) && ispunct(ori_str[i])) {
  7187. new_str += " ";
  7188. new_str += ori_str[i];
  7189. new_str += " ";
  7190. i += 1;
  7191. }
  7192. else if ((utf_char_len == 3) && is_chinese_char(ori_str.substr(i, 3))) {
  7193. new_str += " ";
  7194. new_str += ori_str.substr(i, 3);
  7195. new_str += " ";
  7196. i += 3;
  7197. }
  7198. else {
  7199. new_str += ori_str[i];
  7200. i += 1;
  7201. }
  7202. }
  7203. // split by whitespace
  7204. uint64_t l = 0;
  7205. uint64_t r = 0;
  7206. while (r < new_str.size()) {
  7207. // if is whitespace
  7208. if (isspace(new_str[r])) {
  7209. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  7210. l = r + 1;
  7211. r = l;
  7212. }
  7213. else {
  7214. r += 1;
  7215. }
  7216. }
  7217. if (r > l) {
  7218. words.push_back(new_str.substr(l, (r - l)));
  7219. }
  7220. return words;
  7221. }
  7222. std::string normalize(const std::string & text) {
  7223. // TODO: handle chinese characters? https://github.com/huggingface/tokenizers/blob/ef5f50605ddf9f8caef1598c0e4853862b9707a7/tokenizers/src/normalizers/bert.rs#L98
  7224. std::string text2 = strip_accents(text);
  7225. for (size_t i = 0; i < text2.size(); i += utf8_len(text2[i])) {
  7226. char c = text2[i];
  7227. if (c >= 'A' && c <= 'Z') {
  7228. text2[i] = c - 'A' + 'a';
  7229. }
  7230. }
  7231. return text2;
  7232. }
  7233. bool is_chinese_char(const std::string & str) {
  7234. int len = str.length();
  7235. unsigned int codepoint = 0;
  7236. int num_bytes = 0;
  7237. int i = 0;
  7238. unsigned char ch = static_cast<unsigned char>(str[i]);
  7239. if (ch <= 0x7f) {
  7240. codepoint = ch;
  7241. num_bytes = 1;
  7242. } else if ((ch >> 5) == 0x06) {
  7243. codepoint = ch & 0x1f;
  7244. num_bytes = 2;
  7245. } else if ((ch >> 4) == 0x0e) {
  7246. codepoint = ch & 0x0f;
  7247. num_bytes = 3;
  7248. } else if ((ch >> 3) == 0x1e) {
  7249. codepoint = ch & 0x07;
  7250. num_bytes = 4;
  7251. }
  7252. for (int j = 1; j < num_bytes; ++j) {
  7253. if (i + j >= len) {
  7254. return false; // incomplete UTF-8 character
  7255. }
  7256. unsigned char next_ch = static_cast<unsigned char>(str[i + j]);
  7257. if ((next_ch >> 6) != 0x02) {
  7258. return false; // invalid trailing byte
  7259. }
  7260. codepoint = (codepoint << 6) | (next_ch & 0x3f);
  7261. }
  7262. if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) ||
  7263. (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
  7264. (codepoint >= 0x20000 && codepoint <= 0x2A6DF) ||
  7265. (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
  7266. (codepoint >= 0x2B740 && codepoint <= 0x2B81F) ||
  7267. (codepoint >= 0x2B920 && codepoint <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  7268. (codepoint >= 0xF900 && codepoint <= 0xFAFF) ||
  7269. (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
  7270. (codepoint >= 0x3000 && codepoint <= 0x303F) ||
  7271. (codepoint >= 0xFF00 && codepoint <= 0xFFEF)) {
  7272. return true; // NOLINT
  7273. }
  7274. return false;
  7275. }
  7276. std::string strip_accents(const std::string & input_string) {
  7277. std::string resultString;
  7278. std::map<std::string, char> accent_map = {
  7279. {"À", 'A'}, {"Á", 'A'}, {"Â", 'A'}, {"Ã", 'A'}, {"Ä", 'A'}, {"Å", 'A'},
  7280. {"à", 'a'}, {"á", 'a'}, {"â", 'a'}, {"ã", 'a'}, {"ä", 'a'}, {"å", 'a'},
  7281. {"È", 'E'}, {"É", 'E'}, {"Ê", 'E'}, {"Ë", 'E'}, {"è", 'e'}, {"é", 'e'},
  7282. {"ê", 'e'}, {"ë", 'e'}, {"Ì", 'I'}, {"Í", 'I'}, {"Î", 'I'}, {"Ï", 'I'},
  7283. {"ì", 'i'}, {"í", 'i'}, {"î", 'i'}, {"ï", 'i'}, {"Ò", 'O'}, {"Ó", 'O'},
  7284. {"Ô", 'O'}, {"Õ", 'O'}, {"Ö", 'O'}, {"ò", 'o'}, {"ó", 'o'}, {"ô", 'o'},
  7285. {"õ", 'o'}, {"ö", 'o'}, {"Ù", 'U'}, {"Ú", 'U'}, {"Û", 'U'}, {"Ü", 'U'},
  7286. {"ù", 'u'}, {"ú", 'u'}, {"û", 'u'}, {"ü", 'u'}, {"Ý", 'Y'}, {"ý", 'y'},
  7287. {"Ç", 'C'}, {"ç", 'c'}, {"Ñ", 'N'}, {"ñ", 'n'},
  7288. };
  7289. for (size_t i = 0; i < input_string.length();) {
  7290. int len = utf8_len(input_string[i]);
  7291. std::string curChar = input_string.substr(i, len);
  7292. auto iter = accent_map.find(curChar);
  7293. if (iter != accent_map.end()) {
  7294. resultString += iter->second;
  7295. } else {
  7296. resultString += curChar;
  7297. }
  7298. i += len;
  7299. }
  7300. return resultString;
  7301. }
  7302. static size_t utf8_len(char src) {
  7303. const size_t lookup[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4};
  7304. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  7305. return lookup[highbits];
  7306. }
  7307. const llama_vocab & vocab;
  7308. };
  7309. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  7310. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  7311. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  7312. } FRAGMENT_BUFFER_VARIANT_TYPE;
  7313. struct fragment_buffer_variant {
  7314. fragment_buffer_variant(llama_vocab::id _token)
  7315. :
  7316. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  7317. token(_token),
  7318. raw_text(_dummy),
  7319. offset(0),
  7320. length(0) {}
  7321. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  7322. :
  7323. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  7324. token((llama_vocab::id) - 1),
  7325. raw_text(_raw_text),
  7326. offset(_offset),
  7327. length(_length){
  7328. GGML_ASSERT(_offset >= 0);
  7329. GGML_ASSERT(_length >= 1);
  7330. GGML_ASSERT(offset + length <= raw_text.length());
  7331. }
  7332. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  7333. const llama_vocab::id token;
  7334. const std::string _dummy;
  7335. const std::string & raw_text;
  7336. const uint64_t offset;
  7337. const uint64_t length;
  7338. };
  7339. // #define PRETOKENIZERDEBUG
  7340. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  7341. // for each special token
  7342. for (const auto & st: vocab.special_tokens_cache) {
  7343. const auto & special_token = st.first;
  7344. const auto & special_id = st.second;
  7345. // for each text fragment
  7346. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  7347. while (it != buffer.end()) {
  7348. auto & fragment = (*it);
  7349. // if a fragment is text ( not yet processed )
  7350. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7351. auto * raw_text = &(fragment.raw_text);
  7352. auto raw_text_base_offset = fragment.offset;
  7353. auto raw_text_base_length = fragment.length;
  7354. // loop over the text
  7355. while (true) {
  7356. // find the first occurrence of a given special token in this fragment
  7357. // passing offset argument only limit the "search area" but match coordinates
  7358. // are still relative to the source full raw_text
  7359. auto match = raw_text->find(special_token, raw_text_base_offset);
  7360. // no occurrences found, stop processing this fragment for a given special token
  7361. if (match == std::string::npos) break;
  7362. // check if match is within bounds of offset <-> length
  7363. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  7364. #ifdef PRETOKENIZERDEBUG
  7365. 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());
  7366. #endif
  7367. auto source = std::distance(buffer.begin(), it);
  7368. // if match is further than base offset
  7369. // then we have some text to the left of it
  7370. if (match > raw_text_base_offset) {
  7371. // left
  7372. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  7373. const int64_t left_reminder_length = match - raw_text_base_offset;
  7374. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  7375. #ifdef PRETOKENIZERDEBUG
  7376. 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());
  7377. #endif
  7378. it++;
  7379. }
  7380. // special token
  7381. buffer.emplace_after(it, special_id);
  7382. it++;
  7383. // right
  7384. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  7385. const int64_t right_reminder_offset = match + special_token.length();
  7386. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  7387. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  7388. #ifdef PRETOKENIZERDEBUG
  7389. 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());
  7390. #endif
  7391. it++;
  7392. if (source == 0) {
  7393. buffer.erase_after(buffer.before_begin());
  7394. } else {
  7395. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7396. }
  7397. // repeat for the right side
  7398. raw_text_base_offset = right_reminder_offset;
  7399. raw_text_base_length = right_reminder_length;
  7400. #ifdef PRETOKENIZERDEBUG
  7401. 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());
  7402. #endif
  7403. } else {
  7404. if (source == 0) {
  7405. buffer.erase_after(buffer.before_begin());
  7406. } else {
  7407. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7408. }
  7409. break;
  7410. }
  7411. }
  7412. }
  7413. it++;
  7414. }
  7415. }
  7416. }
  7417. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  7418. std::vector<llama_vocab::id> output;
  7419. // OG tokenizer behavior:
  7420. //
  7421. // tokenizer.encode('', add_bos=True) returns [1]
  7422. // tokenizer.encode('', add_bos=False) returns []
  7423. if (bos && vocab.special_bos_id != -1) {
  7424. output.push_back(vocab.special_bos_id);
  7425. }
  7426. if (raw_text.empty()) {
  7427. return output;
  7428. }
  7429. std::forward_list<fragment_buffer_variant> fragment_buffer;
  7430. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  7431. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  7432. switch (vocab.type) {
  7433. case LLAMA_VOCAB_TYPE_SPM:
  7434. {
  7435. for (const auto & fragment : fragment_buffer) {
  7436. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7437. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  7438. // TODO: It's likely possible to get rid of this string copy entirely
  7439. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  7440. // and passing 'add space prefix' as bool argument
  7441. //
  7442. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7443. if (&fragment == &fragment_buffer.front()) {
  7444. if (vocab.add_space_prefix) {
  7445. raw_text = " " + raw_text; // prefix with space if the first token is not special
  7446. }
  7447. }
  7448. #ifdef PRETOKENIZERDEBUG
  7449. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7450. #endif
  7451. llm_tokenizer_spm tokenizer(vocab);
  7452. llama_escape_whitespace(raw_text);
  7453. tokenizer.tokenize(raw_text, output);
  7454. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7455. output.push_back(fragment.token);
  7456. }
  7457. }
  7458. } break;
  7459. case LLAMA_VOCAB_TYPE_BPE:
  7460. {
  7461. for (const auto & fragment : fragment_buffer) {
  7462. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7463. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7464. #ifdef PRETOKENIZERDEBUG
  7465. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7466. #endif
  7467. llm_tokenizer_bpe tokenizer(vocab);
  7468. tokenizer.tokenize(raw_text, output);
  7469. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7470. output.push_back(fragment.token);
  7471. }
  7472. }
  7473. } break;
  7474. case LLAMA_VOCAB_TYPE_WPM:
  7475. {
  7476. for (const auto & fragment : fragment_buffer) {
  7477. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7478. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7479. #ifdef PRETOKENIZERDEBUG
  7480. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7481. #endif
  7482. llm_tokenizer_wpm tokenizer(vocab);
  7483. tokenizer.tokenize(raw_text, output);
  7484. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7485. output.push_back(fragment.token);
  7486. }
  7487. }
  7488. } break;
  7489. }
  7490. return output;
  7491. }
  7492. //
  7493. // grammar - internal
  7494. //
  7495. struct llama_partial_utf8 {
  7496. uint32_t value; // bit value so far (unshifted)
  7497. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  7498. };
  7499. struct llama_grammar {
  7500. const std::vector<std::vector<llama_grammar_element>> rules;
  7501. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7502. // buffer for partially generated UTF-8 sequence from accepted tokens
  7503. llama_partial_utf8 partial_utf8;
  7504. };
  7505. struct llama_grammar_candidate {
  7506. size_t index;
  7507. const uint32_t * code_points;
  7508. llama_partial_utf8 partial_utf8;
  7509. };
  7510. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  7511. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  7512. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  7513. const std::string & src,
  7514. llama_partial_utf8 partial_start) {
  7515. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  7516. const char * pos = src.c_str();
  7517. std::vector<uint32_t> code_points;
  7518. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  7519. code_points.reserve(src.size() + 1);
  7520. uint32_t value = partial_start.value;
  7521. int n_remain = partial_start.n_remain;
  7522. // continue previous decode, if applicable
  7523. while (*pos != 0 && n_remain > 0) {
  7524. uint8_t next_byte = static_cast<uint8_t>(*pos);
  7525. if ((next_byte >> 6) != 2) {
  7526. // invalid sequence, abort
  7527. code_points.push_back(0);
  7528. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  7529. }
  7530. value = (value << 6) + (next_byte & 0x3F);
  7531. ++pos;
  7532. --n_remain;
  7533. }
  7534. if (partial_start.n_remain > 0 && n_remain == 0) {
  7535. code_points.push_back(value);
  7536. }
  7537. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  7538. while (*pos != 0) {
  7539. uint8_t first_byte = static_cast<uint8_t>(*pos);
  7540. uint8_t highbits = first_byte >> 4;
  7541. n_remain = lookup[highbits] - 1;
  7542. if (n_remain < 0) {
  7543. // invalid sequence, abort
  7544. code_points.clear();
  7545. code_points.push_back(0);
  7546. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  7547. }
  7548. uint8_t mask = (1 << (7 - n_remain)) - 1;
  7549. value = first_byte & mask;
  7550. ++pos;
  7551. while (*pos != 0 && n_remain > 0) {
  7552. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  7553. ++pos;
  7554. --n_remain;
  7555. }
  7556. if (n_remain == 0) {
  7557. code_points.push_back(value);
  7558. }
  7559. }
  7560. code_points.push_back(0);
  7561. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  7562. }
  7563. // returns true iff pos points to the end of one of the definitions of a rule
  7564. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  7565. switch (pos->type) {
  7566. case LLAMA_GRETYPE_END: return true; // NOLINT
  7567. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  7568. default: return false;
  7569. }
  7570. }
  7571. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  7572. // asserts that pos is pointing to a char range element
  7573. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  7574. const llama_grammar_element * pos,
  7575. const uint32_t chr) {
  7576. bool found = false;
  7577. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7578. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  7579. do {
  7580. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7581. // inclusive range, e.g. [a-z]
  7582. found = found || (pos->value <= chr && chr <= pos[1].value);
  7583. pos += 2;
  7584. } else {
  7585. // exact char match, e.g. [a] or "a"
  7586. found = found || pos->value == chr;
  7587. pos += 1;
  7588. }
  7589. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7590. return std::make_pair(found == is_positive_char, pos);
  7591. }
  7592. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  7593. // range at pos (regular or inverse range)
  7594. // asserts that pos is pointing to a char range element
  7595. static bool llama_grammar_match_partial_char(
  7596. const llama_grammar_element * pos,
  7597. const llama_partial_utf8 partial_utf8) {
  7598. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7599. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  7600. uint32_t partial_value = partial_utf8.value;
  7601. int n_remain = partial_utf8.n_remain;
  7602. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  7603. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  7604. return false;
  7605. }
  7606. // range of possible code points this partial UTF-8 sequence could complete to
  7607. uint32_t low = partial_value << (n_remain * 6);
  7608. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  7609. if (low == 0) {
  7610. if (n_remain == 2) {
  7611. low = 1 << 11;
  7612. } else if (n_remain == 3) {
  7613. low = 1 << 16;
  7614. }
  7615. }
  7616. do {
  7617. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7618. // inclusive range, e.g. [a-z]
  7619. if (pos->value <= high && low <= pos[1].value) {
  7620. return is_positive_char;
  7621. }
  7622. pos += 2;
  7623. } else {
  7624. // exact char match, e.g. [a] or "a"
  7625. if (low <= pos->value && pos->value <= high) {
  7626. return is_positive_char;
  7627. }
  7628. pos += 1;
  7629. }
  7630. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7631. return !is_positive_char;
  7632. }
  7633. // transforms a grammar pushdown stack into N possible stacks, all ending
  7634. // at a character range (terminal element)
  7635. static void llama_grammar_advance_stack(
  7636. const std::vector<std::vector<llama_grammar_element>> & rules,
  7637. const std::vector<const llama_grammar_element *> & stack,
  7638. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  7639. if (stack.empty()) {
  7640. new_stacks.emplace_back(stack);
  7641. return;
  7642. }
  7643. const llama_grammar_element * pos = stack.back();
  7644. switch (pos->type) {
  7645. case LLAMA_GRETYPE_RULE_REF: {
  7646. const size_t rule_id = static_cast<size_t>(pos->value);
  7647. const llama_grammar_element * subpos = rules[rule_id].data();
  7648. do {
  7649. // init new stack without the top (pos)
  7650. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7651. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  7652. // if this rule ref is followed by another element, add that to stack
  7653. new_stack.push_back(pos + 1);
  7654. }
  7655. if (!llama_grammar_is_end_of_sequence(subpos)) {
  7656. // if alternate is nonempty, add to stack
  7657. new_stack.push_back(subpos);
  7658. }
  7659. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7660. while (!llama_grammar_is_end_of_sequence(subpos)) {
  7661. // scan to end of alternate def
  7662. subpos++;
  7663. }
  7664. if (subpos->type == LLAMA_GRETYPE_ALT) {
  7665. // there's another alternate def of this rule to process
  7666. subpos++;
  7667. } else {
  7668. break;
  7669. }
  7670. } while (true);
  7671. break;
  7672. }
  7673. case LLAMA_GRETYPE_CHAR:
  7674. case LLAMA_GRETYPE_CHAR_NOT:
  7675. new_stacks.emplace_back(stack);
  7676. break;
  7677. default:
  7678. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  7679. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  7680. // those
  7681. GGML_ASSERT(false);
  7682. }
  7683. }
  7684. // takes a set of possible pushdown stacks on a grammar, which are required to
  7685. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  7686. // produces the N possible stacks if the given char is accepted at those
  7687. // positions
  7688. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  7689. const std::vector<std::vector<llama_grammar_element>> & rules,
  7690. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7691. const uint32_t chr) {
  7692. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  7693. for (const auto & stack : stacks) {
  7694. if (stack.empty()) {
  7695. continue;
  7696. }
  7697. auto match = llama_grammar_match_char(stack.back(), chr);
  7698. if (match.first) {
  7699. const llama_grammar_element * pos = match.second;
  7700. // update top of stack to next element, if any
  7701. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7702. if (!llama_grammar_is_end_of_sequence(pos)) {
  7703. new_stack.push_back(pos);
  7704. }
  7705. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7706. }
  7707. }
  7708. return new_stacks;
  7709. }
  7710. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7711. const std::vector<std::vector<llama_grammar_element>> & rules,
  7712. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7713. const std::vector<llama_grammar_candidate> & candidates);
  7714. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  7715. const std::vector<std::vector<llama_grammar_element>> & rules,
  7716. const std::vector<const llama_grammar_element *> & stack,
  7717. const std::vector<llama_grammar_candidate> & candidates) {
  7718. std::vector<llama_grammar_candidate> rejects;
  7719. if (stack.empty()) {
  7720. for (const auto & tok : candidates) {
  7721. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  7722. rejects.push_back(tok);
  7723. }
  7724. }
  7725. return rejects;
  7726. }
  7727. const llama_grammar_element * stack_pos = stack.back();
  7728. std::vector<llama_grammar_candidate> next_candidates;
  7729. for (const auto & tok : candidates) {
  7730. if (*tok.code_points == 0) {
  7731. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  7732. // that cannot satisfy this position in grammar
  7733. if (tok.partial_utf8.n_remain != 0 &&
  7734. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  7735. rejects.push_back(tok);
  7736. }
  7737. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  7738. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  7739. } else {
  7740. rejects.push_back(tok);
  7741. }
  7742. }
  7743. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  7744. // update top of stack to next element, if any
  7745. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  7746. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  7747. stack_after.push_back(stack_pos_after);
  7748. }
  7749. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  7750. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  7751. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  7752. for (const auto & tok : next_rejects) {
  7753. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  7754. }
  7755. return rejects;
  7756. }
  7757. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7758. const std::vector<std::vector<llama_grammar_element>> & rules,
  7759. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7760. const std::vector<llama_grammar_candidate> & candidates) {
  7761. GGML_ASSERT(!stacks.empty()); // REVIEW
  7762. if (candidates.empty()) {
  7763. return std::vector<llama_grammar_candidate>();
  7764. }
  7765. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  7766. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  7767. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  7768. }
  7769. return rejects;
  7770. }
  7771. //
  7772. // grammar - external
  7773. //
  7774. struct llama_grammar * llama_grammar_init(
  7775. const llama_grammar_element ** rules,
  7776. size_t n_rules,
  7777. size_t start_rule_index) {
  7778. const llama_grammar_element * pos;
  7779. // copy rule definitions into vectors
  7780. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  7781. for (size_t i = 0; i < n_rules; i++) {
  7782. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  7783. vec_rules[i].push_back(*pos);
  7784. }
  7785. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  7786. }
  7787. // loop over alternates of start rule to build initial stacks
  7788. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7789. pos = rules[start_rule_index];
  7790. do {
  7791. std::vector<const llama_grammar_element *> stack;
  7792. if (!llama_grammar_is_end_of_sequence(pos)) {
  7793. // if alternate is nonempty, add to stack
  7794. stack.push_back(pos);
  7795. }
  7796. llama_grammar_advance_stack(vec_rules, stack, stacks);
  7797. while (!llama_grammar_is_end_of_sequence(pos)) {
  7798. // scan to end of alternate def
  7799. pos++;
  7800. }
  7801. if (pos->type == LLAMA_GRETYPE_ALT) {
  7802. // there's another alternate def of this rule to process
  7803. pos++;
  7804. } else {
  7805. break;
  7806. }
  7807. } while (true);
  7808. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  7809. }
  7810. void llama_grammar_free(struct llama_grammar * grammar) {
  7811. delete grammar;
  7812. }
  7813. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  7814. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  7815. // redirect elements in stacks to point to new rules
  7816. for (size_t is = 0; is < result->stacks.size(); is++) {
  7817. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  7818. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  7819. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  7820. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  7821. result->stacks[is][ie] = &result->rules[ir0][ir1];
  7822. }
  7823. }
  7824. }
  7825. }
  7826. }
  7827. return result;
  7828. }
  7829. //
  7830. // sampling
  7831. //
  7832. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  7833. if (seed == LLAMA_DEFAULT_SEED) {
  7834. seed = time(NULL);
  7835. }
  7836. ctx->rng.seed(seed);
  7837. }
  7838. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  7839. GGML_ASSERT(candidates->size > 0);
  7840. const int64_t t_start_sample_us = ggml_time_us();
  7841. // Sort the logits in descending order
  7842. if (!candidates->sorted) {
  7843. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7844. return a.logit > b.logit;
  7845. });
  7846. candidates->sorted = true;
  7847. }
  7848. float max_l = candidates->data[0].logit;
  7849. float cum_sum = 0.0f;
  7850. for (size_t i = 0; i < candidates->size; ++i) {
  7851. float p = expf(candidates->data[i].logit - max_l);
  7852. candidates->data[i].p = p;
  7853. cum_sum += p;
  7854. }
  7855. for (size_t i = 0; i < candidates->size; ++i) {
  7856. candidates->data[i].p /= cum_sum;
  7857. }
  7858. if (ctx) {
  7859. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7860. }
  7861. }
  7862. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  7863. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  7864. // if (k >= (int32_t)candidates->size) {
  7865. // return;
  7866. // }
  7867. const int64_t t_start_sample_us = ggml_time_us();
  7868. if (k <= 0) {
  7869. k = candidates->size;
  7870. }
  7871. k = std::max(k, (int) min_keep);
  7872. k = std::min(k, (int) candidates->size);
  7873. // Sort scores in descending order
  7874. if (!candidates->sorted) {
  7875. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  7876. return a.logit > b.logit;
  7877. };
  7878. if (k <= 128) {
  7879. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  7880. } else {
  7881. constexpr int nbuckets = 128;
  7882. constexpr float bucket_low = -10.0f;
  7883. constexpr float bucket_high = 10.0f;
  7884. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  7885. constexpr float bucker_inter = -bucket_low * bucket_scale;
  7886. std::vector<int> bucket_idx(candidates->size);
  7887. std::vector<int> histo(nbuckets, 0);
  7888. for (int i = 0; i < (int)candidates->size; ++i) {
  7889. const float val = candidates->data[i].logit;
  7890. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  7891. ib = std::max(0, std::min(nbuckets-1, ib));
  7892. bucket_idx[i] = ib;
  7893. ++histo[ib];
  7894. }
  7895. int nhave = 0;
  7896. int ib = nbuckets - 1;
  7897. for ( ; ib >= 0; --ib) {
  7898. nhave += histo[ib];
  7899. if (nhave >= k) break;
  7900. }
  7901. std::vector<llama_token_data> tmp_tokens(nhave);
  7902. auto ptr = tmp_tokens.data();
  7903. std::vector<llama_token_data*> bucket_ptrs;
  7904. bucket_ptrs.reserve(nbuckets - ib);
  7905. for (int j = nbuckets - 1; j >= ib; --j) {
  7906. bucket_ptrs.push_back(ptr);
  7907. ptr += histo[j];
  7908. }
  7909. for (int i = 0; i < (int)candidates->size; ++i) {
  7910. int j = bucket_idx[i];
  7911. if (j >= ib) {
  7912. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  7913. }
  7914. }
  7915. ptr = tmp_tokens.data();
  7916. int ndone = 0;
  7917. for (int j = nbuckets-1; j > ib; --j) {
  7918. std::sort(ptr, ptr + histo[j], comp);
  7919. ptr += histo[j];
  7920. ndone += histo[j];
  7921. }
  7922. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  7923. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  7924. }
  7925. candidates->sorted = true;
  7926. }
  7927. candidates->size = k;
  7928. if (ctx) {
  7929. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7930. }
  7931. }
  7932. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7933. if (p >= 1.0f) {
  7934. return;
  7935. }
  7936. llama_sample_softmax(ctx, candidates);
  7937. const int64_t t_start_sample_us = ggml_time_us();
  7938. // Compute the cumulative probabilities
  7939. float cum_sum = 0.0f;
  7940. size_t last_idx = candidates->size;
  7941. for (size_t i = 0; i < candidates->size; ++i) {
  7942. cum_sum += candidates->data[i].p;
  7943. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  7944. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  7945. if (cum_sum >= p && i + 1 >= min_keep) {
  7946. last_idx = i + 1;
  7947. break;
  7948. }
  7949. }
  7950. // Resize the output vector to keep only the top-p tokens
  7951. candidates->size = last_idx;
  7952. if (ctx) {
  7953. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7954. }
  7955. }
  7956. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7957. if (p <= 0.0f || !candidates->size) {
  7958. return;
  7959. }
  7960. const int64_t t_start_sample_us = ggml_time_us();
  7961. bool min_p_applied = false;
  7962. // if the candidates aren't sorted, try the unsorted implementation first
  7963. if (!candidates->sorted) {
  7964. std::vector<llama_token_data> filtered_tokens;
  7965. float max_logit = -FLT_MAX;
  7966. for (size_t i = 0; i < candidates->size; ++i) {
  7967. max_logit = std::max(max_logit, candidates->data[i].logit);
  7968. }
  7969. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  7970. for (size_t i = 0; i < candidates->size; ++i) {
  7971. if (candidates->data[i].logit >= min_logit) {
  7972. filtered_tokens.push_back(candidates->data[i]);
  7973. }
  7974. }
  7975. // if we have enough values the operation was a success
  7976. if (filtered_tokens.size() >= min_keep) {
  7977. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  7978. candidates->size = filtered_tokens.size();
  7979. min_p_applied = true;
  7980. }
  7981. }
  7982. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  7983. if (!min_p_applied) {
  7984. // Sort the logits in descending order
  7985. if (!candidates->sorted) {
  7986. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7987. return a.logit > b.logit;
  7988. });
  7989. candidates->sorted = true;
  7990. }
  7991. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  7992. size_t i = 1; // first token always matches
  7993. for (; i < candidates->size; ++i) {
  7994. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  7995. break; // prob too small
  7996. }
  7997. }
  7998. // Resize the output vector to keep only the matching tokens
  7999. candidates->size = i;
  8000. }
  8001. if (ctx) {
  8002. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8003. }
  8004. }
  8005. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  8006. if (z >= 1.0f || candidates->size <= 2) {
  8007. return;
  8008. }
  8009. llama_sample_softmax(nullptr, candidates);
  8010. const int64_t t_start_sample_us = ggml_time_us();
  8011. // Compute the first and second derivatives
  8012. std::vector<float> first_derivatives(candidates->size - 1);
  8013. std::vector<float> second_derivatives(candidates->size - 2);
  8014. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  8015. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  8016. }
  8017. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8018. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  8019. }
  8020. // Calculate absolute value of second derivatives
  8021. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8022. second_derivatives[i] = std::abs(second_derivatives[i]);
  8023. }
  8024. // Normalize the second derivatives
  8025. {
  8026. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  8027. if (second_derivatives_sum > 1e-6f) {
  8028. for (float & value : second_derivatives) {
  8029. value /= second_derivatives_sum;
  8030. }
  8031. } else {
  8032. for (float & value : second_derivatives) {
  8033. value = 1.0f / second_derivatives.size();
  8034. }
  8035. }
  8036. }
  8037. float cum_sum = 0.0f;
  8038. size_t last_idx = candidates->size;
  8039. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8040. cum_sum += second_derivatives[i];
  8041. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  8042. if (cum_sum > z && i >= min_keep) {
  8043. last_idx = i;
  8044. break;
  8045. }
  8046. }
  8047. // Resize the output vector to keep only the tokens above the tail location
  8048. candidates->size = last_idx;
  8049. if (ctx) {
  8050. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8051. }
  8052. }
  8053. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8054. // Reference implementation:
  8055. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  8056. if (p >= 1.0f) {
  8057. return;
  8058. }
  8059. // Compute the softmax of logits and calculate entropy
  8060. llama_sample_softmax(nullptr, candidates);
  8061. const int64_t t_start_sample_us = ggml_time_us();
  8062. float entropy = 0.0f;
  8063. for (size_t i = 0; i < candidates->size; ++i) {
  8064. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  8065. }
  8066. // Compute the absolute difference between negative log probability and entropy for each candidate
  8067. std::vector<float> shifted_scores;
  8068. for (size_t i = 0; i < candidates->size; ++i) {
  8069. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  8070. shifted_scores.push_back(shifted_score);
  8071. }
  8072. // Sort tokens based on the shifted_scores and their corresponding indices
  8073. std::vector<size_t> indices(candidates->size);
  8074. std::iota(indices.begin(), indices.end(), 0);
  8075. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  8076. return shifted_scores[a] < shifted_scores[b];
  8077. });
  8078. // Compute the cumulative probabilities
  8079. float cum_sum = 0.0f;
  8080. size_t last_idx = indices.size();
  8081. for (size_t i = 0; i < indices.size(); ++i) {
  8082. size_t idx = indices[i];
  8083. cum_sum += candidates->data[idx].p;
  8084. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  8085. if (cum_sum > p && i >= min_keep - 1) {
  8086. last_idx = i + 1;
  8087. break;
  8088. }
  8089. }
  8090. // Resize the output vector to keep only the locally typical tokens
  8091. std::vector<llama_token_data> new_candidates;
  8092. for (size_t i = 0; i < last_idx; ++i) {
  8093. size_t idx = indices[i];
  8094. new_candidates.push_back(candidates->data[idx]);
  8095. }
  8096. // Replace the data in candidates with the new_candidates data
  8097. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  8098. candidates->size = new_candidates.size();
  8099. candidates->sorted = false;
  8100. if (ctx) {
  8101. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8102. }
  8103. }
  8104. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  8105. const int64_t t_start_sample_us = ggml_time_us();
  8106. // no need to do anything if there is only one (or zero) candidates
  8107. if(candidates_p->size <= 1) {
  8108. return;
  8109. }
  8110. // Calculate maximum possible entropy
  8111. float max_entropy = -logf(1.0f / candidates_p->size);
  8112. llama_sample_softmax(nullptr, candidates_p);
  8113. // Calculate entropy of the softmax probabilities
  8114. float entropy = 0.0f;
  8115. for (size_t i = 0; i < candidates_p->size; ++i) {
  8116. float prob = candidates_p->data[i].p;
  8117. if (prob > 0.0f) { // Ensure no log(0)
  8118. entropy -= prob * logf(prob);
  8119. }
  8120. }
  8121. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  8122. float normalized_entropy = entropy / max_entropy;
  8123. // Map the normalized entropy to the desired temperature range using the power function
  8124. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  8125. #ifdef DEBUG
  8126. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  8127. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  8128. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  8129. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  8130. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  8131. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  8132. #endif
  8133. // Apply the dynamically calculated temperature scaling
  8134. for (size_t i = 0; i < candidates_p->size; ++i) {
  8135. candidates_p->data[i].logit /= dyn_temp;
  8136. }
  8137. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  8138. double max_l_double = candidates_p->data[0].logit;
  8139. double cum_sum_double = 0.0;
  8140. for (size_t i = 0; i < candidates_p->size; ++i) {
  8141. double p = exp(candidates_p->data[i].logit - max_l_double);
  8142. candidates_p->data[i].p = p; // Store the scaled probability
  8143. cum_sum_double += p;
  8144. }
  8145. for (size_t i = 0; i < candidates_p->size; ++i) {
  8146. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  8147. }
  8148. #ifdef DEBUG
  8149. // Print the updated top 25 probabilities after temperature scaling
  8150. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  8151. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  8152. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  8153. }
  8154. #endif
  8155. if (ctx) {
  8156. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8157. }
  8158. }
  8159. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8160. const int64_t t_start_sample_us = ggml_time_us();
  8161. for (size_t i = 0; i < candidates_p->size; ++i) {
  8162. candidates_p->data[i].logit /= temp;
  8163. }
  8164. if (ctx) {
  8165. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8166. }
  8167. }
  8168. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8169. llama_sample_temp(ctx, candidates_p, temp);
  8170. }
  8171. void llama_sample_repetition_penalties(
  8172. struct llama_context * ctx,
  8173. llama_token_data_array * candidates,
  8174. const llama_token * last_tokens,
  8175. size_t penalty_last_n,
  8176. float penalty_repeat,
  8177. float penalty_freq,
  8178. float penalty_present) {
  8179. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  8180. return;
  8181. }
  8182. const int64_t t_start_sample_us = ggml_time_us();
  8183. // Create a frequency map to count occurrences of each token in last_tokens
  8184. std::unordered_map<llama_token, int> token_count;
  8185. for (size_t i = 0; i < penalty_last_n; ++i) {
  8186. token_count[last_tokens[i]]++;
  8187. }
  8188. // Apply frequency and presence penalties to the candidates
  8189. for (size_t i = 0; i < candidates->size; ++i) {
  8190. const auto token_iter = token_count.find(candidates->data[i].id);
  8191. if (token_iter == token_count.end()) {
  8192. continue;
  8193. }
  8194. const int count = token_iter->second;
  8195. // 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.
  8196. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  8197. if (candidates->data[i].logit <= 0) {
  8198. candidates->data[i].logit *= penalty_repeat;
  8199. } else {
  8200. candidates->data[i].logit /= penalty_repeat;
  8201. }
  8202. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  8203. }
  8204. candidates->sorted = false;
  8205. if (ctx) {
  8206. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8207. }
  8208. }
  8209. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  8210. GGML_ASSERT(ctx);
  8211. const int64_t t_start_sample_us = ggml_time_us();
  8212. bool allow_eos = false;
  8213. for (const auto & stack : grammar->stacks) {
  8214. if (stack.empty()) {
  8215. allow_eos = true;
  8216. break;
  8217. }
  8218. }
  8219. const llama_token eos = llama_token_eos(&ctx->model);
  8220. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  8221. candidates_decoded.reserve(candidates->size);
  8222. std::vector<llama_grammar_candidate> candidates_grammar;
  8223. candidates_grammar.reserve(candidates->size);
  8224. for (size_t i = 0; i < candidates->size; ++i) {
  8225. const llama_token id = candidates->data[i].id;
  8226. const std::string piece = llama_token_to_piece(ctx, id);
  8227. if (id == eos) {
  8228. if (!allow_eos) {
  8229. candidates->data[i].logit = -INFINITY;
  8230. }
  8231. } else if (piece.empty() || piece[0] == 0) {
  8232. candidates->data[i].logit = -INFINITY;
  8233. } else {
  8234. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  8235. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  8236. }
  8237. }
  8238. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  8239. for (const auto & reject : rejects) {
  8240. candidates->data[reject.index].logit = -INFINITY;
  8241. }
  8242. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8243. }
  8244. static void llama_log_softmax(float * array, size_t size) {
  8245. float max_l = *std::max_element(array, array + size);
  8246. float sum = 0.f;
  8247. for (size_t i = 0; i < size; ++i) {
  8248. float p = expf(array[i] - max_l);
  8249. sum += p;
  8250. array[i] = p;
  8251. }
  8252. for (size_t i = 0; i < size; ++i) {
  8253. array[i] = logf(array[i] / sum);
  8254. }
  8255. }
  8256. void llama_sample_apply_guidance(
  8257. struct llama_context * ctx,
  8258. float * logits,
  8259. float * logits_guidance,
  8260. float scale) {
  8261. GGML_ASSERT(ctx);
  8262. const auto t_start_sample_us = ggml_time_us();
  8263. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  8264. llama_log_softmax(logits, n_vocab);
  8265. llama_log_softmax(logits_guidance, n_vocab);
  8266. for (int i = 0; i < n_vocab; ++i) {
  8267. auto & l = logits[i];
  8268. const auto & g = logits_guidance[i];
  8269. l = scale * (l - g) + g;
  8270. }
  8271. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8272. }
  8273. void llama_sample_classifier_free_guidance(
  8274. struct llama_context * ctx,
  8275. llama_token_data_array * candidates,
  8276. struct llama_context * guidance_ctx,
  8277. float scale) {
  8278. GGML_ASSERT(ctx);
  8279. int64_t t_start_sample_us;
  8280. t_start_sample_us = ggml_time_us();
  8281. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  8282. GGML_ASSERT(n_vocab == candidates->size);
  8283. GGML_ASSERT(!candidates->sorted);
  8284. std::vector<float> logits_base(n_vocab);
  8285. for (size_t i = 0; i < n_vocab; ++i) {
  8286. logits_base[i] = candidates->data[i].logit;
  8287. }
  8288. float * logits_guidance = llama_get_logits(guidance_ctx);
  8289. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8290. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  8291. t_start_sample_us = ggml_time_us();
  8292. for (size_t i = 0; i < n_vocab; ++i) {
  8293. candidates->data[i].logit = logits_base[i];
  8294. }
  8295. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8296. }
  8297. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  8298. GGML_ASSERT(ctx);
  8299. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  8300. int64_t t_start_sample_us;
  8301. t_start_sample_us = ggml_time_us();
  8302. llama_sample_softmax(nullptr, candidates);
  8303. // Estimate s_hat using the most probable m tokens
  8304. float s_hat = 0.0;
  8305. float sum_ti_bi = 0.0;
  8306. float sum_ti_sq = 0.0;
  8307. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  8308. float t_i = logf(float(i + 2) / float(i + 1));
  8309. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  8310. sum_ti_bi += t_i * b_i;
  8311. sum_ti_sq += t_i * t_i;
  8312. }
  8313. s_hat = sum_ti_bi / sum_ti_sq;
  8314. // Compute k from the estimated s_hat and target surprise value
  8315. float epsilon_hat = s_hat - 1;
  8316. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  8317. // Sample the next word X using top-k sampling
  8318. llama_sample_top_k(nullptr, candidates, int(k), 1);
  8319. if (ctx) {
  8320. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8321. }
  8322. llama_token X = llama_sample_token(ctx, candidates);
  8323. t_start_sample_us = ggml_time_us();
  8324. // Compute error as the difference between observed surprise and target surprise value
  8325. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8326. return candidate.id == X;
  8327. }));
  8328. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8329. float e = observed_surprise - tau;
  8330. // Update mu using the learning rate and error
  8331. *mu = *mu - eta * e;
  8332. if (ctx) {
  8333. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8334. }
  8335. return X;
  8336. }
  8337. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  8338. int64_t t_start_sample_us;
  8339. t_start_sample_us = ggml_time_us();
  8340. llama_sample_softmax(ctx, candidates);
  8341. // Truncate the words with surprise values greater than mu
  8342. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8343. return -log2f(candidate.p) > *mu;
  8344. }));
  8345. if (candidates->size == 0) {
  8346. candidates->size = 1;
  8347. }
  8348. if (ctx) {
  8349. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8350. }
  8351. // Normalize the probabilities of the remaining words
  8352. llama_sample_softmax(ctx, candidates);
  8353. // Sample the next word X from the remaining words
  8354. llama_token X = llama_sample_token(ctx, candidates);
  8355. t_start_sample_us = ggml_time_us();
  8356. // Compute error as the difference between observed surprise and target surprise value
  8357. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8358. return candidate.id == X;
  8359. }));
  8360. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8361. float e = observed_surprise - tau;
  8362. // Update mu using the learning rate and error
  8363. *mu = *mu - eta * e;
  8364. if (ctx) {
  8365. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8366. }
  8367. return X;
  8368. }
  8369. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  8370. const int64_t t_start_sample_us = ggml_time_us();
  8371. // Find max element
  8372. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8373. return a.logit < b.logit;
  8374. });
  8375. llama_token result = max_iter->id;
  8376. if (ctx) {
  8377. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8378. ctx->n_sample++;
  8379. }
  8380. return result;
  8381. }
  8382. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  8383. GGML_ASSERT(ctx);
  8384. const int64_t t_start_sample_us = ggml_time_us();
  8385. llama_sample_softmax(nullptr, candidates);
  8386. std::vector<float> probs;
  8387. probs.reserve(candidates->size);
  8388. for (size_t i = 0; i < candidates->size; ++i) {
  8389. probs.push_back(candidates->data[i].p);
  8390. }
  8391. std::discrete_distribution<> dist(probs.begin(), probs.end());
  8392. auto & rng = ctx->rng;
  8393. int idx = dist(rng);
  8394. llama_token result = candidates->data[idx].id;
  8395. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8396. ctx->n_sample++;
  8397. return result;
  8398. }
  8399. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  8400. const int64_t t_start_sample_us = ggml_time_us();
  8401. if (token == llama_token_eos(&ctx->model)) {
  8402. for (const auto & stack : grammar->stacks) {
  8403. if (stack.empty()) {
  8404. return;
  8405. }
  8406. }
  8407. GGML_ASSERT(false);
  8408. }
  8409. const std::string piece = llama_token_to_piece(ctx, token);
  8410. // Note terminating 0 in decoded string
  8411. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  8412. const auto & code_points = decoded.first;
  8413. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  8414. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  8415. }
  8416. grammar->partial_utf8 = decoded.second;
  8417. GGML_ASSERT(!grammar->stacks.empty());
  8418. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8419. }
  8420. //
  8421. // Beam search
  8422. //
  8423. struct llama_beam {
  8424. std::vector<llama_token> tokens;
  8425. float p; // Cumulative beam probability (renormalized relative to all beams)
  8426. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  8427. // Sort beams by probability. In case of ties, prefer beams at eob.
  8428. bool operator<(const llama_beam & rhs) const {
  8429. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  8430. }
  8431. // Shift off first n tokens and discard them.
  8432. void shift_tokens(const size_t n) {
  8433. if (n) {
  8434. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  8435. tokens.resize(tokens.size() - n);
  8436. }
  8437. }
  8438. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  8439. };
  8440. // A struct for calculating logit-related info.
  8441. struct llama_logit_info {
  8442. const float * const logits;
  8443. const int n_vocab;
  8444. const float max_l;
  8445. const float normalizer;
  8446. struct sum_exp {
  8447. float max_l;
  8448. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  8449. };
  8450. llama_logit_info(llama_context * ctx)
  8451. : logits(llama_get_logits(ctx))
  8452. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  8453. , max_l(*std::max_element(logits, logits + n_vocab))
  8454. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  8455. { }
  8456. llama_token_data get_token_data(const llama_token token_id) const {
  8457. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  8458. return {token_id, logits[token_id], p};
  8459. }
  8460. // Return top k token_data by logit.
  8461. std::vector<llama_token_data> top_k(size_t k) {
  8462. std::vector<llama_token_data> min_heap; // min-heap by logit
  8463. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  8464. min_heap.reserve(k_min);
  8465. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  8466. min_heap.push_back(get_token_data(token_id));
  8467. }
  8468. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  8469. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  8470. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  8471. if (min_heap.front().logit < logits[token_id]) {
  8472. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  8473. min_heap.back().id = token_id;
  8474. min_heap.back().logit = logits[token_id];
  8475. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  8476. }
  8477. }
  8478. return min_heap;
  8479. }
  8480. float probability_from_logit(float logit) const {
  8481. return normalizer * std::exp(logit - max_l);
  8482. }
  8483. };
  8484. struct llama_beam_search_data {
  8485. llama_context * ctx;
  8486. size_t n_beams;
  8487. int n_past;
  8488. int n_predict;
  8489. std::vector<llama_beam> beams;
  8490. std::vector<llama_beam> next_beams;
  8491. // Re-calculated on each loop iteration
  8492. size_t common_prefix_length;
  8493. // Used to communicate to/from callback on beams state.
  8494. std::vector<llama_beam_view> beam_views;
  8495. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  8496. : ctx(ctx)
  8497. , n_beams(n_beams)
  8498. , n_past(n_past)
  8499. , n_predict(n_predict)
  8500. , beam_views(n_beams) {
  8501. beams.reserve(n_beams);
  8502. next_beams.reserve(n_beams);
  8503. }
  8504. // Collapse beams to a single beam given by index.
  8505. void collapse_beams(const size_t beam_idx) {
  8506. if (0u < beam_idx) {
  8507. std::swap(beams[0], beams[beam_idx]);
  8508. }
  8509. beams.resize(1);
  8510. }
  8511. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  8512. // The repetitive patterns below reflect the 2 stages of heaps:
  8513. // * Gather elements until the vector is full, then call std::make_heap() on it.
  8514. // * If the heap is full and a new element is found that should be included, pop the
  8515. // least element to the back(), replace it with the new, then push it into the heap.
  8516. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  8517. // Min-heaps use a greater-than comparator.
  8518. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  8519. if (beam.eob) {
  8520. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  8521. if (next_beams.size() < n_beams) {
  8522. next_beams.push_back(std::move(beam));
  8523. if (next_beams.size() == n_beams) {
  8524. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8525. }
  8526. } else if (next_beams.front().p < beam.p) {
  8527. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8528. next_beams.back() = std::move(beam);
  8529. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8530. }
  8531. } else {
  8532. // beam is not at end-of-sentence, so branch with next top_k tokens.
  8533. if (!beam.tokens.empty()) {
  8534. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  8535. }
  8536. llama_logit_info logit_info(ctx);
  8537. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  8538. size_t i=0;
  8539. if (next_beams.size() < n_beams) {
  8540. for (; next_beams.size() < n_beams ; ++i) {
  8541. llama_beam next_beam = beam;
  8542. next_beam.tokens.push_back(next_tokens[i].id);
  8543. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8544. next_beams.push_back(std::move(next_beam));
  8545. }
  8546. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8547. } else {
  8548. for (; next_beams.front().p == 0.0f ; ++i) {
  8549. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8550. next_beams.back() = beam;
  8551. next_beams.back().tokens.push_back(next_tokens[i].id);
  8552. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8553. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8554. }
  8555. }
  8556. for (; i < n_beams ; ++i) {
  8557. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  8558. if (next_beams.front().p < next_p) {
  8559. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8560. next_beams.back() = beam;
  8561. next_beams.back().tokens.push_back(next_tokens[i].id);
  8562. next_beams.back().p = next_p;
  8563. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8564. }
  8565. }
  8566. }
  8567. }
  8568. // Find common_prefix_length based on beams.
  8569. // Requires beams is not empty.
  8570. size_t find_common_prefix_length() {
  8571. size_t common_prefix_length = beams[0].tokens.size();
  8572. for (size_t i = 1 ; i < beams.size() ; ++i) {
  8573. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  8574. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  8575. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  8576. common_prefix_length = j;
  8577. break;
  8578. }
  8579. }
  8580. }
  8581. return common_prefix_length;
  8582. }
  8583. // Construct beams_state to send back to caller via the callback function.
  8584. // Side effect: set common_prefix_length = find_common_prefix_length();
  8585. llama_beams_state get_beams_state(const bool last_call) {
  8586. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8587. beam_views[i] = beams[i].view();
  8588. }
  8589. common_prefix_length = find_common_prefix_length();
  8590. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  8591. }
  8592. // Loop:
  8593. // * while i < n_predict, AND
  8594. // * any of the beams have not yet reached end-of-beam (eob), AND
  8595. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  8596. // (since all other beam probabilities can only decrease)
  8597. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  8598. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  8599. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  8600. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  8601. !beams[top_beam_index()].eob ; ++i) {
  8602. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  8603. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  8604. if (common_prefix_length) {
  8605. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  8606. n_past += common_prefix_length;
  8607. }
  8608. // Zero-out next_beam probabilities to place them last in following min-heap.
  8609. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  8610. for (llama_beam & beam : beams) {
  8611. beam.shift_tokens(common_prefix_length);
  8612. fill_next_beams_by_top_probabilities(beam);
  8613. }
  8614. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  8615. beams.swap(next_beams);
  8616. renormalize_beam_probabilities(beams);
  8617. }
  8618. collapse_beams(top_beam_index());
  8619. callback(callback_data, get_beams_state(true));
  8620. }
  8621. // As beams grow, the cumulative probabilities decrease.
  8622. // Renormalize them to avoid floating point underflow.
  8623. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  8624. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  8625. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  8626. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  8627. }
  8628. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  8629. size_t top_beam_index() {
  8630. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  8631. }
  8632. // Copy (p,eob) for each beam which may have been changed by the callback.
  8633. void update_beams_from_beam_views() {
  8634. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8635. beams[i].p = beam_views[i].p;
  8636. beams[i].eob = beam_views[i].eob;
  8637. }
  8638. }
  8639. };
  8640. void llama_beam_search(llama_context * ctx,
  8641. llama_beam_search_callback_fn_t callback, void * callback_data,
  8642. size_t n_beams, int n_past, int n_predict) {
  8643. assert(ctx);
  8644. const int64_t t_start_sample_us = ggml_time_us();
  8645. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  8646. beam_search_data.loop(callback, callback_data);
  8647. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8648. ctx->n_sample++;
  8649. }
  8650. //
  8651. // quantization
  8652. //
  8653. struct quantize_state_internal {
  8654. const llama_model & model;
  8655. const llama_model_quantize_params * params;
  8656. int n_attention_wv = 0;
  8657. int n_ffn_down = 0;
  8658. int n_ffn_gate = 0;
  8659. int n_ffn_up = 0;
  8660. int i_attention_wv = 0;
  8661. int i_ffn_down = 0;
  8662. int i_ffn_gate = 0;
  8663. int i_ffn_up = 0;
  8664. int n_k_quantized = 0;
  8665. int n_fallback = 0;
  8666. bool has_imatrix = false;
  8667. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  8668. : model(model)
  8669. , params(params)
  8670. {}
  8671. };
  8672. static void llama_convert_tensor_internal(
  8673. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  8674. const size_t nelements, const int nthread
  8675. ) {
  8676. if (output.size() < nelements) {
  8677. output.resize(nelements);
  8678. }
  8679. float * f32_output = (float *) output.data();
  8680. ggml_type_traits_t qtype;
  8681. if (ggml_is_quantized(tensor->type)) {
  8682. qtype = ggml_internal_get_type_traits(tensor->type);
  8683. if (qtype.to_float == NULL) {
  8684. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  8685. }
  8686. } else if (tensor->type != GGML_TYPE_F16) {
  8687. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  8688. }
  8689. if (nthread < 2) {
  8690. if (tensor->type == GGML_TYPE_F16) {
  8691. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  8692. } else if (ggml_is_quantized(tensor->type)) {
  8693. qtype.to_float(tensor->data, f32_output, nelements);
  8694. } else {
  8695. GGML_ASSERT(false); // unreachable
  8696. }
  8697. return;
  8698. }
  8699. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  8700. size_t block_size_bytes = ggml_type_size(tensor->type);
  8701. GGML_ASSERT(nelements % block_size == 0);
  8702. size_t nblocks = nelements / block_size;
  8703. size_t blocks_per_thread = nblocks / nthread;
  8704. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  8705. size_t in_buff_offs = 0;
  8706. size_t out_buff_offs = 0;
  8707. for (int tnum = 0; tnum < nthread; tnum++) {
  8708. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  8709. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  8710. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  8711. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  8712. if (typ == GGML_TYPE_F16) {
  8713. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  8714. } else {
  8715. qtype.to_float(inbuf, outbuf, nels);
  8716. }
  8717. };
  8718. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  8719. in_buff_offs += thr_block_bytes;
  8720. out_buff_offs += thr_elems;
  8721. }
  8722. for (auto & w : workers) { w.join(); }
  8723. workers.clear();
  8724. }
  8725. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  8726. const std::string name = ggml_get_name(tensor);
  8727. // TODO: avoid hardcoded tensor names - use the TN_* constants
  8728. const llm_arch arch = qs.model.arch;
  8729. const auto tn = LLM_TN(arch);
  8730. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  8731. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  8732. };
  8733. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  8734. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  8735. if (n_expert > 1) {
  8736. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  8737. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  8738. // for getting the current layer as I initially thought, and we need to resort to parsing the
  8739. // tensor name.
  8740. n_layer /= n_expert;
  8741. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  8742. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  8743. }
  8744. if (i_layer < 0 || i_layer >= n_layer) {
  8745. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  8746. }
  8747. }
  8748. return std::make_pair(i_layer, n_layer);
  8749. };
  8750. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  8751. // with the quantization of the output tensor
  8752. if (name == tn(LLM_TENSOR_OUTPUT, "weight") ||
  8753. (LLM_TENSOR_NAMES.at(arch).find(LLM_TENSOR_OUTPUT) == LLM_TENSOR_NAMES.at(arch).end() && name == "token_embd.weight")) {
  8754. int nx = tensor->ne[0];
  8755. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  8756. new_type = GGML_TYPE_Q8_0;
  8757. }
  8758. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8759. new_type = GGML_TYPE_Q5_K;
  8760. }
  8761. else if (new_type != GGML_TYPE_Q8_0) {
  8762. new_type = GGML_TYPE_Q6_K;
  8763. }
  8764. } else if (name == "token_embd.weight") {
  8765. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8766. new_type = GGML_TYPE_Q2_K;
  8767. }
  8768. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8769. new_type = GGML_TYPE_Q4_K;
  8770. }
  8771. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8772. if (name.find("attn_v.weight") != std::string::npos) {
  8773. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  8774. else new_type = GGML_TYPE_Q2_K;
  8775. ++qs.i_attention_wv;
  8776. }
  8777. else if (name.find("ffn_down") != std::string::npos) {
  8778. if (qs.i_ffn_down < qs.n_ffn_down/8) new_type = GGML_TYPE_Q2_K;
  8779. ++qs.i_ffn_down;
  8780. }
  8781. else if (name.find("attn_output.weight") != std::string::npos) {
  8782. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  8783. }
  8784. } else if (name.find("attn_v.weight") != std::string::npos) {
  8785. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  8786. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8787. }
  8788. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  8789. new_type = GGML_TYPE_Q4_K;
  8790. }
  8791. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8792. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_Q3_K : GGML_TYPE_IQ3_XXS;
  8793. }
  8794. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  8795. new_type = GGML_TYPE_Q4_K;
  8796. }
  8797. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  8798. new_type = GGML_TYPE_Q4_K;
  8799. }
  8800. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8801. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8802. }
  8803. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  8804. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL && qs.model.hparams.n_gqa() >= 4) {
  8805. new_type = GGML_TYPE_Q5_K;
  8806. }
  8807. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  8808. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  8809. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  8810. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  8811. (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;
  8812. if (qs.model.type == MODEL_70B) {
  8813. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  8814. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  8815. // nearly negligible increase in model size by quantizing this tensor with more bits:
  8816. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  8817. }
  8818. if (qs.model.hparams.n_expert == 8) {
  8819. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8820. // TODO: explore better strategies
  8821. new_type = GGML_TYPE_Q8_0;
  8822. }
  8823. ++qs.i_attention_wv;
  8824. } else if (name.find("attn_k.weight") != std::string::npos) {
  8825. if (qs.model.hparams.n_expert == 8) {
  8826. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8827. // TODO: explore better strategies
  8828. new_type = GGML_TYPE_Q8_0;
  8829. }
  8830. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  8831. new_type = GGML_TYPE_IQ3_XXS;
  8832. }
  8833. } else if (name.find("attn_q.weight") != std::string::npos) {
  8834. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  8835. new_type = GGML_TYPE_IQ3_XXS;
  8836. }
  8837. } else if (name.find("ffn_down") != std::string::npos) {
  8838. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  8839. int i_layer = info.first, n_layer = info.second;
  8840. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8841. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  8842. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  8843. }
  8844. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  8845. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8846. }
  8847. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8848. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  8849. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  8850. : GGML_TYPE_Q3_K;
  8851. }
  8852. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  8853. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  8854. new_type = GGML_TYPE_Q4_K;
  8855. }
  8856. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  8857. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  8858. }
  8859. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  8860. if (arch == LLM_ARCH_FALCON) {
  8861. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  8862. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8863. } else {
  8864. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  8865. }
  8866. }
  8867. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL && !qs.has_imatrix) {
  8868. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q5_K;
  8869. }
  8870. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  8871. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  8872. new_type = GGML_TYPE_Q5_K;
  8873. }
  8874. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  8875. && qs.has_imatrix && i_layer < n_layer/8) {
  8876. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  8877. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  8878. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  8879. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  8880. }
  8881. ++qs.i_ffn_down;
  8882. } else if (name.find("attn_output.weight") != std::string::npos) {
  8883. if (arch != LLM_ARCH_FALCON) {
  8884. if (qs.model.hparams.n_expert == 8) {
  8885. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  8886. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  8887. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  8888. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  8889. new_type = GGML_TYPE_Q5_K;
  8890. }
  8891. } else {
  8892. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  8893. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_Q3_K;
  8894. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  8895. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  8896. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  8897. }
  8898. } else {
  8899. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  8900. }
  8901. }
  8902. else if (name.find("attn_qkv.weight") != std::string::npos) {
  8903. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  8904. new_type = GGML_TYPE_Q4_K;
  8905. }
  8906. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  8907. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  8908. }
  8909. else if (name.find("ffn_gate") != std::string::npos) {
  8910. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  8911. int i_layer = info.first, n_layer = info.second;
  8912. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  8913. new_type = GGML_TYPE_IQ3_XXS;
  8914. }
  8915. ++qs.i_ffn_gate;
  8916. }
  8917. else if (name.find("ffn_up") != std::string::npos) {
  8918. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  8919. int i_layer = info.first, n_layer = info.second;
  8920. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  8921. new_type = GGML_TYPE_IQ3_XXS;
  8922. }
  8923. ++qs.i_ffn_up;
  8924. }
  8925. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8926. //}
  8927. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  8928. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  8929. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  8930. //}
  8931. // This can be used to reduce the size of the Q5_K_S model.
  8932. // The associated PPL increase is fully in line with the size reduction
  8933. //else {
  8934. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  8935. //}
  8936. bool convert_incompatible_tensor = false;
  8937. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  8938. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  8939. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS ||
  8940. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  8941. int nx = tensor->ne[0];
  8942. int ny = tensor->ne[1];
  8943. if (nx % QK_K != 0) {
  8944. 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));
  8945. convert_incompatible_tensor = true;
  8946. } else {
  8947. ++qs.n_k_quantized;
  8948. }
  8949. }
  8950. if (convert_incompatible_tensor) {
  8951. switch (new_type) {
  8952. case GGML_TYPE_IQ2_XXS:
  8953. case GGML_TYPE_IQ2_XS:
  8954. case GGML_TYPE_IQ3_XXS:
  8955. case GGML_TYPE_IQ3_S:
  8956. case GGML_TYPE_IQ1_S:
  8957. case GGML_TYPE_Q2_K:
  8958. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_IQ4_NL; break;
  8959. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  8960. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  8961. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  8962. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  8963. }
  8964. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  8965. ++qs.n_fallback;
  8966. }
  8967. return new_type;
  8968. }
  8969. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  8970. ggml_type quantized_type;
  8971. llama_ftype ftype = params->ftype;
  8972. switch (params->ftype) {
  8973. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  8974. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  8975. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  8976. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  8977. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  8978. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  8979. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  8980. // K-quants
  8981. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  8982. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  8983. case LLAMA_FTYPE_MOSTLY_Q3_K_XS: quantized_type = GGML_TYPE_IQ3_S; break;
  8984. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  8985. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  8986. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  8987. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  8988. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  8989. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  8990. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  8991. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  8992. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: quantized_type = GGML_TYPE_IQ2_XXS; break;
  8993. case LLAMA_FTYPE_MOSTLY_IQ2_XS: quantized_type = GGML_TYPE_IQ2_XS; break;
  8994. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: quantized_type = GGML_TYPE_IQ3_XXS; break;
  8995. case LLAMA_FTYPE_MOSTLY_IQ1_S: quantized_type = GGML_TYPE_IQ1_S; break;
  8996. case LLAMA_FTYPE_MOSTLY_IQ4_NL: quantized_type = GGML_TYPE_IQ4_NL; break;
  8997. case LLAMA_FTYPE_MOSTLY_IQ3_S: quantized_type = GGML_TYPE_IQ3_S; break;
  8998. case LLAMA_FTYPE_MOSTLY_IQ3_M: quantized_type = GGML_TYPE_IQ3_S; break;
  8999. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  9000. }
  9001. int nthread = params->nthread;
  9002. if (nthread <= 0) {
  9003. nthread = std::thread::hardware_concurrency();
  9004. }
  9005. // mmap consistently increases speed Linux, and also increases speed on Windows with
  9006. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  9007. #if defined(__linux__) || defined(_WIN32)
  9008. constexpr bool use_mmap = true;
  9009. #else
  9010. constexpr bool use_mmap = false;
  9011. #endif
  9012. llama_model_loader ml(fname_inp, use_mmap, NULL);
  9013. ml.init_mapping(false); // no prefetching?
  9014. llama_model model;
  9015. llm_load_arch(ml, model);
  9016. llm_load_hparams(ml, model);
  9017. struct quantize_state_internal qs(model, params);
  9018. if (params->only_copy) {
  9019. ftype = model.ftype;
  9020. }
  9021. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  9022. if (params->imatrix) {
  9023. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  9024. if (imatrix_data) {
  9025. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  9026. qs.has_imatrix = true;
  9027. }
  9028. }
  9029. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  9030. struct gguf_context * ctx_out = gguf_init_empty();
  9031. // copy the KV pairs from the input file
  9032. gguf_set_kv (ctx_out, ml.ctx_gguf);
  9033. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  9034. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  9035. for (int i = 0; i < ml.n_tensors; ++i) {
  9036. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9037. const std::string name = ggml_get_name(meta);
  9038. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9039. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  9040. ++qs.n_attention_wv;
  9041. }
  9042. else if (name.find("ffn_down") != std::string::npos) {
  9043. ++qs.n_ffn_down;
  9044. }
  9045. else if (name.find("ffn_gate") != std::string::npos) {
  9046. ++qs.n_ffn_gate;
  9047. }
  9048. else if (name.find("ffn_up") != std::string::npos) {
  9049. ++qs.n_ffn_up;
  9050. }
  9051. }
  9052. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  9053. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  9054. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  9055. }
  9056. size_t total_size_org = 0;
  9057. size_t total_size_new = 0;
  9058. std::vector<int64_t> hist_all(1 << 4, 0);
  9059. std::vector<std::thread> workers;
  9060. workers.reserve(nthread);
  9061. std::mutex mutex;
  9062. int idx = 0;
  9063. std::vector<no_init<uint8_t>> read_data;
  9064. std::vector<no_init<uint8_t>> work;
  9065. std::vector<no_init<float>> f32_conv_buf;
  9066. // populate the original tensors so we get an initial meta data
  9067. for (int i = 0; i < ml.n_tensors; ++i) {
  9068. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9069. gguf_add_tensor(ctx_out, meta);
  9070. }
  9071. std::ofstream fout(fname_out, std::ios::binary);
  9072. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  9073. const size_t meta_size = gguf_get_meta_size(ctx_out);
  9074. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  9075. // placeholder for the meta data
  9076. ::zeros(fout, meta_size);
  9077. for (int i = 0; i < ml.n_tensors; ++i) {
  9078. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  9079. const std::string name = ggml_get_name(tensor);
  9080. if (!ml.use_mmap) {
  9081. if (read_data.size() < ggml_nbytes(tensor)) {
  9082. read_data.resize(ggml_nbytes(tensor));
  9083. }
  9084. tensor->data = read_data.data();
  9085. }
  9086. ml.load_data_for(tensor);
  9087. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  9088. ++idx, ml.n_tensors,
  9089. ggml_get_name(tensor),
  9090. llama_format_tensor_shape(tensor).c_str(),
  9091. ggml_type_name(tensor->type));
  9092. // This used to be a regex, but <regex> has an extreme cost to compile times.
  9093. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  9094. // quantize only 2D tensors
  9095. quantize &= (ggml_n_dims(tensor) == 2);
  9096. quantize &= params->quantize_output_tensor || name != "output.weight";
  9097. quantize &= !params->only_copy;
  9098. // do not quantize expert gating tensors
  9099. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_FFN_GATE_INP, "weight");
  9100. // do not quantize positional embeddings and token types (BERT)
  9101. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  9102. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  9103. enum ggml_type new_type;
  9104. void * new_data;
  9105. size_t new_size;
  9106. if (quantize) {
  9107. new_type = quantized_type;
  9108. if (!params->pure) {
  9109. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  9110. }
  9111. // If we've decided to quantize to the same type the tensor is already
  9112. // in then there's nothing to do.
  9113. quantize = tensor->type != new_type;
  9114. }
  9115. if (!quantize) {
  9116. new_type = tensor->type;
  9117. new_data = tensor->data;
  9118. new_size = ggml_nbytes(tensor);
  9119. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  9120. } else {
  9121. const size_t nelements = ggml_nelements(tensor);
  9122. const float * imatrix = nullptr;
  9123. if (imatrix_data) {
  9124. auto it = imatrix_data->find(tensor->name);
  9125. if (it == imatrix_data->end()) {
  9126. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  9127. } else {
  9128. if (it->second.size() == (size_t)tensor->ne[0]) {
  9129. imatrix = it->second.data();
  9130. } else {
  9131. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  9132. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  9133. }
  9134. }
  9135. }
  9136. if ((new_type == GGML_TYPE_IQ2_XXS ||
  9137. new_type == GGML_TYPE_IQ2_XS ||
  9138. new_type == GGML_TYPE_IQ1_S ||
  9139. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  9140. LLAMA_LOG_ERROR("\n\n============================================================\n");
  9141. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  9142. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  9143. LLAMA_LOG_ERROR("============================================================\n\n");
  9144. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  9145. }
  9146. float * f32_data;
  9147. if (tensor->type == GGML_TYPE_F32) {
  9148. f32_data = (float *) tensor->data;
  9149. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  9150. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  9151. } else {
  9152. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  9153. f32_data = (float *) f32_conv_buf.data();
  9154. }
  9155. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  9156. fflush(stdout);
  9157. if (work.size() < nelements * 4) {
  9158. work.resize(nelements * 4); // upper bound on size
  9159. }
  9160. new_data = work.data();
  9161. std::array<int64_t, 1 << 4> hist_cur = {};
  9162. const int n_per_row = tensor->ne[0];
  9163. const int nrows = nelements / n_per_row;
  9164. static const int min_chunk_size = 32 * 512;
  9165. 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);
  9166. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  9167. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  9168. if (nthread_use < 2) {
  9169. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  9170. } else {
  9171. int counter = 0;
  9172. new_size = 0;
  9173. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  9174. nrows, n_per_row, imatrix]() {
  9175. std::array<int64_t, 1 << 4> local_hist = {};
  9176. const int nrows_per_chunk = chunk_size / n_per_row;
  9177. size_t local_size = 0;
  9178. while (true) {
  9179. std::unique_lock<std::mutex> lock(mutex);
  9180. int first_row = counter; counter += nrows_per_chunk;
  9181. if (first_row >= nrows) {
  9182. if (local_size > 0) {
  9183. for (int j=0; j<int(local_hist.size()); ++j) {
  9184. hist_cur[j] += local_hist[j];
  9185. }
  9186. new_size += local_size;
  9187. }
  9188. break;
  9189. }
  9190. lock.unlock();
  9191. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  9192. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  9193. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  9194. }
  9195. };
  9196. for (int it = 0; it < nthread_use - 1; ++it) {
  9197. workers.emplace_back(compute);
  9198. }
  9199. compute();
  9200. for (auto & w : workers) { w.join(); }
  9201. workers.clear();
  9202. }
  9203. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  9204. int64_t tot_count = 0;
  9205. for (size_t i = 0; i < hist_cur.size(); i++) {
  9206. hist_all[i] += hist_cur[i];
  9207. tot_count += hist_cur[i];
  9208. }
  9209. if (tot_count > 0) {
  9210. LLAMA_LOG_INFO(" | hist: ");
  9211. for (size_t i = 0; i < hist_cur.size(); i++) {
  9212. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  9213. }
  9214. }
  9215. LLAMA_LOG_INFO("\n");
  9216. }
  9217. total_size_org += ggml_nbytes(tensor);
  9218. total_size_new += new_size;
  9219. // update the gguf meta data as we go
  9220. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  9221. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  9222. // write tensor data + padding
  9223. fout.write((const char *) new_data, new_size);
  9224. zeros(fout, GGML_PAD(new_size, align) - new_size);
  9225. }
  9226. // go back to beginning of file and write the updated meta data
  9227. {
  9228. fout.seekp(0);
  9229. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  9230. gguf_get_meta_data(ctx_out, data.data());
  9231. fout.write((const char *) data.data(), data.size());
  9232. }
  9233. fout.close();
  9234. gguf_free(ctx_out);
  9235. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  9236. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  9237. // print histogram for all tensors
  9238. {
  9239. int64_t sum_all = 0;
  9240. for (size_t i = 0; i < hist_all.size(); i++) {
  9241. sum_all += hist_all[i];
  9242. }
  9243. if (sum_all > 0) {
  9244. LLAMA_LOG_INFO("%s: hist: ", __func__);
  9245. for (size_t i = 0; i < hist_all.size(); i++) {
  9246. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  9247. }
  9248. LLAMA_LOG_INFO("\n");
  9249. }
  9250. }
  9251. if (qs.n_fallback > 0) {
  9252. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  9253. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  9254. }
  9255. }
  9256. static int llama_apply_lora_from_file_internal(
  9257. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  9258. ) {
  9259. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  9260. const int64_t t_start_lora_us = ggml_time_us();
  9261. llama_file fin(path_lora, "rb");
  9262. // verify magic and version
  9263. {
  9264. uint32_t magic = fin.read_u32();
  9265. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  9266. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  9267. return 1;
  9268. }
  9269. uint32_t format_version = fin.read_u32();
  9270. if (format_version != 1) {
  9271. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  9272. return 1;
  9273. }
  9274. }
  9275. int32_t lora_r = fin.read_u32();
  9276. int32_t lora_alpha = fin.read_u32();
  9277. float scaling = scale * (float)lora_alpha / (float)lora_r;
  9278. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  9279. // load base model
  9280. std::unique_ptr<llama_model_loader> ml;
  9281. if (path_base_model) {
  9282. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  9283. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  9284. ml->init_mapping(/*prefetch*/ false); // no prefetching
  9285. }
  9286. struct tensor_meta {
  9287. std::string name;
  9288. ggml_type type;
  9289. int32_t ne[2];
  9290. size_t offset;
  9291. };
  9292. std::map<std::string, tensor_meta> tensor_meta_map;
  9293. // load all tensor meta
  9294. while (true) {
  9295. if (fin.tell() == fin.size) {
  9296. // eof
  9297. break;
  9298. }
  9299. int32_t n_dims;
  9300. int32_t name_len;
  9301. int32_t ftype;
  9302. fin.read_raw(&n_dims, sizeof(n_dims));
  9303. fin.read_raw(&name_len, sizeof(name_len));
  9304. fin.read_raw(&ftype, sizeof(ftype));
  9305. if (n_dims != 1 && n_dims != 2) {
  9306. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  9307. return 1;
  9308. }
  9309. int32_t ne[2] = { 1, 1 };
  9310. for (int i = 0; i < n_dims; ++i) {
  9311. fin.read_raw(&ne[i], sizeof(ne[i]));
  9312. }
  9313. std::string name;
  9314. {
  9315. GGML_ASSERT(name_len < GGML_MAX_NAME);
  9316. char buf[GGML_MAX_NAME];
  9317. fin.read_raw(buf, name_len);
  9318. name = std::string(buf, name_len);
  9319. }
  9320. // check for lora suffix
  9321. std::string lora_suffix;
  9322. if (name.length() > 6) {
  9323. lora_suffix = name.substr(name.length() - 6);
  9324. }
  9325. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  9326. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  9327. return 1;
  9328. }
  9329. // tensor type
  9330. ggml_type wtype;
  9331. switch (ftype) {
  9332. case 0: wtype = GGML_TYPE_F32; break;
  9333. case 1: wtype = GGML_TYPE_F16; break;
  9334. default:
  9335. {
  9336. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  9337. __func__, ftype);
  9338. return 1;
  9339. }
  9340. }
  9341. // data offset
  9342. size_t offset = fin.tell();
  9343. offset = (offset + 31) & -32;
  9344. // skip tensor data
  9345. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  9346. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  9347. }
  9348. bool warned = false;
  9349. int n_tensors = 0;
  9350. // apply
  9351. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  9352. if (backend_cpu == nullptr) {
  9353. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  9354. return 1;
  9355. }
  9356. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  9357. std::vector<no_init<uint8_t>> read_buf;
  9358. for (const auto & it : model.tensors_by_name) {
  9359. const std::string & base_name = it.first;
  9360. ggml_tensor * model_t = it.second;
  9361. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  9362. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  9363. continue;
  9364. }
  9365. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  9366. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  9367. ggml_init_params lora_init_params = {
  9368. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  9369. /* .mem_buffer */ nullptr,
  9370. /* .no_alloc */ true,
  9371. };
  9372. ggml_context * lora_ctx = ggml_init(lora_init_params);
  9373. if (lora_ctx == nullptr) {
  9374. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  9375. ggml_backend_free(backend_cpu);
  9376. return 1;
  9377. }
  9378. // create tensors
  9379. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  9380. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  9381. ggml_set_name(loraA, metaA.name.c_str());
  9382. ggml_set_name(loraB, metaB.name.c_str());
  9383. ggml_tensor * base_t;
  9384. if (ml) {
  9385. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  9386. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  9387. return 1;
  9388. }
  9389. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  9390. } else {
  9391. base_t = ggml_dup_tensor(lora_ctx, model_t);
  9392. }
  9393. ggml_set_name(base_t, base_name.c_str());
  9394. // allocate in backend buffer
  9395. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9396. if (lora_buf == nullptr) {
  9397. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  9398. return 1;
  9399. }
  9400. // load tensor data
  9401. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  9402. read_buf.resize(ggml_nbytes(tensor));
  9403. fin.seek(tensor_meta.offset, SEEK_SET);
  9404. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  9405. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  9406. };
  9407. load_tensor(metaA, loraA);
  9408. load_tensor(metaB, loraB);
  9409. // load base model tensor data
  9410. if (ml) {
  9411. ml->load_data_for(base_t);
  9412. } else {
  9413. ggml_backend_tensor_copy(model_t, base_t);
  9414. }
  9415. if (ggml_is_quantized(base_t->type) && !warned) {
  9416. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  9417. "use a f16 or f32 base model with --lora-base\n", __func__);
  9418. warned = true;
  9419. }
  9420. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  9421. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  9422. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  9423. ggml_free(lora_ctx);
  9424. ggml_backend_buffer_free(lora_buf);
  9425. ggml_backend_free(backend_cpu);
  9426. return 1;
  9427. }
  9428. auto build_lora_graph = [&]() {
  9429. // w = w + BA*s
  9430. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  9431. ggml_set_name(BA, "BA");
  9432. if (scaling != 1.0f) {
  9433. BA = ggml_scale(lora_ctx, BA, scaling);
  9434. ggml_set_name(BA, "BA_scaled");
  9435. }
  9436. ggml_tensor * r;
  9437. r = ggml_add_inplace(lora_ctx, base_t, BA);
  9438. ggml_set_name(r, "r_add");
  9439. if (base_t->type != model_t->type) {
  9440. // convert the result to the model type
  9441. r = ggml_cast(lora_ctx, r, model_t->type);
  9442. ggml_set_name(r, "r_cast");
  9443. }
  9444. return r;
  9445. };
  9446. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  9447. ggml_tensor * r = build_lora_graph();
  9448. ggml_build_forward_expand(gf, r);
  9449. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9450. if (graph_buf == nullptr) {
  9451. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  9452. ggml_free(lora_ctx);
  9453. ggml_backend_buffer_free(lora_buf);
  9454. ggml_backend_free(backend_cpu);
  9455. return 1;
  9456. }
  9457. ggml_backend_graph_compute(backend_cpu, gf);
  9458. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  9459. #if 0
  9460. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  9461. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  9462. // sched compute
  9463. ggml_build_forward_expand(gf, build_graph());
  9464. ggml_backend_sched_init_measure(sched, gf);
  9465. // create the graph again, since the previous one was destroyed by the measure
  9466. ggml_graph_clear(gf);
  9467. ggml_build_forward_expand(gf, build_graph());
  9468. ggml_backend_sched_graph_compute(sched, gf);
  9469. ggml_backend_sched_free(sched);
  9470. #endif
  9471. ggml_backend_buffer_free(lora_buf);
  9472. ggml_backend_buffer_free(graph_buf);
  9473. ggml_free(lora_ctx);
  9474. n_tensors++;
  9475. if (n_tensors % 4 == 0) {
  9476. LLAMA_LOG_INFO(".");
  9477. }
  9478. }
  9479. ggml_backend_free(backend_cpu);
  9480. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  9481. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  9482. return 0;
  9483. }
  9484. //
  9485. // interface implementation
  9486. //
  9487. struct llama_model_params llama_model_default_params() {
  9488. struct llama_model_params result = {
  9489. /*.n_gpu_layers =*/ 0,
  9490. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  9491. /*.main_gpu =*/ 0,
  9492. /*.tensor_split =*/ nullptr,
  9493. /*.progress_callback =*/ nullptr,
  9494. /*.progress_callback_user_data =*/ nullptr,
  9495. /*.kv_overrides =*/ nullptr,
  9496. /*.vocab_only =*/ false,
  9497. /*.use_mmap =*/ true,
  9498. /*.use_mlock =*/ false,
  9499. };
  9500. #ifdef GGML_USE_METAL
  9501. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  9502. result.n_gpu_layers = 999;
  9503. #endif
  9504. return result;
  9505. }
  9506. struct llama_context_params llama_context_default_params() {
  9507. struct llama_context_params result = {
  9508. /*.seed =*/ LLAMA_DEFAULT_SEED,
  9509. /*.n_ctx =*/ 512,
  9510. /*.n_batch =*/ 512,
  9511. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  9512. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  9513. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  9514. /*.rope_freq_base =*/ 0.0f,
  9515. /*.rope_freq_scale =*/ 0.0f,
  9516. /*.yarn_ext_factor =*/ -1.0f,
  9517. /*.yarn_attn_factor =*/ 1.0f,
  9518. /*.yarn_beta_fast =*/ 32.0f,
  9519. /*.yarn_beta_slow =*/ 1.0f,
  9520. /*.yarn_orig_ctx =*/ 0,
  9521. /*.cb_eval =*/ nullptr,
  9522. /*.cb_eval_user_data =*/ nullptr,
  9523. /*.type_k =*/ GGML_TYPE_F16,
  9524. /*.type_v =*/ GGML_TYPE_F16,
  9525. /*.mul_mat_q =*/ true,
  9526. /*.logits_all =*/ false,
  9527. /*.embedding =*/ false,
  9528. /*.offload_kqv =*/ true,
  9529. /*.do_pooling =*/ true,
  9530. };
  9531. return result;
  9532. }
  9533. struct llama_model_quantize_params llama_model_quantize_default_params() {
  9534. struct llama_model_quantize_params result = {
  9535. /*.nthread =*/ 0,
  9536. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  9537. /*.allow_requantize =*/ false,
  9538. /*.quantize_output_tensor =*/ true,
  9539. /*.only_copy =*/ false,
  9540. /*.pure =*/ false,
  9541. /*.imatrix =*/ nullptr,
  9542. };
  9543. return result;
  9544. }
  9545. size_t llama_max_devices(void) {
  9546. #if defined(GGML_USE_METAL)
  9547. return 1;
  9548. #elif defined(GGML_USE_CUBLAS)
  9549. return GGML_CUDA_MAX_DEVICES;
  9550. #elif defined(GGML_USE_SYCL)
  9551. return GGML_SYCL_MAX_DEVICES;
  9552. #elif defined(GGML_USE_VULKAN)
  9553. return GGML_VK_MAX_DEVICES;
  9554. #else
  9555. return 1;
  9556. #endif
  9557. }
  9558. bool llama_supports_mmap(void) {
  9559. return llama_mmap::SUPPORTED;
  9560. }
  9561. bool llama_supports_mlock(void) {
  9562. return llama_mlock::SUPPORTED;
  9563. }
  9564. bool llama_supports_gpu_offload(void) {
  9565. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  9566. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  9567. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  9568. return true;
  9569. #else
  9570. return false;
  9571. #endif
  9572. }
  9573. // deprecated:
  9574. bool llama_mmap_supported(void) {
  9575. return llama_supports_mmap();
  9576. }
  9577. bool llama_mlock_supported(void) {
  9578. return llama_supports_mlock();
  9579. }
  9580. void llama_backend_init(void) {
  9581. ggml_time_init();
  9582. // needed to initialize f16 tables
  9583. {
  9584. struct ggml_init_params params = { 0, NULL, false };
  9585. struct ggml_context * ctx = ggml_init(params);
  9586. ggml_free(ctx);
  9587. }
  9588. #ifdef GGML_USE_MPI
  9589. ggml_mpi_backend_init();
  9590. #endif
  9591. }
  9592. void llama_numa_init(enum ggml_numa_strategy numa) {
  9593. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  9594. ggml_numa_init(numa);
  9595. }
  9596. }
  9597. void llama_backend_free(void) {
  9598. #ifdef GGML_USE_MPI
  9599. ggml_mpi_backend_free();
  9600. #endif
  9601. ggml_quantize_free();
  9602. }
  9603. int64_t llama_time_us(void) {
  9604. return ggml_time_us();
  9605. }
  9606. struct llama_model * llama_load_model_from_file(
  9607. const char * path_model,
  9608. struct llama_model_params params) {
  9609. ggml_time_init();
  9610. llama_model * model = new llama_model;
  9611. unsigned cur_percentage = 0;
  9612. if (params.progress_callback == NULL) {
  9613. params.progress_callback_user_data = &cur_percentage;
  9614. params.progress_callback = [](float progress, void * ctx) {
  9615. unsigned * cur_percentage_p = (unsigned *) ctx;
  9616. unsigned percentage = (unsigned) (100 * progress);
  9617. while (percentage > *cur_percentage_p) {
  9618. *cur_percentage_p = percentage;
  9619. LLAMA_LOG_INFO(".");
  9620. if (percentage >= 100) {
  9621. LLAMA_LOG_INFO("\n");
  9622. }
  9623. }
  9624. return true;
  9625. };
  9626. }
  9627. int status = llama_model_load(path_model, *model, params);
  9628. GGML_ASSERT(status <= 0);
  9629. if (status < 0) {
  9630. if (status == -1) {
  9631. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  9632. } else if (status == -2) {
  9633. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  9634. }
  9635. delete model;
  9636. return nullptr;
  9637. }
  9638. return model;
  9639. }
  9640. void llama_free_model(struct llama_model * model) {
  9641. delete model;
  9642. }
  9643. struct llama_context * llama_new_context_with_model(
  9644. struct llama_model * model,
  9645. struct llama_context_params params) {
  9646. if (!model) {
  9647. return nullptr;
  9648. }
  9649. llama_context * ctx = new llama_context(*model);
  9650. const auto & hparams = model->hparams;
  9651. auto & cparams = ctx->cparams;
  9652. cparams.n_batch = params.n_batch;
  9653. cparams.n_threads = params.n_threads;
  9654. cparams.n_threads_batch = params.n_threads_batch;
  9655. cparams.yarn_ext_factor = params.yarn_ext_factor;
  9656. cparams.yarn_attn_factor = params.yarn_attn_factor;
  9657. cparams.yarn_beta_fast = params.yarn_beta_fast;
  9658. cparams.yarn_beta_slow = params.yarn_beta_slow;
  9659. cparams.mul_mat_q = params.mul_mat_q;
  9660. cparams.offload_kqv = params.offload_kqv;
  9661. cparams.do_pooling = params.do_pooling;
  9662. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  9663. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  9664. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  9665. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  9666. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  9667. hparams.n_ctx_train;
  9668. cparams.cb_eval = params.cb_eval;
  9669. cparams.cb_eval_user_data = params.cb_eval_user_data;
  9670. auto rope_scaling_type = params.rope_scaling_type;
  9671. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  9672. rope_scaling_type = hparams.rope_scaling_type_train;
  9673. }
  9674. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  9675. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  9676. }
  9677. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  9678. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  9679. }
  9680. if (params.seed == LLAMA_DEFAULT_SEED) {
  9681. params.seed = time(NULL);
  9682. }
  9683. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  9684. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  9685. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  9686. ctx->rng = std::mt19937(params.seed);
  9687. ctx->logits_all = params.logits_all;
  9688. const ggml_type type_k = params.type_k;
  9689. const ggml_type type_v = params.type_v;
  9690. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  9691. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  9692. if (!hparams.vocab_only) {
  9693. // initialize backends
  9694. #ifdef GGML_USE_METAL
  9695. if (model->n_gpu_layers > 0) {
  9696. ctx->backend_metal = ggml_backend_metal_init();
  9697. if (ctx->backend_metal == nullptr) {
  9698. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  9699. llama_free(ctx);
  9700. return nullptr;
  9701. }
  9702. ctx->backends.push_back(ctx->backend_metal);
  9703. }
  9704. #elif defined(GGML_USE_CUBLAS)
  9705. if (model->n_gpu_layers > 0) {
  9706. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  9707. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  9708. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  9709. if (backend == nullptr) {
  9710. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  9711. llama_free(ctx);
  9712. return nullptr;
  9713. }
  9714. ctx->backends.push_back(backend);
  9715. } else {
  9716. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  9717. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  9718. ggml_backend_t backend = ggml_backend_cuda_init(device);
  9719. if (backend == nullptr) {
  9720. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  9721. llama_free(ctx);
  9722. return nullptr;
  9723. }
  9724. ctx->backends.push_back(backend);
  9725. }
  9726. }
  9727. }
  9728. #elif defined(GGML_USE_VULKAN)
  9729. if (model->n_gpu_layers > 0) {
  9730. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  9731. ggml_backend_t backend = ggml_backend_vk_init(device);
  9732. if (backend == nullptr) {
  9733. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  9734. llama_free(ctx);
  9735. return nullptr;
  9736. }
  9737. ctx->backends.push_back(backend);
  9738. }
  9739. }
  9740. #elif defined(GGML_USE_SYCL)
  9741. if (model->n_gpu_layers > 0) {
  9742. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  9743. if (backend == nullptr) {
  9744. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  9745. llama_free(ctx);
  9746. return nullptr;
  9747. }
  9748. ctx->backends.push_back(backend);
  9749. }
  9750. #elif defined(GGML_USE_KOMPUTE)
  9751. if (model->n_gpu_layers > 0) {
  9752. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  9753. if (backend == nullptr) {
  9754. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  9755. llama_free(ctx);
  9756. return nullptr;
  9757. }
  9758. ctx->backends.push_back(backend);
  9759. }
  9760. #endif
  9761. ctx->backend_cpu = ggml_backend_cpu_init();
  9762. if (ctx->backend_cpu == nullptr) {
  9763. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  9764. llama_free(ctx);
  9765. return nullptr;
  9766. }
  9767. ctx->backends.push_back(ctx->backend_cpu);
  9768. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  9769. cparams.n_ctx, cparams.offload_kqv)) {
  9770. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  9771. llama_free(ctx);
  9772. return nullptr;
  9773. }
  9774. {
  9775. size_t memory_size_k = 0;
  9776. size_t memory_size_v = 0;
  9777. for (auto & k : ctx->kv_self.k_l) {
  9778. memory_size_k += ggml_nbytes(k);
  9779. }
  9780. for (auto & v : ctx->kv_self.v_l) {
  9781. memory_size_v += ggml_nbytes(v);
  9782. }
  9783. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  9784. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  9785. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  9786. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  9787. }
  9788. // resized during inference, reserve maximum
  9789. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  9790. if (params.embedding) {
  9791. ctx->embedding.resize(hparams.n_embd);
  9792. }
  9793. // graph inputs
  9794. {
  9795. ggml_init_params init_params = {
  9796. /* .mem_size */ ggml_tensor_overhead()*8,
  9797. /* .mem_buffer */ nullptr,
  9798. /* .no_alloc */ true,
  9799. };
  9800. ctx->ctx_input = ggml_init(init_params);
  9801. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9802. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  9803. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9804. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  9805. ctx->inp_KQ_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx);
  9806. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  9807. ctx->inp_mean = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_batch, cparams.n_batch);
  9808. ctx->inp_cls = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9809. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  9810. ggml_set_name(ctx->inp_embd, "inp_embd");
  9811. ggml_set_name(ctx->inp_pos, "inp_pos");
  9812. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  9813. ggml_set_name(ctx->inp_KQ_pos, "inp_KQ_pos");
  9814. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  9815. ggml_set_name(ctx->inp_mean, "inp_mean");
  9816. ggml_set_name(ctx->inp_cls, "inp_cls");
  9817. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  9818. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  9819. ggml_backend_buffer_name(ctx->buf_input),
  9820. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  9821. }
  9822. // scheduler and compute buffers
  9823. {
  9824. // buffer types used for the compute buffer of each backend
  9825. std::vector<ggml_backend_buffer_type_t> backend_buft;
  9826. for (auto * backend : ctx->backends) {
  9827. if (ggml_backend_is_cpu(backend)) {
  9828. // use host buffers for the CPU backend compute buffer
  9829. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  9830. } else {
  9831. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  9832. }
  9833. }
  9834. // buffer used to store the computation graph and the tensor meta data
  9835. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  9836. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  9837. // build worst-case graph
  9838. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  9839. int n_past = cparams.n_ctx - n_tokens;
  9840. 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
  9841. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  9842. // initialize scheduler with the worst-case graph
  9843. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  9844. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  9845. llama_free(ctx);
  9846. return nullptr;
  9847. }
  9848. for (size_t i = 0; i < ctx->backends.size(); i++) {
  9849. ggml_backend_t backend = ctx->backends[i];
  9850. ggml_backend_buffer_type_t buft = backend_buft[i];
  9851. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  9852. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  9853. ggml_backend_buft_name(buft),
  9854. size / 1024.0 / 1024.0);
  9855. }
  9856. // note: the number of splits during measure is higher than during inference due to the kv shift
  9857. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  9858. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  9859. }
  9860. }
  9861. #ifdef GGML_USE_MPI
  9862. ctx->ctx_mpi = ggml_mpi_init();
  9863. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  9864. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  9865. // TODO: needs fix after #3228
  9866. GGML_ASSERT(false && "not implemented");
  9867. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  9868. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  9869. llama_backend_free();
  9870. exit(1);
  9871. }
  9872. #endif
  9873. return ctx;
  9874. }
  9875. void llama_free(struct llama_context * ctx) {
  9876. delete ctx;
  9877. }
  9878. const llama_model * llama_get_model(const struct llama_context * ctx) {
  9879. return &ctx->model;
  9880. }
  9881. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  9882. return ctx->cparams.n_ctx;
  9883. }
  9884. uint32_t llama_n_batch(const struct llama_context * ctx) {
  9885. return ctx->cparams.n_batch;
  9886. }
  9887. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  9888. return model->vocab.type;
  9889. }
  9890. int32_t llama_n_vocab(const struct llama_model * model) {
  9891. return model->vocab.id_to_token.size();
  9892. }
  9893. int32_t llama_n_ctx_train(const struct llama_model * model) {
  9894. return model->hparams.n_ctx_train;
  9895. }
  9896. int32_t llama_n_embd(const struct llama_model * model) {
  9897. return model->hparams.n_embd;
  9898. }
  9899. float llama_rope_freq_scale_train(const struct llama_model * model) {
  9900. return model->hparams.rope_freq_scale_train;
  9901. }
  9902. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  9903. const auto & it = model->gguf_kv.find(key);
  9904. if (it == model->gguf_kv.end()) {
  9905. if (buf_size > 0) {
  9906. buf[0] = '\0';
  9907. }
  9908. return -1;
  9909. }
  9910. return snprintf(buf, buf_size, "%s", it->second.c_str());
  9911. }
  9912. int32_t llama_model_meta_count(const struct llama_model * model) {
  9913. return (int)model->gguf_kv.size();
  9914. }
  9915. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  9916. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  9917. if (buf_size > 0) {
  9918. buf[0] = '\0';
  9919. }
  9920. return -1;
  9921. }
  9922. auto it = model->gguf_kv.begin();
  9923. std::advance(it, i);
  9924. return snprintf(buf, buf_size, "%s", it->first.c_str());
  9925. }
  9926. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  9927. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  9928. if (buf_size > 0) {
  9929. buf[0] = '\0';
  9930. }
  9931. return -1;
  9932. }
  9933. auto it = model->gguf_kv.begin();
  9934. std::advance(it, i);
  9935. return snprintf(buf, buf_size, "%s", it->second.c_str());
  9936. }
  9937. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  9938. return snprintf(buf, buf_size, "%s %s %s",
  9939. llama_model_arch_name(model->arch),
  9940. llama_model_type_name(model->type),
  9941. llama_model_ftype_name(model->ftype).c_str());
  9942. }
  9943. uint64_t llama_model_size(const struct llama_model * model) {
  9944. uint64_t size = 0;
  9945. for (const auto & it : model->tensors_by_name) {
  9946. size += ggml_nbytes(it.second);
  9947. }
  9948. return size;
  9949. }
  9950. uint64_t llama_model_n_params(const struct llama_model * model) {
  9951. uint64_t nparams = 0;
  9952. for (const auto & it : model->tensors_by_name) {
  9953. nparams += ggml_nelements(it.second);
  9954. }
  9955. return nparams;
  9956. }
  9957. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  9958. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  9959. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  9960. return it.first == name;
  9961. });
  9962. if (it == model->tensors_by_name.end()) {
  9963. return nullptr;
  9964. }
  9965. return it->second;
  9966. }
  9967. uint32_t llama_model_quantize(
  9968. const char * fname_inp,
  9969. const char * fname_out,
  9970. const llama_model_quantize_params * params) {
  9971. try {
  9972. llama_model_quantize_internal(fname_inp, fname_out, params);
  9973. return 0;
  9974. } catch (const std::exception & err) {
  9975. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  9976. return 1;
  9977. }
  9978. }
  9979. 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) {
  9980. try {
  9981. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  9982. } catch (const std::exception & err) {
  9983. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9984. return 1;
  9985. }
  9986. }
  9987. 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) {
  9988. try {
  9989. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  9990. } catch (const std::exception & err) {
  9991. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9992. return 1;
  9993. }
  9994. }
  9995. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  9996. struct llama_kv_cache_view result = {
  9997. /*.n_cells = */ 0,
  9998. /*.n_max_seq = */ n_max_seq,
  9999. /*.token_count = */ 0,
  10000. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  10001. /*.max_contiguous = */ 0,
  10002. /*.max_contiguous_idx = */ -1,
  10003. /*.cells = */ nullptr,
  10004. /*.cells_sequences = */ nullptr,
  10005. };
  10006. return result;
  10007. }
  10008. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  10009. if (view->cells != nullptr) {
  10010. free(view->cells);
  10011. view->cells = nullptr;
  10012. }
  10013. if (view->cells_sequences != nullptr) {
  10014. free(view->cells_sequences);
  10015. view->cells_sequences = nullptr;
  10016. }
  10017. }
  10018. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  10019. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  10020. view->n_cells = int32_t(ctx->kv_self.size);
  10021. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  10022. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  10023. view->cells = (struct llama_kv_cache_view_cell *)p;
  10024. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  10025. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  10026. view->cells_sequences = (llama_seq_id *)p;
  10027. }
  10028. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  10029. llama_kv_cache_view_cell * c_curr = view->cells;
  10030. llama_seq_id * cs_curr = view->cells_sequences;
  10031. int32_t used_cells = 0;
  10032. int32_t token_count = 0;
  10033. int32_t curr_contig_idx = -1;
  10034. uint32_t max_contig = 0;
  10035. int32_t max_contig_idx = -1;
  10036. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  10037. const size_t curr_size = kv_cells[i].seq_id.size();
  10038. token_count += curr_size;
  10039. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  10040. if (curr_size > 0) {
  10041. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  10042. max_contig = i - curr_contig_idx;
  10043. max_contig_idx = curr_contig_idx;
  10044. }
  10045. curr_contig_idx = -1;
  10046. } else if (curr_contig_idx < 0) {
  10047. curr_contig_idx = i;
  10048. }
  10049. int seq_idx = 0;
  10050. for (const llama_seq_id it : kv_cells[i].seq_id) {
  10051. if (seq_idx >= view->n_max_seq) {
  10052. break;
  10053. }
  10054. cs_curr[seq_idx] = it;
  10055. seq_idx++;
  10056. }
  10057. if (seq_idx != 0) {
  10058. used_cells++;
  10059. }
  10060. for (; seq_idx < view->n_max_seq; seq_idx++) {
  10061. cs_curr[seq_idx] = -1;
  10062. }
  10063. }
  10064. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  10065. max_contig_idx = curr_contig_idx;
  10066. max_contig = kv_cells.size() - curr_contig_idx;
  10067. }
  10068. view->max_contiguous = max_contig;
  10069. view->max_contiguous_idx = max_contig_idx;
  10070. view->token_count = token_count;
  10071. view->used_cells = used_cells;
  10072. if (uint32_t(used_cells) != ctx->kv_self.used) {
  10073. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  10074. __func__, ctx->kv_self.used, used_cells);
  10075. }
  10076. }
  10077. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  10078. int result = 0;
  10079. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  10080. result += ctx->kv_self.cells[i].seq_id.size();
  10081. }
  10082. return result;
  10083. }
  10084. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  10085. return ctx->kv_self.used;
  10086. }
  10087. void llama_kv_cache_clear(struct llama_context * ctx) {
  10088. llama_kv_cache_clear(ctx->kv_self);
  10089. }
  10090. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  10091. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  10092. }
  10093. 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) {
  10094. if (seq_id_src == seq_id_dst) {
  10095. return;
  10096. }
  10097. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  10098. }
  10099. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  10100. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  10101. }
  10102. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  10103. if (delta == 0) {
  10104. return;
  10105. }
  10106. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  10107. }
  10108. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  10109. if (d == 1) {
  10110. return;
  10111. }
  10112. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  10113. }
  10114. // Returns the *maximum* size of the state
  10115. size_t llama_get_state_size(const struct llama_context * ctx) {
  10116. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  10117. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  10118. const size_t s_rng_size = sizeof(size_t);
  10119. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  10120. const size_t s_logits_size = sizeof(size_t);
  10121. // assume worst case for logits although only currently set ones are serialized
  10122. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  10123. const size_t s_embedding_size = sizeof(size_t);
  10124. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  10125. const size_t s_kv_size = sizeof(size_t);
  10126. const size_t s_kv_ntok = sizeof(int);
  10127. const size_t s_kv = ctx->kv_self.total_size();
  10128. const size_t s_total = (
  10129. + s_rng_size
  10130. + s_rng
  10131. + s_logits_size
  10132. + s_logits
  10133. + s_embedding_size
  10134. + s_embedding
  10135. + s_kv_size
  10136. + s_kv_ntok
  10137. + s_kv
  10138. );
  10139. return s_total;
  10140. }
  10141. // llama_context_data
  10142. struct llama_data_context {
  10143. virtual void write(const void * src, size_t size) = 0;
  10144. virtual size_t get_size_written() = 0;
  10145. virtual ~llama_data_context() = default;
  10146. };
  10147. struct llama_data_buffer_context : llama_data_context {
  10148. uint8_t * ptr;
  10149. size_t size_written = 0;
  10150. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  10151. void write(const void * src, size_t size) override {
  10152. memcpy(ptr, src, size);
  10153. ptr += size;
  10154. size_written += size;
  10155. }
  10156. size_t get_size_written() override {
  10157. return size_written;
  10158. }
  10159. };
  10160. struct llama_data_file_context : llama_data_context {
  10161. llama_file * file;
  10162. size_t size_written = 0;
  10163. llama_data_file_context(llama_file * f) : file(f) {}
  10164. void write(const void * src, size_t size) override {
  10165. file->write_raw(src, size);
  10166. size_written += size;
  10167. }
  10168. size_t get_size_written() override {
  10169. return size_written;
  10170. }
  10171. };
  10172. /** copy state data into either a buffer or file depending on the passed in context
  10173. *
  10174. * file context:
  10175. * llama_file file("/path", "wb");
  10176. * llama_data_file_context data_ctx(&file);
  10177. * llama_copy_state_data(ctx, &data_ctx);
  10178. *
  10179. * buffer context:
  10180. * std::vector<uint8_t> buf(max_size, 0);
  10181. * llama_data_buffer_context data_ctx(&buf.data());
  10182. * llama_copy_state_data(ctx, &data_ctx);
  10183. *
  10184. */
  10185. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  10186. // copy rng
  10187. {
  10188. std::ostringstream rng_ss;
  10189. rng_ss << ctx->rng;
  10190. const std::string & rng_str = rng_ss.str();
  10191. const size_t rng_size = rng_str.size();
  10192. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10193. data_ctx->write(&rng_size, sizeof(rng_size));
  10194. data_ctx->write(rng_str.data(), rng_size);
  10195. }
  10196. // copy logits
  10197. {
  10198. const size_t logits_size = ctx->logits.size();
  10199. data_ctx->write(&logits_size, sizeof(logits_size));
  10200. if (logits_size) {
  10201. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  10202. }
  10203. }
  10204. // copy embeddings
  10205. {
  10206. const size_t embedding_size = ctx->embedding.size();
  10207. data_ctx->write(&embedding_size, sizeof(embedding_size));
  10208. if (embedding_size) {
  10209. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  10210. }
  10211. }
  10212. // copy kv cache
  10213. {
  10214. const auto & kv_self = ctx->kv_self;
  10215. const auto & hparams = ctx->model.hparams;
  10216. const auto & cparams = ctx->cparams;
  10217. const auto n_layer = hparams.n_layer;
  10218. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  10219. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  10220. const auto n_ctx = cparams.n_ctx;
  10221. const size_t kv_buf_size = kv_self.total_size();
  10222. const uint32_t kv_head = kv_self.head;
  10223. const uint32_t kv_size = kv_self.size;
  10224. const uint32_t kv_used = kv_self.used;
  10225. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  10226. data_ctx->write(&kv_head, sizeof(kv_head));
  10227. data_ctx->write(&kv_size, sizeof(kv_size));
  10228. data_ctx->write(&kv_used, sizeof(kv_used));
  10229. if (kv_buf_size) {
  10230. std::vector<uint8_t> tmp_buf;
  10231. for (int il = 0; il < (int) n_layer; ++il) {
  10232. size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10233. tmp_buf.resize(k_size);
  10234. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  10235. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10236. // v is not contiguous, copy row by row
  10237. size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10238. size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10239. tmp_buf.resize(v_row_size);
  10240. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10241. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  10242. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10243. }
  10244. }
  10245. }
  10246. for (uint32_t i = 0; i < kv_size; ++i) {
  10247. const auto & cell = kv_self.cells[i];
  10248. const llama_pos pos = cell.pos;
  10249. const size_t seq_id_size = cell.seq_id.size();
  10250. data_ctx->write(&pos, sizeof(pos));
  10251. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  10252. for (auto seq_id : cell.seq_id) {
  10253. data_ctx->write(&seq_id, sizeof(seq_id));
  10254. }
  10255. }
  10256. }
  10257. }
  10258. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  10259. llama_data_buffer_context data_ctx(dst);
  10260. llama_copy_state_data_internal(ctx, &data_ctx);
  10261. return data_ctx.get_size_written();
  10262. }
  10263. // Sets the state reading from the specified source address
  10264. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  10265. uint8_t * inp = src;
  10266. // set rng
  10267. {
  10268. size_t rng_size;
  10269. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  10270. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10271. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  10272. std::istringstream rng_ss(rng_str);
  10273. rng_ss >> ctx->rng;
  10274. GGML_ASSERT(!rng_ss.fail());
  10275. }
  10276. // set logits
  10277. {
  10278. size_t logits_size;
  10279. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  10280. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  10281. if (logits_size) {
  10282. ctx->logits.resize(logits_size);
  10283. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  10284. inp += logits_size * sizeof(float);
  10285. }
  10286. }
  10287. // set embeddings
  10288. {
  10289. size_t embedding_size;
  10290. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  10291. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  10292. if (embedding_size) {
  10293. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  10294. inp += embedding_size * sizeof(float);
  10295. }
  10296. }
  10297. // set kv cache
  10298. {
  10299. const auto & kv_self = ctx->kv_self;
  10300. const auto & hparams = ctx->model.hparams;
  10301. const auto & cparams = ctx->cparams;
  10302. const int n_layer = hparams.n_layer;
  10303. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  10304. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  10305. const int n_ctx = cparams.n_ctx;
  10306. size_t kv_buf_size;
  10307. uint32_t kv_head;
  10308. uint32_t kv_size;
  10309. uint32_t kv_used;
  10310. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  10311. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  10312. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  10313. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  10314. if (kv_buf_size) {
  10315. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  10316. for (int il = 0; il < (int) n_layer; ++il) {
  10317. size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10318. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  10319. inp += k_size;
  10320. // v is not contiguous, copy row by row
  10321. size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10322. size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10323. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10324. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  10325. inp += v_row_size;
  10326. }
  10327. }
  10328. }
  10329. ctx->kv_self.head = kv_head;
  10330. ctx->kv_self.size = kv_size;
  10331. ctx->kv_self.used = kv_used;
  10332. ctx->kv_self.cells.resize(kv_size);
  10333. for (uint32_t i = 0; i < kv_size; ++i) {
  10334. llama_pos pos;
  10335. size_t seq_id_size;
  10336. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  10337. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  10338. ctx->kv_self.cells[i].pos = pos;
  10339. llama_seq_id seq_id;
  10340. for (size_t j = 0; j < seq_id_size; ++j) {
  10341. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  10342. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  10343. }
  10344. }
  10345. }
  10346. const size_t nread = inp - src;
  10347. const size_t max_size = llama_get_state_size(ctx);
  10348. GGML_ASSERT(nread <= max_size);
  10349. return nread;
  10350. }
  10351. 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) {
  10352. llama_file file(path_session, "rb");
  10353. // sanity checks
  10354. {
  10355. const uint32_t magic = file.read_u32();
  10356. const uint32_t version = file.read_u32();
  10357. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  10358. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  10359. return false;
  10360. }
  10361. llama_hparams session_hparams;
  10362. file.read_raw(&session_hparams, sizeof(llama_hparams));
  10363. if (session_hparams != ctx->model.hparams) {
  10364. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  10365. return false;
  10366. }
  10367. }
  10368. // load the prompt
  10369. {
  10370. const uint32_t n_token_count = file.read_u32();
  10371. if (n_token_count > n_token_capacity) {
  10372. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  10373. return false;
  10374. }
  10375. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  10376. *n_token_count_out = n_token_count;
  10377. }
  10378. // restore the context state
  10379. {
  10380. const size_t n_state_size_cur = file.size - file.tell();
  10381. const size_t n_state_size_max = llama_get_state_size(ctx);
  10382. if (n_state_size_cur > n_state_size_max) {
  10383. 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);
  10384. return false;
  10385. }
  10386. std::vector<uint8_t> state_data(n_state_size_max);
  10387. file.read_raw(state_data.data(), n_state_size_cur);
  10388. llama_set_state_data(ctx, state_data.data());
  10389. }
  10390. return true;
  10391. }
  10392. 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) {
  10393. try {
  10394. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  10395. } catch (const std::exception & err) {
  10396. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  10397. return false;
  10398. }
  10399. }
  10400. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  10401. llama_file file(path_session, "wb");
  10402. file.write_u32(LLAMA_SESSION_MAGIC);
  10403. file.write_u32(LLAMA_SESSION_VERSION);
  10404. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  10405. // save the prompt
  10406. file.write_u32((uint32_t) n_token_count);
  10407. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  10408. // save the context state using stream saving
  10409. llama_data_file_context data_ctx(&file);
  10410. llama_copy_state_data_internal(ctx, &data_ctx);
  10411. return true;
  10412. }
  10413. int llama_eval(
  10414. struct llama_context * ctx,
  10415. llama_token * tokens,
  10416. int32_t n_tokens,
  10417. int32_t n_past) {
  10418. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10419. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  10420. if (ret < 0) {
  10421. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10422. }
  10423. return ret;
  10424. }
  10425. int llama_eval_embd(
  10426. struct llama_context * ctx,
  10427. float * embd,
  10428. int32_t n_tokens,
  10429. int32_t n_past) {
  10430. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10431. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  10432. const int ret = llama_decode_internal(*ctx, batch);
  10433. if (ret < 0) {
  10434. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10435. }
  10436. return ret;
  10437. }
  10438. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  10439. ctx->cparams.n_threads = n_threads;
  10440. ctx->cparams.n_threads_batch = n_threads_batch;
  10441. }
  10442. struct llama_batch llama_batch_get_one(
  10443. llama_token * tokens,
  10444. int32_t n_tokens,
  10445. llama_pos pos_0,
  10446. llama_seq_id seq_id) {
  10447. return {
  10448. /*n_tokens =*/ n_tokens,
  10449. /*tokens =*/ tokens,
  10450. /*embd =*/ nullptr,
  10451. /*pos =*/ nullptr,
  10452. /*n_seq_id =*/ nullptr,
  10453. /*seq_id =*/ nullptr,
  10454. /*logits =*/ nullptr,
  10455. /*all_pos_0 =*/ pos_0,
  10456. /*all_pos_1 =*/ 1,
  10457. /*all_seq_id =*/ seq_id,
  10458. };
  10459. }
  10460. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  10461. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  10462. if (embd) {
  10463. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  10464. } else {
  10465. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  10466. }
  10467. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  10468. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  10469. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  10470. for (int i = 0; i < n_tokens_alloc; ++i) {
  10471. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  10472. }
  10473. batch.seq_id[n_tokens_alloc] = nullptr;
  10474. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  10475. return batch;
  10476. }
  10477. void llama_batch_free(struct llama_batch batch) {
  10478. if (batch.token) free(batch.token);
  10479. if (batch.embd) free(batch.embd);
  10480. if (batch.pos) free(batch.pos);
  10481. if (batch.n_seq_id) free(batch.n_seq_id);
  10482. if (batch.seq_id) {
  10483. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  10484. free(batch.seq_id[i]);
  10485. }
  10486. free(batch.seq_id);
  10487. }
  10488. if (batch.logits) free(batch.logits);
  10489. }
  10490. int32_t llama_decode(
  10491. struct llama_context * ctx,
  10492. struct llama_batch batch) {
  10493. const int ret = llama_decode_internal(*ctx, batch);
  10494. if (ret < 0) {
  10495. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10496. }
  10497. return ret;
  10498. }
  10499. float * llama_get_logits(struct llama_context * ctx) {
  10500. return ctx->logits.data();
  10501. }
  10502. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  10503. assert(ctx->logits_valid.at(i));
  10504. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  10505. }
  10506. float * llama_get_embeddings(struct llama_context * ctx) {
  10507. return ctx->embedding.data();
  10508. }
  10509. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  10510. return ctx->embedding.data() + i*ctx->model.hparams.n_embd;
  10511. }
  10512. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  10513. return model->vocab.id_to_token[token].text.c_str();
  10514. }
  10515. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  10516. return model->vocab.id_to_token[token].score;
  10517. }
  10518. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  10519. return model->vocab.id_to_token[token].type;
  10520. }
  10521. llama_token llama_token_bos(const struct llama_model * model) {
  10522. return model->vocab.special_bos_id;
  10523. }
  10524. llama_token llama_token_eos(const struct llama_model * model) {
  10525. return model->vocab.special_eos_id;
  10526. }
  10527. llama_token llama_token_nl(const struct llama_model * model) {
  10528. return model->vocab.linefeed_id;
  10529. }
  10530. int32_t llama_add_bos_token(const struct llama_model * model) {
  10531. return model->vocab.special_add_bos;
  10532. }
  10533. int32_t llama_add_eos_token(const struct llama_model * model) {
  10534. return model->vocab.special_add_eos;
  10535. }
  10536. llama_token llama_token_prefix(const struct llama_model * model) {
  10537. return model->vocab.special_prefix_id;
  10538. }
  10539. llama_token llama_token_middle(const struct llama_model * model) {
  10540. return model->vocab.special_middle_id;
  10541. }
  10542. llama_token llama_token_suffix(const struct llama_model * model) {
  10543. return model->vocab.special_suffix_id;
  10544. }
  10545. llama_token llama_token_eot(const struct llama_model * model) {
  10546. return model->vocab.special_eot_id;
  10547. }
  10548. int32_t llama_tokenize(
  10549. const struct llama_model * model,
  10550. const char * text,
  10551. int32_t text_len,
  10552. llama_token * tokens,
  10553. int32_t n_max_tokens,
  10554. bool add_bos,
  10555. bool special) {
  10556. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  10557. if (n_max_tokens < (int) res.size()) {
  10558. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  10559. return -((int) res.size());
  10560. }
  10561. for (size_t i = 0; i < res.size(); i++) {
  10562. tokens[i] = res[i];
  10563. }
  10564. return res.size();
  10565. }
  10566. static std::string llama_decode_text(const std::string & text) {
  10567. std::string decoded_text;
  10568. auto unicode_sequences = codepoints_from_utf8(text);
  10569. for (auto& unicode_sequence : unicode_sequences) {
  10570. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  10571. }
  10572. return decoded_text;
  10573. }
  10574. // does not write null-terminator to buf
  10575. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  10576. if (0 <= token && token < llama_n_vocab(model)) {
  10577. switch (llama_vocab_get_type(model->vocab)) {
  10578. case LLAMA_VOCAB_TYPE_WPM:
  10579. case LLAMA_VOCAB_TYPE_SPM: {
  10580. // NOTE: we accept all unsupported token types,
  10581. // suppressing them like CONTROL tokens.
  10582. if (llama_is_normal_token(model->vocab, token)) {
  10583. std::string result = model->vocab.id_to_token[token].text;
  10584. llama_unescape_whitespace(result);
  10585. if (length < (int) result.length()) {
  10586. return -(int) result.length();
  10587. }
  10588. memcpy(buf, result.c_str(), result.length());
  10589. return result.length();
  10590. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10591. std::string result = model->vocab.id_to_token[token].text;
  10592. if (length < (int) result.length()) {
  10593. return -result.length();
  10594. }
  10595. memcpy(buf, result.c_str(), result.length());
  10596. return result.length();
  10597. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  10598. if (length < 3) {
  10599. return -3;
  10600. }
  10601. memcpy(buf, "\xe2\x96\x85", 3);
  10602. return 3;
  10603. } else if (llama_is_control_token(model->vocab, token)) {
  10604. ;
  10605. } else if (llama_is_byte_token(model->vocab, token)) {
  10606. if (length < 1) {
  10607. return -1;
  10608. }
  10609. buf[0] = llama_token_to_byte(model->vocab, token);
  10610. return 1;
  10611. }
  10612. break;
  10613. }
  10614. case LLAMA_VOCAB_TYPE_BPE: {
  10615. // NOTE: we accept all unsupported token types,
  10616. // suppressing them like CONTROL tokens.
  10617. if (llama_is_normal_token(model->vocab, token)) {
  10618. std::string result = model->vocab.id_to_token[token].text;
  10619. result = llama_decode_text(result);
  10620. if (length < (int) result.length()) {
  10621. return -(int) result.length();
  10622. }
  10623. memcpy(buf, result.c_str(), result.length());
  10624. return result.length();
  10625. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10626. std::string result = model->vocab.id_to_token[token].text;
  10627. if (length < (int) result.length()) {
  10628. return -result.length();
  10629. }
  10630. memcpy(buf, result.c_str(), result.length());
  10631. return result.length();
  10632. } else if (llama_is_control_token(model->vocab, token)) {
  10633. ;
  10634. }
  10635. break;
  10636. }
  10637. default:
  10638. GGML_ASSERT(false);
  10639. }
  10640. }
  10641. return 0;
  10642. }
  10643. // trim whitespace from the beginning and end of a string
  10644. static std::string trim(const std::string & str) {
  10645. size_t start = 0;
  10646. size_t end = str.size();
  10647. while (start < end && isspace(str[start])) {
  10648. start += 1;
  10649. }
  10650. while (end > start && isspace(str[end - 1])) {
  10651. end -= 1;
  10652. }
  10653. return str.substr(start, end - start);
  10654. }
  10655. // Simple version of "llama_apply_chat_template" that only works with strings
  10656. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  10657. static int32_t llama_chat_apply_template_internal(
  10658. const std::string & tmpl,
  10659. const std::vector<const llama_chat_message *> & chat,
  10660. std::string & dest, bool add_ass) {
  10661. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  10662. std::stringstream ss;
  10663. if (tmpl.find("<|im_start|>") != std::string::npos) {
  10664. // chatml template
  10665. for (auto message : chat) {
  10666. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  10667. }
  10668. if (add_ass) {
  10669. ss << "<|im_start|>assistant\n";
  10670. }
  10671. } else if (tmpl.find("[INST]") != std::string::npos) {
  10672. // llama2 template and its variants
  10673. // [variant] support system message
  10674. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  10675. // [variant] space before + after response
  10676. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  10677. // [variant] add BOS inside history
  10678. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  10679. // [variant] trim spaces from the input message
  10680. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  10681. // construct the prompt
  10682. bool is_inside_turn = true; // skip BOS at the beginning
  10683. ss << "[INST] ";
  10684. for (auto message : chat) {
  10685. std::string content = strip_message ? trim(message->content) : message->content;
  10686. std::string role(message->role);
  10687. if (!is_inside_turn) {
  10688. is_inside_turn = true;
  10689. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  10690. }
  10691. if (role == "system") {
  10692. if (support_system_message) {
  10693. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  10694. } else {
  10695. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  10696. ss << content << "\n";
  10697. }
  10698. } else if (role == "user") {
  10699. ss << content << " [/INST]";
  10700. } else {
  10701. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  10702. is_inside_turn = false;
  10703. }
  10704. }
  10705. // llama2 templates seem to not care about "add_generation_prompt"
  10706. } else if (tmpl.find("<|user|>") != std::string::npos) {
  10707. // zephyr template
  10708. for (auto message : chat) {
  10709. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  10710. }
  10711. if (add_ass) {
  10712. ss << "<|assistant|>\n";
  10713. }
  10714. } else if (tmpl.find("bos_token + message['role']") != std::string::npos) {
  10715. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  10716. for (auto message : chat) {
  10717. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  10718. ss << bos << message->role << "\n" << message->content << "</s>\n";
  10719. }
  10720. if (add_ass) {
  10721. ss << "<s>assistant\n";
  10722. }
  10723. } else if (tmpl.find("<start_of_turn>") != std::string::npos) {
  10724. // google/gemma-7b-it
  10725. std::string system_prompt = "";
  10726. for (auto message : chat) {
  10727. std::string role(message->role);
  10728. if (role == "system") {
  10729. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  10730. system_prompt = trim(message->content);
  10731. continue;
  10732. }
  10733. // in gemma, "assistant" is "model"
  10734. role = role == "assistant" ? "model" : message->role;
  10735. ss << "<start_of_turn>" << role << "\n";
  10736. if (!system_prompt.empty() && role != "model") {
  10737. ss << system_prompt << "\n\n";
  10738. system_prompt = "";
  10739. }
  10740. ss << trim(message->content) << "<end_of_turn>\n";
  10741. }
  10742. if (add_ass) {
  10743. ss << "<start_of_turn>model\n";
  10744. }
  10745. } else {
  10746. // template not supported
  10747. return -1;
  10748. }
  10749. dest = ss.str();
  10750. return dest.size();
  10751. }
  10752. LLAMA_API int32_t llama_chat_apply_template(
  10753. const struct llama_model * model,
  10754. const char * tmpl,
  10755. const struct llama_chat_message * chat,
  10756. size_t n_msg,
  10757. bool add_ass,
  10758. char * buf,
  10759. int32_t length) {
  10760. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  10761. if (tmpl == nullptr) {
  10762. GGML_ASSERT(model != nullptr);
  10763. // load template from model
  10764. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  10765. std::string template_key = "tokenizer.chat_template";
  10766. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  10767. if (res < 0) {
  10768. // worst case: there is no information about template, we will use chatml by default
  10769. curr_tmpl = "<|im_start|>"; // see llama_chat_apply_template_internal
  10770. } else {
  10771. curr_tmpl = std::string(model_template.data(), model_template.size());
  10772. }
  10773. }
  10774. // format the chat to string
  10775. std::vector<const llama_chat_message *> chat_vec;
  10776. chat_vec.resize(n_msg);
  10777. for (size_t i = 0; i < n_msg; i++) {
  10778. chat_vec[i] = &chat[i];
  10779. }
  10780. std::string formatted_chat;
  10781. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  10782. if (res < 0) {
  10783. return res;
  10784. }
  10785. strncpy(buf, formatted_chat.c_str(), length);
  10786. return res;
  10787. }
  10788. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  10789. struct llama_timings result = {
  10790. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  10791. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  10792. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  10793. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  10794. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  10795. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  10796. /*.n_sample =*/ std::max(1, ctx->n_sample),
  10797. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  10798. /*.n_eval =*/ std::max(1, ctx->n_eval),
  10799. };
  10800. return result;
  10801. }
  10802. void llama_print_timings(struct llama_context * ctx) {
  10803. const llama_timings timings = llama_get_timings(ctx);
  10804. LLAMA_LOG_INFO("\n");
  10805. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  10806. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10807. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  10808. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  10809. __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);
  10810. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  10811. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  10812. 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));
  10813. }
  10814. void llama_reset_timings(struct llama_context * ctx) {
  10815. ctx->t_start_us = ggml_time_us();
  10816. ctx->t_sample_us = ctx->n_sample = 0;
  10817. ctx->t_eval_us = ctx->n_eval = 0;
  10818. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  10819. }
  10820. const char * llama_print_system_info(void) {
  10821. static std::string s;
  10822. s = "";
  10823. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  10824. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  10825. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  10826. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  10827. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  10828. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  10829. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  10830. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  10831. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  10832. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  10833. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  10834. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  10835. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  10836. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  10837. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  10838. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  10839. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  10840. return s.c_str();
  10841. }
  10842. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  10843. fprintf(stream, "\n");
  10844. fprintf(stream, "###########\n");
  10845. fprintf(stream, "# Timings #\n");
  10846. fprintf(stream, "###########\n");
  10847. fprintf(stream, "\n");
  10848. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  10849. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  10850. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  10851. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  10852. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  10853. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  10854. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  10855. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  10856. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  10857. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  10858. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  10859. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  10860. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  10861. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  10862. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  10863. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  10864. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  10865. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  10866. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  10867. }
  10868. // For internal test use
  10869. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  10870. struct llama_context * ctx
  10871. ) {
  10872. return ctx->model.tensors_by_name;
  10873. }
  10874. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  10875. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  10876. g_state.log_callback_user_data = user_data;
  10877. #ifdef GGML_USE_METAL
  10878. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  10879. #endif
  10880. }
  10881. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  10882. va_list args_copy;
  10883. va_copy(args_copy, args);
  10884. char buffer[128];
  10885. int len = vsnprintf(buffer, 128, format, args);
  10886. if (len < 128) {
  10887. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  10888. } else {
  10889. char* buffer2 = new char[len+1];
  10890. vsnprintf(buffer2, len+1, format, args_copy);
  10891. buffer2[len] = 0;
  10892. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  10893. delete[] buffer2;
  10894. }
  10895. va_end(args_copy);
  10896. }
  10897. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  10898. va_list args;
  10899. va_start(args, format);
  10900. llama_log_internal_v(level, format, args);
  10901. va_end(args);
  10902. }
  10903. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  10904. (void) level;
  10905. (void) user_data;
  10906. fputs(text, stderr);
  10907. fflush(stderr);
  10908. }