llama.cpp 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956
  1. // Defines fileno on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #include <cstddef>
  5. #include <cstdint>
  6. #include <cstdio>
  7. #endif
  8. #include "llama.h"
  9. #include "ggml.h"
  10. #include "ggml-alloc.h"
  11. #ifdef GGML_USE_CUBLAS
  12. # include "ggml-cuda.h"
  13. #elif defined(GGML_USE_CLBLAST)
  14. # include "ggml-opencl.h"
  15. #endif
  16. #ifdef GGML_USE_METAL
  17. # include "ggml-metal.h"
  18. #endif
  19. #ifdef GGML_USE_MPI
  20. # include "ggml-mpi.h"
  21. #endif
  22. #ifdef GGML_USE_K_QUANTS
  23. # ifndef QK_K
  24. # ifdef GGML_QKK_64
  25. # define QK_K 64
  26. # else
  27. # define QK_K 256
  28. # endif
  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. #endif
  37. #if defined(_POSIX_MEMLOCK_RANGE)
  38. #include <sys/resource.h>
  39. #endif
  40. #endif
  41. #endif
  42. #if defined(_WIN32)
  43. #define WIN32_LEAN_AND_MEAN
  44. #ifndef NOMINMAX
  45. #define NOMINMAX
  46. #endif
  47. #include <windows.h>
  48. #include <io.h>
  49. #include <stdio.h> // for _fseeki64
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cinttypes>
  55. #include <climits>
  56. #include <cstdarg>
  57. #include <cstring>
  58. #include <ctime>
  59. #include <fstream>
  60. #include <initializer_list>
  61. #include <map>
  62. #include <memory>
  63. #include <mutex>
  64. #include <numeric>
  65. #include <queue>
  66. #include <random>
  67. #include <regex>
  68. #include <sstream>
  69. #include <thread>
  70. #include <unordered_map>
  71. #if defined(_MSC_VER)
  72. #pragma warning(disable: 4244 4267) // possible loss of data
  73. #endif
  74. #ifdef __GNUC__
  75. #ifdef __MINGW32__
  76. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  77. #else
  78. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  79. #endif
  80. #else
  81. #define LLAMA_ATTRIBUTE_FORMAT(...)
  82. #endif
  83. //
  84. // logging
  85. //
  86. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  87. static void llama_log_internal (llama_log_level level, const char* format, ...);
  88. static void llama_log_callback_default(llama_log_level level, const char * text, void * user_data);
  89. #define LLAMA_LOG_INFO(...) llama_log_internal(LLAMA_LOG_LEVEL_INFO , __VA_ARGS__)
  90. #define LLAMA_LOG_WARN(...) llama_log_internal(LLAMA_LOG_LEVEL_WARN , __VA_ARGS__)
  91. #define LLAMA_LOG_ERROR(...) llama_log_internal(LLAMA_LOG_LEVEL_ERROR, __VA_ARGS__)
  92. //
  93. // helpers
  94. //
  95. static size_t utf8_len(char src) {
  96. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  97. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  98. return lookup[highbits];
  99. }
  100. void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  101. for (size_t pos = 0; ; pos += replace.length()) {
  102. pos = s.find(search, pos);
  103. if (pos == std::string::npos) break;
  104. s.erase(pos, search.length());
  105. s.insert(pos, replace);
  106. }
  107. }
  108. static void zeros(std::ofstream & file, size_t n) {
  109. char zero = 0;
  110. for (size_t i = 0; i < n; ++i) {
  111. file.write(&zero, 1);
  112. }
  113. }
  114. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  115. static std::string format(const char * fmt, ...) {
  116. va_list ap;
  117. va_list ap2;
  118. va_start(ap, fmt);
  119. va_copy(ap2, ap);
  120. int size = vsnprintf(NULL, 0, fmt, ap);
  121. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  122. std::vector<char> buf(size + 1);
  123. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  124. GGML_ASSERT(size2 == size);
  125. va_end(ap2);
  126. va_end(ap);
  127. return std::string(buf.data(), size);
  128. }
  129. //
  130. // gguf constants (sync with gguf.py)
  131. //
  132. enum llm_arch {
  133. LLM_ARCH_LLAMA,
  134. LLM_ARCH_FALCON,
  135. LLM_ARCH_GPT2,
  136. LLM_ARCH_GPTJ,
  137. LLM_ARCH_GPTNEOX,
  138. LLM_ARCH_MPT,
  139. LLM_ARCH_UNKNOWN,
  140. };
  141. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  142. { LLM_ARCH_LLAMA, "llama" },
  143. { LLM_ARCH_FALCON, "falcon" },
  144. { LLM_ARCH_GPT2, "gpt2" },
  145. { LLM_ARCH_GPTJ, "gptj" },
  146. { LLM_ARCH_GPTNEOX, "gptneox" },
  147. { LLM_ARCH_MPT, "mpt" },
  148. };
  149. enum llm_kv {
  150. LLM_KV_GENERAL_ARCHITECTURE,
  151. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  152. LLM_KV_GENERAL_ALIGNMENT,
  153. LLM_KV_GENERAL_NAME,
  154. LLM_KV_GENERAL_AUTHOR,
  155. LLM_KV_GENERAL_URL,
  156. LLM_KV_GENERAL_DESCRIPTION,
  157. LLM_KV_GENERAL_LICENSE,
  158. LLM_KV_GENERAL_SOURCE_URL,
  159. LLM_KV_GENERAL_SOURCE_HF_REPO,
  160. LLM_KV_CONTEXT_LENGTH,
  161. LLM_KV_EMBEDDING_LENGTH,
  162. LLM_KV_BLOCK_COUNT,
  163. LLM_KV_FEED_FORWARD_LENGTH,
  164. LLM_KV_USE_PARALLEL_RESIDUAL,
  165. LLM_KV_TENSOR_DATA_LAYOUT,
  166. LLM_KV_ATTENTION_HEAD_COUNT,
  167. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  168. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  169. LLM_KV_ATTENTION_CLAMP_KQV,
  170. LLM_KV_ATTENTION_LAYERNORM_EPS,
  171. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  172. LLM_KV_ROPE_DIMENSION_COUNT,
  173. LLM_KV_ROPE_SCALE_LINEAR,
  174. LLM_KV_TOKENIZER_MODEL,
  175. LLM_KV_TOKENIZER_LIST,
  176. LLM_KV_TOKENIZER_TOKEN_TYPE,
  177. LLM_KV_TOKENIZER_SCORES,
  178. LLM_KV_TOKENIZER_MERGES,
  179. LLM_KV_TOKENIZER_BOS_ID,
  180. LLM_KV_TOKENIZER_EOS_ID,
  181. LLM_KV_TOKENIZER_UNK_ID,
  182. LLM_KV_TOKENIZER_SEP_ID,
  183. LLM_KV_TOKENIZER_PAD_ID,
  184. LLM_KV_TOKENIZER_HF_JSON,
  185. LLM_KV_TOKENIZER_RWKV,
  186. };
  187. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  188. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  189. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  190. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  191. { LLM_KV_GENERAL_NAME, "general.name" },
  192. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  193. { LLM_KV_GENERAL_URL, "general.url" },
  194. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  195. { LLM_KV_GENERAL_LICENSE, "general.license" },
  196. { LLM_KV_GENERAL_SOURCE_URL, "general.source_url" },
  197. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source_hf_repo" },
  198. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  199. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  200. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  201. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  202. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  203. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  204. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  205. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  206. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  207. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  208. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  209. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  210. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  211. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  212. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  213. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  214. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  215. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  216. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  217. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  218. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  219. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  220. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  221. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  222. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  223. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  224. };
  225. struct LLM_KV {
  226. LLM_KV(llm_arch arch) : arch(arch) {}
  227. llm_arch arch;
  228. std::string operator()(llm_kv kv) const {
  229. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  230. }
  231. };
  232. enum llm_tensor {
  233. LLM_TENSOR_TOKEN_EMBD,
  234. LLM_TENSOR_POS_EMBD,
  235. LLM_TENSOR_OUTPUT,
  236. LLM_TENSOR_OUTPUT_NORM,
  237. LLM_TENSOR_ROPE_FREQS,
  238. LLM_TENSOR_ATTN_Q,
  239. LLM_TENSOR_ATTN_K,
  240. LLM_TENSOR_ATTN_V,
  241. LLM_TENSOR_ATTN_QKV,
  242. LLM_TENSOR_ATTN_OUT,
  243. LLM_TENSOR_ATTN_NORM,
  244. LLM_TENSOR_ATTN_NORM_2,
  245. LLM_TENSOR_ATTN_ROT_EMBD,
  246. LLM_TENSOR_FFN_GATE,
  247. LLM_TENSOR_FFN_DOWN,
  248. LLM_TENSOR_FFN_UP,
  249. LLM_TENSOR_FFN_NORM,
  250. };
  251. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  252. {
  253. LLM_ARCH_LLAMA,
  254. {
  255. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  256. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  257. { LLM_TENSOR_OUTPUT, "output" },
  258. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  259. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  260. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  261. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  262. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  263. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  264. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  265. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  266. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  267. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  268. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  269. },
  270. },
  271. {
  272. LLM_ARCH_FALCON,
  273. {
  274. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  275. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  276. { LLM_TENSOR_OUTPUT, "output" },
  277. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  278. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  279. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  280. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  281. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  282. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  283. },
  284. },
  285. };
  286. static llm_arch llm_arch_from_string(const std::string & name) {
  287. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  288. if (kv.second == name) {
  289. return kv.first;
  290. }
  291. }
  292. return LLM_ARCH_UNKNOWN;
  293. }
  294. // helper to handle gguf constants
  295. // usage:
  296. //
  297. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  298. //
  299. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  300. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  301. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  302. //
  303. struct LLM_TN {
  304. LLM_TN(llm_arch arch) : arch(arch) {}
  305. llm_arch arch;
  306. std::string operator()(llm_tensor tensor) const {
  307. return LLM_TENSOR_NAMES[arch].at(tensor);
  308. }
  309. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  310. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  311. }
  312. std::string operator()(llm_tensor tensor, int bid) const {
  313. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  314. }
  315. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  316. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  317. }
  318. };
  319. //
  320. // gguf helpers
  321. //
  322. #define GGUF_GET_KEY(ctx, dst, func, type, req, key) \
  323. { \
  324. const std::string skey(key); \
  325. const int kid = gguf_find_key(ctx, skey.c_str()); \
  326. if (kid >= 0) { \
  327. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  328. if (ktype != (type)) { \
  329. throw std::runtime_error(format("key %s has wrong type: %s", skey.c_str(), gguf_type_name(ktype))); \
  330. } \
  331. (dst) = func(ctx, kid); \
  332. } else if (req) { \
  333. throw std::runtime_error(format("key not found in model: %s", skey.c_str())); \
  334. } \
  335. }
  336. //
  337. // ggml helpers
  338. //
  339. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  340. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  341. if (plan.work_size > 0) {
  342. buf.resize(plan.work_size);
  343. plan.work_data = buf.data();
  344. }
  345. ggml_graph_compute(graph, &plan);
  346. }
  347. //
  348. // llama helpers
  349. //
  350. #ifdef GGML_USE_CUBLAS
  351. # define llama_host_malloc(n) ggml_cuda_host_malloc(n)
  352. # define llama_host_free(data) ggml_cuda_host_free(data)
  353. #elif GGML_USE_METAL
  354. # define llama_host_malloc(n) ggml_metal_host_malloc(n)
  355. # define llama_host_free(data) ggml_metal_host_free(data)
  356. #else
  357. # define llama_host_malloc(n) malloc(n)
  358. # define llama_host_free(data) free(data)
  359. #endif
  360. #if defined(_WIN32)
  361. static std::string llama_format_win_err(DWORD err) {
  362. LPSTR buf;
  363. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  364. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  365. if (!size) {
  366. return "FormatMessageA failed";
  367. }
  368. std::string ret(buf, size);
  369. LocalFree(buf);
  370. return ret;
  371. }
  372. #endif
  373. struct llama_buffer {
  374. void * data = NULL;
  375. size_t size = 0;
  376. // fallback to malloc / free
  377. // useful in cases where CUDA can try to allocate PINNED memory
  378. bool fallback = false;
  379. void resize(size_t n) {
  380. llama_host_free(data);
  381. data = llama_host_malloc(n);
  382. if (!data) {
  383. fallback = true;
  384. data = malloc(n);
  385. } else {
  386. fallback = false;
  387. }
  388. GGML_ASSERT(data);
  389. size = n;
  390. }
  391. ~llama_buffer() {
  392. if (data) {
  393. if (fallback) { // NOLINT
  394. free(data);
  395. } else {
  396. llama_host_free(data);
  397. }
  398. }
  399. data = NULL;
  400. }
  401. };
  402. struct llama_file {
  403. // use FILE * so we don't have to re-open the file to mmap
  404. FILE * fp;
  405. size_t size;
  406. llama_file(const char * fname, const char * mode) {
  407. fp = std::fopen(fname, mode);
  408. if (fp == NULL) {
  409. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  410. }
  411. seek(0, SEEK_END);
  412. size = tell();
  413. seek(0, SEEK_SET);
  414. }
  415. size_t tell() const {
  416. #ifdef _WIN32
  417. __int64 ret = _ftelli64(fp);
  418. #else
  419. long ret = std::ftell(fp);
  420. #endif
  421. GGML_ASSERT(ret != -1); // this really shouldn't fail
  422. return (size_t) ret;
  423. }
  424. void seek(size_t offset, int whence) const {
  425. #ifdef _WIN32
  426. int ret = _fseeki64(fp, (__int64) offset, whence);
  427. #else
  428. int ret = std::fseek(fp, (long) offset, whence);
  429. #endif
  430. GGML_ASSERT(ret == 0); // same
  431. }
  432. void read_raw(void * ptr, size_t len) const {
  433. if (len == 0) {
  434. return;
  435. }
  436. errno = 0;
  437. std::size_t ret = std::fread(ptr, len, 1, fp);
  438. if (ferror(fp)) {
  439. throw std::runtime_error(format("read error: %s", strerror(errno)));
  440. }
  441. if (ret != 1) {
  442. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  443. }
  444. }
  445. uint32_t read_u32() const {
  446. uint32_t ret;
  447. read_raw(&ret, sizeof(ret));
  448. return ret;
  449. }
  450. void write_raw(const void * ptr, size_t len) const {
  451. if (len == 0) {
  452. return;
  453. }
  454. errno = 0;
  455. size_t ret = std::fwrite(ptr, len, 1, fp);
  456. if (ret != 1) {
  457. throw std::runtime_error(format("write error: %s", strerror(errno)));
  458. }
  459. }
  460. void write_u32(std::uint32_t val) const {
  461. write_raw(&val, sizeof(val));
  462. }
  463. ~llama_file() {
  464. if (fp) {
  465. std::fclose(fp);
  466. }
  467. }
  468. };
  469. struct llama_mmap {
  470. void * addr;
  471. size_t size;
  472. llama_mmap(const llama_mmap &) = delete;
  473. #ifdef _POSIX_MAPPED_FILES
  474. static constexpr bool SUPPORTED = true;
  475. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  476. size = file->size;
  477. int fd = fileno(file->fp);
  478. int flags = MAP_SHARED;
  479. // prefetch/readahead impairs performance on NUMA systems
  480. if (numa) { prefetch = 0; }
  481. #ifdef __linux__
  482. if (prefetch) { flags |= MAP_POPULATE; }
  483. #endif
  484. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  485. if (addr == MAP_FAILED) {
  486. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  487. }
  488. if (prefetch > 0) {
  489. // Advise the kernel to preload the mapped memory
  490. if (madvise(addr, std::min(file->size, prefetch), MADV_WILLNEED)) {
  491. fprintf(stderr, "warning: madvise(.., MADV_WILLNEED) failed: %s\n",
  492. strerror(errno));
  493. }
  494. }
  495. if (numa) {
  496. // advise the kernel not to use readahead
  497. // (because the next page might not belong on the same node)
  498. if (madvise(addr, file->size, MADV_RANDOM)) {
  499. fprintf(stderr, "warning: madvise(.., MADV_RANDOM) failed: %s\n",
  500. strerror(errno));
  501. }
  502. }
  503. }
  504. ~llama_mmap() {
  505. munmap(addr, size);
  506. }
  507. #elif defined(_WIN32)
  508. static constexpr bool SUPPORTED = true;
  509. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  510. (void) numa;
  511. size = file->size;
  512. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  513. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  514. DWORD error = GetLastError();
  515. if (hMapping == NULL) {
  516. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  517. }
  518. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  519. error = GetLastError();
  520. CloseHandle(hMapping);
  521. if (addr == NULL) {
  522. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  523. }
  524. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  525. if (prefetch) {
  526. // Advise the kernel to preload the mapped memory
  527. WIN32_MEMORY_RANGE_ENTRY range;
  528. range.VirtualAddress = addr;
  529. range.NumberOfBytes = (SIZE_T)size;
  530. if (!PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  531. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  532. llama_format_win_err(GetLastError()).c_str());
  533. }
  534. }
  535. #else
  536. #pragma message("warning: You are building for pre-Windows 8; prefetch not supported")
  537. #endif // _WIN32_WINNT >= _WIN32_WINNT_WIN8
  538. }
  539. ~llama_mmap() {
  540. if (!UnmapViewOfFile(addr)) {
  541. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  542. llama_format_win_err(GetLastError()).c_str());
  543. }
  544. }
  545. #else
  546. static constexpr bool SUPPORTED = false;
  547. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  548. (void) file;
  549. (void) prefetch;
  550. (void) numa;
  551. throw std::runtime_error(std::string("mmap not supported"));
  552. }
  553. #endif
  554. };
  555. // Represents some region of memory being locked using mlock or VirtualLock;
  556. // will automatically unlock on destruction.
  557. struct llama_mlock {
  558. void * addr = NULL;
  559. size_t size = 0;
  560. bool failed_already = false;
  561. llama_mlock() {}
  562. llama_mlock(const llama_mlock &) = delete;
  563. ~llama_mlock() {
  564. if (size) {
  565. raw_unlock(addr, size);
  566. }
  567. }
  568. void init(void * ptr) {
  569. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  570. addr = ptr;
  571. }
  572. void grow_to(size_t target_size) {
  573. GGML_ASSERT(addr);
  574. if (failed_already) {
  575. return;
  576. }
  577. size_t granularity = lock_granularity();
  578. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  579. if (target_size > size) {
  580. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  581. size = target_size;
  582. } else {
  583. failed_already = true;
  584. }
  585. }
  586. }
  587. #ifdef _POSIX_MEMLOCK_RANGE
  588. static constexpr bool SUPPORTED = true;
  589. static size_t lock_granularity() {
  590. return (size_t) sysconf(_SC_PAGESIZE);
  591. }
  592. #ifdef __APPLE__
  593. #define MLOCK_SUGGESTION \
  594. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  595. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  596. #else
  597. #define MLOCK_SUGGESTION \
  598. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  599. #endif
  600. bool raw_lock(const void * addr, size_t size) const {
  601. if (!mlock(addr, size)) {
  602. return true;
  603. }
  604. char* errmsg = std::strerror(errno);
  605. bool suggest = (errno == ENOMEM);
  606. // Check if the resource limit is fine after all
  607. struct rlimit lock_limit;
  608. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  609. suggest = false;
  610. }
  611. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  612. suggest = false;
  613. }
  614. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  615. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  616. return false;
  617. }
  618. #undef MLOCK_SUGGESTION
  619. static void raw_unlock(void * addr, size_t size) {
  620. if (munlock(addr, size)) {
  621. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  622. }
  623. }
  624. #elif defined(_WIN32)
  625. static constexpr bool SUPPORTED = true;
  626. static size_t lock_granularity() {
  627. SYSTEM_INFO si;
  628. GetSystemInfo(&si);
  629. return (size_t) si.dwPageSize;
  630. }
  631. bool raw_lock(void * ptr, size_t len) const {
  632. for (int tries = 1; ; tries++) {
  633. if (VirtualLock(ptr, len)) {
  634. return true;
  635. }
  636. if (tries == 2) {
  637. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  638. len, size, llama_format_win_err(GetLastError()).c_str());
  639. return false;
  640. }
  641. // It failed but this was only the first try; increase the working
  642. // set size and try again.
  643. SIZE_T min_ws_size, max_ws_size;
  644. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  645. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  646. llama_format_win_err(GetLastError()).c_str());
  647. return false;
  648. }
  649. // Per MSDN: "The maximum number of pages that a process can lock
  650. // is equal to the number of pages in its minimum working set minus
  651. // a small overhead."
  652. // Hopefully a megabyte is enough overhead:
  653. size_t increment = len + 1048576;
  654. // The minimum must be <= the maximum, so we need to increase both:
  655. min_ws_size += increment;
  656. max_ws_size += increment;
  657. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  658. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  659. llama_format_win_err(GetLastError()).c_str());
  660. return false;
  661. }
  662. }
  663. }
  664. static void raw_unlock(void * ptr, size_t len) {
  665. if (!VirtualUnlock(ptr, len)) {
  666. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  667. llama_format_win_err(GetLastError()).c_str());
  668. }
  669. }
  670. #else
  671. static constexpr bool SUPPORTED = false;
  672. static size_t lock_granularity() {
  673. return (size_t) 65536;
  674. }
  675. bool raw_lock(const void * addr, size_t len) const {
  676. fprintf(stderr, "warning: mlock not supported on this system\n");
  677. return false;
  678. }
  679. static void raw_unlock(const void * addr, size_t len) {}
  680. #endif
  681. };
  682. typedef void (*offload_func_t)(struct ggml_tensor * tensor);
  683. static void llama_nop(struct ggml_tensor * tensor) { // don't offload by default
  684. (void) tensor;
  685. }
  686. static std::string llama_token_to_text(const struct llama_context * ctx, llama_token token) {
  687. std::vector<char> result(8, 0);
  688. const int n_tokens = llama_token_to_str(ctx, token, result.data(), result.size());
  689. if (n_tokens < 0) {
  690. result.resize(-n_tokens);
  691. int check = llama_token_to_str(ctx, token, result.data(), result.size());
  692. GGML_ASSERT(check == -n_tokens);
  693. } else {
  694. result.resize(n_tokens);
  695. }
  696. return std::string(result.data(), result.size());
  697. }
  698. //
  699. // globals
  700. //
  701. struct llama_state {
  702. // We save the log callback globally
  703. llama_log_callback log_callback = llama_log_callback_default;
  704. void * log_callback_user_data = nullptr;
  705. };
  706. static llama_state g_state;
  707. // available llama models
  708. enum e_model {
  709. MODEL_UNKNOWN,
  710. MODEL_3B,
  711. MODEL_7B,
  712. MODEL_13B,
  713. MODEL_30B,
  714. MODEL_40B,
  715. MODEL_65B,
  716. MODEL_70B,
  717. };
  718. static const size_t kB = 1024;
  719. static const size_t MB = kB*kB;
  720. // default hparams (LLaMA 7B)
  721. struct llama_hparams {
  722. uint32_t n_vocab = 32000;
  723. uint32_t n_ctx_train = 2048; // the context size used during training
  724. uint32_t n_ctx = 512; // the context size used during inference
  725. uint32_t n_embd = 4096;
  726. uint32_t n_head = 32;
  727. uint32_t n_head_kv = 32;
  728. uint32_t n_layer = 32;
  729. uint32_t n_rot = 64;
  730. uint32_t n_ff = 11008;
  731. float f_norm_eps = 1e-5;
  732. float f_norm_rms_eps = 1e-5;
  733. float rope_freq_base = 10000.0f;
  734. float rope_freq_scale = 1.0f;
  735. bool operator!=(const llama_hparams & other) const {
  736. return static_cast<bool>(memcmp(this, &other, sizeof(llama_hparams))); // NOLINT
  737. }
  738. uint32_t n_gqa() const {
  739. return n_head/n_head_kv;
  740. }
  741. uint32_t n_embd_head() const {
  742. return n_embd/n_head;
  743. }
  744. uint32_t n_embd_gqa() const {
  745. return n_embd/n_gqa();
  746. }
  747. size_t kv_size() const {
  748. size_t result = 2ull;
  749. result *= (size_t) n_embd_gqa();
  750. result *= (size_t) n_ctx;
  751. result *= (size_t) n_layer;
  752. result *= sizeof(ggml_fp16_t);
  753. return result;
  754. }
  755. };
  756. struct llama_layer {
  757. // normalization
  758. struct ggml_tensor * attn_norm;
  759. struct ggml_tensor * attn_norm_b;
  760. struct ggml_tensor * attn_norm_2;
  761. struct ggml_tensor * attn_norm_2_b;
  762. // attention
  763. struct ggml_tensor * wq;
  764. struct ggml_tensor * wk;
  765. struct ggml_tensor * wv;
  766. struct ggml_tensor * wo;
  767. struct ggml_tensor * wqkv;
  768. // normalization
  769. struct ggml_tensor * ffn_norm;
  770. // ff
  771. struct ggml_tensor * w1; // ffn_gate
  772. struct ggml_tensor * w2; // ffn_down
  773. struct ggml_tensor * w3; // ffn_up
  774. };
  775. struct llama_kv_cache {
  776. struct ggml_tensor * k = NULL;
  777. struct ggml_tensor * v = NULL;
  778. struct ggml_context * ctx = NULL;
  779. llama_buffer buf;
  780. int n; // number of tokens currently in the cache
  781. ~llama_kv_cache() {
  782. if (ctx) {
  783. ggml_free(ctx);
  784. }
  785. #ifdef GGML_USE_CUBLAS
  786. ggml_cuda_free_data(k);
  787. ggml_cuda_free_data(v);
  788. #endif // GGML_USE_CUBLAS
  789. }
  790. };
  791. struct llama_vocab {
  792. using id = int32_t;
  793. using token = std::string;
  794. using ttype = llama_token_type;
  795. struct token_data {
  796. token text;
  797. float score;
  798. ttype type;
  799. };
  800. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  801. std::unordered_map<token, id> token_to_id;
  802. std::vector<token_data> id_to_token;
  803. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  804. // default LLaMA special tokens
  805. id special_bos_id = 1;
  806. id special_eos_id = 2;
  807. id special_unk_id = 0;
  808. id special_sep_id = -1;
  809. id special_pad_id = -1;
  810. id linefeed_id = 13;
  811. int find_bpe_rank(std::string token_left, std::string token_right) const {
  812. replace_all(token_left, " ", "Ġ");
  813. replace_all(token_left, "\n", "Ċ");
  814. replace_all(token_right, " ", "Ġ");
  815. replace_all(token_right, "\n", "Ċ");
  816. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  817. if (it == bpe_ranks.end()) {
  818. return -1;
  819. }
  820. return it->second;
  821. }
  822. };
  823. struct llama_model {
  824. e_model type = MODEL_UNKNOWN;
  825. llm_arch arch = LLM_ARCH_UNKNOWN;
  826. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  827. std::string name = "n/a";
  828. llama_hparams hparams;
  829. llama_vocab vocab;
  830. struct ggml_tensor * tok_embeddings;
  831. struct ggml_tensor * output_norm;
  832. struct ggml_tensor * output_norm_b;
  833. struct ggml_tensor * output;
  834. std::vector<llama_layer> layers;
  835. int n_gpu_layers;
  836. // context
  837. struct ggml_context * ctx = NULL;
  838. // the model memory buffer
  839. llama_buffer buf;
  840. // model memory mapped file
  841. std::unique_ptr<llama_mmap> mapping;
  842. // objects representing data potentially being locked in memory
  843. llama_mlock mlock_buf;
  844. llama_mlock mlock_mmap;
  845. // for quantize-stats only
  846. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  847. int64_t t_load_us = 0;
  848. int64_t t_start_us = 0;
  849. ~llama_model() {
  850. if (ctx) {
  851. ggml_free(ctx);
  852. }
  853. #ifdef GGML_USE_CUBLAS
  854. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  855. ggml_cuda_free_data(tensors_by_name[i].second);
  856. }
  857. ggml_cuda_free_scratch();
  858. #elif defined(GGML_USE_CLBLAST)
  859. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  860. ggml_cl_free_data(tensors_by_name[i].second);
  861. }
  862. #endif
  863. }
  864. };
  865. struct llama_context {
  866. llama_context(const llama_model & model) : model(model), t_load_us(model.t_load_us), t_start_us(model.t_start_us) {}
  867. ~llama_context() {
  868. if (model_owner) {
  869. delete &model;
  870. }
  871. #ifdef GGML_USE_METAL
  872. if (ctx_metal) {
  873. ggml_metal_free(ctx_metal);
  874. }
  875. #endif
  876. if (alloc) {
  877. ggml_allocr_free(alloc);
  878. }
  879. }
  880. std::mt19937 rng;
  881. bool has_evaluated_once = false;
  882. int64_t t_sample_us = 0;
  883. int64_t t_eval_us = 0;
  884. int64_t t_p_eval_us = 0;
  885. int32_t n_sample = 0; // number of tokens sampled
  886. int32_t n_eval = 0; // number of eval calls
  887. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  888. const llama_model & model;
  889. bool model_owner = false;
  890. int64_t t_load_us;
  891. int64_t t_start_us;
  892. // key + value cache for the self attention
  893. struct llama_kv_cache kv_self;
  894. // decode output (2-dimensional array: [n_tokens][n_vocab])
  895. std::vector<float> logits;
  896. bool logits_all = false;
  897. // input embedding (1-dimensional array: [n_embd])
  898. std::vector<float> embedding;
  899. // reusable buffer for `struct ggml_graph_plan.work_data`
  900. std::vector<uint8_t> work_buffer;
  901. // memory buffers used to evaluate the model
  902. llama_buffer buf_compute;
  903. llama_buffer buf_alloc;
  904. ggml_allocr * alloc = NULL;
  905. #ifdef GGML_USE_METAL
  906. ggml_metal_context * ctx_metal = NULL;
  907. #endif
  908. #ifdef GGML_USE_MPI
  909. ggml_mpi_context * ctx_mpi = NULL;
  910. #endif
  911. };
  912. //
  913. // kv cache helpers
  914. //
  915. static bool llama_kv_cache_init(
  916. const struct llama_hparams & hparams,
  917. struct llama_kv_cache & cache,
  918. ggml_type wtype,
  919. int n_ctx,
  920. int n_gpu_layers) {
  921. const int n_embd = hparams.n_embd_gqa();
  922. const int n_layer = hparams.n_layer;
  923. const int64_t n_mem = n_layer*n_ctx;
  924. const int64_t n_elements = n_embd*n_mem;
  925. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  926. cache.n = 0;
  927. struct ggml_init_params params;
  928. params.mem_size = cache.buf.size;
  929. params.mem_buffer = cache.buf.data;
  930. params.no_alloc = false;
  931. cache.ctx = ggml_init(params);
  932. if (!cache.ctx) {
  933. LLAMA_LOG_ERROR("%s: failed to allocate memory for kv cache\n", __func__);
  934. return false;
  935. }
  936. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  937. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  938. ggml_set_name(cache.k, "cache_k");
  939. ggml_set_name(cache.v, "cache_v");
  940. (void) n_gpu_layers;
  941. #ifdef GGML_USE_CUBLAS
  942. if (n_gpu_layers > n_layer + 1) {
  943. ggml_cuda_assign_buffers_no_scratch(cache.v);
  944. }
  945. if (n_gpu_layers > n_layer + 2) {
  946. ggml_cuda_assign_buffers_no_scratch(cache.k);
  947. }
  948. #endif // GGML_USE_CUBLAS
  949. return true;
  950. }
  951. //
  952. // model loading and saving
  953. //
  954. enum llama_fver {
  955. GGUF_FILE_VERSION_V1 = 1,
  956. };
  957. static const char * llama_file_version_name(llama_fver version) {
  958. switch (version) {
  959. case GGUF_FILE_VERSION_V1: return "GGUF V1 (latest)";
  960. }
  961. return "unknown";
  962. }
  963. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  964. char buf[256];
  965. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  966. for (size_t i = 1; i < ne.size(); i++) {
  967. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  968. }
  969. return buf;
  970. }
  971. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  972. char buf[256];
  973. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  974. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  975. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  976. }
  977. return buf;
  978. }
  979. struct llama_model_loader {
  980. int n_kv = 0;
  981. int n_tensors = 0;
  982. int n_created = 0;
  983. int64_t n_elements = 0;
  984. bool use_mmap = false;
  985. llama_file file;
  986. llama_ftype ftype;
  987. llama_fver fver;
  988. std::unique_ptr<llama_mmap> mapping;
  989. struct gguf_context * ctx_gguf = NULL;
  990. struct ggml_context * ctx_meta = NULL;
  991. llama_model_loader(const std::string & fname, bool use_mmap) : file(fname.c_str(), "rb") {
  992. struct gguf_init_params params = {
  993. /*.no_alloc = */ true,
  994. /*.ctx = */ &ctx_meta,
  995. };
  996. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  997. if (!ctx_gguf) {
  998. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  999. }
  1000. n_kv = gguf_get_n_kv(ctx_gguf);
  1001. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1002. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1003. for (int i = 0; i < n_tensors; i++) {
  1004. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1005. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1006. n_elements += ggml_nelements(t);
  1007. }
  1008. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1009. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1010. // determine file type based on the number of tensors for each quantization and print meta data
  1011. // TODO: make optional
  1012. {
  1013. std::map<enum ggml_type, uint32_t> n_type;
  1014. uint32_t n_type_max = 0;
  1015. enum ggml_type type_max = GGML_TYPE_F32;
  1016. for (int i = 0; i < n_tensors; i++) {
  1017. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1018. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, name);
  1019. n_type[meta->type]++;
  1020. if (n_type_max < n_type[meta->type]) {
  1021. n_type_max = n_type[meta->type];
  1022. type_max = meta->type;
  1023. }
  1024. LLAMA_LOG_INFO("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, name, ggml_type_name(meta->type), llama_format_tensor_shape(meta).c_str());
  1025. }
  1026. switch (type_max) {
  1027. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1028. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1029. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1030. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1031. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1032. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1033. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1034. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1035. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1036. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1037. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1038. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1039. default:
  1040. {
  1041. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1042. ftype = LLAMA_FTYPE_ALL_F32;
  1043. } break;
  1044. }
  1045. // this is a way to mark that we have "guessed" the file type
  1046. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  1047. {
  1048. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  1049. if (kid >= 0) {
  1050. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  1051. }
  1052. }
  1053. for (int i = 0; i < n_kv; i++) {
  1054. const char * name = gguf_get_key(ctx_gguf, i);
  1055. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1056. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-8s\n", __func__, i, name, gguf_type_name(type));
  1057. }
  1058. // print type counts
  1059. for (auto & kv : n_type) {
  1060. if (kv.second == 0) {
  1061. continue;
  1062. }
  1063. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  1064. }
  1065. }
  1066. if (!llama_mmap::SUPPORTED) {
  1067. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  1068. use_mmap = false;
  1069. }
  1070. this->use_mmap = use_mmap;
  1071. }
  1072. ~llama_model_loader() {
  1073. if (ctx_gguf) {
  1074. gguf_free(ctx_gguf);
  1075. }
  1076. if (ctx_meta) {
  1077. ggml_free(ctx_meta);
  1078. }
  1079. }
  1080. std::string get_arch_name() const {
  1081. const auto kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1082. std::string arch_name;
  1083. GGUF_GET_KEY(ctx_gguf, arch_name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_ARCHITECTURE));
  1084. return arch_name;
  1085. }
  1086. enum llm_arch get_arch() const {
  1087. const std::string arch_name = get_arch_name();
  1088. return llm_arch_from_string(arch_name);
  1089. }
  1090. const char * get_tensor_name(int i) const {
  1091. return gguf_get_tensor_name(ctx_gguf, i);
  1092. }
  1093. struct ggml_tensor * get_tensor_meta(int i) const {
  1094. return ggml_get_tensor(ctx_meta, get_tensor_name(i));
  1095. }
  1096. void calc_sizes(size_t & ctx_size_p, size_t & mmapped_size_p) const {
  1097. ctx_size_p = 0;
  1098. mmapped_size_p = 0;
  1099. for (int i = 0; i < n_tensors; i++) {
  1100. struct ggml_tensor * meta = get_tensor_meta(i);
  1101. ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  1102. (use_mmap ? mmapped_size_p : ctx_size_p) += ggml_nbytes_pad(meta);
  1103. }
  1104. }
  1105. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta, ggml_backend backend) {
  1106. if (backend != GGML_BACKEND_CPU) {
  1107. ggml_set_no_alloc(ctx, true);
  1108. }
  1109. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  1110. tensor->backend = backend; // TODO: ggml_set_backend
  1111. ggml_set_name(tensor, ggml_get_name(meta));
  1112. if (backend != GGML_BACKEND_CPU) {
  1113. ggml_set_no_alloc(ctx, use_mmap);
  1114. }
  1115. n_created++;
  1116. return tensor;
  1117. }
  1118. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, ggml_backend backend) {
  1119. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  1120. if (cur == NULL) {
  1121. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  1122. }
  1123. {
  1124. bool is_ok = true;
  1125. for (size_t i = 0; i < ne.size(); ++i) {
  1126. if (ne[i] != cur->ne[i]) {
  1127. is_ok = false;
  1128. break;
  1129. }
  1130. }
  1131. if (!is_ok) {
  1132. throw std::runtime_error(
  1133. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  1134. __func__, name.c_str(),
  1135. llama_format_tensor_shape(ne).c_str(),
  1136. llama_format_tensor_shape(cur).c_str()));
  1137. }
  1138. }
  1139. return create_tensor_for(ctx, cur, backend);
  1140. }
  1141. void done_getting_tensors() const {
  1142. if (n_created != n_tensors) {
  1143. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  1144. }
  1145. }
  1146. size_t file_offset(const char * name) const {
  1147. const int idx = gguf_find_tensor(ctx_gguf, name);
  1148. if (idx < 0) {
  1149. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  1150. }
  1151. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  1152. }
  1153. void load_data_for(struct ggml_tensor * cur) const {
  1154. const size_t offs = file_offset(ggml_get_name(cur));
  1155. if (use_mmap) {
  1156. cur->data = (uint8_t *) mapping->addr + offs;
  1157. } else {
  1158. file.seek(offs, SEEK_SET);
  1159. file.read_raw(cur->data, ggml_nbytes(cur));
  1160. }
  1161. }
  1162. void load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  1163. size_t size_data = 0;
  1164. size_t size_lock = 0;
  1165. size_t size_pref = 0; // prefetch
  1166. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1167. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1168. size_data += ggml_nbytes(cur);
  1169. if (cur->backend == GGML_BACKEND_CPU) {
  1170. size_pref += ggml_nbytes(cur);
  1171. }
  1172. }
  1173. if (use_mmap) {
  1174. mapping.reset(new llama_mmap(&file, size_pref, ggml_is_numa()));
  1175. if (lmlock) {
  1176. lmlock->init(mapping->addr);
  1177. }
  1178. }
  1179. size_t done_size = 0;
  1180. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1181. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1182. GGML_ASSERT(cur); // unused tensors should have been caught by load_data already
  1183. if (progress_callback) {
  1184. progress_callback((float) done_size / size_data, progress_callback_user_data);
  1185. }
  1186. // allocate temp buffer if not using mmap
  1187. if (!use_mmap && cur->data == NULL) {
  1188. GGML_ASSERT(cur->backend != GGML_BACKEND_CPU);
  1189. cur->data = malloc(ggml_nbytes(cur));
  1190. }
  1191. load_data_for(cur);
  1192. switch (cur->backend) {
  1193. case GGML_BACKEND_CPU:
  1194. if (use_mmap && lmlock) {
  1195. size_lock += ggml_nbytes(cur);
  1196. lmlock->grow_to(size_lock);
  1197. }
  1198. break;
  1199. #if defined(GGML_USE_CUBLAS)
  1200. case GGML_BACKEND_GPU:
  1201. case GGML_BACKEND_GPU_SPLIT:
  1202. // old code:
  1203. //ggml_cuda_transform_tensor(lt.data, lt.ggml_tensor);
  1204. // TODO: test if this works !!
  1205. ggml_cuda_transform_tensor(cur->data, cur);
  1206. if (!use_mmap) {
  1207. free(cur->data);
  1208. }
  1209. break;
  1210. #elif defined(GGML_USE_CLBLAST)
  1211. case GGML_BACKEND_GPU:
  1212. ggml_cl_transform_tensor(cur->data, cur);
  1213. if (!use_mmap) {
  1214. free(cur->data);
  1215. }
  1216. break;
  1217. #endif
  1218. default:
  1219. continue;
  1220. }
  1221. done_size += ggml_nbytes(cur);
  1222. }
  1223. }
  1224. };
  1225. //
  1226. // load LLaMA models
  1227. //
  1228. std::string llama_model_ftype_name(enum llama_ftype ftype) {
  1229. if (ftype & LLAMA_FTYPE_GUESSED) {
  1230. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  1231. }
  1232. switch (ftype) {
  1233. case LLAMA_FTYPE_ALL_F32: return "all F32";
  1234. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  1235. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  1236. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  1237. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  1238. return "mostly Q4_1, some F16";
  1239. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  1240. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  1241. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  1242. // K-quants
  1243. case LLAMA_FTYPE_MOSTLY_Q2_K: return "mostly Q2_K";
  1244. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "mostly Q3_K - Small";
  1245. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "mostly Q3_K - Medium";
  1246. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "mostly Q3_K - Large";
  1247. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "mostly Q4_K - Small";
  1248. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "mostly Q4_K - Medium";
  1249. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "mostly Q5_K - Small";
  1250. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "mostly Q5_K - Medium";
  1251. case LLAMA_FTYPE_MOSTLY_Q6_K: return "mostly Q6_K";
  1252. default: return "unknown, may not work";
  1253. }
  1254. }
  1255. static const char * llama_model_type_name(e_model type) {
  1256. switch (type) {
  1257. case MODEL_3B: return "3B";
  1258. case MODEL_7B: return "7B";
  1259. case MODEL_13B: return "13B";
  1260. case MODEL_30B: return "30B";
  1261. case MODEL_40B: return "40B";
  1262. case MODEL_65B: return "65B";
  1263. case MODEL_70B: return "70B";
  1264. default: return "?B";
  1265. }
  1266. }
  1267. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  1268. model.arch = ml.get_arch();
  1269. if (model.arch == LLM_ARCH_UNKNOWN) {
  1270. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  1271. }
  1272. }
  1273. static void llm_load_hparams(
  1274. llama_model_loader & ml,
  1275. llama_model & model,
  1276. int n_ctx,
  1277. float rope_freq_base,
  1278. float rope_freq_scale) {
  1279. struct gguf_context * ctx = ml.ctx_gguf;
  1280. const auto kv = LLM_KV(model.arch);
  1281. auto & hparams = model.hparams;
  1282. // get general kv
  1283. GGUF_GET_KEY(ctx, model.name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_NAME));
  1284. // get hparams kv
  1285. GGUF_GET_KEY(ctx, hparams.n_vocab, gguf_get_arr_n, GGUF_TYPE_ARRAY, true, kv(LLM_KV_TOKENIZER_LIST));
  1286. GGUF_GET_KEY(ctx, hparams.n_ctx_train, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_CONTEXT_LENGTH));
  1287. GGUF_GET_KEY(ctx, hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_EMBEDDING_LENGTH));
  1288. GGUF_GET_KEY(ctx, hparams.n_ff, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_FEED_FORWARD_LENGTH));
  1289. GGUF_GET_KEY(ctx, hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_ATTENTION_HEAD_COUNT));
  1290. GGUF_GET_KEY(ctx, hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_BLOCK_COUNT));
  1291. // n_head_kv is optional, default to n_head
  1292. hparams.n_head_kv = hparams.n_head;
  1293. GGUF_GET_KEY(ctx, hparams.n_head_kv, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ATTENTION_HEAD_COUNT_KV));
  1294. // TODO: manually setting rope scale should override this
  1295. // rope_freq_scale (inverse of the kv) is optional
  1296. {
  1297. float ropescale = 1.0f;
  1298. GGUF_GET_KEY(ctx, ropescale, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_SCALE_LINEAR));
  1299. if (ropescale != 1.0f) {
  1300. rope_freq_scale = 1.0f/ropescale;
  1301. }
  1302. }
  1303. // sanity check for n_rot (optional)
  1304. {
  1305. hparams.n_rot = hparams.n_embd / hparams.n_head;
  1306. GGUF_GET_KEY(ctx, hparams.n_rot, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ROPE_DIMENSION_COUNT));
  1307. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  1308. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  1309. }
  1310. }
  1311. // arch-specific KVs
  1312. switch (model.arch) {
  1313. case LLM_ARCH_LLAMA:
  1314. {
  1315. GGUF_GET_KEY(ctx, hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS));
  1316. switch (hparams.n_layer) {
  1317. case 26: model.type = e_model::MODEL_3B; break;
  1318. case 32: model.type = e_model::MODEL_7B; break;
  1319. case 40: model.type = e_model::MODEL_13B; break;
  1320. case 60: model.type = e_model::MODEL_30B; break;
  1321. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  1322. default: model.type = e_model::MODEL_UNKNOWN;
  1323. }
  1324. } break;
  1325. case LLM_ARCH_FALCON:
  1326. {
  1327. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1328. switch (hparams.n_layer) {
  1329. case 32: model.type = e_model::MODEL_7B; break;
  1330. case 60: model.type = e_model::MODEL_40B; break;
  1331. default: model.type = e_model::MODEL_UNKNOWN;
  1332. }
  1333. } break;
  1334. default: (void)0;
  1335. };
  1336. model.ftype = ml.ftype;
  1337. hparams.n_ctx = n_ctx;
  1338. hparams.rope_freq_base = rope_freq_base;
  1339. hparams.rope_freq_scale = rope_freq_scale;
  1340. }
  1341. // TODO: This should probably be in llama.h
  1342. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, const std::string & raw_text, bool bos, bool escape);
  1343. static void llm_load_vocab(
  1344. llama_model_loader & ml,
  1345. llama_model & model) {
  1346. auto & vocab = model.vocab;
  1347. struct gguf_context * ctx = ml.ctx_gguf;
  1348. const auto kv = LLM_KV(model.arch);
  1349. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  1350. if (token_idx == -1) {
  1351. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  1352. }
  1353. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  1354. if (score_idx == -1) {
  1355. throw std::runtime_error("cannot find tokenizer scores in model file\n");
  1356. }
  1357. const float * scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  1358. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  1359. if (toktype_idx == -1) {
  1360. throw std::runtime_error("cannot find token type list in GGUF file\n");
  1361. }
  1362. const int * toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  1363. // determine vocab type
  1364. {
  1365. std::string tokenizer_name;
  1366. GGUF_GET_KEY(ctx, tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, kv(LLM_KV_TOKENIZER_MODEL));
  1367. if (tokenizer_name == "llama") {
  1368. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1369. // default special tokens
  1370. vocab.special_bos_id = 1;
  1371. vocab.special_eos_id = 2;
  1372. vocab.special_unk_id = 0;
  1373. vocab.special_sep_id = -1;
  1374. vocab.special_pad_id = -1;
  1375. } else if (tokenizer_name == "gpt2") {
  1376. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  1377. // read bpe merges and populate bpe ranks
  1378. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  1379. if (merges_keyidx == -1) {
  1380. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  1381. }
  1382. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  1383. for (int i = 0; i < n_merges; i++) {
  1384. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  1385. std::string first;
  1386. std::string second;
  1387. const size_t pos = word.find(' ', 1);
  1388. if (pos != std::string::npos) {
  1389. first = word.substr(0, pos);
  1390. second = word.substr(pos + 1);
  1391. }
  1392. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  1393. }
  1394. // default special tokens
  1395. vocab.special_bos_id = 11;
  1396. vocab.special_eos_id = 11;
  1397. vocab.special_unk_id = -1;
  1398. vocab.special_sep_id = -1;
  1399. vocab.special_pad_id = -1;
  1400. } else {
  1401. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  1402. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  1403. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1404. }
  1405. }
  1406. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  1407. vocab.id_to_token.resize(n_vocab);
  1408. for (uint32_t i = 0; i < n_vocab; i++) {
  1409. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  1410. vocab.token_to_id[word] = i;
  1411. auto & token_data = vocab.id_to_token[i];
  1412. token_data.text = std::move(word);
  1413. token_data.score = scores[i];
  1414. token_data.type = (llama_token_type) toktypes[i];
  1415. }
  1416. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  1417. vocab.linefeed_id = llama_tokenize_internal(vocab, "\n", false, false)[0];
  1418. // special tokens
  1419. GGUF_GET_KEY(ctx, vocab.special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_BOS_ID));
  1420. GGUF_GET_KEY(ctx, vocab.special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_EOS_ID));
  1421. GGUF_GET_KEY(ctx, vocab.special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_UNK_ID));
  1422. GGUF_GET_KEY(ctx, vocab.special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_SEP_ID));
  1423. GGUF_GET_KEY(ctx, vocab.special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_PAD_ID));
  1424. }
  1425. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  1426. const auto & hparams = model.hparams;
  1427. const auto & vocab = model.vocab;
  1428. // hparams
  1429. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  1430. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  1431. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  1432. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  1433. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  1434. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  1435. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, hparams.n_ctx);
  1436. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  1437. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  1438. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  1439. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  1440. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot); // a.k.a. n_embd_head, n_head_dim
  1441. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  1442. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  1443. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  1444. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  1445. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, hparams.rope_freq_base);
  1446. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, hparams.rope_freq_scale);
  1447. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  1448. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  1449. LLAMA_LOG_INFO("%s: model size = %.2f B\n", __func__, ml.n_elements*1e-9);
  1450. // general kv
  1451. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  1452. // special tokens
  1453. 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() ); }
  1454. 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() ); }
  1455. 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() ); }
  1456. 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() ); }
  1457. 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() ); }
  1458. 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() ); }
  1459. }
  1460. static void llm_load_tensors(
  1461. llama_model_loader & ml,
  1462. llama_model & model,
  1463. int n_batch,
  1464. int n_gpu_layers,
  1465. int main_gpu,
  1466. const float * tensor_split,
  1467. const bool mul_mat_q,
  1468. bool low_vram,
  1469. ggml_type memory_type,
  1470. bool use_mlock,
  1471. llama_progress_callback progress_callback,
  1472. void * progress_callback_user_data) {
  1473. model.t_start_us = ggml_time_us();
  1474. auto & ctx = model.ctx;
  1475. auto & hparams = model.hparams;
  1476. model.n_gpu_layers = n_gpu_layers;
  1477. size_t ctx_size;
  1478. size_t mmapped_size;
  1479. ml.calc_sizes(ctx_size, mmapped_size);
  1480. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MB\n", __func__, ctx_size/1024.0/1024.0);
  1481. // create the ggml context
  1482. {
  1483. model.buf.resize(ctx_size);
  1484. if (use_mlock) {
  1485. model.mlock_buf.init (model.buf.data);
  1486. model.mlock_buf.grow_to(model.buf.size);
  1487. }
  1488. struct ggml_init_params params = {
  1489. /*.mem_size =*/ model.buf.size,
  1490. /*.mem_buffer =*/ model.buf.data,
  1491. /*.no_alloc =*/ ml.use_mmap,
  1492. };
  1493. model.ctx = ggml_init(params);
  1494. if (!model.ctx) {
  1495. throw std::runtime_error(format("ggml_init() failed"));
  1496. }
  1497. }
  1498. (void) main_gpu;
  1499. (void) mul_mat_q;
  1500. #if defined(GGML_USE_CUBLAS)
  1501. LLAMA_LOG_INFO("%s: using CUDA for GPU acceleration\n", __func__);
  1502. ggml_cuda_set_main_device(main_gpu);
  1503. ggml_cuda_set_mul_mat_q(mul_mat_q);
  1504. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1505. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU_SPLIT
  1506. #elif defined(GGML_USE_CLBLAST)
  1507. LLAMA_LOG_INFO("%s: using OpenCL for GPU acceleration\n", __func__);
  1508. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1509. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU
  1510. #else
  1511. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_CPU
  1512. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_CPU
  1513. #endif
  1514. // prepare memory for the weights
  1515. size_t vram_weights = 0;
  1516. {
  1517. const int64_t n_embd = hparams.n_embd;
  1518. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  1519. const int64_t n_layer = hparams.n_layer;
  1520. const int64_t n_vocab = hparams.n_vocab;
  1521. const auto tn = LLM_TN(model.arch);
  1522. switch (model.arch) {
  1523. case LLM_ARCH_LLAMA:
  1524. {
  1525. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1526. // output
  1527. {
  1528. ggml_backend backend_norm;
  1529. ggml_backend backend_output;
  1530. if (n_gpu_layers > int(n_layer)) {
  1531. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1532. // on Windows however this is detrimental unless everything is on the GPU
  1533. #ifndef _WIN32
  1534. backend_norm = low_vram ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1535. #else
  1536. backend_norm = low_vram || n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1537. #endif // _WIN32
  1538. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1539. } else {
  1540. backend_norm = GGML_BACKEND_CPU;
  1541. backend_output = GGML_BACKEND_CPU;
  1542. }
  1543. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1544. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1545. if (backend_norm == GGML_BACKEND_GPU) {
  1546. vram_weights += ggml_nbytes(model.output_norm);
  1547. }
  1548. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1549. vram_weights += ggml_nbytes(model.output);
  1550. }
  1551. }
  1552. const uint32_t n_ff = hparams.n_ff;
  1553. const int i_gpu_start = n_layer - n_gpu_layers;
  1554. model.layers.resize(n_layer);
  1555. for (uint32_t i = 0; i < n_layer; ++i) {
  1556. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1557. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1558. auto & layer = model.layers[i];
  1559. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  1560. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  1561. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1562. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1563. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  1564. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  1565. layer.w1 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  1566. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  1567. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  1568. if (backend == GGML_BACKEND_GPU) {
  1569. vram_weights +=
  1570. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  1571. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  1572. ggml_nbytes(layer.w1) + ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1573. }
  1574. }
  1575. } break;
  1576. case LLM_ARCH_FALCON:
  1577. {
  1578. // TODO: CPU-only for now
  1579. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1580. // output
  1581. {
  1582. ggml_backend backend_norm;
  1583. ggml_backend backend_output;
  1584. if (n_gpu_layers > int(n_layer)) {
  1585. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1586. // on Windows however this is detrimental unless everything is on the GPU
  1587. #ifndef _WIN32
  1588. backend_norm = low_vram ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1589. #else
  1590. backend_norm = low_vram || n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1591. #endif // _WIN32
  1592. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1593. } else {
  1594. backend_norm = GGML_BACKEND_CPU;
  1595. backend_output = GGML_BACKEND_CPU;
  1596. }
  1597. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1598. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  1599. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1600. }
  1601. const uint32_t n_ff = hparams.n_ff;
  1602. const int i_gpu_start = n_layer - n_gpu_layers;
  1603. model.layers.resize(n_layer);
  1604. for (uint32_t i = 0; i < n_layer; ++i) {
  1605. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1606. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1607. auto & layer = model.layers[i];
  1608. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  1609. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  1610. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  1611. layer.attn_norm_2 = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, backend);
  1612. layer.attn_norm_2_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, backend);
  1613. }
  1614. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  1615. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  1616. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  1617. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  1618. }
  1619. } break;
  1620. default:
  1621. throw std::runtime_error("unknown architecture");
  1622. };
  1623. }
  1624. ml.done_getting_tensors();
  1625. // print memory requirements
  1626. {
  1627. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  1628. // this is the total memory required to run the inference
  1629. size_t mem_required =
  1630. ctx_size +
  1631. mmapped_size - vram_weights; // weights in VRAM not in memory
  1632. // this is the memory required by one llama_state
  1633. const size_t mem_required_state = scale*hparams.kv_size();
  1634. LLAMA_LOG_INFO("%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  1635. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  1636. (void) n_batch;
  1637. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1638. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  1639. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  1640. if (n_gpu_layers > (int) hparams.n_layer) {
  1641. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  1642. }
  1643. size_t vram_kv_cache = 0;
  1644. #ifdef GGML_USE_CUBLAS
  1645. const int max_backend_supported_layers = hparams.n_layer + 3;
  1646. const int max_offloadable_layers = low_vram ? hparams.n_layer + 1 : hparams.n_layer + 3;
  1647. if (n_gpu_layers > (int) hparams.n_layer + 1) {
  1648. if (low_vram) {
  1649. LLAMA_LOG_INFO("%s: cannot offload v cache to GPU due to low VRAM option\n", __func__);
  1650. } else {
  1651. LLAMA_LOG_INFO("%s: offloading v cache to GPU\n", __func__);
  1652. vram_kv_cache += hparams.kv_size() / 2;
  1653. }
  1654. }
  1655. if (n_gpu_layers > (int) hparams.n_layer + 2) {
  1656. if (low_vram) {
  1657. LLAMA_LOG_WARN("%s: cannot offload k cache to GPU due to low VRAM option\n", __func__);
  1658. } else {
  1659. LLAMA_LOG_INFO("%s: offloading k cache to GPU\n", __func__);
  1660. vram_kv_cache += hparams.kv_size() / 2;
  1661. }
  1662. }
  1663. #elif defined(GGML_USE_CLBLAST)
  1664. const int max_backend_supported_layers = hparams.n_layer + 1;
  1665. const int max_offloadable_layers = hparams.n_layer + 1;
  1666. #endif // GGML_USE_CUBLAS
  1667. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n",
  1668. __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  1669. LLAMA_LOG_INFO("%s: VRAM used: %zu MB\n",
  1670. __func__, (vram_weights + vram_kv_cache + MB - 1) / MB); // round up
  1671. #else
  1672. (void) n_gpu_layers;
  1673. #endif // defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1674. }
  1675. // populate `tensors_by_name`
  1676. for (int i = 0; i < ml.n_tensors; ++i) {
  1677. struct ggml_tensor * cur = ggml_get_tensor(ctx, ml.get_tensor_name(i));
  1678. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  1679. }
  1680. (void) tensor_split;
  1681. #if defined(GGML_USE_CUBLAS)
  1682. {
  1683. ggml_cuda_set_tensor_split(tensor_split);
  1684. }
  1685. #endif
  1686. ml.load_all_data(ctx, progress_callback, progress_callback_user_data, use_mlock ? &model.mlock_mmap : NULL);
  1687. if (progress_callback) {
  1688. progress_callback(1.0f, progress_callback_user_data);
  1689. }
  1690. model.mapping = std::move(ml.mapping);
  1691. // loading time will be recalculate after the first eval, so
  1692. // we take page faults deferred by mmap() into consideration
  1693. model.t_load_us = ggml_time_us() - model.t_start_us;
  1694. }
  1695. static bool llama_model_load(
  1696. const std::string & fname,
  1697. llama_model & model,
  1698. int n_ctx,
  1699. int n_batch,
  1700. int n_gpu_layers,
  1701. int main_gpu,
  1702. const float * tensor_split,
  1703. const bool mul_mat_q,
  1704. float rope_freq_base,
  1705. float rope_freq_scale,
  1706. bool low_vram,
  1707. ggml_type memory_type,
  1708. bool use_mmap,
  1709. bool use_mlock,
  1710. bool vocab_only,
  1711. llama_progress_callback progress_callback,
  1712. void *progress_callback_user_data) {
  1713. try {
  1714. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap));
  1715. llm_load_arch (*ml, model);
  1716. llm_load_hparams(*ml, model, n_ctx, rope_freq_base, rope_freq_scale);
  1717. llm_load_vocab (*ml, model);
  1718. llm_load_print_meta(*ml, model);
  1719. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  1720. throw std::runtime_error("vocab size mismatch");
  1721. }
  1722. if (vocab_only) {
  1723. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  1724. return true;
  1725. }
  1726. llm_load_tensors(
  1727. *ml, model, n_batch, n_gpu_layers,
  1728. main_gpu, tensor_split, mul_mat_q, low_vram, memory_type,
  1729. use_mlock, progress_callback, progress_callback_user_data);
  1730. } catch (const std::exception & err) {
  1731. LLAMA_LOG_ERROR("error loading model: %s\n", err.what());
  1732. return false;
  1733. }
  1734. return true;
  1735. }
  1736. static struct ggml_cgraph * llm_build_llama(
  1737. llama_context & lctx,
  1738. const llama_token * tokens,
  1739. const float * embd,
  1740. int n_tokens,
  1741. int n_past) {
  1742. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  1743. const int N = n_tokens;
  1744. const auto & model = lctx.model;
  1745. const auto & hparams = model.hparams;
  1746. const auto & kv_self = lctx.kv_self;
  1747. GGML_ASSERT(!!kv_self.ctx);
  1748. const int64_t n_embd = hparams.n_embd;
  1749. const int64_t n_layer = hparams.n_layer;
  1750. const int64_t n_ctx = hparams.n_ctx;
  1751. const int64_t n_head = hparams.n_head;
  1752. const int64_t n_head_kv = hparams.n_head_kv;
  1753. const int64_t n_embd_head = hparams.n_embd_head();
  1754. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  1755. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1756. const float freq_base = hparams.rope_freq_base;
  1757. const float freq_scale = hparams.rope_freq_scale;
  1758. const float norm_rms_eps = hparams.f_norm_rms_eps;
  1759. const int n_gpu_layers = model.n_gpu_layers;
  1760. auto & buf_compute = lctx.buf_compute;
  1761. struct ggml_init_params params = {
  1762. /*.mem_size =*/ buf_compute.size,
  1763. /*.mem_buffer =*/ buf_compute.data,
  1764. /*.no_alloc =*/ false,
  1765. };
  1766. params.no_alloc = true;
  1767. struct ggml_context * ctx0 = ggml_init(params);
  1768. ggml_cgraph * gf = ggml_new_graph(ctx0);
  1769. struct ggml_tensor * cur;
  1770. struct ggml_tensor * inpL;
  1771. if (tokens) {
  1772. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  1773. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  1774. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1775. memcpy(inp_tokens->data, tokens, N*ggml_element_size(inp_tokens));
  1776. }
  1777. ggml_set_name(inp_tokens, "inp_tokens");
  1778. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  1779. } else {
  1780. #ifdef GGML_USE_MPI
  1781. GGML_ASSERT(false && "not implemented");
  1782. #endif
  1783. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N);
  1784. ggml_allocr_alloc(lctx.alloc, inpL);
  1785. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1786. memcpy(inpL->data, embd, N * n_embd * ggml_element_size(inpL));
  1787. }
  1788. }
  1789. const int i_gpu_start = n_layer - n_gpu_layers;
  1790. (void) i_gpu_start;
  1791. // offload functions set the tensor output backend to GPU
  1792. // tensors are GPU-accelerated if any input or the output has been offloaded
  1793. //
  1794. // with the low VRAM option VRAM scratch is disabled in llama_load_model_internal
  1795. // in that case ggml_cuda_assign_buffers has no effect
  1796. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  1797. offload_func_t offload_func_kq = llama_nop;
  1798. offload_func_t offload_func_v = llama_nop;
  1799. #ifdef GGML_USE_CUBLAS
  1800. if (n_gpu_layers > n_layer) {
  1801. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  1802. }
  1803. if (n_gpu_layers > n_layer + 1) {
  1804. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  1805. }
  1806. if (n_gpu_layers > n_layer + 2) {
  1807. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  1808. }
  1809. #endif // GGML_USE_CUBLAS
  1810. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  1811. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  1812. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1813. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  1814. }
  1815. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  1816. for (int il = 0; il < n_layer; ++il) {
  1817. ggml_format_name(inpL, "layer_inp_%d", il);
  1818. offload_func_t offload_func = llama_nop;
  1819. #ifdef GGML_USE_CUBLAS
  1820. if (il >= i_gpu_start) {
  1821. offload_func = ggml_cuda_assign_buffers_no_alloc;
  1822. }
  1823. #endif // GGML_USE_CUBLAS
  1824. struct ggml_tensor * inpSA = inpL;
  1825. // norm
  1826. {
  1827. cur = ggml_rms_norm(ctx0, inpL, norm_rms_eps);
  1828. offload_func(cur);
  1829. ggml_set_name(cur, "rms_norm_0");
  1830. // cur = cur*attn_norm(broadcasted)
  1831. cur = ggml_mul(ctx0, cur, model.layers[il].attn_norm);
  1832. offload_func(cur);
  1833. ggml_set_name(cur, "attention_norm_0");
  1834. }
  1835. // self-attention
  1836. {
  1837. // compute Q and K and RoPE them
  1838. struct ggml_tensor * tmpk = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  1839. offload_func_kq(tmpk);
  1840. ggml_set_name(tmpk, "tmpk");
  1841. struct ggml_tensor * tmpq = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  1842. offload_func_kq(tmpq);
  1843. ggml_set_name(tmpq, "tmpq");
  1844. struct ggml_tensor * Kcur = ggml_rope_custom_inplace(ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, N), n_past, n_embd_head, 0, 0, freq_base, freq_scale);
  1845. offload_func_kq(Kcur);
  1846. ggml_set_name(Kcur, "Kcur");
  1847. struct ggml_tensor * Qcur = ggml_rope_custom_inplace(ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, N), n_past, n_embd_head, 0, 0, freq_base, freq_scale);
  1848. offload_func_kq(Qcur);
  1849. ggml_set_name(Qcur, "Qcur");
  1850. // store key and value to memory
  1851. {
  1852. // compute the transposed [N, n_embd] V matrix
  1853. struct ggml_tensor * tmpv = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  1854. offload_func_v(tmpv);
  1855. ggml_set_name(tmpv, "tmpv");
  1856. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, tmpv, n_embd_gqa, N));
  1857. offload_func_v(Vcur);
  1858. ggml_set_name(Vcur, "Vcur");
  1859. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + n_past));
  1860. offload_func_kq(k);
  1861. ggml_set_name(k, "k");
  1862. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd_gqa,
  1863. ( n_ctx)*ggml_element_size(kv_self.v),
  1864. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + n_past*ggml_element_size(kv_self.v));
  1865. offload_func_v(v);
  1866. ggml_set_name(v, "v");
  1867. // important: storing RoPE-ed version of K in the KV cache!
  1868. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  1869. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  1870. }
  1871. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  1872. offload_func_kq(Q);
  1873. ggml_set_name(Q, "Q");
  1874. struct ggml_tensor * K =
  1875. ggml_view_3d(ctx0, kv_self.k,
  1876. n_embd_head, n_past + N, n_head_kv,
  1877. ggml_element_size(kv_self.k)*n_embd_gqa,
  1878. ggml_element_size(kv_self.k)*n_embd_head,
  1879. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  1880. offload_func_kq(K);
  1881. ggml_set_name(K, "K");
  1882. // K * Q
  1883. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1884. offload_func_kq(KQ);
  1885. ggml_set_name(KQ, "KQ");
  1886. // KQ_scaled = KQ / sqrt(n_embd_head)
  1887. // KQ_scaled shape [n_past + N, N, n_head, 1]
  1888. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  1889. offload_func_kq(KQ_scaled);
  1890. ggml_set_name(KQ_scaled, "KQ_scaled");
  1891. // KQ_masked = mask_past(KQ_scaled)
  1892. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  1893. offload_func_kq(KQ_masked);
  1894. ggml_set_name(KQ_masked, "KQ_masked");
  1895. // KQ = soft_max(KQ_masked)
  1896. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  1897. offload_func_v(KQ_soft_max);
  1898. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  1899. // split cached V into n_head heads
  1900. struct ggml_tensor * V =
  1901. ggml_view_3d(ctx0, kv_self.v,
  1902. n_past + N, n_embd_head, n_head_kv,
  1903. ggml_element_size(kv_self.v)*n_ctx,
  1904. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  1905. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  1906. offload_func_v(V);
  1907. ggml_set_name(V, "V");
  1908. #if 1
  1909. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  1910. offload_func_v(KQV);
  1911. ggml_set_name(KQV, "KQV");
  1912. #else
  1913. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  1914. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  1915. // is there a better way?
  1916. struct ggml_tensor * V_cont = ggml_cpy(ctx0, V, ggml_new_tensor_3d(ctx0, kv_self.v->type, n_past + N, n_embd_head, n_head));
  1917. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  1918. #endif
  1919. // KQV_merged = KQV.permute(0, 2, 1, 3)
  1920. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1921. offload_func_v(KQV_merged);
  1922. ggml_set_name(KQV_merged, "KQV_merged");
  1923. // cur = KQV_merged.contiguous().view(n_embd, N)
  1924. cur = ggml_cpy(ctx0,
  1925. KQV_merged,
  1926. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  1927. offload_func_v(cur);
  1928. ggml_set_name(cur, "KQV_merged_contiguous");
  1929. // projection (no bias)
  1930. cur = ggml_mul_mat(ctx0,
  1931. model.layers[il].wo,
  1932. cur);
  1933. offload_func(cur);
  1934. ggml_set_name(cur, "result_wo");
  1935. }
  1936. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  1937. offload_func(inpFF);
  1938. ggml_set_name(inpFF, "inpFF");
  1939. // feed-forward network
  1940. {
  1941. // norm
  1942. {
  1943. cur = ggml_rms_norm(ctx0, inpFF, norm_rms_eps);
  1944. offload_func(cur);
  1945. ggml_set_name(cur, "rms_norm_1");
  1946. // cur = cur*ffn_norm(broadcasted)
  1947. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_norm);
  1948. offload_func(cur);
  1949. ggml_set_name(cur, "ffn_norm");
  1950. }
  1951. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  1952. model.layers[il].w3,
  1953. cur);
  1954. offload_func(tmp);
  1955. ggml_set_name(tmp, "result_w3");
  1956. cur = ggml_mul_mat(ctx0,
  1957. model.layers[il].w1,
  1958. cur);
  1959. offload_func(cur);
  1960. ggml_set_name(cur, "result_w1");
  1961. // SILU activation
  1962. cur = ggml_silu(ctx0, cur);
  1963. offload_func(cur);
  1964. ggml_set_name(cur, "silu");
  1965. cur = ggml_mul(ctx0, cur, tmp);
  1966. offload_func(cur);
  1967. ggml_set_name(cur, "silu_x_result_w3");
  1968. cur = ggml_mul_mat(ctx0,
  1969. model.layers[il].w2,
  1970. cur);
  1971. offload_func(cur);
  1972. ggml_set_name(cur, "result_w2");
  1973. }
  1974. cur = ggml_add(ctx0, cur, inpFF);
  1975. offload_func(cur);
  1976. ggml_set_name(cur, "inpFF_+_result_w2");
  1977. // input for next layer
  1978. inpL = cur;
  1979. }
  1980. cur = inpL;
  1981. // norm
  1982. {
  1983. cur = ggml_rms_norm(ctx0, cur, norm_rms_eps);
  1984. offload_func_nr(cur);
  1985. ggml_set_name(cur, "rms_norm_2");
  1986. // cur = cur*norm(broadcasted)
  1987. cur = ggml_mul(ctx0, cur, model.output_norm);
  1988. // offload_func_nr(cur); // TODO CPU + GPU mirrored backend
  1989. ggml_set_name(cur, "result_norm");
  1990. }
  1991. // lm_head
  1992. cur = ggml_mul_mat(ctx0, model.output, cur);
  1993. ggml_set_name(cur, "result_output");
  1994. ggml_build_forward_expand(gf, cur);
  1995. ggml_free(ctx0);
  1996. return gf;
  1997. }
  1998. static struct ggml_cgraph * llm_build_falcon(
  1999. llama_context & lctx,
  2000. const llama_token * tokens,
  2001. const float * embd,
  2002. int n_tokens,
  2003. int n_past) {
  2004. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  2005. const int N = n_tokens;
  2006. const auto & model = lctx.model;
  2007. const auto & hparams = model.hparams;
  2008. const auto & kv_self = lctx.kv_self;
  2009. GGML_ASSERT(!!kv_self.ctx);
  2010. const int64_t n_embd = hparams.n_embd;
  2011. const int64_t n_layer = hparams.n_layer;
  2012. const int64_t n_ctx = hparams.n_ctx;
  2013. const int64_t n_head = hparams.n_head;
  2014. const int64_t n_head_kv = hparams.n_head_kv;
  2015. const int64_t n_embd_head = hparams.n_embd_head();
  2016. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2017. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2018. const float freq_base = hparams.rope_freq_base;
  2019. const float freq_scale = hparams.rope_freq_scale;
  2020. const float norm_eps = hparams.f_norm_eps;
  2021. const int n_gpu_layers = model.n_gpu_layers;
  2022. auto & buf_compute = lctx.buf_compute;
  2023. struct ggml_init_params params = {
  2024. /*.mem_size =*/ buf_compute.size,
  2025. /*.mem_buffer =*/ buf_compute.data,
  2026. /*.no_alloc =*/ false,
  2027. };
  2028. params.no_alloc = true;
  2029. struct ggml_context * ctx0 = ggml_init(params);
  2030. ggml_cgraph * gf = ggml_new_graph(ctx0);
  2031. struct ggml_tensor * cur;
  2032. struct ggml_tensor * inpL;
  2033. if (tokens) {
  2034. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  2035. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  2036. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2037. memcpy(inp_tokens->data, tokens, N*ggml_element_size(inp_tokens));
  2038. }
  2039. ggml_set_name(inp_tokens, "inp_tokens");
  2040. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  2041. } else {
  2042. #ifdef GGML_USE_MPI
  2043. GGML_ASSERT(false && "not implemented");
  2044. #endif
  2045. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N);
  2046. ggml_allocr_alloc(lctx.alloc, inpL);
  2047. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2048. memcpy(inpL->data, embd, N * n_embd * ggml_element_size(inpL));
  2049. }
  2050. }
  2051. const int i_gpu_start = n_layer - n_gpu_layers;
  2052. (void) i_gpu_start;
  2053. // offload functions set the tensor output backend to GPU
  2054. // tensors are GPU-accelerated if any input or the output has been offloaded
  2055. //
  2056. // with the low VRAM option VRAM scratch is disabled in llama_load_model_internal
  2057. // in that case ggml_cuda_assign_buffers has no effect
  2058. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  2059. offload_func_t offload_func_kq = llama_nop;
  2060. offload_func_t offload_func_v = llama_nop;
  2061. #ifdef GGML_USE_CUBLAS
  2062. if (n_gpu_layers > n_layer) {
  2063. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  2064. }
  2065. if (n_gpu_layers > n_layer + 1) {
  2066. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  2067. }
  2068. if (n_gpu_layers > n_layer + 2) {
  2069. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  2070. }
  2071. #endif // GGML_USE_CUBLAS
  2072. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  2073. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  2074. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2075. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  2076. }
  2077. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  2078. for (int il = 0; il < n_layer; ++il) {
  2079. struct ggml_tensor * attn_norm;
  2080. offload_func_t offload_func = llama_nop;
  2081. #ifdef GGML_USE_CUBLAS
  2082. if (il >= i_gpu_start) {
  2083. offload_func = ggml_cuda_assign_buffers_no_alloc;
  2084. }
  2085. #endif // GGML_USE_CUBLAS
  2086. // self-attention
  2087. // TODO: refactor into common function (shared with LLaMA)
  2088. {
  2089. attn_norm = ggml_norm(ctx0, inpL, norm_eps);
  2090. offload_func(attn_norm);
  2091. attn_norm = ggml_add(ctx0,
  2092. ggml_mul(ctx0, attn_norm, model.layers[il].attn_norm),
  2093. model.layers[il].attn_norm_b);
  2094. offload_func(attn_norm->src[0]);
  2095. offload_func(attn_norm);
  2096. if (model.layers[il].attn_norm_2) { // Falcon-40B
  2097. cur = ggml_norm(ctx0, inpL, norm_eps);
  2098. offload_func(cur);
  2099. cur = ggml_add(ctx0,
  2100. ggml_mul(ctx0, cur, model.layers[il].attn_norm_2),
  2101. model.layers[il].attn_norm_2_b);
  2102. offload_func(cur->src[0]);
  2103. offload_func(cur);
  2104. } else { // Falcon 7B
  2105. cur = attn_norm;
  2106. }
  2107. // compute QKV
  2108. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  2109. offload_func_kq(cur);
  2110. // Note that the strides for Kcur, Vcur are set up so that the
  2111. // resulting views are misaligned with the tensor's storage
  2112. // (by applying the K/V offset we shift the tensor's original
  2113. // view to stick out behind the viewed QKV tensor's allocated
  2114. // memory, so to say). This is ok because no actual accesses
  2115. // happen to that out-of-range memory, but it can require some
  2116. // trickery when trying to accurately dump these views for
  2117. // debugging.
  2118. const size_t wsize = ggml_type_size(cur->type);
  2119. struct ggml_tensor * tmpq = ggml_view_3d(
  2120. ctx0, cur, n_embd_head, n_head, N,
  2121. wsize * n_embd_head,
  2122. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2123. 0);
  2124. offload_func_kq(tmpq);
  2125. struct ggml_tensor * tmpk = ggml_view_3d(
  2126. ctx0, cur, n_embd_head, n_head_kv, N,
  2127. wsize * n_embd_head,
  2128. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2129. wsize * n_embd_head * n_head);
  2130. offload_func_kq(tmpk);
  2131. struct ggml_tensor * tmpv = ggml_view_3d(
  2132. ctx0, cur, n_embd_head, n_head_kv, N,
  2133. wsize * n_embd_head,
  2134. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2135. wsize * n_embd_head * (n_head + n_head_kv));
  2136. offload_func_v(tmpv);
  2137. // using mode = 2 for neox mode
  2138. struct ggml_tensor * Qcur = ggml_rope_custom_inplace(ctx0, tmpq, n_past, n_embd_head, 2, 0, freq_base, freq_scale);
  2139. offload_func_kq(Qcur);
  2140. struct ggml_tensor * Kcur = ggml_rope_custom_inplace(ctx0, tmpk, n_past, n_embd_head, 2, 0, freq_base, freq_scale);
  2141. offload_func_kq(Kcur);
  2142. {
  2143. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_cont(ctx0, tmpv), n_embd_gqa, N));
  2144. offload_func_v(Vcur);
  2145. offload_func_v(Vcur->src[0]->src[0]);
  2146. ggml_set_name(Vcur, "Vcur");
  2147. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + n_past));
  2148. offload_func_kq(k);
  2149. ggml_set_name(k, "k");
  2150. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd_gqa,
  2151. ( n_ctx)*ggml_element_size(kv_self.v),
  2152. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + n_past*ggml_element_size(kv_self.v));
  2153. offload_func_v(v);
  2154. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  2155. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  2156. }
  2157. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  2158. offload_func_kq(Q);
  2159. ggml_set_name(Q, "Q");
  2160. struct ggml_tensor * K =
  2161. ggml_view_3d(ctx0, kv_self.k,
  2162. n_embd_head, n_past + N, n_head_kv,
  2163. ggml_element_size(kv_self.k)*n_embd_gqa,
  2164. ggml_element_size(kv_self.k)*n_embd_head,
  2165. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  2166. offload_func_kq(K);
  2167. ggml_set_name(K, "K");
  2168. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  2169. offload_func_kq(KQ);
  2170. ggml_set_name(KQ, "KQ");
  2171. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  2172. offload_func_kq(KQ_scaled);
  2173. ggml_set_name(KQ_scaled, "KQ_scaled");
  2174. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  2175. offload_func_kq(KQ_masked);
  2176. ggml_set_name(KQ_masked, "KQ_masked");
  2177. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  2178. offload_func_v(KQ_soft_max);
  2179. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  2180. struct ggml_tensor * V =
  2181. ggml_view_3d(ctx0, kv_self.v,
  2182. n_past + N, n_embd_head, n_head_kv,
  2183. ggml_element_size(kv_self.v)*n_ctx,
  2184. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  2185. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  2186. offload_func_v(V);
  2187. ggml_set_name(V, "V");
  2188. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  2189. offload_func_v(KQV);
  2190. ggml_set_name(KQV, "KQV");
  2191. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  2192. offload_func_v(KQV_merged);
  2193. ggml_set_name(KQV_merged, "KQV_merged");
  2194. cur = ggml_cpy(ctx0, KQV_merged, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  2195. offload_func_v(cur);
  2196. ggml_set_name(cur, "KQV_merged_contiguous");
  2197. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  2198. offload_func(cur);
  2199. ggml_set_name(cur, "result_wo");
  2200. }
  2201. struct ggml_tensor * attn_out = cur;
  2202. // feed forward
  2203. {
  2204. struct ggml_tensor * inpFF = attn_norm;
  2205. cur = ggml_mul_mat(ctx0, model.layers[il].w3, inpFF);
  2206. // TODO: this is temporary needed to introduce artificial dependency between FF and ATTN
  2207. // adding this, because there seems to be a bug in the Metal concurrency optimization
  2208. // without this line, the results are non-deterministic and wrong
  2209. cur->src[2] = attn_out;
  2210. offload_func(cur);
  2211. cur = ggml_gelu(ctx0, cur);
  2212. offload_func(cur);
  2213. cur = ggml_mul_mat(ctx0, model.layers[il].w2, cur);
  2214. offload_func(cur);
  2215. }
  2216. cur = ggml_add(ctx0, cur, attn_out);
  2217. offload_func(cur);
  2218. cur = ggml_add(ctx0, cur, inpL);
  2219. offload_func(cur);
  2220. // input for next layer
  2221. inpL = cur;
  2222. }
  2223. cur = inpL;
  2224. // norm
  2225. {
  2226. cur = ggml_norm(ctx0, cur, norm_eps);
  2227. offload_func_nr(cur);
  2228. cur = ggml_add(ctx0,
  2229. ggml_mul(ctx0, cur, model.output_norm),
  2230. model.output_norm_b);
  2231. ggml_set_name(cur, "result_norm");
  2232. }
  2233. cur = ggml_mul_mat(ctx0, model.output, cur);
  2234. ggml_set_name(cur, "result_output");
  2235. ggml_build_forward_expand(gf, cur);
  2236. ggml_free(ctx0);
  2237. return gf;
  2238. }
  2239. static struct ggml_cgraph * llama_build_graph(
  2240. llama_context & lctx,
  2241. const llama_token * tokens,
  2242. const float * embd,
  2243. int n_tokens,
  2244. int n_past) {
  2245. const auto & model = lctx.model;
  2246. struct ggml_cgraph * result = NULL;
  2247. switch (model.arch) {
  2248. case LLM_ARCH_LLAMA:
  2249. {
  2250. result = llm_build_llama(lctx, tokens, embd, n_tokens, n_past);
  2251. } break;
  2252. case LLM_ARCH_FALCON:
  2253. {
  2254. result = llm_build_falcon(lctx, tokens, embd, n_tokens, n_past);
  2255. } break;
  2256. default:
  2257. GGML_ASSERT(false);
  2258. };
  2259. return result;
  2260. }
  2261. // evaluate the transformer
  2262. //
  2263. // - lctx: llama context
  2264. // - tokens: new batch of tokens to process
  2265. // - embd embeddings input
  2266. // - n_tokens number of tokens
  2267. // - n_past: the context size so far
  2268. // - n_threads: number of threads to use
  2269. //
  2270. static bool llama_eval_internal(
  2271. llama_context & lctx,
  2272. const llama_token * tokens,
  2273. const float * embd,
  2274. int n_tokens,
  2275. int n_past,
  2276. int n_threads,
  2277. const char * cgraph_fname) {
  2278. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  2279. GGML_ASSERT(n_tokens > 0);
  2280. GGML_ASSERT(n_past >= 0);
  2281. GGML_ASSERT(n_threads > 0);
  2282. // TODO: keep the values of n_batch and n_ctx
  2283. // GGML_ASSERT(n_tokens <= n_batch);
  2284. // GGML_ASSERT(n_past + n_tokens <= n_ctx);
  2285. const int64_t t_start_us = ggml_time_us();
  2286. #ifdef GGML_USE_MPI
  2287. ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  2288. #endif
  2289. const int N = n_tokens;
  2290. const auto & model = lctx.model;
  2291. const auto & hparams = model.hparams;
  2292. const auto & kv_self = lctx.kv_self;
  2293. GGML_ASSERT(!!kv_self.ctx);
  2294. const int64_t n_embd = hparams.n_embd;
  2295. const int64_t n_vocab = hparams.n_vocab;
  2296. ggml_allocr_reset(lctx.alloc);
  2297. ggml_cgraph * gf = llama_build_graph(lctx, tokens, embd, n_tokens, n_past);
  2298. ggml_allocr_alloc_graph(lctx.alloc, gf);
  2299. #ifdef GGML_USE_CUBLAS
  2300. for (int i = 0; i < gf->n_leafs; i++) {
  2301. ggml_tensor * node = gf->leafs[i];
  2302. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  2303. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  2304. }
  2305. }
  2306. for (int i = 0; i < gf->n_nodes; i++) {
  2307. ggml_tensor * node = gf->nodes[i];
  2308. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  2309. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  2310. }
  2311. }
  2312. #endif
  2313. // 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);
  2314. // for big prompts, if BLAS is enabled, it is better to use only one thread
  2315. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  2316. n_threads = N >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas() ? 1 : n_threads;
  2317. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  2318. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  2319. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  2320. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  2321. #if GGML_USE_MPI
  2322. const int64_t n_layer = hparams.n_layer;
  2323. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  2324. #endif
  2325. #ifdef GGML_USE_METAL
  2326. if (lctx.ctx_metal) {
  2327. ggml_metal_set_n_cb (lctx.ctx_metal, n_threads);
  2328. ggml_metal_graph_compute(lctx.ctx_metal, gf);
  2329. ggml_metal_get_tensor (lctx.ctx_metal, res);
  2330. if (!lctx.embedding.empty()) {
  2331. ggml_metal_get_tensor(lctx.ctx_metal, embeddings);
  2332. }
  2333. } else {
  2334. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  2335. }
  2336. #else
  2337. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  2338. #endif
  2339. #if GGML_USE_MPI
  2340. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  2341. #endif
  2342. // update kv token count
  2343. lctx.kv_self.n = n_past + N;
  2344. if (cgraph_fname) {
  2345. ggml_graph_export(gf, cgraph_fname);
  2346. }
  2347. #ifdef GGML_PERF
  2348. // print timing information per ggml operation (for debugging purposes)
  2349. // requires GGML_PERF to be defined
  2350. ggml_graph_print(gf);
  2351. #endif
  2352. // plot the computation graph in dot format (for debugging purposes)
  2353. //if (n_past%100 == 0) {
  2354. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  2355. //}
  2356. // extract logits
  2357. {
  2358. auto & logits_out = lctx.logits;
  2359. if (lctx.logits_all) {
  2360. logits_out.resize(n_vocab * N);
  2361. memcpy(logits_out.data(), (float *) ggml_get_data(res), sizeof(float)*n_vocab*N);
  2362. } else {
  2363. // return result for just the last token
  2364. logits_out.resize(n_vocab);
  2365. memcpy(logits_out.data(), (float *) ggml_get_data(res) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  2366. }
  2367. }
  2368. // extract embeddings
  2369. if (!lctx.embedding.empty()) {
  2370. auto & embedding_out = lctx.embedding;
  2371. embedding_out.resize(n_embd);
  2372. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  2373. }
  2374. // measure the performance only for the single-token evals
  2375. if (N == 1) {
  2376. lctx.t_eval_us += ggml_time_us() - t_start_us;
  2377. lctx.n_eval++;
  2378. }
  2379. else if (N > 1) {
  2380. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  2381. lctx.n_p_eval += N;
  2382. }
  2383. return true;
  2384. }
  2385. //
  2386. // tokenizer
  2387. //
  2388. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  2389. return vocab.type;
  2390. }
  2391. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  2392. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  2393. }
  2394. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  2395. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  2396. }
  2397. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  2398. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  2399. }
  2400. static bool llama_is_user_defined_token(const llama_vocab & vocab, llama_token id) {
  2401. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  2402. }
  2403. static bool llama_is_unused_token(const llama_vocab & vocab, llama_token id) {
  2404. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNUSED;
  2405. }
  2406. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  2407. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  2408. }
  2409. static bool llama_is_bos_token(const llama_vocab & vocab, llama_token id) {
  2410. GGML_ASSERT(llama_is_control_token(vocab, id));
  2411. return id == vocab.special_bos_id;
  2412. }
  2413. static bool llama_is_eos_token(const llama_vocab & vocab, llama_token id ) {
  2414. GGML_ASSERT(llama_is_control_token(vocab, id));
  2415. return id == vocab.special_eos_id;
  2416. }
  2417. static bool llama_is_pad_token(const llama_vocab & vocab, llama_token id ) {
  2418. GGML_ASSERT(id < 0 || llama_is_control_token(vocab, id));
  2419. return id == vocab.special_pad_id;
  2420. }
  2421. static uint8_t llama_token_to_byte(const llama_vocab & vocab, llama_token id) {
  2422. GGML_ASSERT(llama_is_byte_token(vocab, id));
  2423. const auto& token_data = vocab.id_to_token.at(id);
  2424. auto buf = token_data.text.substr(3, 2);
  2425. return strtol(buf.c_str(), NULL, 16);
  2426. }
  2427. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  2428. char buf[7];
  2429. int result = snprintf(buf, sizeof(buf), "<0x%02X>", ch);
  2430. GGML_ASSERT(0 <= result && result < 7);
  2431. return vocab.token_to_id.at(buf);
  2432. }
  2433. static std::string llama_escape_whitespace(const std::string& text) {
  2434. std::string result = "\xe2\x96\x81";
  2435. for (size_t offs = 0; offs < text.length(); ++offs) {
  2436. if (text[offs] == ' ') {
  2437. result += "\xe2\x96\x81";
  2438. } else {
  2439. result += text[offs];
  2440. }
  2441. }
  2442. return result;
  2443. }
  2444. static std::string llama_unescape_whitespace(const std::string& word) {
  2445. if (word.length() >= 3 && word.substr(0, 3) == "\xe2\x96\x81") {
  2446. return std::string(" ") + word.substr(3);
  2447. }
  2448. return word;
  2449. }
  2450. struct llm_symbol {
  2451. using index = int;
  2452. index prev;
  2453. index next;
  2454. const char * text;
  2455. size_t n;
  2456. };
  2457. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  2458. // SPM tokenizer
  2459. // original implementation:
  2460. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  2461. struct llm_bigram_spm {
  2462. struct comparator {
  2463. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  2464. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  2465. }
  2466. };
  2467. using queue_storage = std::vector<llm_bigram_spm>;
  2468. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  2469. llm_symbol::index left;
  2470. llm_symbol::index right;
  2471. float score;
  2472. size_t size;
  2473. };
  2474. struct llm_tokenizer_spm {
  2475. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  2476. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  2477. // split string into utf8 chars
  2478. int index = 0;
  2479. size_t offs = 0;
  2480. while (offs < text.size()) {
  2481. llm_symbol sym;
  2482. size_t len = utf8_len(text[offs]);
  2483. GGML_ASSERT(offs + len <= text.size());
  2484. sym.text = text.c_str() + offs;
  2485. sym.n = len;
  2486. offs += len;
  2487. sym.prev = index - 1;
  2488. sym.next = offs == text.size() ? -1 : index + 1;
  2489. index++;
  2490. symbols.emplace_back(sym);
  2491. }
  2492. // seed the work queue with all possible 2-character tokens.
  2493. for (size_t i = 1; i < symbols.size(); ++i) {
  2494. try_add_bigram(i - 1, i);
  2495. }
  2496. // keep substituting the highest frequency pairs for as long as we can.
  2497. while (!work_queue.empty()) {
  2498. auto bigram = work_queue.top();
  2499. work_queue.pop();
  2500. auto & left_sym = symbols[bigram.left];
  2501. auto & right_sym = symbols[bigram.right];
  2502. // if one of the symbols already got merged, skip it.
  2503. if (left_sym.n == 0 || right_sym.n == 0 ||
  2504. left_sym.n + right_sym.n != bigram.size) {
  2505. continue;
  2506. }
  2507. // merge the right sym into the left one
  2508. left_sym.n += right_sym.n;
  2509. right_sym.n = 0;
  2510. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  2511. // remove the right sym from the chain
  2512. left_sym.next = right_sym.next;
  2513. if (right_sym.next >= 0) {
  2514. symbols[right_sym.next].prev = bigram.left;
  2515. }
  2516. // find more substitutions
  2517. try_add_bigram(left_sym.prev, bigram.left);
  2518. try_add_bigram(bigram.left, left_sym.next);
  2519. }
  2520. for (int i = 0; i != -1; i = symbols[i].next) {
  2521. auto & symbol = symbols[i];
  2522. resegment(symbol, output);
  2523. }
  2524. }
  2525. private:
  2526. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  2527. auto text = std::string(symbol.text, symbol.n);
  2528. auto token = vocab.token_to_id.find(text);
  2529. // Do we need to support is_unused?
  2530. if (token != vocab.token_to_id.end()) {
  2531. output.push_back((*token).second);
  2532. return;
  2533. }
  2534. const auto p = rev_merge.find(text);
  2535. if (p == rev_merge.end()) {
  2536. // output any symbols that did not form tokens as bytes.
  2537. for (int j = 0; j < (int)symbol.n; ++j) {
  2538. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  2539. output.push_back(token_id);
  2540. }
  2541. return;
  2542. }
  2543. resegment(symbols[p->second.first], output);
  2544. resegment(symbols[p->second.second], output);
  2545. }
  2546. void try_add_bigram(int left, int right) {
  2547. if (left == -1 || right == -1) {
  2548. return;
  2549. }
  2550. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  2551. auto token = vocab.token_to_id.find(text);
  2552. if (token == vocab.token_to_id.end()) {
  2553. return;
  2554. }
  2555. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  2556. return;
  2557. }
  2558. const auto & tok_data = vocab.id_to_token[(*token).second];
  2559. llm_bigram_spm bigram;
  2560. bigram.left = left;
  2561. bigram.right = right;
  2562. bigram.score = tok_data.score;
  2563. bigram.size = text.size();
  2564. work_queue.push(bigram);
  2565. // Do we need to support is_unused?
  2566. rev_merge[text] = std::make_pair(left, right);
  2567. }
  2568. const llama_vocab & vocab;
  2569. std::vector<llm_symbol> symbols;
  2570. llm_bigram_spm::queue work_queue;
  2571. std::map<std::string, std::pair<int, int>> rev_merge;
  2572. };
  2573. // BPE tokenizer
  2574. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  2575. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  2576. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  2577. struct llm_bigram_bpe {
  2578. struct comparator {
  2579. bool operator()(llm_bigram_bpe & l, llm_bigram_bpe & r) {
  2580. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  2581. }
  2582. };
  2583. using queue_storage = std::vector<llm_bigram_bpe>;
  2584. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  2585. llm_symbol::index left;
  2586. llm_symbol::index right;
  2587. std::string text;
  2588. int rank;
  2589. size_t size;
  2590. };
  2591. struct llm_tokenizer_bpe {
  2592. llm_tokenizer_bpe(const llama_vocab & vocab, bool g2ws): vocab(vocab) { flag_g2ws = g2ws; }
  2593. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  2594. int final_prev_index = -1;
  2595. auto word_collection = bpe_gpt2_preprocess(text);
  2596. symbols_final.clear();
  2597. for (auto & word : word_collection) {
  2598. work_queue = llm_bigram_bpe::queue();
  2599. symbols.clear();
  2600. int index = 0;
  2601. size_t offset = 0;
  2602. while (offset < word.size()) {
  2603. llm_symbol sym;
  2604. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  2605. sym.text = word.c_str() + offset;
  2606. sym.n = 1;
  2607. sym.n = char_len;
  2608. offset += sym.n;
  2609. sym.prev = index - 1;
  2610. sym.next = offset == word.size() ? -1 : index + 1;
  2611. index++;
  2612. symbols.emplace_back(sym);
  2613. }
  2614. for (size_t i = 1; i < symbols.size(); ++i) {
  2615. add_new_bigram(i - 1, i);
  2616. }
  2617. // build token(s)
  2618. while (!work_queue.empty()) {
  2619. auto bigram = work_queue.top();
  2620. work_queue.pop();
  2621. auto & left_symbol = symbols[bigram.left];
  2622. auto & right_symbol = symbols[bigram.right];
  2623. if (left_symbol.n == 0 || right_symbol.n == 0) {
  2624. continue;
  2625. }
  2626. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  2627. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  2628. if (left_token + right_token != bigram.text) {
  2629. continue; // Skip this bigram if it's outdated
  2630. }
  2631. // merge the right sym into the left one
  2632. left_symbol.n += right_symbol.n;
  2633. right_symbol.n = 0;
  2634. // remove the right sym from the chain
  2635. left_symbol.next = right_symbol.next;
  2636. if (right_symbol.next >= 0) {
  2637. symbols[right_symbol.next].prev = bigram.left;
  2638. }
  2639. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  2640. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  2641. }
  2642. // add the fnished tokens to the final list keeping correct order for next and prev
  2643. for (auto & sym : symbols) {
  2644. if (sym.n > 0) {
  2645. sym.prev = final_prev_index;
  2646. sym.next = -1;
  2647. if (final_prev_index != -1) {
  2648. symbols_final[final_prev_index].next = symbols_final.size();
  2649. }
  2650. symbols_final.emplace_back(sym);
  2651. final_prev_index = symbols_final.size() - 1;
  2652. }
  2653. }
  2654. }
  2655. symbols = symbols_final;
  2656. if (!symbols.empty()) {
  2657. for (int i = 0; i != -1; i = symbols[i].next) {
  2658. auto & symbol = symbols[i];
  2659. if (symbol.n == 0) {
  2660. continue;
  2661. }
  2662. const std::string str = std::string(symbol.text, symbol.n);
  2663. const auto token = vocab.token_to_id.find(str);
  2664. if (token == vocab.token_to_id.end()) {
  2665. for (auto j = str.begin(); j != str.end(); ++j) {
  2666. std::string byte_str(1, *j);
  2667. auto token_multibyte = vocab.token_to_id.find(byte_str);
  2668. if (token_multibyte == vocab.token_to_id.end()) {
  2669. fprintf(stderr,"ERROR: byte not found in vocab: '%s'\n", byte_str.c_str());
  2670. }
  2671. output.push_back((*token_multibyte).second);
  2672. }
  2673. } else {
  2674. output.push_back((*token).second);
  2675. }
  2676. }
  2677. }
  2678. }
  2679. private:
  2680. void add_new_bigram(int left, int right) {
  2681. if (left == -1 || right == -1) {
  2682. return;
  2683. }
  2684. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  2685. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  2686. int rank_found = -1;
  2687. rank_found = vocab.find_bpe_rank(left_token, right_token);
  2688. if (rank_found < 0) {
  2689. return;
  2690. }
  2691. llm_bigram_bpe bigram;
  2692. bigram.left = left;
  2693. bigram.right = right;
  2694. bigram.text = left_token + right_token;
  2695. bigram.size = left_token.size() + right_token.size();
  2696. bigram.rank = rank_found;
  2697. work_queue.push(bigram);
  2698. }
  2699. // probably not 100% correct
  2700. // TODO: this is quite slow - how to make it more efficient?
  2701. static std::vector<std::string> bpe_gpt2_preprocess(std::string text) {
  2702. std::vector<std::string> words;
  2703. // ref: https://github.com/openai/gpt-2/blob/a74da5d99abaaba920de8131d64da2862a8f213b/src/encoder.py#L53
  2704. const std::string pattern = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
  2705. const std::regex re(pattern);
  2706. std::smatch m;
  2707. while (std::regex_search(text, m, re)) {
  2708. for (auto x : m) {
  2709. words.push_back(x);
  2710. }
  2711. text = m.suffix();
  2712. }
  2713. return words;
  2714. }
  2715. bool flag_g2ws = false;
  2716. const llama_vocab & vocab;
  2717. std::vector<llm_symbol> symbols;
  2718. std::vector<llm_symbol> symbols_final;
  2719. llm_bigram_bpe::queue work_queue;
  2720. };
  2721. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, const std::string & raw_text, bool bos, bool escape) {
  2722. std::vector<llama_vocab::id> output;
  2723. if (raw_text.empty()) {
  2724. return output;
  2725. }
  2726. switch (vocab.type) {
  2727. case LLAMA_VOCAB_TYPE_SPM:
  2728. {
  2729. llm_tokenizer_spm tokenizer(vocab);
  2730. if (bos) {
  2731. output.push_back(vocab.special_bos_id);
  2732. }
  2733. std::string text;
  2734. if (escape) {
  2735. text = llama_escape_whitespace(raw_text);
  2736. } else {
  2737. text = raw_text;
  2738. }
  2739. tokenizer.tokenize(text, output);
  2740. } break;
  2741. case LLAMA_VOCAB_TYPE_BPE:
  2742. {
  2743. llm_tokenizer_bpe tokenizer(vocab, escape);
  2744. if (bos && vocab.special_bos_id != -1) {
  2745. output.push_back(vocab.special_bos_id);
  2746. }
  2747. tokenizer.tokenize(raw_text, output);
  2748. } break;
  2749. };
  2750. return output;
  2751. }
  2752. //
  2753. // grammar - internal
  2754. //
  2755. struct llama_partial_utf8 {
  2756. uint32_t value; // bit value so far (unshifted)
  2757. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  2758. };
  2759. struct llama_grammar {
  2760. const std::vector<std::vector<llama_grammar_element>> rules;
  2761. std::vector<std::vector<const llama_grammar_element *>> stacks;
  2762. // buffer for partially generated UTF-8 sequence from accepted tokens
  2763. llama_partial_utf8 partial_utf8;
  2764. };
  2765. struct llama_grammar_candidate {
  2766. size_t index;
  2767. const uint32_t * code_points;
  2768. llama_partial_utf8 partial_utf8;
  2769. };
  2770. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  2771. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  2772. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  2773. const char * src,
  2774. llama_partial_utf8 partial_start) {
  2775. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  2776. const char * pos = src;
  2777. std::vector<uint32_t> code_points;
  2778. uint32_t value = partial_start.value;
  2779. int n_remain = partial_start.n_remain;
  2780. // continue previous decode, if applicable
  2781. while (*pos != 0 && n_remain > 0) {
  2782. uint8_t next_byte = static_cast<uint8_t>(*pos);
  2783. if ((next_byte >> 6) != 2) {
  2784. // invalid sequence, abort
  2785. code_points.push_back(0);
  2786. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  2787. }
  2788. value = (value << 6) + (next_byte & 0x3F);
  2789. ++pos;
  2790. --n_remain;
  2791. }
  2792. if (partial_start.n_remain > 0 && n_remain == 0) {
  2793. code_points.push_back(value);
  2794. }
  2795. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  2796. while (*pos != 0) {
  2797. uint8_t first_byte = static_cast<uint8_t>(*pos);
  2798. uint8_t highbits = first_byte >> 4;
  2799. n_remain = lookup[highbits] - 1;
  2800. if (n_remain < 0) {
  2801. // invalid sequence, abort
  2802. code_points.clear();
  2803. code_points.push_back(0);
  2804. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  2805. }
  2806. uint8_t mask = (1 << (7 - n_remain)) - 1;
  2807. value = first_byte & mask;
  2808. ++pos;
  2809. while (*pos != 0 && n_remain > 0) {
  2810. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  2811. ++pos;
  2812. --n_remain;
  2813. }
  2814. if (n_remain == 0) {
  2815. code_points.push_back(value);
  2816. }
  2817. }
  2818. code_points.push_back(0);
  2819. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  2820. }
  2821. // returns true iff pos points to the end of one of the definitions of a rule
  2822. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  2823. switch (pos->type) {
  2824. case LLAMA_GRETYPE_END: return true; // NOLINT
  2825. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  2826. default: return false;
  2827. }
  2828. }
  2829. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  2830. // asserts that pos is pointing to a char range element
  2831. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  2832. const llama_grammar_element * pos,
  2833. const uint32_t chr) {
  2834. bool found = false;
  2835. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2836. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  2837. do {
  2838. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2839. // inclusive range, e.g. [a-z]
  2840. found = found || (pos->value <= chr && chr <= pos[1].value);
  2841. pos += 2;
  2842. } else {
  2843. // exact char match, e.g. [a] or "a"
  2844. found = found || pos->value == chr;
  2845. pos += 1;
  2846. }
  2847. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2848. return std::make_pair(found == is_positive_char, pos);
  2849. }
  2850. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  2851. // range at pos (regular or inverse range)
  2852. // asserts that pos is pointing to a char range element
  2853. static bool llama_grammar_match_partial_char(
  2854. const llama_grammar_element * pos,
  2855. const llama_partial_utf8 partial_utf8) {
  2856. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2857. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  2858. uint32_t partial_value = partial_utf8.value;
  2859. int n_remain = partial_utf8.n_remain;
  2860. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  2861. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  2862. return false;
  2863. }
  2864. // range of possible code points this partial UTF-8 sequence could complete to
  2865. uint32_t low = partial_value << (n_remain * 6);
  2866. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  2867. if (low == 0) {
  2868. if (n_remain == 2) {
  2869. low = 1 << 11;
  2870. } else if (n_remain == 3) {
  2871. low = 1 << 16;
  2872. }
  2873. }
  2874. do {
  2875. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2876. // inclusive range, e.g. [a-z]
  2877. if (pos->value <= high && low <= pos[1].value) {
  2878. return is_positive_char;
  2879. }
  2880. pos += 2;
  2881. } else {
  2882. // exact char match, e.g. [a] or "a"
  2883. if (low <= pos->value && pos->value <= high) {
  2884. return is_positive_char;
  2885. }
  2886. pos += 1;
  2887. }
  2888. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2889. return !is_positive_char;
  2890. }
  2891. // transforms a grammar pushdown stack into N possible stacks, all ending
  2892. // at a character range (terminal element)
  2893. static void llama_grammar_advance_stack(
  2894. const std::vector<std::vector<llama_grammar_element>> & rules,
  2895. const std::vector<const llama_grammar_element *> & stack,
  2896. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  2897. if (stack.empty()) {
  2898. new_stacks.push_back(stack);
  2899. return;
  2900. }
  2901. const llama_grammar_element * pos = stack.back();
  2902. switch (pos->type) {
  2903. case LLAMA_GRETYPE_RULE_REF: {
  2904. const size_t rule_id = static_cast<size_t>(pos->value);
  2905. const llama_grammar_element * subpos = rules[rule_id].data();
  2906. do {
  2907. // init new stack without the top (pos)
  2908. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  2909. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  2910. // if this rule ref is followed by another element, add that to stack
  2911. new_stack.push_back(pos + 1);
  2912. }
  2913. if (!llama_grammar_is_end_of_sequence(subpos)) {
  2914. // if alternate is nonempty, add to stack
  2915. new_stack.push_back(subpos);
  2916. }
  2917. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  2918. while (!llama_grammar_is_end_of_sequence(subpos)) {
  2919. // scan to end of alternate def
  2920. subpos++;
  2921. }
  2922. if (subpos->type == LLAMA_GRETYPE_ALT) {
  2923. // there's another alternate def of this rule to process
  2924. subpos++;
  2925. } else {
  2926. break;
  2927. }
  2928. } while (true);
  2929. break;
  2930. }
  2931. case LLAMA_GRETYPE_CHAR:
  2932. case LLAMA_GRETYPE_CHAR_NOT:
  2933. new_stacks.push_back(stack);
  2934. break;
  2935. default:
  2936. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  2937. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  2938. // those
  2939. GGML_ASSERT(false);
  2940. }
  2941. }
  2942. // takes a set of possible pushdown stacks on a grammar, which are required to
  2943. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  2944. // produces the N possible stacks if the given char is accepted at those
  2945. // positions
  2946. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  2947. const std::vector<std::vector<llama_grammar_element>> & rules,
  2948. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  2949. const uint32_t chr) {
  2950. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  2951. for (const auto & stack : stacks) {
  2952. if (stack.empty()) {
  2953. continue;
  2954. }
  2955. auto match = llama_grammar_match_char(stack.back(), chr);
  2956. if (match.first) {
  2957. const llama_grammar_element * pos = match.second;
  2958. // update top of stack to next element, if any
  2959. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  2960. if (!llama_grammar_is_end_of_sequence(pos)) {
  2961. new_stack.push_back(pos);
  2962. }
  2963. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  2964. }
  2965. }
  2966. return new_stacks;
  2967. }
  2968. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  2969. const std::vector<std::vector<llama_grammar_element>> & rules,
  2970. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  2971. const std::vector<llama_grammar_candidate> & candidates);
  2972. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  2973. const std::vector<std::vector<llama_grammar_element>> & rules,
  2974. const std::vector<const llama_grammar_element *> & stack,
  2975. const std::vector<llama_grammar_candidate> & candidates) {
  2976. std::vector<llama_grammar_candidate> rejects;
  2977. if (stack.empty()) {
  2978. for (auto tok : candidates) {
  2979. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  2980. rejects.push_back(tok);
  2981. }
  2982. }
  2983. return rejects;
  2984. }
  2985. const llama_grammar_element * stack_pos = stack.back();
  2986. std::vector<llama_grammar_candidate> next_candidates;
  2987. for (auto tok : candidates) {
  2988. if (*tok.code_points == 0) {
  2989. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  2990. // that cannot satisfy this position in grammar
  2991. if (tok.partial_utf8.n_remain != 0 &&
  2992. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  2993. rejects.push_back(tok);
  2994. }
  2995. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  2996. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  2997. } else {
  2998. rejects.push_back(tok);
  2999. }
  3000. }
  3001. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  3002. // update top of stack to next element, if any
  3003. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  3004. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  3005. stack_after.push_back(stack_pos_after);
  3006. }
  3007. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  3008. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  3009. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  3010. for (auto tok : next_rejects) {
  3011. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  3012. }
  3013. return rejects;
  3014. }
  3015. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  3016. const std::vector<std::vector<llama_grammar_element>> & rules,
  3017. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  3018. const std::vector<llama_grammar_candidate> & candidates) {
  3019. GGML_ASSERT(!stacks.empty()); // REVIEW
  3020. if (candidates.empty()) {
  3021. return std::vector<llama_grammar_candidate>();
  3022. }
  3023. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  3024. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  3025. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  3026. }
  3027. return rejects;
  3028. }
  3029. //
  3030. // grammar - external
  3031. //
  3032. struct llama_grammar * llama_grammar_init(
  3033. const llama_grammar_element ** rules,
  3034. size_t n_rules,
  3035. size_t start_rule_index) {
  3036. const llama_grammar_element * pos;
  3037. // copy rule definitions into vectors
  3038. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  3039. for (size_t i = 0; i < n_rules; i++) {
  3040. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  3041. vec_rules[i].push_back(*pos);
  3042. }
  3043. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  3044. }
  3045. // loop over alternates of start rule to build initial stacks
  3046. std::vector<std::vector<const llama_grammar_element *>> stacks;
  3047. pos = rules[start_rule_index];
  3048. do {
  3049. std::vector<const llama_grammar_element *> stack;
  3050. if (!llama_grammar_is_end_of_sequence(pos)) {
  3051. // if alternate is nonempty, add to stack
  3052. stack.push_back(pos);
  3053. }
  3054. llama_grammar_advance_stack(vec_rules, stack, stacks);
  3055. while (!llama_grammar_is_end_of_sequence(pos)) {
  3056. // scan to end of alternate def
  3057. pos++;
  3058. }
  3059. if (pos->type == LLAMA_GRETYPE_ALT) {
  3060. // there's another alternate def of this rule to process
  3061. pos++;
  3062. } else {
  3063. break;
  3064. }
  3065. } while (true);
  3066. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  3067. }
  3068. void llama_grammar_free(struct llama_grammar * grammar) {
  3069. delete grammar;
  3070. }
  3071. //
  3072. // sampling
  3073. //
  3074. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  3075. GGML_ASSERT(candidates->size > 0);
  3076. const int64_t t_start_sample_us = ggml_time_us();
  3077. // Sort the logits in descending order
  3078. if (!candidates->sorted) {
  3079. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  3080. return a.logit > b.logit;
  3081. });
  3082. candidates->sorted = true;
  3083. }
  3084. float max_l = candidates->data[0].logit;
  3085. float cum_sum = 0.0f;
  3086. for (size_t i = 0; i < candidates->size; ++i) {
  3087. float p = expf(candidates->data[i].logit - max_l);
  3088. candidates->data[i].p = p;
  3089. cum_sum += p;
  3090. }
  3091. for (size_t i = 0; i < candidates->size; ++i) {
  3092. candidates->data[i].p /= cum_sum;
  3093. }
  3094. if (ctx) {
  3095. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3096. }
  3097. }
  3098. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  3099. const int64_t t_start_sample_us = ggml_time_us();
  3100. k = std::max(k, (int) min_keep);
  3101. k = std::min(k, (int) candidates->size);
  3102. // Sort scores in descending order
  3103. if (!candidates->sorted) {
  3104. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  3105. return a.logit > b.logit;
  3106. };
  3107. if (k == (int) candidates->size) {
  3108. std::sort(candidates->data, candidates->data + candidates->size, comp);
  3109. } else {
  3110. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  3111. }
  3112. candidates->sorted = true;
  3113. }
  3114. candidates->size = k;
  3115. if (ctx) {
  3116. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3117. }
  3118. }
  3119. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  3120. if (p >= 1.0f) {
  3121. return;
  3122. }
  3123. llama_sample_softmax(ctx, candidates);
  3124. const int64_t t_start_sample_us = ggml_time_us();
  3125. // Compute the cumulative probabilities
  3126. float cum_sum = 0.0f;
  3127. size_t last_idx = candidates->size;
  3128. for (size_t i = 0; i < candidates->size; ++i) {
  3129. cum_sum += candidates->data[i].p;
  3130. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  3131. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  3132. if (cum_sum >= p && i + 1 >= min_keep) {
  3133. last_idx = i + 1;
  3134. break;
  3135. }
  3136. }
  3137. // Resize the output vector to keep only the top-p tokens
  3138. candidates->size = last_idx;
  3139. if (ctx) {
  3140. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3141. }
  3142. }
  3143. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  3144. if (z >= 1.0f || candidates->size <= 2) {
  3145. return;
  3146. }
  3147. llama_sample_softmax(nullptr, candidates);
  3148. const int64_t t_start_sample_us = ggml_time_us();
  3149. // Compute the first and second derivatives
  3150. std::vector<float> first_derivatives(candidates->size - 1);
  3151. std::vector<float> second_derivatives(candidates->size - 2);
  3152. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  3153. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  3154. }
  3155. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3156. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  3157. }
  3158. // Calculate absolute value of second derivatives
  3159. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3160. second_derivatives[i] = abs(second_derivatives[i]);
  3161. }
  3162. // Normalize the second derivatives
  3163. {
  3164. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  3165. if (second_derivatives_sum > 1e-6f) {
  3166. for (float & value : second_derivatives) {
  3167. value /= second_derivatives_sum;
  3168. }
  3169. } else {
  3170. for (float & value : second_derivatives) {
  3171. value = 1.0f / second_derivatives.size();
  3172. }
  3173. }
  3174. }
  3175. float cum_sum = 0.0f;
  3176. size_t last_idx = candidates->size;
  3177. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3178. cum_sum += second_derivatives[i];
  3179. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  3180. if (cum_sum > z && i >= min_keep) {
  3181. last_idx = i;
  3182. break;
  3183. }
  3184. }
  3185. // Resize the output vector to keep only the tokens above the tail location
  3186. candidates->size = last_idx;
  3187. if (ctx) {
  3188. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3189. }
  3190. }
  3191. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  3192. // Reference implementation:
  3193. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  3194. if (p >= 1.0f) {
  3195. return;
  3196. }
  3197. // Compute the softmax of logits and calculate entropy
  3198. llama_sample_softmax(nullptr, candidates);
  3199. const int64_t t_start_sample_us = ggml_time_us();
  3200. float entropy = 0.0f;
  3201. for (size_t i = 0; i < candidates->size; ++i) {
  3202. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  3203. }
  3204. // Compute the absolute difference between negative log probability and entropy for each candidate
  3205. std::vector<float> shifted_scores;
  3206. for (size_t i = 0; i < candidates->size; ++i) {
  3207. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  3208. shifted_scores.push_back(shifted_score);
  3209. }
  3210. // Sort tokens based on the shifted_scores and their corresponding indices
  3211. std::vector<size_t> indices(candidates->size);
  3212. std::iota(indices.begin(), indices.end(), 0);
  3213. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  3214. return shifted_scores[a] < shifted_scores[b];
  3215. });
  3216. // Compute the cumulative probabilities
  3217. float cum_sum = 0.0f;
  3218. size_t last_idx = indices.size();
  3219. for (size_t i = 0; i < indices.size(); ++i) {
  3220. size_t idx = indices[i];
  3221. cum_sum += candidates->data[idx].p;
  3222. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  3223. if (cum_sum > p && i >= min_keep - 1) {
  3224. last_idx = i + 1;
  3225. break;
  3226. }
  3227. }
  3228. // Resize the output vector to keep only the locally typical tokens
  3229. std::vector<llama_token_data> new_candidates;
  3230. for (size_t i = 0; i < last_idx; ++i) {
  3231. size_t idx = indices[i];
  3232. new_candidates.push_back(candidates->data[idx]);
  3233. }
  3234. // Replace the data in candidates with the new_candidates data
  3235. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  3236. candidates->size = new_candidates.size();
  3237. if (ctx) {
  3238. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3239. }
  3240. }
  3241. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  3242. const int64_t t_start_sample_us = ggml_time_us();
  3243. for (size_t i = 0; i < candidates_p->size; ++i) {
  3244. candidates_p->data[i].logit /= temp;
  3245. }
  3246. if (ctx) {
  3247. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3248. }
  3249. }
  3250. void llama_sample_repetition_penalty(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens, size_t last_tokens_size, float penalty) {
  3251. if (last_tokens_size == 0 || penalty == 1.0f) {
  3252. return;
  3253. }
  3254. const int64_t t_start_sample_us = ggml_time_us();
  3255. for (size_t i = 0; i < candidates->size; ++i) {
  3256. const auto * token_iter = std::find(last_tokens, last_tokens + last_tokens_size, candidates->data[i].id);
  3257. if (token_iter == last_tokens + last_tokens_size) {
  3258. continue;
  3259. }
  3260. // 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.
  3261. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  3262. if (candidates->data[i].logit <= 0) {
  3263. candidates->data[i].logit *= penalty;
  3264. } else {
  3265. candidates->data[i].logit /= penalty;
  3266. }
  3267. }
  3268. candidates->sorted = false;
  3269. if (ctx) {
  3270. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3271. }
  3272. }
  3273. void llama_sample_frequency_and_presence_penalties(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens_p, size_t last_tokens_size, float alpha_frequency, float alpha_presence) {
  3274. if (last_tokens_size == 0 || (alpha_frequency == 0.0f && alpha_presence == 0.0f)) {
  3275. return;
  3276. }
  3277. const int64_t t_start_sample_us = ggml_time_us();
  3278. // Create a frequency map to count occurrences of each token in last_tokens
  3279. std::unordered_map<llama_token, int> token_count;
  3280. for (size_t i = 0; i < last_tokens_size; ++i) {
  3281. token_count[last_tokens_p[i]]++;
  3282. }
  3283. // Apply frequency and presence penalties to the candidates
  3284. for (size_t i = 0; i < candidates->size; ++i) {
  3285. auto token_iter = token_count.find(candidates->data[i].id);
  3286. if (token_iter == token_count.end()) {
  3287. continue;
  3288. }
  3289. int count = token_iter->second;
  3290. candidates->data[i].logit -= float(count) * alpha_frequency + float(count > 0) * alpha_presence;
  3291. }
  3292. candidates->sorted = false;
  3293. if (ctx) {
  3294. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3295. }
  3296. }
  3297. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  3298. GGML_ASSERT(ctx);
  3299. const int64_t t_start_sample_us = ggml_time_us();
  3300. bool allow_eos = false;
  3301. for (const auto & stack : grammar->stacks) {
  3302. if (stack.empty()) {
  3303. allow_eos = true;
  3304. break;
  3305. }
  3306. }
  3307. const llama_token eos = llama_token_eos(ctx);
  3308. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  3309. std::vector<llama_grammar_candidate> candidates_grammar;
  3310. for (size_t i = 0; i < candidates->size; ++i) {
  3311. const llama_token id = candidates->data[i].id;
  3312. const std::string text = llama_token_to_text(ctx, id);
  3313. if (id == eos) {
  3314. if (!allow_eos) {
  3315. candidates->data[i].logit = -INFINITY;
  3316. }
  3317. } else if (text.empty()) {
  3318. candidates->data[i].logit = -INFINITY;
  3319. } else {
  3320. candidates_decoded.push_back(decode_utf8(text.c_str(), grammar->partial_utf8));
  3321. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  3322. }
  3323. }
  3324. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  3325. for (const auto & reject : rejects) {
  3326. candidates->data[reject.index].logit = -INFINITY;
  3327. }
  3328. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3329. }
  3330. static void llama_log_softmax(float * array, size_t size) {
  3331. float max_l = *std::max_element(array, array + size);
  3332. float sum = 0.f;
  3333. for (size_t i = 0; i < size; ++i) {
  3334. float p = expf(array[i] - max_l);
  3335. sum += p;
  3336. array[i] = p;
  3337. }
  3338. for (size_t i = 0; i < size; ++i) {
  3339. array[i] = logf(array[i] / sum);
  3340. }
  3341. }
  3342. void llama_sample_classifier_free_guidance(
  3343. struct llama_context * ctx,
  3344. llama_token_data_array * candidates,
  3345. struct llama_context * guidance_ctx,
  3346. float scale) {
  3347. int64_t t_start_sample_us = ggml_time_us();
  3348. GGML_ASSERT(ctx);
  3349. auto n_vocab = llama_n_vocab(ctx);
  3350. GGML_ASSERT(n_vocab == (int)candidates->size);
  3351. GGML_ASSERT(!candidates->sorted);
  3352. std::vector<float> logits_base;
  3353. logits_base.reserve(candidates->size);
  3354. for (size_t i = 0; i < candidates->size; ++i) {
  3355. logits_base.push_back(candidates->data[i].logit);
  3356. }
  3357. llama_log_softmax(logits_base.data(), candidates->size);
  3358. float* logits_guidance = llama_get_logits(guidance_ctx);
  3359. llama_log_softmax(logits_guidance, n_vocab);
  3360. for (int i = 0; i < n_vocab; ++i) {
  3361. float logit_guidance = logits_guidance[i];
  3362. float logit_base = logits_base[i];
  3363. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  3364. }
  3365. if (ctx) {
  3366. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3367. }
  3368. }
  3369. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  3370. GGML_ASSERT(ctx);
  3371. auto N = float(llama_n_vocab(ctx));
  3372. int64_t t_start_sample_us;
  3373. t_start_sample_us = ggml_time_us();
  3374. llama_sample_softmax(nullptr, candidates);
  3375. // Estimate s_hat using the most probable m tokens
  3376. float s_hat = 0.0;
  3377. float sum_ti_bi = 0.0;
  3378. float sum_ti_sq = 0.0;
  3379. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  3380. float t_i = logf(float(i + 2) / float(i + 1));
  3381. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  3382. sum_ti_bi += t_i * b_i;
  3383. sum_ti_sq += t_i * t_i;
  3384. }
  3385. s_hat = sum_ti_bi / sum_ti_sq;
  3386. // Compute k from the estimated s_hat and target surprise value
  3387. float epsilon_hat = s_hat - 1;
  3388. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  3389. // Sample the next word X using top-k sampling
  3390. llama_sample_top_k(nullptr, candidates, int(k), 1);
  3391. if (ctx) {
  3392. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3393. }
  3394. llama_token X = llama_sample_token(ctx, candidates);
  3395. t_start_sample_us = ggml_time_us();
  3396. // Compute error as the difference between observed surprise and target surprise value
  3397. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3398. return candidate.id == X;
  3399. }));
  3400. float observed_surprise = -log2f(candidates->data[X_idx].p);
  3401. float e = observed_surprise - tau;
  3402. // Update mu using the learning rate and error
  3403. *mu = *mu - eta * e;
  3404. if (ctx) {
  3405. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3406. }
  3407. return X;
  3408. }
  3409. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  3410. int64_t t_start_sample_us;
  3411. t_start_sample_us = ggml_time_us();
  3412. llama_sample_softmax(ctx, candidates);
  3413. // Truncate the words with surprise values greater than mu
  3414. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3415. return -log2f(candidate.p) > *mu;
  3416. }));
  3417. if (candidates->size == 0) {
  3418. candidates->size = 1;
  3419. }
  3420. if (ctx) {
  3421. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3422. }
  3423. // Normalize the probabilities of the remaining words
  3424. llama_sample_softmax(ctx, candidates);
  3425. // Sample the next word X from the remaining words
  3426. llama_token X = llama_sample_token(ctx, candidates);
  3427. t_start_sample_us = ggml_time_us();
  3428. // Compute error as the difference between observed surprise and target surprise value
  3429. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3430. return candidate.id == X;
  3431. }));
  3432. float observed_surprise = -log2f(candidates->data[X_idx].p);
  3433. float e = observed_surprise - tau;
  3434. // Update mu using the learning rate and error
  3435. *mu = *mu - eta * e;
  3436. if (ctx) {
  3437. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3438. }
  3439. return X;
  3440. }
  3441. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  3442. const int64_t t_start_sample_us = ggml_time_us();
  3443. // Find max element
  3444. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  3445. return a.logit < b.logit;
  3446. });
  3447. llama_token result = max_iter->id;
  3448. if (ctx) {
  3449. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3450. ctx->n_sample++;
  3451. }
  3452. return result;
  3453. }
  3454. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  3455. GGML_ASSERT(ctx);
  3456. const int64_t t_start_sample_us = ggml_time_us();
  3457. llama_sample_softmax(nullptr, candidates);
  3458. std::vector<float> probs;
  3459. probs.reserve(candidates->size);
  3460. for (size_t i = 0; i < candidates->size; ++i) {
  3461. probs.push_back(candidates->data[i].p);
  3462. }
  3463. std::discrete_distribution<> dist(probs.begin(), probs.end());
  3464. auto & rng = ctx->rng;
  3465. int idx = dist(rng);
  3466. llama_token result = candidates->data[idx].id;
  3467. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3468. ctx->n_sample++;
  3469. return result;
  3470. }
  3471. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  3472. const int64_t t_start_sample_us = ggml_time_us();
  3473. if (token == llama_token_eos(ctx)) {
  3474. for (const auto & stack : grammar->stacks) {
  3475. if (stack.empty()) {
  3476. return;
  3477. }
  3478. }
  3479. GGML_ASSERT(false);
  3480. }
  3481. const std::string text = llama_token_to_text(ctx, token);
  3482. // Note terminating 0 in decoded string
  3483. const auto decoded = decode_utf8(text.c_str(), grammar->partial_utf8);
  3484. const auto & code_points = decoded.first;
  3485. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  3486. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  3487. }
  3488. grammar->partial_utf8 = decoded.second;
  3489. GGML_ASSERT(!grammar->stacks.empty());
  3490. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3491. }
  3492. //
  3493. // quantization
  3494. //
  3495. static void llama_convert_tensor_internal(struct ggml_tensor * tensor, std::vector<float> & output, const size_t nelements, const int nthread) {
  3496. if (output.size() < nelements) {
  3497. output.resize(nelements);
  3498. }
  3499. float * f32_output = (float *) output.data();
  3500. ggml_type_traits_t qtype;
  3501. if (ggml_is_quantized(tensor->type)) {
  3502. qtype = ggml_internal_get_type_traits(tensor->type);
  3503. if (qtype.to_float == NULL) {
  3504. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  3505. }
  3506. } else if (tensor->type != GGML_TYPE_F16) {
  3507. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  3508. }
  3509. if (nthread < 2) {
  3510. if (tensor->type == GGML_TYPE_F16) {
  3511. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  3512. } else if (ggml_is_quantized(tensor->type)) {
  3513. qtype.to_float(tensor->data, f32_output, nelements);
  3514. } else {
  3515. GGML_ASSERT(false); // unreachable
  3516. }
  3517. return;
  3518. }
  3519. auto block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  3520. auto block_size_bytes = ggml_type_size(tensor->type);
  3521. GGML_ASSERT(nelements % block_size == 0);
  3522. auto nblocks = nelements / block_size;
  3523. auto blocks_per_thread = nblocks / nthread;
  3524. auto spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  3525. std::vector<std::thread> workers;
  3526. for (auto tnum = 0, in_buff_offs = 0, out_buff_offs = 0; tnum < nthread; tnum++) {
  3527. auto thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  3528. auto thr_elems = thr_blocks * block_size; // number of elements for this thread
  3529. auto thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  3530. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  3531. if (typ == GGML_TYPE_F16) {
  3532. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  3533. } else {
  3534. qtype.to_float(inbuf, outbuf, nels);
  3535. }
  3536. };
  3537. workers.push_back(std::thread(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems));
  3538. in_buff_offs += thr_block_bytes;
  3539. out_buff_offs += thr_elems;
  3540. }
  3541. for (auto & worker : workers) {
  3542. worker.join();
  3543. }
  3544. }
  3545. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  3546. ggml_type quantized_type;
  3547. llama_ftype ftype = params->ftype;
  3548. switch (params->ftype) {
  3549. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  3550. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  3551. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  3552. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  3553. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  3554. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  3555. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  3556. #ifdef GGML_USE_K_QUANTS
  3557. // K-quants
  3558. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  3559. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  3560. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  3561. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  3562. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  3563. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  3564. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  3565. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  3566. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  3567. #endif
  3568. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  3569. }
  3570. int nthread = params->nthread;
  3571. if (nthread <= 0) {
  3572. nthread = std::thread::hardware_concurrency();
  3573. }
  3574. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname_inp, /*use_mmap*/ false));
  3575. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  3576. struct gguf_context * ctx_out = gguf_init_empty();
  3577. // copy the KV pairs from the input file
  3578. gguf_set_kv (ctx_out, ml->ctx_gguf);
  3579. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  3580. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  3581. #ifdef GGML_USE_K_QUANTS
  3582. int n_attention_wv = 0;
  3583. int n_feed_forward_w2 = 0;
  3584. for (int i = 0; i < ml->n_tensors; ++i) {
  3585. struct ggml_tensor * meta = ml->get_tensor_meta(i);
  3586. const std::string name = ggml_get_name(meta);
  3587. // TODO: avoid hardcoded tensor names - use the TN_* constants
  3588. if (name.find("attn_v.weight") != std::string::npos) {
  3589. ++n_attention_wv;
  3590. }
  3591. else if (name.find("ffn_down.weight") != std::string::npos) {
  3592. ++n_feed_forward_w2;
  3593. }
  3594. }
  3595. int i_attention_wv = 0;
  3596. int i_feed_forward_w2 = 0;
  3597. #endif
  3598. size_t total_size_org = 0;
  3599. size_t total_size_new = 0;
  3600. std::vector<int64_t> hist_all(1 << 4, 0);
  3601. std::vector<std::thread> workers;
  3602. std::mutex mutex;
  3603. auto use_more_bits = [] (int i_layer, int num_layers) -> bool {
  3604. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  3605. };
  3606. int idx = 0;
  3607. std::vector<uint8_t> read_data;
  3608. std::vector<uint8_t> work;
  3609. // populate the original tensors so we get an initial meta data
  3610. for (int i = 0; i < ml->n_tensors; ++i) {
  3611. struct ggml_tensor * meta = ml->get_tensor_meta(i);
  3612. gguf_add_tensor(ctx_out, meta);
  3613. }
  3614. std::ofstream fout(fname_out, std::ios::binary);
  3615. const size_t meta_size = gguf_get_meta_size(ctx_out);
  3616. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  3617. // placeholder for the meta data
  3618. ::zeros(fout, meta_size);
  3619. for (int i = 0; i < ml->n_tensors; ++i) {
  3620. struct ggml_tensor * tensor = ml->get_tensor_meta(i);
  3621. const std::string name = ggml_get_name(tensor);
  3622. read_data.resize(ggml_nbytes(tensor));
  3623. tensor->data = read_data.data();
  3624. ml->load_data_for(tensor);
  3625. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  3626. ++idx, ml->n_tensors,
  3627. ggml_get_name(tensor),
  3628. llama_format_tensor_shape(tensor).c_str(),
  3629. ggml_type_name(tensor->type));
  3630. // This used to be a regex, but <regex> has an extreme cost to compile times.
  3631. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  3632. // quantize only 2D tensors
  3633. quantize &= (tensor->n_dims == 2);
  3634. quantize &= params->quantize_output_tensor || name != "output.weight";
  3635. quantize &= quantized_type != tensor->type;
  3636. enum ggml_type new_type;
  3637. void * new_data;
  3638. size_t new_size;
  3639. if (!quantize) {
  3640. new_type = tensor->type;
  3641. new_data = tensor->data;
  3642. new_size = ggml_nbytes(tensor);
  3643. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  3644. } else {
  3645. new_type = quantized_type;
  3646. #ifdef GGML_USE_K_QUANTS
  3647. // TODO: avoid hardcoded tensor names - use the TN_* constants
  3648. const auto tn = LLM_TN(ml->get_arch());
  3649. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  3650. int nx = tensor->ne[0];
  3651. int ny = tensor->ne[1];
  3652. if (nx % QK_K == 0 && ny % QK_K == 0) {
  3653. new_type = GGML_TYPE_Q6_K;
  3654. }
  3655. } else if (name.find("attn_v.weight") != std::string::npos) {
  3656. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3657. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  3658. new_type = i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  3659. }
  3660. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  3661. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  3662. use_more_bits(i_attention_wv, n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  3663. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  3664. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  3665. (i_attention_wv < n_attention_wv/8 || i_attention_wv >= 7*n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  3666. ++i_attention_wv;
  3667. } else if (name.find("ffn_down.weight") != std::string::npos) {
  3668. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3669. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  3670. new_type = i_feed_forward_w2 < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  3671. }
  3672. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  3673. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  3674. use_more_bits(i_feed_forward_w2, n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  3675. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && i_feed_forward_w2 < 4) new_type = GGML_TYPE_Q5_K;
  3676. ++i_feed_forward_w2;
  3677. } else if (name.find("attn_output.weight") != std::string::npos) {
  3678. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  3679. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  3680. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  3681. }
  3682. else if (name.find("ffn_gate.weight") != std::string::npos || name.find("ffn_up.weight") != std::string::npos) {
  3683. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3684. }
  3685. // This can be used to reduce the size of the Q5_K_S model.
  3686. // The associated PPL increase is fully in line with the size reduction
  3687. //else {
  3688. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  3689. //}
  3690. bool convert_incompatible_tensor = false;
  3691. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  3692. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  3693. int nx = tensor->ne[0];
  3694. int ny = tensor->ne[1];
  3695. if (nx % QK_K != 0 || ny % QK_K != 0) {
  3696. LLAMA_LOG_INFO("\n\nTensor sizes %d x %d are not divisible by %d, required for k-quants.\n",nx,ny,QK_K);
  3697. convert_incompatible_tensor = true;
  3698. }
  3699. }
  3700. if (convert_incompatible_tensor) {
  3701. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  3702. new_type = GGML_TYPE_F16; //fall back to F16 instead of just failing.
  3703. LLAMA_LOG_WARN("F16 will be used for this tensor instead.\n");
  3704. } else if (name == tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  3705. new_type = GGML_TYPE_Q4_0; //fall back to Q4_0 instead of just failing.
  3706. LLAMA_LOG_WARN("Q4_0 will be used for this tensor instead.\n");
  3707. } else {
  3708. throw std::runtime_error("Unsupported tensor size encountered\n");
  3709. }
  3710. }
  3711. #endif
  3712. const size_t nelements = ggml_nelements(tensor);
  3713. float * f32_data;
  3714. std::vector<float> f32_conv_buf;
  3715. if (tensor->type == GGML_TYPE_F32) {
  3716. f32_data = (float *) tensor->data;
  3717. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  3718. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  3719. } else {
  3720. llama_convert_tensor_internal(tensor, f32_conv_buf, nelements, nthread);
  3721. f32_data = (float *) f32_conv_buf.data();
  3722. }
  3723. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  3724. fflush(stdout);
  3725. work.resize(nelements * 4); // upper bound on size
  3726. new_data = work.data();
  3727. std::vector<int64_t> hist_cur(1 << 4, 0);
  3728. static const int chunk_size = 32 * 512;
  3729. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  3730. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  3731. if (nthread_use < 2) {
  3732. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  3733. } else {
  3734. size_t counter = 0;
  3735. new_size = 0;
  3736. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements]() {
  3737. std::vector<int64_t> local_hist;
  3738. size_t local_size = 0;
  3739. while (true) {
  3740. std::unique_lock<std::mutex> lock(mutex);
  3741. size_t first = counter; counter += chunk_size;
  3742. if (first >= nelements) {
  3743. if (!local_hist.empty()) {
  3744. for (int j=0; j<int(local_hist.size()); ++j) {
  3745. hist_cur[j] += local_hist[j];
  3746. }
  3747. new_size += local_size;
  3748. }
  3749. break;
  3750. }
  3751. lock.unlock();
  3752. size_t last = std::min(nelements, first + chunk_size);
  3753. if (local_hist.empty()) {
  3754. local_hist.resize(hist_cur.size(), 0);
  3755. }
  3756. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  3757. }
  3758. };
  3759. if ((int) workers.size() < nthread_use - 1) {
  3760. workers.resize(nthread_use - 1);
  3761. }
  3762. for (int it = 0; it < nthread_use - 1; ++it) {
  3763. workers[it] = std::thread(compute);
  3764. }
  3765. compute();
  3766. for (int it = 0; it < nthread_use - 1; ++it) {
  3767. workers[it].join();
  3768. }
  3769. }
  3770. LLAMA_LOG_INFO("size = %8.2f MB -> %8.2f MB | hist: ", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  3771. int64_t tot_count = 0;
  3772. for (size_t i = 0; i < hist_cur.size(); i++) {
  3773. hist_all[i] += hist_cur[i];
  3774. tot_count += hist_cur[i];
  3775. }
  3776. if (tot_count > 0) {
  3777. for (size_t i = 0; i < hist_cur.size(); i++) {
  3778. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  3779. }
  3780. }
  3781. LLAMA_LOG_INFO("\n");
  3782. }
  3783. total_size_org += ggml_nbytes(tensor);
  3784. total_size_new += new_size;
  3785. // update the gguf meta data as we go
  3786. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  3787. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  3788. // write tensor data + padding
  3789. fout.write((const char *) new_data, new_size);
  3790. zeros(fout, GGML_PAD(new_size, align) - new_size);
  3791. }
  3792. // go back to beginning of file and write the updated meta data
  3793. {
  3794. fout.seekp(0);
  3795. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  3796. gguf_get_meta_data(ctx_out, data.data());
  3797. fout.write((const char *) data.data(), data.size());
  3798. }
  3799. fout.close();
  3800. gguf_free(ctx_out);
  3801. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  3802. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  3803. // print histogram for all tensors
  3804. {
  3805. int64_t sum_all = 0;
  3806. for (size_t i = 0; i < hist_all.size(); i++) {
  3807. sum_all += hist_all[i];
  3808. }
  3809. if (sum_all > 0) {
  3810. LLAMA_LOG_INFO("%s: hist: ", __func__);
  3811. for (size_t i = 0; i < hist_all.size(); i++) {
  3812. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  3813. }
  3814. LLAMA_LOG_INFO("\n");
  3815. }
  3816. }
  3817. }
  3818. // TODO: after the GGUF PR, this likely won't work and needs to be updated
  3819. int llama_apply_lora_from_file_internal(const struct llama_model & model, const char * path_lora, const char * path_base_model, int n_threads) {
  3820. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  3821. const int64_t t_start_lora_us = ggml_time_us();
  3822. auto fin = std::ifstream(path_lora, std::ios::binary);
  3823. if (!fin) {
  3824. LLAMA_LOG_ERROR("%s: failed to open '%s'\n", __func__, path_lora);
  3825. return 1;
  3826. }
  3827. // verify magic and version
  3828. {
  3829. uint32_t magic;
  3830. fin.read((char *) &magic, sizeof(magic));
  3831. uint32_t format_version;
  3832. fin.read((char *) &format_version, sizeof(format_version));
  3833. if (format_version != 1) {
  3834. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  3835. return 1;
  3836. }
  3837. }
  3838. int32_t lora_r;
  3839. int32_t lora_alpha;
  3840. fin.read((char *) &lora_r, sizeof(lora_r));
  3841. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  3842. float scaling = (float)lora_alpha / (float)lora_r;
  3843. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  3844. // create a temporary ggml context to store the lora tensors
  3845. // todo: calculate size from biggest possible tensor
  3846. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  3847. struct ggml_init_params params;
  3848. params.mem_size = lora_buf.size();
  3849. params.mem_buffer = lora_buf.data();
  3850. params.no_alloc = false;
  3851. ggml_context * lora_ctx = ggml_init(params);
  3852. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  3853. // create a name -> tensor map of the model to accelerate lookups
  3854. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  3855. for (const auto & kv : model.tensors_by_name) {
  3856. model_tensors.insert(kv);
  3857. }
  3858. // load base model
  3859. std::unique_ptr<llama_model_loader> ml;
  3860. ggml_context * base_ctx = NULL;
  3861. std::vector<uint8_t> base_buf;
  3862. if (path_base_model) {
  3863. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  3864. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true));
  3865. size_t ctx_size;
  3866. size_t mmapped_size;
  3867. ml->calc_sizes(ctx_size, mmapped_size);
  3868. base_buf.resize(ctx_size);
  3869. ggml_init_params base_params;
  3870. base_params.mem_size = base_buf.size();
  3871. base_params.mem_buffer = base_buf.data();
  3872. base_params.no_alloc = ml->use_mmap;
  3873. base_ctx = ggml_init(base_params);
  3874. // maybe this should in llama_model_loader
  3875. if (ml->use_mmap) {
  3876. ml->mapping.reset(new llama_mmap(&ml->file, /* prefetch */ 0, ggml_is_numa()));
  3877. }
  3878. }
  3879. // read tensors and apply
  3880. bool warned = false;
  3881. int n_tensors = 0;
  3882. std::vector<uint8_t> work_buffer;
  3883. while (true) {
  3884. int32_t n_dims;
  3885. int32_t length;
  3886. int32_t ftype;
  3887. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  3888. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  3889. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  3890. if (fin.eof()) {
  3891. break;
  3892. }
  3893. int32_t ne[2] = { 1, 1 };
  3894. for (int i = 0; i < n_dims; ++i) {
  3895. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  3896. }
  3897. std::string name;
  3898. {
  3899. char buf[1024];
  3900. fin.read(buf, length);
  3901. name = std::string(buf, length);
  3902. }
  3903. // check for lora suffix and get the type of tensor
  3904. const std::string lora_suffix = ".lora";
  3905. size_t pos = name.rfind(lora_suffix);
  3906. if (pos == std::string::npos) {
  3907. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  3908. return 1;
  3909. }
  3910. std::string lora_type = name.substr(pos + lora_suffix.length());
  3911. std::string base_name = name;
  3912. base_name.erase(pos);
  3913. // LLAMA_LOG_INFO("%s: %s => %s (lora type %s) \n", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  3914. if (model_tensors.find(base_name) == model_tensors.end()) {
  3915. LLAMA_LOG_ERROR("%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  3916. return 1;
  3917. }
  3918. // create ggml tensor
  3919. ggml_type wtype;
  3920. switch (ftype) {
  3921. case 0: wtype = GGML_TYPE_F32; break;
  3922. case 1: wtype = GGML_TYPE_F16; break;
  3923. default:
  3924. {
  3925. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  3926. __func__, ftype);
  3927. return false;
  3928. }
  3929. }
  3930. ggml_tensor * lora_tensor;
  3931. if (n_dims == 2) {
  3932. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  3933. }
  3934. else {
  3935. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  3936. return 1;
  3937. }
  3938. ggml_set_name(lora_tensor, "lora_tensor");
  3939. // load tensor data
  3940. size_t offset = fin.tellg();
  3941. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  3942. offset = (offset + 31) & -32;
  3943. fin.seekg(offset);
  3944. fin.read((char*)lora_tensor->data, tensor_data_size);
  3945. lora_tensors[name] = lora_tensor;
  3946. // check if we have both A and B tensors and apply
  3947. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  3948. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  3949. ggml_tensor * dest_t = model_tensors[base_name];
  3950. offload_func_t offload_func = llama_nop;
  3951. offload_func_t offload_func_force_inplace = llama_nop;
  3952. #ifdef GGML_USE_CUBLAS
  3953. if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
  3954. if (dest_t->type != GGML_TYPE_F16) {
  3955. throw std::runtime_error(format(
  3956. "%s: error: the simultaneous use of LoRAs and GPU acceleration is only supported for f16 models", __func__));
  3957. }
  3958. offload_func = ggml_cuda_assign_buffers;
  3959. offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
  3960. }
  3961. #endif // GGML_USE_CUBLAS
  3962. ggml_tensor * base_t;
  3963. if (ml) {
  3964. struct gguf_context * ctx_gguf = ml->ctx_gguf;
  3965. // load from base model
  3966. if (gguf_find_tensor(ctx_gguf, base_name.c_str()) < 0) {
  3967. // TODO: throw
  3968. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  3969. return 1;
  3970. }
  3971. // TODO: not tested!! maybe not working!
  3972. base_t = ml->create_tensor(base_ctx, base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] }, GGML_BACKEND_CPU);
  3973. ml->load_data_for(base_t);
  3974. } else {
  3975. base_t = dest_t;
  3976. }
  3977. if (ggml_is_quantized(base_t->type)) {
  3978. if (!warned) {
  3979. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  3980. "use a f16 or f32 base model with --lora-base\n", __func__);
  3981. warned = true;
  3982. }
  3983. }
  3984. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  3985. GGML_ASSERT(loraA->type == GGML_TYPE_F32);
  3986. ggml_set_name(loraA, "loraA");
  3987. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  3988. GGML_ASSERT(loraB->type == GGML_TYPE_F32);
  3989. ggml_set_name(loraB, "loraB");
  3990. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  3991. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  3992. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  3993. return 1;
  3994. }
  3995. // w = w + BA*s
  3996. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  3997. offload_func(BA);
  3998. ggml_set_name(BA, "BA");
  3999. if (scaling != 1.0f) {
  4000. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  4001. ggml_set_name(scale_tensor, "scale_tensor");
  4002. BA = ggml_scale_inplace(lora_ctx, BA, scale_tensor);
  4003. offload_func(BA);
  4004. ggml_set_name(BA, "BA_scaled");
  4005. }
  4006. ggml_tensor * r;
  4007. if (base_t == dest_t) {
  4008. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  4009. offload_func_force_inplace(r);
  4010. ggml_set_name(r, "r_add_inplace");
  4011. }
  4012. else {
  4013. r = ggml_add(lora_ctx, base_t, BA);
  4014. offload_func(r);
  4015. ggml_set_name(r, "r_add");
  4016. r = ggml_cpy(lora_ctx, r, dest_t);
  4017. offload_func(r);
  4018. ggml_set_name(r, "r_cpy");
  4019. }
  4020. struct ggml_cgraph gf = ggml_build_forward(r);
  4021. ggml_graph_compute_helper(work_buffer, &gf, n_threads);
  4022. // we won't need these tensors again, reset the context to save memory
  4023. ggml_free(lora_ctx);
  4024. lora_ctx = ggml_init(params);
  4025. lora_tensors.clear();
  4026. n_tensors++;
  4027. if (n_tensors % 4 == 0) {
  4028. LLAMA_LOG_INFO(".");
  4029. }
  4030. }
  4031. }
  4032. // TODO: this should be in a destructor, it will leak on failure
  4033. ggml_free(lora_ctx);
  4034. if (base_ctx) {
  4035. ggml_free(base_ctx);
  4036. }
  4037. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  4038. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  4039. return 0;
  4040. }
  4041. //
  4042. // interface implementation
  4043. //
  4044. struct llama_context_params llama_context_default_params() {
  4045. struct llama_context_params result = {
  4046. /*.seed =*/ LLAMA_DEFAULT_SEED,
  4047. /*.n_ctx =*/ 512,
  4048. /*.n_batch =*/ 512,
  4049. /*.gpu_layers =*/ 0,
  4050. /*.main_gpu =*/ 0,
  4051. /*.tensor_split =*/ nullptr,
  4052. /*.rope_freq_base =*/ 10000.0f,
  4053. /*.rope_freq_scale =*/ 1.0f,
  4054. /*.progress_callback =*/ nullptr,
  4055. /*.progress_callback_user_data =*/ nullptr,
  4056. /*.low_vram =*/ false,
  4057. /*.mul_mat_q =*/ false,
  4058. /*.f16_kv =*/ true,
  4059. /*.logits_all =*/ false,
  4060. /*.vocab_only =*/ false,
  4061. /*.use_mmap =*/ true,
  4062. /*.use_mlock =*/ false,
  4063. /*.embedding =*/ false,
  4064. };
  4065. return result;
  4066. }
  4067. struct llama_model_quantize_params llama_model_quantize_default_params() {
  4068. struct llama_model_quantize_params result = {
  4069. /*.nthread =*/ 0,
  4070. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  4071. /*.allow_requantize =*/ false,
  4072. /*.quantize_output_tensor =*/ true,
  4073. };
  4074. return result;
  4075. }
  4076. int llama_max_devices(void) {
  4077. return LLAMA_MAX_DEVICES;
  4078. }
  4079. bool llama_mmap_supported(void) {
  4080. return llama_mmap::SUPPORTED;
  4081. }
  4082. bool llama_mlock_supported(void) {
  4083. return llama_mlock::SUPPORTED;
  4084. }
  4085. void llama_backend_init(bool numa) {
  4086. ggml_time_init();
  4087. // needed to initialize f16 tables
  4088. {
  4089. struct ggml_init_params params = { 0, NULL, false };
  4090. struct ggml_context * ctx = ggml_init(params);
  4091. ggml_free(ctx);
  4092. }
  4093. if (numa) {
  4094. ggml_numa_init();
  4095. }
  4096. #ifdef GGML_USE_MPI
  4097. ggml_mpi_backend_init();
  4098. #endif
  4099. }
  4100. void llama_backend_free(void) {
  4101. #ifdef GGML_USE_MPI
  4102. ggml_mpi_backend_free();
  4103. #endif
  4104. }
  4105. int64_t llama_time_us(void) {
  4106. return ggml_time_us();
  4107. }
  4108. struct llama_model * llama_load_model_from_file(
  4109. const char * path_model,
  4110. struct llama_context_params params) {
  4111. ggml_time_init();
  4112. llama_model * model = new llama_model;
  4113. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  4114. unsigned cur_percentage = 0;
  4115. if (params.progress_callback == NULL) {
  4116. params.progress_callback_user_data = &cur_percentage;
  4117. params.progress_callback = [](float progress, void * ctx) {
  4118. unsigned * cur_percentage_p = (unsigned *) ctx;
  4119. unsigned percentage = (unsigned) (100 * progress);
  4120. while (percentage > *cur_percentage_p) {
  4121. *cur_percentage_p = percentage;
  4122. LLAMA_LOG_INFO(".");
  4123. if (percentage >= 100) {
  4124. LLAMA_LOG_INFO("\n");
  4125. }
  4126. }
  4127. };
  4128. }
  4129. if (!llama_model_load(path_model, *model, params.n_ctx, params.n_batch, params.n_gpu_layers,
  4130. params.main_gpu, params.tensor_split, params.mul_mat_q, params.rope_freq_base, params.rope_freq_scale,
  4131. params.low_vram, memory_type, params.use_mmap, params.use_mlock, params.vocab_only,
  4132. params.progress_callback, params.progress_callback_user_data)) {
  4133. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  4134. delete model;
  4135. return nullptr;
  4136. }
  4137. return model;
  4138. }
  4139. void llama_free_model(struct llama_model * model) {
  4140. delete model;
  4141. }
  4142. struct llama_context * llama_new_context_with_model(
  4143. struct llama_model * model,
  4144. struct llama_context_params params) {
  4145. if (!model) {
  4146. return nullptr;
  4147. }
  4148. llama_context * ctx = new llama_context(*model);
  4149. if (params.seed == LLAMA_DEFAULT_SEED) {
  4150. params.seed = time(NULL);
  4151. }
  4152. ctx->rng = std::mt19937(params.seed);
  4153. ctx->logits_all = params.logits_all;
  4154. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  4155. // reserve memory for context buffers
  4156. if (!params.vocab_only) {
  4157. if (!llama_kv_cache_init(ctx->model.hparams, ctx->kv_self, memory_type, ctx->model.hparams.n_ctx, params.n_gpu_layers)) {
  4158. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  4159. llama_free(ctx);
  4160. return nullptr;
  4161. }
  4162. {
  4163. const size_t memory_size = ggml_nbytes(ctx->kv_self.k) + ggml_nbytes(ctx->kv_self.v);
  4164. LLAMA_LOG_INFO("%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  4165. }
  4166. const auto & hparams = ctx->model.hparams;
  4167. // resized during inference
  4168. if (params.logits_all) {
  4169. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  4170. } else {
  4171. ctx->logits.reserve(hparams.n_vocab);
  4172. }
  4173. if (params.embedding){
  4174. ctx->embedding.resize(hparams.n_embd);
  4175. }
  4176. {
  4177. static const size_t tensor_alignment = 32;
  4178. // the compute buffer is used to store the tensor and graph structs, while the allocator buffer is used for the tensor data
  4179. ctx->buf_compute.resize(ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead());
  4180. // create measure allocator
  4181. ctx->alloc = ggml_allocr_new_measure(tensor_alignment);
  4182. // build worst-case graph
  4183. int n_tokens = std::min((int)hparams.n_ctx, params.n_batch);
  4184. int n_past = hparams.n_ctx - n_tokens;
  4185. llama_token token = llama_token_bos(ctx); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  4186. ggml_cgraph * gf = llama_build_graph(*ctx, &token, NULL, n_tokens, n_past);
  4187. #ifdef GGML_USE_METAL
  4188. if (params.n_gpu_layers > 0) {
  4189. ctx->ctx_metal = ggml_metal_init(1);
  4190. if (!ctx->ctx_metal) {
  4191. LLAMA_LOG_ERROR("%s: ggml_metal_init() failed\n", __func__);
  4192. llama_free(ctx);
  4193. return NULL;
  4194. }
  4195. ggml_metal_graph_find_concurrency(ctx->ctx_metal, gf, false);
  4196. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  4197. }
  4198. #endif
  4199. // measure memory requirements for the graph
  4200. size_t alloc_size = ggml_allocr_alloc_graph(ctx->alloc, gf) + tensor_alignment;
  4201. LLAMA_LOG_INFO("%s: compute buffer total size = %7.2f MB\n", __func__, (ctx->buf_compute.size + alloc_size) / 1024.0 / 1024.0);
  4202. // recreate allocator with exact memory requirements
  4203. ggml_allocr_free(ctx->alloc);
  4204. ctx->buf_alloc.resize(alloc_size);
  4205. ctx->alloc = ggml_allocr_new(ctx->buf_alloc.data, ctx->buf_alloc.size, tensor_alignment);
  4206. #ifdef GGML_USE_METAL
  4207. if (ctx->ctx_metal) {
  4208. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  4209. }
  4210. #endif
  4211. #ifdef GGML_USE_CUBLAS
  4212. if (params.low_vram) {
  4213. LLAMA_LOG_INFO("%s: not allocating a VRAM scratch buffer due to low VRAM option\n", __func__);
  4214. ggml_cuda_set_scratch_size(0); // disable scratch
  4215. } else {
  4216. ggml_cuda_set_scratch_size(alloc_size);
  4217. LLAMA_LOG_INFO("%s: VRAM scratch buffer: %.2f MB\n", __func__, alloc_size / 1024.0 / 1024.0);
  4218. }
  4219. #endif
  4220. }
  4221. }
  4222. #ifdef GGML_USE_METAL
  4223. if (params.n_gpu_layers > 0) {
  4224. // this allocates all Metal resources and memory buffers
  4225. void * data_ptr = NULL;
  4226. size_t data_size = 0;
  4227. if (params.use_mmap) {
  4228. data_ptr = ctx->model.mapping->addr;
  4229. data_size = ctx->model.mapping->size;
  4230. } else {
  4231. data_ptr = ggml_get_mem_buffer(ctx->model.ctx);
  4232. data_size = ggml_get_mem_size (ctx->model.ctx);
  4233. }
  4234. const size_t max_size = ggml_get_max_tensor_size(ctx->model.ctx);
  4235. LLAMA_LOG_INFO("%s: max tensor size = %8.2f MB\n", __func__, max_size/1024.0/1024.0);
  4236. #define LLAMA_METAL_CHECK_BUF(result) \
  4237. if (!(result)) { \
  4238. LLAMA_LOG_ERROR("%s: failed to add buffer\n", __func__); \
  4239. llama_free(ctx); \
  4240. return NULL; \
  4241. }
  4242. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "data", data_ptr, data_size, max_size));
  4243. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "eval", ctx->buf_compute.data, ctx->buf_compute.size, 0));
  4244. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "kv", ctx->kv_self.buf.data, ctx->kv_self.buf.size, 0));
  4245. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "alloc", ctx->buf_alloc.data, ctx->buf_alloc.size, 0));
  4246. #undef LLAMA_METAL_CHECK_BUF
  4247. }
  4248. #endif
  4249. #ifdef GGML_USE_MPI
  4250. ctx->ctx_mpi = ggml_mpi_init();
  4251. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  4252. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  4253. const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  4254. while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  4255. llama_backend_free();
  4256. exit(1);
  4257. }
  4258. #endif
  4259. return ctx;
  4260. }
  4261. struct llama_context * llama_init_from_file(
  4262. const char * path_model,
  4263. struct llama_context_params params) {
  4264. struct llama_model * model = llama_load_model_from_file(path_model, params);
  4265. if (!model) {
  4266. return nullptr;
  4267. }
  4268. struct llama_context * ctx = llama_new_context_with_model(model, params);
  4269. ctx->model_owner = true;
  4270. return ctx;
  4271. }
  4272. void llama_free(struct llama_context * ctx) {
  4273. delete ctx;
  4274. }
  4275. int llama_n_vocab(const struct llama_context * ctx) {
  4276. return ctx->model.vocab.id_to_token.size();
  4277. }
  4278. int llama_n_ctx(const struct llama_context * ctx) {
  4279. return ctx->model.hparams.n_ctx;
  4280. }
  4281. int llama_n_embd(const struct llama_context * ctx) {
  4282. return ctx->model.hparams.n_embd;
  4283. }
  4284. enum llama_vocab_type llama_vocab_type(const struct llama_context * ctx) {
  4285. return ctx->model.vocab.type;
  4286. }
  4287. int llama_model_n_vocab(const struct llama_model * model) {
  4288. return model->vocab.id_to_token.size();
  4289. }
  4290. int llama_model_n_ctx(const struct llama_model * model) {
  4291. return model->hparams.n_ctx;
  4292. }
  4293. int llama_model_n_embd(const struct llama_model * model) {
  4294. return model->hparams.n_embd;
  4295. }
  4296. int llama_model_type(const struct llama_model * model, char * buf, size_t buf_size) {
  4297. return snprintf(buf, buf_size, "%s %s %s",
  4298. model->name.c_str(),
  4299. llama_model_type_name(model->type),
  4300. llama_model_ftype_name(model->ftype).c_str());
  4301. }
  4302. int llama_model_quantize(
  4303. const char * fname_inp,
  4304. const char * fname_out,
  4305. const llama_model_quantize_params * params) {
  4306. try {
  4307. llama_model_quantize_internal(fname_inp, fname_out, params);
  4308. return 0;
  4309. } catch (const std::exception & err) {
  4310. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  4311. return 1;
  4312. }
  4313. }
  4314. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  4315. try {
  4316. return llama_apply_lora_from_file_internal(ctx->model, path_lora, path_base_model, n_threads);
  4317. } catch (const std::exception & err) {
  4318. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  4319. return 1;
  4320. }
  4321. }
  4322. int llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, const char * path_base_model, int n_threads) {
  4323. try {
  4324. return llama_apply_lora_from_file_internal(*model, path_lora, path_base_model, n_threads);
  4325. } catch (const std::exception & err) {
  4326. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  4327. return 1;
  4328. }
  4329. }
  4330. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  4331. return ctx->kv_self.n;
  4332. }
  4333. #define LLAMA_MAX_RNG_STATE (64*1024)
  4334. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  4335. if (seed == LLAMA_DEFAULT_SEED) {
  4336. seed = time(NULL);
  4337. }
  4338. ctx->rng.seed(seed);
  4339. }
  4340. // Returns the *maximum* size of the state
  4341. size_t llama_get_state_size(const struct llama_context * ctx) {
  4342. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  4343. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  4344. const size_t s_rng_size = sizeof(size_t);
  4345. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  4346. const size_t s_logits_capacity = sizeof(size_t);
  4347. const size_t s_logits_size = sizeof(size_t);
  4348. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  4349. const size_t s_embedding_size = sizeof(size_t);
  4350. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  4351. const size_t s_kv_size = sizeof(size_t);
  4352. const size_t s_kv_ntok = sizeof(int);
  4353. const size_t s_kv = ctx->kv_self.buf.size;
  4354. const size_t s_total = (
  4355. + s_rng_size
  4356. + s_rng
  4357. + s_logits_capacity
  4358. + s_logits_size
  4359. + s_logits
  4360. + s_embedding_size
  4361. + s_embedding
  4362. + s_kv_size
  4363. + s_kv_ntok
  4364. + s_kv
  4365. );
  4366. return s_total;
  4367. }
  4368. // llama_context_data
  4369. struct llama_data_context {
  4370. virtual void write(const void * src, size_t size) = 0;
  4371. virtual size_t get_size_written() = 0;
  4372. virtual ~llama_data_context() = default;
  4373. };
  4374. struct llama_data_buffer_context : llama_data_context {
  4375. uint8_t * ptr;
  4376. size_t size_written = 0;
  4377. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  4378. void write(const void * src, size_t size) override {
  4379. memcpy(ptr, src, size);
  4380. ptr += size;
  4381. size_written += size;
  4382. }
  4383. size_t get_size_written() override {
  4384. return size_written;
  4385. }
  4386. };
  4387. struct llama_data_file_context : llama_data_context {
  4388. llama_file * file;
  4389. size_t size_written = 0;
  4390. llama_data_file_context(llama_file * f) : file(f) {}
  4391. void write(const void * src, size_t size) override {
  4392. file->write_raw(src, size);
  4393. size_written += size;
  4394. }
  4395. size_t get_size_written() override {
  4396. return size_written;
  4397. }
  4398. };
  4399. /** copy state data into either a buffer or file depending on the passed in context
  4400. *
  4401. * file context:
  4402. * llama_file file("/path", "wb");
  4403. * llama_data_file_context data_ctx(&file);
  4404. * llama_copy_state_data(ctx, &data_ctx);
  4405. *
  4406. * buffer context:
  4407. * std::vector<uint8_t> buf(max_size, 0);
  4408. * llama_data_buffer_context data_ctx(&buf.data());
  4409. * llama_copy_state_data(ctx, &data_ctx);
  4410. *
  4411. */
  4412. void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  4413. // copy rng
  4414. {
  4415. std::stringstream rng_ss;
  4416. rng_ss << ctx->rng;
  4417. const size_t rng_size = rng_ss.str().size();
  4418. char rng_buf[LLAMA_MAX_RNG_STATE];
  4419. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  4420. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  4421. data_ctx->write(&rng_size, sizeof(rng_size));
  4422. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  4423. }
  4424. // copy logits
  4425. {
  4426. const size_t logits_cap = ctx->logits.capacity();
  4427. const size_t logits_size = ctx->logits.size();
  4428. data_ctx->write(&logits_cap, sizeof(logits_cap));
  4429. data_ctx->write(&logits_size, sizeof(logits_size));
  4430. if (logits_size) {
  4431. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  4432. }
  4433. // If there is a gap between the size and the capacity, write padding
  4434. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  4435. if (padding_size > 0) {
  4436. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  4437. data_ctx->write(padding.data(), padding_size);
  4438. }
  4439. }
  4440. // copy embeddings
  4441. {
  4442. const size_t embedding_size = ctx->embedding.size();
  4443. data_ctx->write(&embedding_size, sizeof(embedding_size));
  4444. if (embedding_size) {
  4445. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  4446. }
  4447. }
  4448. // copy kv cache
  4449. {
  4450. const auto & kv_self = ctx->kv_self;
  4451. const auto & hparams = ctx->model.hparams;
  4452. const int n_layer = hparams.n_layer;
  4453. const int n_embd = hparams.n_embd_gqa();
  4454. const int n_ctx = hparams.n_ctx;
  4455. const size_t kv_size = kv_self.buf.size;
  4456. const int kv_ntok = llama_get_kv_cache_token_count(ctx);
  4457. data_ctx->write(&kv_size, sizeof(kv_size));
  4458. data_ctx->write(&kv_ntok, sizeof(kv_ntok));
  4459. if (kv_size) {
  4460. const size_t elt_size = ggml_element_size(kv_self.k);
  4461. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  4462. ggml_cgraph gf{};
  4463. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  4464. std::vector<uint8_t> kout3d_data(ggml_nbytes(kout3d), 0);
  4465. kout3d->data = kout3d_data.data();
  4466. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  4467. std::vector<uint8_t> vout3d_data(ggml_nbytes(vout3d), 0);
  4468. vout3d->data = vout3d_data.data();
  4469. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  4470. n_embd, kv_ntok, n_layer,
  4471. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  4472. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  4473. kv_ntok, n_embd, n_layer,
  4474. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  4475. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  4476. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  4477. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  4478. ggml_free(cpy_ctx);
  4479. // our data is now in the kout3d_data and vout3d_data buffers
  4480. // write them to file
  4481. data_ctx->write(kout3d_data.data(), kout3d_data.size());
  4482. data_ctx->write(vout3d_data.data(), vout3d_data.size());
  4483. }
  4484. }
  4485. }
  4486. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  4487. llama_data_buffer_context data_ctx(dst);
  4488. llama_copy_state_data_internal(ctx, &data_ctx);
  4489. return data_ctx.get_size_written();
  4490. }
  4491. // Sets the state reading from the specified source address
  4492. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  4493. uint8_t * inp = src;
  4494. // set rng
  4495. {
  4496. size_t rng_size;
  4497. char rng_buf[LLAMA_MAX_RNG_STATE];
  4498. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  4499. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  4500. std::stringstream rng_ss;
  4501. rng_ss.str(std::string(&rng_buf[0], rng_size));
  4502. rng_ss >> ctx->rng;
  4503. GGML_ASSERT(rng_ss.fail() == false);
  4504. }
  4505. // set logits
  4506. {
  4507. size_t logits_cap;
  4508. size_t logits_size;
  4509. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  4510. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  4511. GGML_ASSERT(ctx->logits.capacity() == logits_cap);
  4512. if (logits_size) {
  4513. ctx->logits.resize(logits_size);
  4514. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  4515. }
  4516. inp += logits_cap * sizeof(float);
  4517. }
  4518. // set embeddings
  4519. {
  4520. size_t embedding_size;
  4521. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  4522. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  4523. if (embedding_size) {
  4524. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  4525. inp += embedding_size * sizeof(float);
  4526. }
  4527. }
  4528. // set kv cache
  4529. {
  4530. const auto & kv_self = ctx->kv_self;
  4531. const auto & hparams = ctx->model.hparams;
  4532. const int n_layer = hparams.n_layer;
  4533. const int n_embd = hparams.n_embd_gqa();
  4534. const int n_ctx = hparams.n_ctx;
  4535. size_t kv_size;
  4536. int kv_ntok;
  4537. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  4538. memcpy(&kv_ntok, inp, sizeof(kv_ntok)); inp += sizeof(kv_ntok);
  4539. if (kv_size) {
  4540. GGML_ASSERT(kv_self.buf.size == kv_size);
  4541. const size_t elt_size = ggml_element_size(kv_self.k);
  4542. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  4543. ggml_cgraph gf{};
  4544. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  4545. kin3d->data = (void *) inp;
  4546. inp += ggml_nbytes(kin3d);
  4547. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  4548. vin3d->data = (void *) inp;
  4549. inp += ggml_nbytes(vin3d);
  4550. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  4551. n_embd, kv_ntok, n_layer,
  4552. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  4553. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  4554. kv_ntok, n_embd, n_layer,
  4555. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  4556. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  4557. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  4558. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  4559. ggml_free(cpy_ctx);
  4560. }
  4561. ctx->kv_self.n = kv_ntok;
  4562. }
  4563. const size_t nread = inp - src;
  4564. const size_t max_size = llama_get_state_size(ctx);
  4565. GGML_ASSERT(nread <= max_size);
  4566. return nread;
  4567. }
  4568. 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) {
  4569. llama_file file(path_session, "rb");
  4570. // sanity checks
  4571. {
  4572. const uint32_t magic = file.read_u32();
  4573. const uint32_t version = file.read_u32();
  4574. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  4575. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  4576. return false;
  4577. }
  4578. llama_hparams session_hparams;
  4579. file.read_raw(&session_hparams, sizeof(llama_hparams));
  4580. if (session_hparams != ctx->model.hparams) {
  4581. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  4582. return false;
  4583. }
  4584. }
  4585. // load the prompt
  4586. {
  4587. const uint32_t n_token_count = file.read_u32();
  4588. if (n_token_count > n_token_capacity) {
  4589. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  4590. return false;
  4591. }
  4592. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  4593. *n_token_count_out = n_token_count;
  4594. }
  4595. // restore the context state
  4596. {
  4597. const size_t n_state_size_cur = file.size - file.tell();
  4598. const size_t n_state_size_max = llama_get_state_size(ctx);
  4599. if (n_state_size_cur > n_state_size_max) {
  4600. 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);
  4601. return false;
  4602. }
  4603. std::vector<uint8_t> state_data(n_state_size_max);
  4604. file.read_raw(state_data.data(), n_state_size_cur);
  4605. llama_set_state_data(ctx, state_data.data());
  4606. }
  4607. return true;
  4608. }
  4609. 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) {
  4610. try {
  4611. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  4612. } catch (const std::exception & err) {
  4613. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  4614. return false;
  4615. }
  4616. }
  4617. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  4618. llama_file file(path_session, "wb");
  4619. file.write_u32(LLAMA_SESSION_MAGIC);
  4620. file.write_u32(LLAMA_SESSION_VERSION);
  4621. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  4622. // save the prompt
  4623. file.write_u32((uint32_t) n_token_count);
  4624. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  4625. // save the context state using stream saving
  4626. llama_data_file_context data_ctx(&file);
  4627. llama_copy_state_data_internal(ctx, &data_ctx);
  4628. return true;
  4629. }
  4630. int llama_eval(
  4631. struct llama_context * ctx,
  4632. const llama_token * tokens,
  4633. int n_tokens,
  4634. int n_past,
  4635. int n_threads) {
  4636. if (!llama_eval_internal(*ctx, tokens, nullptr, n_tokens, n_past, n_threads, nullptr)) {
  4637. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  4638. return 1;
  4639. }
  4640. // get a more accurate load time, upon first eval
  4641. // TODO: fix this
  4642. if (!ctx->has_evaluated_once) {
  4643. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  4644. ctx->has_evaluated_once = true;
  4645. }
  4646. return 0;
  4647. }
  4648. int llama_eval_embd(
  4649. struct llama_context * ctx,
  4650. const float * embd,
  4651. int n_tokens,
  4652. int n_past,
  4653. int n_threads) {
  4654. if (!llama_eval_internal(*ctx, nullptr, embd, n_tokens, n_past, n_threads, nullptr)) {
  4655. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  4656. return 1;
  4657. }
  4658. // get a more accurate load time, upon first eval
  4659. // TODO: fix this
  4660. if (!ctx->has_evaluated_once) {
  4661. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  4662. ctx->has_evaluated_once = true;
  4663. }
  4664. return 0;
  4665. }
  4666. int llama_eval_export(struct llama_context * ctx, const char * fname) {
  4667. const int n_batch = 1;
  4668. const int n_ctx = 512 - n_batch;
  4669. const std::vector<llama_token> tmp(n_batch, llama_token_bos(ctx));
  4670. if (!llama_eval_internal(*ctx, tmp.data(), nullptr, tmp.size(), n_ctx, 1, fname)) {
  4671. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  4672. return 1;
  4673. }
  4674. return 0;
  4675. }
  4676. float * llama_get_logits(struct llama_context * ctx) {
  4677. return ctx->logits.data();
  4678. }
  4679. float * llama_get_embeddings(struct llama_context * ctx) {
  4680. return ctx->embedding.data();
  4681. }
  4682. const char * llama_token_get_text(const struct llama_context * ctx, llama_token token) {
  4683. return ctx->model.vocab.id_to_token[token].text.c_str();
  4684. }
  4685. float llama_token_get_score(const struct llama_context * ctx, llama_token token) {
  4686. return ctx->model.vocab.id_to_token[token].score;
  4687. }
  4688. llama_token_type llama_token_get_type(const struct llama_context * ctx, llama_token token) {
  4689. return ctx->model.vocab.id_to_token[token].type;
  4690. }
  4691. llama_token llama_token_bos(const struct llama_context * ctx) {
  4692. return ctx->model.vocab.special_bos_id;
  4693. }
  4694. llama_token llama_token_eos(const struct llama_context * ctx) {
  4695. return ctx->model.vocab.special_eos_id;
  4696. }
  4697. llama_token llama_token_nl(const struct llama_context * ctx) {
  4698. return ctx->model.vocab.linefeed_id;
  4699. }
  4700. int llama_tokenize(
  4701. struct llama_context * ctx,
  4702. const char * text,
  4703. llama_token * tokens,
  4704. int n_max_tokens,
  4705. bool add_bos) {
  4706. return llama_tokenize_with_model(&ctx->model, text, tokens, n_max_tokens, add_bos);
  4707. }
  4708. int llama_tokenize_with_model(
  4709. const struct llama_model * model,
  4710. const char * text,
  4711. llama_token * tokens,
  4712. int n_max_tokens,
  4713. bool add_bos) {
  4714. auto escape = llama_vocab_get_type(model->vocab) == LLAMA_VOCAB_TYPE_SPM;
  4715. auto res = llama_tokenize_internal(model->vocab, text, add_bos, escape);
  4716. if (n_max_tokens < (int) res.size()) {
  4717. LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  4718. return -((int) res.size());
  4719. }
  4720. for (size_t i = 0; i < res.size(); i++) {
  4721. tokens[i] = res[i];
  4722. }
  4723. return res.size();
  4724. }
  4725. int llama_token_to_str(const struct llama_context * ctx, llama_token token, char * buf, int length) {
  4726. return llama_token_to_str_with_model(&ctx->model, token, buf, length);
  4727. }
  4728. // does not write null-terminator to str
  4729. int llama_token_to_str_with_model(const struct llama_model * model, llama_token token, char * buf, int length) {
  4730. if (0 <= token && token < llama_model_n_vocab(model)) {
  4731. if (llama_is_normal_token(model->vocab, token)) {
  4732. std::string result = model->vocab.id_to_token[token].text;
  4733. if (llama_vocab_get_type(model->vocab) == LLAMA_VOCAB_TYPE_SPM) {
  4734. result = llama_unescape_whitespace(result);
  4735. }
  4736. if (length < (int) result.length()) {
  4737. return -result.length();
  4738. }
  4739. memcpy(buf, result.c_str(), result.length());
  4740. return result.length();
  4741. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  4742. if (length < 3) {
  4743. return -3;
  4744. }
  4745. buf[0] = '\xe2';
  4746. buf[1] = '\x96';
  4747. buf[2] = '\x85';
  4748. return 3;
  4749. } else if (llama_is_control_token(model->vocab, token)) {
  4750. ;
  4751. } else if (llama_is_byte_token(model->vocab, token)) {
  4752. if (length < 1) {
  4753. return -1;
  4754. }
  4755. buf[0] = llama_token_to_byte(model->vocab, token);
  4756. return 1;
  4757. }
  4758. }
  4759. return 0;
  4760. }
  4761. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  4762. struct llama_timings result = {
  4763. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  4764. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  4765. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  4766. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  4767. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  4768. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  4769. /*.n_sample =*/ std::max(1, ctx->n_sample),
  4770. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  4771. /*.n_eval =*/ std::max(1, ctx->n_eval),
  4772. };
  4773. return result;
  4774. }
  4775. void llama_print_timings(struct llama_context * ctx) {
  4776. const llama_timings timings = llama_get_timings(ctx);
  4777. LLAMA_LOG_INFO("\n");
  4778. LLAMA_LOG_INFO("%s: load time = %8.2f ms\n", __func__, timings.t_load_ms);
  4779. LLAMA_LOG_INFO("%s: sample time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  4780. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  4781. LLAMA_LOG_INFO("%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  4782. __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);
  4783. LLAMA_LOG_INFO("%s: eval time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  4784. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  4785. LLAMA_LOG_INFO("%s: total time = %8.2f ms\n", __func__, (timings.t_end_ms - timings.t_start_ms));
  4786. }
  4787. void llama_reset_timings(struct llama_context * ctx) {
  4788. ctx->t_start_us = ggml_time_us();
  4789. ctx->t_sample_us = ctx->n_sample = 0;
  4790. ctx->t_eval_us = ctx->n_eval = 0;
  4791. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  4792. }
  4793. const char * llama_print_system_info(void) {
  4794. static std::string s;
  4795. s = "";
  4796. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  4797. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  4798. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  4799. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  4800. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  4801. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  4802. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  4803. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  4804. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  4805. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  4806. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  4807. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  4808. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  4809. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  4810. return s.c_str();
  4811. }
  4812. // For internal test use
  4813. const std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  4814. return ctx->model.tensors_by_name;
  4815. }
  4816. void llama_log_set(llama_log_callback log_callback, void * user_data) {
  4817. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  4818. g_state.log_callback_user_data = user_data;
  4819. }
  4820. #if defined(_MSC_VER) && !defined(vsnprintf)
  4821. #define vsnprintf _vsnprintf
  4822. #endif
  4823. static void llama_log_internal_v(llama_log_level level, const char * format, va_list args) {
  4824. va_list args_copy;
  4825. va_copy(args_copy, args);
  4826. char buffer[128];
  4827. int len = vsnprintf(buffer, 128, format, args);
  4828. if (len < 128) {
  4829. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  4830. } else {
  4831. char* buffer2 = new char[len+1];
  4832. vsnprintf(buffer2, len+1, format, args_copy);
  4833. buffer2[len] = 0;
  4834. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  4835. delete[] buffer2;
  4836. }
  4837. va_end(args_copy);
  4838. }
  4839. static void llama_log_internal(llama_log_level level, const char * format, ...) {
  4840. va_list args;
  4841. va_start(args, format);
  4842. llama_log_internal_v(level, format, args);
  4843. va_end(args);
  4844. }
  4845. static void llama_log_callback_default(llama_log_level level, const char * text, void * user_data) {
  4846. (void) level;
  4847. (void) user_data;
  4848. fputs(text, stderr);
  4849. fflush(stderr);
  4850. }