ggml.c 759 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238
  1. #define _CRT_SECURE_NO_DEPRECATE // Disables ridiculous "unsafe" warnings on Windows
  2. #define _USE_MATH_DEFINES // For M_PI on MSVC
  3. #include "ggml-backend.h"
  4. #include "ggml-impl.h"
  5. #include "ggml-cpu-impl.h"
  6. #include "ggml-quants.h"
  7. #include "ggml.h"
  8. #include "ggml-aarch64.h"
  9. #if defined(_MSC_VER) || defined(__MINGW32__)
  10. #include <malloc.h> // using malloc.h with MSC/MINGW
  11. #elif !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
  12. #include <alloca.h>
  13. #endif
  14. #include <assert.h>
  15. #include <errno.h>
  16. #include <time.h>
  17. #include <math.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <stdint.h>
  21. #include <inttypes.h>
  22. #include <stdio.h>
  23. #include <float.h>
  24. #include <limits.h>
  25. #include <stdarg.h>
  26. #include <signal.h>
  27. #if defined(__gnu_linux__)
  28. #include <syscall.h>
  29. #endif
  30. #ifdef GGML_USE_OPENMP
  31. #include <omp.h>
  32. #endif
  33. #ifdef GGML_USE_METAL
  34. #include <unistd.h>
  35. #endif
  36. #if defined(__ARM_FEATURE_SVE) || defined(__ARM_FEATURE_MATMUL_INT8)
  37. #undef GGML_USE_LLAMAFILE
  38. #endif
  39. #ifdef GGML_USE_LLAMAFILE
  40. #include <llamafile/sgemm.h>
  41. #endif
  42. #if defined(_MSC_VER)
  43. // disable "possible loss of data" to avoid hundreds of casts
  44. // we should just be careful :)
  45. #pragma warning(disable: 4244 4267)
  46. // disable POSIX deprecation warnings
  47. // these functions are never going away, anyway
  48. #pragma warning(disable: 4996)
  49. // unreachable code because of multiple instances of code after GGML_ABORT
  50. #pragma warning(disable: 4702)
  51. #endif
  52. // Note: once we move threading into a separate C++ file
  53. // will use std::hardware_destructive_interference_size instead of hardcoding it here
  54. // and we'll use C++ attribute syntax.
  55. #define GGML_CACHE_LINE 64
  56. #if defined(__clang__) || defined(__GNUC__)
  57. #define GGML_CACHE_ALIGN __attribute__((aligned(GGML_CACHE_LINE)))
  58. #endif
  59. #if defined(__has_feature)
  60. #if __has_feature(thread_sanitizer)
  61. #define GGML_TSAN_ENABLED 1
  62. #endif
  63. #else // __has_feature
  64. #if defined(__SANITIZE_THREAD__)
  65. #define GGML_TSAN_ENABLED 1
  66. #endif
  67. #endif // __has_feature
  68. #if defined(_WIN32)
  69. #define WIN32_LEAN_AND_MEAN
  70. #ifndef NOMINMAX
  71. #define NOMINMAX
  72. #endif
  73. #include <windows.h>
  74. #if !defined(__clang__)
  75. #define GGML_CACHE_ALIGN __declspec(align(GGML_CACHE_LINE))
  76. typedef volatile LONG atomic_int;
  77. typedef atomic_int atomic_bool;
  78. typedef atomic_int atomic_flag;
  79. #define ATOMIC_FLAG_INIT 0
  80. typedef enum {
  81. memory_order_relaxed,
  82. memory_order_consume,
  83. memory_order_acquire,
  84. memory_order_release,
  85. memory_order_acq_rel,
  86. memory_order_seq_cst
  87. } memory_order;
  88. static void atomic_store(atomic_int * ptr, LONG val) {
  89. InterlockedExchange(ptr, val);
  90. }
  91. static void atomic_store_explicit(atomic_int * ptr, LONG val, memory_order mo) {
  92. // TODO: add support for explicit memory order
  93. InterlockedExchange(ptr, val);
  94. }
  95. static LONG atomic_load(atomic_int * ptr) {
  96. return InterlockedCompareExchange(ptr, 0, 0);
  97. }
  98. static LONG atomic_load_explicit(atomic_int * ptr, memory_order mo) {
  99. // TODO: add support for explicit memory order
  100. return InterlockedCompareExchange(ptr, 0, 0);
  101. }
  102. static LONG atomic_fetch_add(atomic_int * ptr, LONG inc) {
  103. return InterlockedExchangeAdd(ptr, inc);
  104. }
  105. static LONG atomic_fetch_add_explicit(atomic_int * ptr, LONG inc, memory_order mo) {
  106. // TODO: add support for explicit memory order
  107. return InterlockedExchangeAdd(ptr, inc);
  108. }
  109. static atomic_bool atomic_flag_test_and_set(atomic_flag * ptr) {
  110. return InterlockedExchange(ptr, 1);
  111. }
  112. static void atomic_flag_clear(atomic_flag * ptr) {
  113. InterlockedExchange(ptr, 0);
  114. }
  115. static void atomic_thread_fence(memory_order mo) {
  116. MemoryBarrier();
  117. }
  118. #else // clang
  119. #include <stdatomic.h>
  120. #endif
  121. typedef HANDLE pthread_t;
  122. typedef DWORD thread_ret_t;
  123. static int pthread_create(pthread_t * out, void * unused, thread_ret_t(*func)(void *), void * arg) {
  124. (void) unused;
  125. HANDLE handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) func, arg, 0, NULL);
  126. if (handle == NULL)
  127. {
  128. return EAGAIN;
  129. }
  130. *out = handle;
  131. return 0;
  132. }
  133. static int pthread_join(pthread_t thread, void * unused) {
  134. (void) unused;
  135. int ret = (int) WaitForSingleObject(thread, INFINITE);
  136. CloseHandle(thread);
  137. return ret;
  138. }
  139. static int sched_yield (void) {
  140. Sleep (0);
  141. return 0;
  142. }
  143. #else
  144. #include <pthread.h>
  145. #include <stdatomic.h>
  146. #include <sched.h>
  147. #if defined(__FreeBSD__)
  148. #include <pthread_np.h>
  149. #endif
  150. typedef void * thread_ret_t;
  151. #include <sys/types.h>
  152. #include <sys/stat.h>
  153. #include <unistd.h>
  154. #endif
  155. typedef pthread_t ggml_thread_t;
  156. #ifdef GGML_USE_CPU_HBM
  157. #include <hbwmalloc.h>
  158. #endif
  159. #if defined(__APPLE__)
  160. #include <TargetConditionals.h>
  161. #endif
  162. #if (defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) && \
  163. (!defined(TARGET_OS_TV) && !defined(TARGET_OS_WATCH))
  164. #include <sys/wait.h>
  165. #if defined(__ANDROID__)
  166. #include <unwind.h>
  167. #include <dlfcn.h>
  168. #include <stdio.h>
  169. struct backtrace_state {
  170. void ** current;
  171. void ** end;
  172. };
  173. static _Unwind_Reason_Code unwind_callback(struct _Unwind_Context* context, void* arg) {
  174. struct backtrace_state * state = (struct backtrace_state *)arg;
  175. uintptr_t pc = _Unwind_GetIP(context);
  176. if (pc) {
  177. if (state->current == state->end) {
  178. return _URC_END_OF_STACK;
  179. } else {
  180. *state->current++ = (void*)pc;
  181. }
  182. }
  183. return _URC_NO_REASON;
  184. }
  185. static void ggml_print_backtrace_symbols(void) {
  186. const int max = 100;
  187. void* buffer[max];
  188. struct backtrace_state state = {buffer, buffer + max};
  189. _Unwind_Backtrace(unwind_callback, &state);
  190. int count = state.current - buffer;
  191. for (int idx = 0; idx < count; ++idx) {
  192. const void * addr = buffer[idx];
  193. const char * symbol = "";
  194. Dl_info info;
  195. if (dladdr(addr, &info) && info.dli_sname) {
  196. symbol = info.dli_sname;
  197. }
  198. fprintf(stderr, "%d: %p %s\n", idx, addr, symbol);
  199. }
  200. }
  201. #elif defined(__linux__) && defined(__GLIBC__)
  202. #include <execinfo.h>
  203. static void ggml_print_backtrace_symbols(void) {
  204. void * trace[100];
  205. int nptrs = backtrace(trace, sizeof(trace)/sizeof(trace[0]));
  206. backtrace_symbols_fd(trace, nptrs, STDERR_FILENO);
  207. }
  208. #else
  209. static void ggml_print_backtrace_symbols(void) {
  210. // platform not supported
  211. }
  212. #endif
  213. static void ggml_print_backtrace(void) {
  214. char attach[32];
  215. snprintf(attach, sizeof(attach), "attach %d", getpid());
  216. int pid = fork();
  217. if (pid == 0) {
  218. // try gdb
  219. execlp("gdb", "gdb", "--batch",
  220. "-ex", "set style enabled on",
  221. "-ex", attach,
  222. "-ex", "bt -frame-info source-and-location",
  223. "-ex", "detach",
  224. "-ex", "quit",
  225. (char *) NULL);
  226. // try lldb
  227. execlp("lldb", "lldb", "--batch",
  228. "-o", "bt",
  229. "-o", "quit",
  230. "-p", attach,
  231. (char *) NULL);
  232. exit(EXIT_FAILURE);
  233. } else {
  234. int wstatus;
  235. waitpid(pid, &wstatus, 0);
  236. if (WIFEXITED(wstatus)) {
  237. if (WEXITSTATUS(wstatus) == EXIT_FAILURE) {
  238. // gdb failed, fallback to backtrace_symbols
  239. ggml_print_backtrace_symbols();
  240. }
  241. }
  242. }
  243. }
  244. #else
  245. static void ggml_print_backtrace(void) {
  246. // platform not supported
  247. }
  248. #endif
  249. void ggml_abort(const char * file, int line, const char * fmt, ...) {
  250. fflush(stdout);
  251. fprintf(stderr, "%s:%d: ", file, line);
  252. va_list args;
  253. va_start(args, fmt);
  254. vfprintf(stderr, fmt, args);
  255. va_end(args);
  256. fprintf(stderr, "\n");
  257. ggml_print_backtrace();
  258. abort();
  259. }
  260. #define GGML_DEBUG 0
  261. #define GGML_GELU_FP16
  262. #define GGML_GELU_QUICK_FP16
  263. #define GGML_SOFT_MAX_UNROLL 4
  264. #define GGML_VEC_DOT_UNROLL 2
  265. #define GGML_VEC_MAD_UNROLL 32
  266. //
  267. // logging
  268. //
  269. #if (GGML_DEBUG >= 1)
  270. #define GGML_PRINT_DEBUG(...) printf(__VA_ARGS__)
  271. #else
  272. #define GGML_PRINT_DEBUG(...)
  273. #endif
  274. #if (GGML_DEBUG >= 5)
  275. #define GGML_PRINT_DEBUG_5(...) printf(__VA_ARGS__)
  276. #else
  277. #define GGML_PRINT_DEBUG_5(...)
  278. #endif
  279. #if (GGML_DEBUG >= 10)
  280. #define GGML_PRINT_DEBUG_10(...) printf(__VA_ARGS__)
  281. #else
  282. #define GGML_PRINT_DEBUG_10(...)
  283. #endif
  284. #define GGML_PRINT(...) printf(__VA_ARGS__)
  285. //
  286. // end of logging block
  287. //
  288. #ifdef GGML_USE_ACCELERATE
  289. // uncomment to use vDSP for soft max computation
  290. // note: not sure if it is actually faster
  291. //#define GGML_SOFT_MAX_ACCELERATE
  292. #endif
  293. #if defined(_MSC_VER) || defined(__MINGW32__)
  294. #define GGML_ALIGNED_MALLOC(size) _aligned_malloc(size, GGML_MEM_ALIGN)
  295. #define GGML_ALIGNED_FREE(ptr) _aligned_free(ptr)
  296. #else
  297. inline static void * ggml_aligned_malloc(size_t size) {
  298. if (size == 0) {
  299. GGML_PRINT("WARNING: Behavior may be unexpected when allocating 0 bytes for ggml_aligned_malloc!\n");
  300. return NULL;
  301. }
  302. void * aligned_memory = NULL;
  303. #ifdef GGML_USE_CPU_HBM
  304. int result = hbw_posix_memalign(&aligned_memory, 16, size);
  305. #elif GGML_USE_METAL
  306. int result = posix_memalign(&aligned_memory, sysconf(_SC_PAGESIZE), size);
  307. #else
  308. int result = posix_memalign(&aligned_memory, GGML_MEM_ALIGN, size);
  309. #endif
  310. if (result != 0) {
  311. // Handle allocation failure
  312. const char *error_desc = "unknown allocation error";
  313. switch (result) {
  314. case EINVAL:
  315. error_desc = "invalid alignment value";
  316. break;
  317. case ENOMEM:
  318. error_desc = "insufficient memory";
  319. break;
  320. }
  321. GGML_PRINT("%s: %s (attempted to allocate %6.2f MB)\n", __func__, error_desc, size/(1024.0*1024.0));
  322. GGML_ABORT("fatal error");
  323. return NULL;
  324. }
  325. return aligned_memory;
  326. }
  327. #define GGML_ALIGNED_MALLOC(size) ggml_aligned_malloc(size)
  328. #ifdef GGML_USE_CPU_HBM
  329. #define GGML_ALIGNED_FREE(ptr) if(NULL != ptr) hbw_free(ptr)
  330. #else
  331. #define GGML_ALIGNED_FREE(ptr) free(ptr)
  332. #endif
  333. #endif
  334. inline static void * ggml_malloc(size_t size) {
  335. if (size == 0) {
  336. GGML_PRINT("WARNING: Behavior may be unexpected when allocating 0 bytes for ggml_malloc!\n");
  337. return NULL;
  338. }
  339. void * result = malloc(size);
  340. if (result == NULL) {
  341. GGML_PRINT("%s: failed to allocate %6.2f MB\n", __func__, size/(1024.0*1024.0));
  342. GGML_ABORT("fatal error");
  343. }
  344. return result;
  345. }
  346. // calloc
  347. inline static void * ggml_calloc(size_t num, size_t size) {
  348. if (num == 0 || size == 0) {
  349. GGML_PRINT("WARNING: Behavior may be unexpected when allocating 0 bytes for ggml_calloc!\n");
  350. return NULL;
  351. }
  352. void * result = calloc(num, size);
  353. if (result == NULL) {
  354. GGML_PRINT("%s: failed to allocate %6.2f MB\n", __func__, size/(1024.0*1024.0));
  355. GGML_ABORT("fatal error");
  356. }
  357. return result;
  358. }
  359. #define GGML_MALLOC(size) ggml_malloc(size)
  360. #define GGML_CALLOC(num, size) ggml_calloc(num, size)
  361. #define GGML_FREE(ptr) free(ptr)
  362. #define UNUSED GGML_UNUSED
  363. #define SWAP(x, y, T) do { T SWAP = x; (x) = y; (y) = SWAP; } while (0)
  364. #if defined(GGML_USE_ACCELERATE)
  365. #include <Accelerate/Accelerate.h>
  366. #endif
  367. // floating point type used to accumulate sums
  368. typedef double ggml_float;
  369. #undef MIN
  370. #undef MAX
  371. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  372. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  373. //
  374. // global data
  375. //
  376. // precomputed gelu table for f16 (128 KB)
  377. static ggml_fp16_t ggml_table_gelu_f16[1 << 16];
  378. // precomputed quick gelu table for f16 (128 KB)
  379. static ggml_fp16_t ggml_table_gelu_quick_f16[1 << 16];
  380. // precomputed f32 table for f16 (256 KB) (ggml-impl.h)
  381. float ggml_table_f32_f16[1 << 16];
  382. #if defined(__ARM_ARCH)
  383. struct ggml_arm_arch_features_type {
  384. int has_neon;
  385. int has_i8mm;
  386. int has_sve;
  387. int sve_cnt;
  388. } ggml_arm_arch_features = {-1, -1, -1, 0};
  389. #endif
  390. GGML_CALL const char * ggml_status_to_string(enum ggml_status status) {
  391. switch (status) {
  392. case GGML_STATUS_ALLOC_FAILED: return "GGML status: error (failed to allocate memory)";
  393. case GGML_STATUS_FAILED: return "GGML status: error (operation failed)";
  394. case GGML_STATUS_SUCCESS: return "GGML status: success";
  395. case GGML_STATUS_ABORTED: return "GGML status: warning (operation aborted)";
  396. }
  397. return "GGML status: unknown";
  398. }
  399. float ggml_fp16_to_fp32(ggml_fp16_t x) {
  400. #define ggml_fp16_to_fp32 do_not_use__ggml_fp16_to_fp32__in_ggml
  401. return GGML_FP16_TO_FP32(x);
  402. }
  403. ggml_fp16_t ggml_fp32_to_fp16(float x) {
  404. #define ggml_fp32_to_fp16 do_not_use__ggml_fp32_to_fp16__in_ggml
  405. return GGML_FP32_TO_FP16(x);
  406. }
  407. float ggml_bf16_to_fp32(ggml_bf16_t x) {
  408. #define ggml_bf16_to_fp32 do_not_use__ggml_bf16_to_fp32__in_ggml
  409. return GGML_BF16_TO_FP32(x); // it just left shifts
  410. }
  411. ggml_bf16_t ggml_fp32_to_bf16(float x) {
  412. #define ggml_fp32_to_bf16 do_not_use__ggml_fp32_to_bf16__in_ggml
  413. return GGML_FP32_TO_BF16(x);
  414. }
  415. void ggml_fp16_to_fp32_row(const ggml_fp16_t * x, float * y, int64_t n) {
  416. for (int64_t i = 0; i < n; i++) {
  417. y[i] = GGML_FP16_TO_FP32(x[i]);
  418. }
  419. }
  420. void ggml_fp32_to_fp16_row(const float * x, ggml_fp16_t * y, int64_t n) {
  421. int64_t i = 0;
  422. #if defined(__F16C__)
  423. for (; i + 7 < n; i += 8) {
  424. __m256 x_vec = _mm256_loadu_ps(x + i);
  425. __m128i y_vec = _mm256_cvtps_ph(x_vec, _MM_FROUND_TO_NEAREST_INT);
  426. _mm_storeu_si128((__m128i *)(y + i), y_vec);
  427. }
  428. for(; i + 3 < n; i += 4) {
  429. __m128 x_vec = _mm_loadu_ps(x + i);
  430. __m128i y_vec = _mm_cvtps_ph(x_vec, _MM_FROUND_TO_NEAREST_INT);
  431. _mm_storel_epi64((__m128i *)(y + i), y_vec);
  432. }
  433. #endif
  434. for (; i < n; i++) {
  435. y[i] = GGML_FP32_TO_FP16(x[i]);
  436. }
  437. }
  438. void ggml_bf16_to_fp32_row(const ggml_bf16_t * x, float * y, int64_t n) {
  439. int64_t i = 0;
  440. #if defined(__AVX512F__)
  441. for (; i + 16 <= n; i += 16) {
  442. _mm512_storeu_ps(y + i,
  443. _mm512_castsi512_ps(
  444. _mm512_slli_epi32(
  445. _mm512_cvtepu16_epi32(
  446. _mm256_loadu_si256(
  447. (const __m256i *)(x + i))),
  448. 16)));
  449. }
  450. #elif defined(__AVX2__)
  451. for (; i + 8 <= n; i += 8) {
  452. _mm256_storeu_ps(y + i,
  453. _mm256_castsi256_ps(
  454. _mm256_slli_epi32(
  455. _mm256_cvtepu16_epi32(
  456. _mm_loadu_si128(
  457. (const __m128i *)(x + i))),
  458. 16)));
  459. }
  460. #endif
  461. for (; i < n; i++) {
  462. y[i] = GGML_BF16_TO_FP32(x[i]);
  463. }
  464. }
  465. void ggml_fp32_to_bf16_row_ref(const float * x, ggml_bf16_t * y, int64_t n) {
  466. for (int i = 0; i < n; i++) {
  467. y[i] = ggml_compute_fp32_to_bf16(x[i]);
  468. }
  469. }
  470. void ggml_fp32_to_bf16_row(const float * x, ggml_bf16_t * y, int64_t n) {
  471. int i = 0;
  472. #if defined(__AVX512BF16__)
  473. // subnormals are flushed to zero on this platform
  474. for (; i + 32 <= n; i += 32) {
  475. _mm512_storeu_si512(
  476. (__m512i *)(y + i),
  477. m512i(_mm512_cvtne2ps_pbh(_mm512_loadu_ps(x + i + 16),
  478. _mm512_loadu_ps(x + i))));
  479. }
  480. #endif
  481. for (; i < n; i++) {
  482. y[i] = GGML_FP32_TO_BF16(x[i]);
  483. }
  484. }
  485. bool ggml_guid_matches(ggml_guid_t guid_a, ggml_guid_t guid_b) {
  486. return memcmp(guid_a, guid_b, sizeof(ggml_guid)) == 0;
  487. }
  488. //
  489. // timing
  490. //
  491. #if defined(_MSC_VER) || defined(__MINGW32__)
  492. static int64_t timer_freq, timer_start;
  493. void ggml_time_init(void) {
  494. LARGE_INTEGER t;
  495. QueryPerformanceFrequency(&t);
  496. timer_freq = t.QuadPart;
  497. // The multiplication by 1000 or 1000000 below can cause an overflow if timer_freq
  498. // and the uptime is high enough.
  499. // We subtract the program start time to reduce the likelihood of that happening.
  500. QueryPerformanceCounter(&t);
  501. timer_start = t.QuadPart;
  502. }
  503. int64_t ggml_time_ms(void) {
  504. LARGE_INTEGER t;
  505. QueryPerformanceCounter(&t);
  506. return ((t.QuadPart-timer_start) * 1000) / timer_freq;
  507. }
  508. int64_t ggml_time_us(void) {
  509. LARGE_INTEGER t;
  510. QueryPerformanceCounter(&t);
  511. return ((t.QuadPart-timer_start) * 1000000) / timer_freq;
  512. }
  513. #else
  514. void ggml_time_init(void) {}
  515. int64_t ggml_time_ms(void) {
  516. struct timespec ts;
  517. clock_gettime(CLOCK_MONOTONIC, &ts);
  518. return (int64_t)ts.tv_sec*1000 + (int64_t)ts.tv_nsec/1000000;
  519. }
  520. int64_t ggml_time_us(void) {
  521. struct timespec ts;
  522. clock_gettime(CLOCK_MONOTONIC, &ts);
  523. return (int64_t)ts.tv_sec*1000000 + (int64_t)ts.tv_nsec/1000;
  524. }
  525. #endif
  526. int64_t ggml_cycles(void) {
  527. return clock();
  528. }
  529. int64_t ggml_cycles_per_ms(void) {
  530. return CLOCKS_PER_SEC/1000;
  531. }
  532. //
  533. // cross-platform UTF-8 file paths
  534. //
  535. #ifdef _WIN32
  536. static wchar_t * ggml_mbstowcs(const char * mbs) {
  537. int wlen = MultiByteToWideChar(CP_UTF8, 0, mbs, -1, NULL, 0);
  538. if (!wlen) {
  539. errno = EINVAL;
  540. return NULL;
  541. }
  542. wchar_t * wbuf = GGML_MALLOC(wlen * sizeof(wchar_t));
  543. wlen = MultiByteToWideChar(CP_UTF8, 0, mbs, -1, wbuf, wlen);
  544. if (!wlen) {
  545. GGML_FREE(wbuf);
  546. errno = EINVAL;
  547. return NULL;
  548. }
  549. return wbuf;
  550. }
  551. #endif
  552. FILE * ggml_fopen(const char * fname, const char * mode) {
  553. #ifdef _WIN32
  554. FILE * file = NULL;
  555. // convert fname (UTF-8)
  556. wchar_t * wfname = ggml_mbstowcs(fname);
  557. if (wfname) {
  558. // convert mode (ANSI)
  559. wchar_t * wmode = GGML_MALLOC((strlen(mode) + 1) * sizeof(wchar_t));
  560. wchar_t * wmode_p = wmode;
  561. do {
  562. *wmode_p++ = (wchar_t)*mode;
  563. } while (*mode++);
  564. // open file
  565. file = _wfopen(wfname, wmode);
  566. GGML_FREE(wfname);
  567. GGML_FREE(wmode);
  568. }
  569. return file;
  570. #else
  571. return fopen(fname, mode);
  572. #endif
  573. }
  574. //
  575. // cache line
  576. //
  577. #if defined(__cpp_lib_hardware_interference_size)
  578. #define CACHE_LINE_SIZE hardware_destructive_interference_size
  579. #else
  580. #if defined(__POWER9_VECTOR__)
  581. #define CACHE_LINE_SIZE 128
  582. #else
  583. #define CACHE_LINE_SIZE 64
  584. #endif
  585. #endif
  586. static const size_t CACHE_LINE_SIZE_F32 = CACHE_LINE_SIZE/sizeof(float);
  587. static void ggml_vec_dot_f32(int n, float * restrict s, size_t bs, const float * restrict x, size_t bx, const float * restrict y, size_t by, int nrc);
  588. static void ggml_vec_dot_f16(int n, float * restrict s, size_t bs, ggml_fp16_t * restrict x, size_t bx, ggml_fp16_t * restrict y, size_t by, int nrc);
  589. static void ggml_vec_dot_bf16(int n, float * restrict s, size_t bs, ggml_bf16_t * restrict x, size_t bx, ggml_bf16_t * restrict y, size_t by, int nrc);
  590. static const ggml_type_traits_t type_traits[GGML_TYPE_COUNT] = {
  591. [GGML_TYPE_I8] = {
  592. .type_name = "i8",
  593. .blck_size = 1,
  594. .type_size = sizeof(int8_t),
  595. .is_quantized = false,
  596. },
  597. [GGML_TYPE_I16] = {
  598. .type_name = "i16",
  599. .blck_size = 1,
  600. .type_size = sizeof(int16_t),
  601. .is_quantized = false,
  602. },
  603. [GGML_TYPE_I32] = {
  604. .type_name = "i32",
  605. .blck_size = 1,
  606. .type_size = sizeof(int32_t),
  607. .is_quantized = false,
  608. },
  609. [GGML_TYPE_I64] = {
  610. .type_name = "i64",
  611. .blck_size = 1,
  612. .type_size = sizeof(int64_t),
  613. .is_quantized = false,
  614. },
  615. [GGML_TYPE_F64] = {
  616. .type_name = "f64",
  617. .blck_size = 1,
  618. .type_size = sizeof(double),
  619. .is_quantized = false,
  620. .nrows = 1,
  621. },
  622. [GGML_TYPE_F32] = {
  623. .type_name = "f32",
  624. .blck_size = 1,
  625. .type_size = sizeof(float),
  626. .is_quantized = false,
  627. .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_f32,
  628. .vec_dot_type = GGML_TYPE_F32,
  629. .nrows = 1,
  630. },
  631. [GGML_TYPE_F16] = {
  632. .type_name = "f16",
  633. .blck_size = 1,
  634. .type_size = sizeof(ggml_fp16_t),
  635. .is_quantized = false,
  636. .to_float = (ggml_to_float_t) ggml_fp16_to_fp32_row,
  637. .from_float = (ggml_from_float_t) ggml_fp32_to_fp16_row,
  638. .from_float_ref = (ggml_from_float_t) ggml_fp32_to_fp16_row,
  639. .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_f16,
  640. .vec_dot_type = GGML_TYPE_F16,
  641. .nrows = 1,
  642. },
  643. [GGML_TYPE_Q4_0] = {
  644. .type_name = "q4_0",
  645. .blck_size = QK4_0,
  646. .type_size = sizeof(block_q4_0),
  647. .is_quantized = true,
  648. .to_float = (ggml_to_float_t) dequantize_row_q4_0,
  649. .from_float = quantize_row_q4_0,
  650. .from_float_ref = (ggml_from_float_t) quantize_row_q4_0_ref,
  651. .vec_dot = ggml_vec_dot_q4_0_q8_0,
  652. .vec_dot_type = GGML_TYPE_Q8_0,
  653. #if defined (__ARM_FEATURE_MATMUL_INT8)
  654. .nrows = 2,
  655. #else
  656. .nrows = 1,
  657. #endif
  658. },
  659. [GGML_TYPE_Q4_1] = {
  660. .type_name = "q4_1",
  661. .blck_size = QK4_1,
  662. .type_size = sizeof(block_q4_1),
  663. .is_quantized = true,
  664. .to_float = (ggml_to_float_t) dequantize_row_q4_1,
  665. .from_float = quantize_row_q4_1,
  666. .from_float_ref = (ggml_from_float_t) quantize_row_q4_1_ref,
  667. .vec_dot = ggml_vec_dot_q4_1_q8_1,
  668. .vec_dot_type = GGML_TYPE_Q8_1,
  669. #if defined (__ARM_FEATURE_MATMUL_INT8)
  670. .nrows = 2,
  671. #else
  672. .nrows = 1,
  673. #endif
  674. },
  675. [4] = { // GGML_TYPE_Q4_2
  676. .type_name = "DEPRECATED",
  677. .blck_size = 0,
  678. .type_size = 0,
  679. .is_quantized = false,
  680. .to_float = NULL,
  681. .from_float = NULL,
  682. .from_float_ref = NULL,
  683. .vec_dot = NULL,
  684. .vec_dot_type = GGML_TYPE_COUNT,
  685. .nrows = 1,
  686. },
  687. [5] = { // GGML_TYPE_Q4_3
  688. .type_name = "DEPRECATED",
  689. .blck_size = 0,
  690. .type_size = 0,
  691. .is_quantized = false,
  692. .to_float = NULL,
  693. .from_float = NULL,
  694. .from_float_ref = NULL,
  695. .vec_dot = NULL,
  696. .vec_dot_type = GGML_TYPE_COUNT,
  697. .nrows = 1,
  698. },
  699. [GGML_TYPE_Q5_0] = {
  700. .type_name = "q5_0",
  701. .blck_size = QK5_0,
  702. .type_size = sizeof(block_q5_0),
  703. .is_quantized = true,
  704. .to_float = (ggml_to_float_t) dequantize_row_q5_0,
  705. .from_float = quantize_row_q5_0,
  706. .from_float_ref = (ggml_from_float_t) quantize_row_q5_0_ref,
  707. .vec_dot = ggml_vec_dot_q5_0_q8_0,
  708. .vec_dot_type = GGML_TYPE_Q8_0,
  709. .nrows = 1,
  710. },
  711. [GGML_TYPE_Q5_1] = {
  712. .type_name = "q5_1",
  713. .blck_size = QK5_1,
  714. .type_size = sizeof(block_q5_1),
  715. .is_quantized = true,
  716. .to_float = (ggml_to_float_t) dequantize_row_q5_1,
  717. .from_float = quantize_row_q5_1,
  718. .from_float_ref = (ggml_from_float_t) quantize_row_q5_1_ref,
  719. .vec_dot = ggml_vec_dot_q5_1_q8_1,
  720. .vec_dot_type = GGML_TYPE_Q8_1,
  721. .nrows = 1,
  722. },
  723. [GGML_TYPE_Q8_0] = {
  724. .type_name = "q8_0",
  725. .blck_size = QK8_0,
  726. .type_size = sizeof(block_q8_0),
  727. .is_quantized = true,
  728. .to_float = (ggml_to_float_t) dequantize_row_q8_0,
  729. .from_float = quantize_row_q8_0,
  730. .from_float_ref = (ggml_from_float_t) quantize_row_q8_0_ref,
  731. .from_float_to_mat = quantize_mat_q8_0,
  732. .vec_dot = ggml_vec_dot_q8_0_q8_0,
  733. .vec_dot_type = GGML_TYPE_Q8_0,
  734. #if defined (__ARM_FEATURE_MATMUL_INT8)
  735. .nrows = 2,
  736. #else
  737. .nrows = 1,
  738. #endif
  739. },
  740. [GGML_TYPE_Q8_1] = {
  741. .type_name = "q8_1",
  742. .blck_size = QK8_1,
  743. .type_size = sizeof(block_q8_1),
  744. .is_quantized = true,
  745. .from_float = quantize_row_q8_1,
  746. .from_float_ref = (ggml_from_float_t) quantize_row_q8_1_ref,
  747. .vec_dot_type = GGML_TYPE_Q8_1,
  748. .nrows = 1,
  749. },
  750. [GGML_TYPE_Q2_K] = {
  751. .type_name = "q2_K",
  752. .blck_size = QK_K,
  753. .type_size = sizeof(block_q2_K),
  754. .is_quantized = true,
  755. .to_float = (ggml_to_float_t) dequantize_row_q2_K,
  756. .from_float = quantize_row_q2_K,
  757. .from_float_ref = (ggml_from_float_t) quantize_row_q2_K_ref,
  758. .vec_dot = ggml_vec_dot_q2_K_q8_K,
  759. .vec_dot_type = GGML_TYPE_Q8_K,
  760. .nrows = 1,
  761. },
  762. [GGML_TYPE_Q3_K] = {
  763. .type_name = "q3_K",
  764. .blck_size = QK_K,
  765. .type_size = sizeof(block_q3_K),
  766. .is_quantized = true,
  767. .to_float = (ggml_to_float_t) dequantize_row_q3_K,
  768. .from_float = quantize_row_q3_K,
  769. .from_float_ref = (ggml_from_float_t) quantize_row_q3_K_ref,
  770. .vec_dot = ggml_vec_dot_q3_K_q8_K,
  771. .vec_dot_type = GGML_TYPE_Q8_K,
  772. .nrows = 1,
  773. },
  774. [GGML_TYPE_Q4_K] = {
  775. .type_name = "q4_K",
  776. .blck_size = QK_K,
  777. .type_size = sizeof(block_q4_K),
  778. .is_quantized = true,
  779. .to_float = (ggml_to_float_t) dequantize_row_q4_K,
  780. .from_float = quantize_row_q4_K,
  781. .from_float_ref = (ggml_from_float_t) quantize_row_q4_K_ref,
  782. .vec_dot = ggml_vec_dot_q4_K_q8_K,
  783. .vec_dot_type = GGML_TYPE_Q8_K,
  784. .nrows = 1,
  785. },
  786. [GGML_TYPE_Q5_K] = {
  787. .type_name = "q5_K",
  788. .blck_size = QK_K,
  789. .type_size = sizeof(block_q5_K),
  790. .is_quantized = true,
  791. .to_float = (ggml_to_float_t) dequantize_row_q5_K,
  792. .from_float = quantize_row_q5_K,
  793. .from_float_ref = (ggml_from_float_t) quantize_row_q5_K_ref,
  794. .vec_dot = ggml_vec_dot_q5_K_q8_K,
  795. .vec_dot_type = GGML_TYPE_Q8_K,
  796. .nrows = 1,
  797. },
  798. [GGML_TYPE_Q6_K] = {
  799. .type_name = "q6_K",
  800. .blck_size = QK_K,
  801. .type_size = sizeof(block_q6_K),
  802. .is_quantized = true,
  803. .to_float = (ggml_to_float_t) dequantize_row_q6_K,
  804. .from_float = quantize_row_q6_K,
  805. .from_float_ref = (ggml_from_float_t) quantize_row_q6_K_ref,
  806. .vec_dot = ggml_vec_dot_q6_K_q8_K,
  807. .vec_dot_type = GGML_TYPE_Q8_K,
  808. .nrows = 1,
  809. },
  810. [GGML_TYPE_IQ2_XXS] = {
  811. .type_name = "iq2_xxs",
  812. .blck_size = QK_K,
  813. .type_size = sizeof(block_iq2_xxs),
  814. .is_quantized = true,
  815. .to_float = (ggml_to_float_t) dequantize_row_iq2_xxs,
  816. .from_float = NULL,
  817. .from_float_ref = NULL,
  818. .vec_dot = ggml_vec_dot_iq2_xxs_q8_K,
  819. .vec_dot_type = GGML_TYPE_Q8_K,
  820. .nrows = 1,
  821. },
  822. [GGML_TYPE_IQ2_XS] = {
  823. .type_name = "iq2_xs",
  824. .blck_size = QK_K,
  825. .type_size = sizeof(block_iq2_xs),
  826. .is_quantized = true,
  827. .to_float = (ggml_to_float_t) dequantize_row_iq2_xs,
  828. .from_float = NULL,
  829. .from_float_ref = NULL,
  830. .vec_dot = ggml_vec_dot_iq2_xs_q8_K,
  831. .vec_dot_type = GGML_TYPE_Q8_K,
  832. .nrows = 1,
  833. },
  834. [GGML_TYPE_IQ3_XXS] = {
  835. .type_name = "iq3_xxs",
  836. .blck_size = QK_K,
  837. .type_size = sizeof(block_iq3_xxs),
  838. .is_quantized = true,
  839. .to_float = (ggml_to_float_t) dequantize_row_iq3_xxs,
  840. .from_float = quantize_row_iq3_xxs,
  841. .from_float_ref = (ggml_from_float_t)quantize_row_iq3_xxs_ref,
  842. .vec_dot = ggml_vec_dot_iq3_xxs_q8_K,
  843. .vec_dot_type = GGML_TYPE_Q8_K,
  844. .nrows = 1,
  845. },
  846. [GGML_TYPE_IQ3_S] = {
  847. .type_name = "iq3_s",
  848. .blck_size = QK_K,
  849. .type_size = sizeof(block_iq3_s),
  850. .is_quantized = true,
  851. .to_float = (ggml_to_float_t) dequantize_row_iq3_s,
  852. .from_float = quantize_row_iq3_s,
  853. .from_float_ref = (ggml_from_float_t)quantize_row_iq3_s_ref,
  854. .vec_dot = ggml_vec_dot_iq3_s_q8_K,
  855. .vec_dot_type = GGML_TYPE_Q8_K,
  856. .nrows = 1,
  857. },
  858. [GGML_TYPE_IQ2_S] = {
  859. .type_name = "iq2_s",
  860. .blck_size = QK_K,
  861. .type_size = sizeof(block_iq2_s),
  862. .is_quantized = true,
  863. .to_float = (ggml_to_float_t) dequantize_row_iq2_s,
  864. .from_float = quantize_row_iq2_s,
  865. .from_float_ref = (ggml_from_float_t)quantize_row_iq2_s_ref,
  866. .vec_dot = ggml_vec_dot_iq2_s_q8_K,
  867. .vec_dot_type = GGML_TYPE_Q8_K,
  868. .nrows = 1,
  869. },
  870. [GGML_TYPE_IQ1_S] = {
  871. .type_name = "iq1_s",
  872. .blck_size = QK_K,
  873. .type_size = sizeof(block_iq1_s),
  874. .is_quantized = true,
  875. .to_float = (ggml_to_float_t) dequantize_row_iq1_s,
  876. .from_float = NULL,
  877. .from_float_ref = NULL,
  878. .vec_dot = ggml_vec_dot_iq1_s_q8_K,
  879. .vec_dot_type = GGML_TYPE_Q8_K,
  880. .nrows = 1,
  881. },
  882. [GGML_TYPE_IQ1_M] = {
  883. .type_name = "iq1_m",
  884. .blck_size = QK_K,
  885. .type_size = sizeof(block_iq1_m),
  886. .is_quantized = true,
  887. .to_float = (ggml_to_float_t) dequantize_row_iq1_m,
  888. .from_float = NULL,
  889. .from_float_ref = NULL,
  890. .vec_dot = ggml_vec_dot_iq1_m_q8_K,
  891. .vec_dot_type = GGML_TYPE_Q8_K,
  892. .nrows = 1,
  893. },
  894. [GGML_TYPE_IQ4_NL] = {
  895. .type_name = "iq4_nl",
  896. .blck_size = QK4_NL,
  897. .type_size = sizeof(block_iq4_nl),
  898. .is_quantized = true,
  899. .to_float = (ggml_to_float_t) dequantize_row_iq4_nl,
  900. .from_float = quantize_row_iq4_nl,
  901. .from_float_ref = (ggml_from_float_t)quantize_row_iq4_nl_ref,
  902. .vec_dot = ggml_vec_dot_iq4_nl_q8_0,
  903. .vec_dot_type = GGML_TYPE_Q8_0,
  904. .nrows = 1,
  905. },
  906. [GGML_TYPE_IQ4_XS] = {
  907. .type_name = "iq4_xs",
  908. .blck_size = QK_K,
  909. .type_size = sizeof(block_iq4_xs),
  910. .is_quantized = true,
  911. .to_float = (ggml_to_float_t) dequantize_row_iq4_xs,
  912. .from_float = quantize_row_iq4_xs,
  913. .from_float_ref = (ggml_from_float_t)quantize_row_iq4_xs_ref,
  914. .vec_dot = ggml_vec_dot_iq4_xs_q8_K,
  915. .vec_dot_type = GGML_TYPE_Q8_K,
  916. .nrows = 1,
  917. },
  918. [GGML_TYPE_Q8_K] = {
  919. .type_name = "q8_K",
  920. .blck_size = QK_K,
  921. .type_size = sizeof(block_q8_K),
  922. .is_quantized = true,
  923. .from_float = quantize_row_q8_K,
  924. },
  925. [GGML_TYPE_BF16] = {
  926. .type_name = "bf16",
  927. .blck_size = 1,
  928. .type_size = sizeof(ggml_bf16_t),
  929. .is_quantized = false,
  930. .to_float = (ggml_to_float_t) ggml_bf16_to_fp32_row,
  931. .from_float = (ggml_from_float_t) ggml_fp32_to_bf16_row,
  932. .from_float_ref = (ggml_from_float_t) ggml_fp32_to_bf16_row_ref,
  933. .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_bf16,
  934. .vec_dot_type = GGML_TYPE_BF16,
  935. .nrows = 1,
  936. },
  937. [GGML_TYPE_Q4_0_4_4] = {
  938. .type_name = "q4_0_4x4",
  939. .blck_size = QK4_0,
  940. .blck_size_interleave = 4,
  941. .type_size = sizeof(block_q4_0),
  942. .is_quantized = true,
  943. .to_float = NULL,
  944. .from_float = NULL,
  945. .from_float_ref = NULL,
  946. .vec_dot = NULL,
  947. .vec_dot_type = GGML_TYPE_Q8_0,
  948. .nrows = 1,
  949. .ncols = 4,
  950. .gemv = ggml_gemv_q4_0_4x4_q8_0,
  951. .gemm = ggml_gemm_q4_0_4x4_q8_0,
  952. },
  953. [GGML_TYPE_Q4_0_4_8] = {
  954. .type_name = "q4_0_4x8",
  955. .blck_size = QK4_0,
  956. .blck_size_interleave = 8,
  957. .type_size = sizeof(block_q4_0),
  958. .is_quantized = true,
  959. .to_float = NULL,
  960. .from_float = NULL,
  961. .from_float_ref = NULL,
  962. .vec_dot = NULL,
  963. .vec_dot_type = GGML_TYPE_Q8_0,
  964. .nrows = 1,
  965. .ncols = 4,
  966. .gemv = ggml_gemv_q4_0_4x8_q8_0,
  967. .gemm = ggml_gemm_q4_0_4x8_q8_0,
  968. },
  969. [GGML_TYPE_Q4_0_8_8] = {
  970. .type_name = "q4_0_8x8",
  971. .blck_size = QK4_0,
  972. .blck_size_interleave = 8,
  973. .type_size = sizeof(block_q4_0),
  974. .is_quantized = true,
  975. .to_float = NULL,
  976. .from_float = NULL,
  977. .from_float_ref = NULL,
  978. .vec_dot = NULL,
  979. .vec_dot_type = GGML_TYPE_Q8_0,
  980. .nrows = 1,
  981. .ncols = 8,
  982. .gemv = ggml_gemv_q4_0_8x8_q8_0,
  983. .gemm = ggml_gemm_q4_0_8x8_q8_0,
  984. },
  985. [GGML_TYPE_TQ1_0] = {
  986. .type_name = "tq1_0",
  987. .blck_size = QK_K,
  988. .type_size = sizeof(block_tq1_0),
  989. .is_quantized = true,
  990. .to_float = (ggml_to_float_t) dequantize_row_tq1_0,
  991. .from_float = quantize_row_tq1_0,
  992. .from_float_ref = (ggml_from_float_t) quantize_row_tq1_0_ref,
  993. .vec_dot = ggml_vec_dot_tq1_0_q8_K,
  994. .vec_dot_type = GGML_TYPE_Q8_K,
  995. .nrows = 1,
  996. },
  997. [GGML_TYPE_TQ2_0] = {
  998. .type_name = "tq2_0",
  999. .blck_size = QK_K,
  1000. .type_size = sizeof(block_tq2_0),
  1001. .is_quantized = true,
  1002. .to_float = (ggml_to_float_t) dequantize_row_tq2_0,
  1003. .from_float = quantize_row_tq2_0,
  1004. .from_float_ref = (ggml_from_float_t) quantize_row_tq2_0_ref,
  1005. .vec_dot = ggml_vec_dot_tq2_0_q8_K,
  1006. .vec_dot_type = GGML_TYPE_Q8_K,
  1007. .nrows = 1,
  1008. },
  1009. };
  1010. // For internal test use
  1011. ggml_type_traits_t ggml_internal_get_type_traits(enum ggml_type type) {
  1012. GGML_ASSERT(type < GGML_TYPE_COUNT);
  1013. return type_traits[type];
  1014. }
  1015. //
  1016. // simd mappings
  1017. //
  1018. // we define a common set of C macros which map to specific intrinsics based on the current architecture
  1019. // we then implement the fundamental computation operations below using only these macros
  1020. // adding support for new architectures requires to define the corresponding SIMD macros
  1021. //
  1022. // GGML_F32_STEP / GGML_F16_STEP
  1023. // number of elements to process in a single step
  1024. //
  1025. // GGML_F32_EPR / GGML_F16_EPR
  1026. // number of elements to fit in a single register
  1027. //
  1028. #if defined(__ARM_NEON) && defined(__ARM_FEATURE_FMA)
  1029. #define GGML_SIMD
  1030. // F32 NEON
  1031. #define GGML_F32_STEP 16
  1032. #define GGML_F32_EPR 4
  1033. #define GGML_F32x4 float32x4_t
  1034. #define GGML_F32x4_ZERO vdupq_n_f32(0.0f)
  1035. #define GGML_F32x4_SET1(x) vdupq_n_f32(x)
  1036. #define GGML_F32x4_LOAD vld1q_f32
  1037. #define GGML_F32x4_STORE vst1q_f32
  1038. #define GGML_F32x4_FMA(a, b, c) vfmaq_f32(a, b, c)
  1039. #define GGML_F32x4_ADD vaddq_f32
  1040. #define GGML_F32x4_MUL vmulq_f32
  1041. #define GGML_F32x4_REDUCE_ONE(x) vaddvq_f32(x)
  1042. #define GGML_F32x4_REDUCE(res, x) \
  1043. { \
  1044. int offset = GGML_F32_ARR >> 1; \
  1045. for (int i = 0; i < offset; ++i) { \
  1046. (x)[i] = vaddq_f32((x)[i], (x)[offset+i]); \
  1047. } \
  1048. offset >>= 1; \
  1049. for (int i = 0; i < offset; ++i) { \
  1050. (x)[i] = vaddq_f32((x)[i], (x)[offset+i]); \
  1051. } \
  1052. offset >>= 1; \
  1053. for (int i = 0; i < offset; ++i) { \
  1054. (x)[i] = vaddq_f32((x)[i], (x)[offset+i]); \
  1055. } \
  1056. (res) = GGML_F32x4_REDUCE_ONE((x)[0]); \
  1057. }
  1058. #define GGML_F32_VEC GGML_F32x4
  1059. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1060. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1061. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1062. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1063. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1064. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1065. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1066. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1067. // F16 NEON
  1068. #if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
  1069. #define GGML_F16_STEP 32
  1070. #define GGML_F16_EPR 8
  1071. #define GGML_F16x8 float16x8_t
  1072. #define GGML_F16x8_ZERO vdupq_n_f16(0.0f)
  1073. #define GGML_F16x8_SET1(x) vdupq_n_f16(x)
  1074. #define GGML_F16x8_LOAD(x) vld1q_f16((const ggml_fp16_internal_t *)(x))
  1075. #define GGML_F16x8_STORE vst1q_f16
  1076. #define GGML_F16x8_FMA(a, b, c) vfmaq_f16(a, b, c)
  1077. #define GGML_F16x8_ADD vaddq_f16
  1078. #define GGML_F16x8_MUL vmulq_f16
  1079. #define GGML_F16x8_REDUCE(res, x) \
  1080. do { \
  1081. int offset = GGML_F16_ARR >> 1; \
  1082. for (int i = 0; i < offset; ++i) { \
  1083. (x)[i] = vaddq_f16((x)[i], (x)[offset+i]); \
  1084. } \
  1085. offset >>= 1; \
  1086. for (int i = 0; i < offset; ++i) { \
  1087. (x)[i] = vaddq_f16((x)[i], (x)[offset+i]); \
  1088. } \
  1089. offset >>= 1; \
  1090. for (int i = 0; i < offset; ++i) { \
  1091. (x)[i] = vaddq_f16((x)[i], (x)[offset+i]); \
  1092. } \
  1093. const float32x4_t t0 = vcvt_f32_f16(vget_low_f16 ((x)[0])); \
  1094. const float32x4_t t1 = vcvt_f32_f16(vget_high_f16((x)[0])); \
  1095. (res) = (ggml_float) vaddvq_f32(vaddq_f32(t0, t1)); \
  1096. } while (0)
  1097. #define GGML_F16_VEC GGML_F16x8
  1098. #define GGML_F16_VEC_ZERO GGML_F16x8_ZERO
  1099. #define GGML_F16_VEC_SET1 GGML_F16x8_SET1
  1100. #define GGML_F16_VEC_LOAD(p, i) GGML_F16x8_LOAD(p)
  1101. #define GGML_F16_VEC_STORE(p, r, i) GGML_F16x8_STORE((ggml_fp16_internal_t *)(p), (r)[i])
  1102. #define GGML_F16_VEC_FMA GGML_F16x8_FMA
  1103. #define GGML_F16_VEC_ADD GGML_F16x8_ADD
  1104. #define GGML_F16_VEC_MUL GGML_F16x8_MUL
  1105. #define GGML_F16_VEC_REDUCE GGML_F16x8_REDUCE
  1106. #else
  1107. // if FP16 vector arithmetic is not supported, we use FP32 instead
  1108. // and take advantage of the vcvt_ functions to convert to/from FP16
  1109. #define GGML_F16_STEP 16
  1110. #define GGML_F16_EPR 4
  1111. #define GGML_F32Cx4 float32x4_t
  1112. #define GGML_F32Cx4_ZERO vdupq_n_f32(0.0f)
  1113. #define GGML_F32Cx4_SET1(x) vdupq_n_f32(x)
  1114. #define GGML_F32Cx4_LOAD(x) vcvt_f32_f16(vld1_f16((const ggml_fp16_internal_t *)(x)))
  1115. #define GGML_F32Cx4_STORE(x, y) vst1_f16(x, vcvt_f16_f32(y))
  1116. #define GGML_F32Cx4_FMA(a, b, c) vfmaq_f32(a, b, c)
  1117. #define GGML_F32Cx4_ADD vaddq_f32
  1118. #define GGML_F32Cx4_MUL vmulq_f32
  1119. #define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
  1120. #define GGML_F16_VEC GGML_F32Cx4
  1121. #define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
  1122. #define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
  1123. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
  1124. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE((ggml_fp16_internal_t *)(p), r[i])
  1125. #define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
  1126. #define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
  1127. #define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
  1128. #define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
  1129. #endif
  1130. #elif defined(__AVX512F__)
  1131. #define GGML_SIMD
  1132. // F32 AVX512
  1133. #define GGML_F32_STEP 64
  1134. #define GGML_F32_EPR 16
  1135. #define GGML_F32x16 __m512
  1136. #define GGML_F32x16_ZERO _mm512_setzero_ps()
  1137. #define GGML_F32x16_SET1(x) _mm512_set1_ps(x)
  1138. #define GGML_F32x16_LOAD _mm512_loadu_ps
  1139. #define GGML_F32x16_STORE _mm512_storeu_ps
  1140. // _mm512_fmadd_ps is defined in AVX512F so no guard is required
  1141. #define GGML_F32x16_FMA(a, b, c) _mm512_fmadd_ps(b, c, a)
  1142. #define GGML_F32x16_ADD _mm512_add_ps
  1143. #define GGML_F32x16_MUL _mm512_mul_ps
  1144. #define GGML_F32x16_REDUCE(res, x) \
  1145. do { \
  1146. int offset = GGML_F32_ARR >> 1; \
  1147. for (int i = 0; i < offset; ++i) { \
  1148. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1149. } \
  1150. offset >>= 1; \
  1151. for (int i = 0; i < offset; ++i) { \
  1152. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1153. } \
  1154. offset >>= 1; \
  1155. for (int i = 0; i < offset; ++i) { \
  1156. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1157. } \
  1158. res = _mm512_reduce_add_ps(x[0]); \
  1159. } while (0)
  1160. // TODO: is this optimal ?
  1161. #define GGML_F32_VEC GGML_F32x16
  1162. #define GGML_F32_VEC_ZERO GGML_F32x16_ZERO
  1163. #define GGML_F32_VEC_SET1 GGML_F32x16_SET1
  1164. #define GGML_F32_VEC_LOAD GGML_F32x16_LOAD
  1165. #define GGML_F32_VEC_STORE GGML_F32x16_STORE
  1166. #define GGML_F32_VEC_FMA GGML_F32x16_FMA
  1167. #define GGML_F32_VEC_ADD GGML_F32x16_ADD
  1168. #define GGML_F32_VEC_MUL GGML_F32x16_MUL
  1169. #define GGML_F32_VEC_REDUCE GGML_F32x16_REDUCE
  1170. // F16 AVX512
  1171. // F16 AVX
  1172. #define GGML_F16_STEP 64
  1173. #define GGML_F16_EPR 16
  1174. // AVX512 has FP16 extension (AVX512_FP16) but I don't have it on my machine so I use FP32 instead
  1175. #define GGML_F32Cx16 __m512
  1176. #define GGML_F32Cx16_ZERO _mm512_setzero_ps()
  1177. #define GGML_F32Cx16_SET1(x) _mm512_set1_ps(x)
  1178. // unlike _mm256_cvt intrinsics that require F16C, _mm512_cvt is defined in AVX512F
  1179. // so F16C guard isn't required
  1180. #define GGML_F32Cx16_LOAD(x) _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(x)))
  1181. #define GGML_F32Cx16_STORE(x, y) _mm256_storeu_si256((__m256i *)(x), _mm512_cvtps_ph(y, 0))
  1182. #define GGML_F32Cx16_FMA(a, b, c) _mm512_fmadd_ps(b, c, a)
  1183. #define GGML_F32Cx16_ADD _mm512_add_ps
  1184. #define GGML_F32Cx16_MUL _mm512_mul_ps
  1185. #define GGML_F32Cx16_REDUCE(res, x) \
  1186. do { \
  1187. int offset = GGML_F32_ARR >> 1; \
  1188. for (int i = 0; i < offset; ++i) { \
  1189. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1190. } \
  1191. offset >>= 1; \
  1192. for (int i = 0; i < offset; ++i) { \
  1193. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1194. } \
  1195. offset >>= 1; \
  1196. for (int i = 0; i < offset; ++i) { \
  1197. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1198. } \
  1199. res = _mm512_reduce_add_ps(x[0]); \
  1200. } while (0)
  1201. #define GGML_F16_VEC GGML_F32Cx16
  1202. #define GGML_F16_VEC_ZERO GGML_F32Cx16_ZERO
  1203. #define GGML_F16_VEC_SET1 GGML_F32Cx16_SET1
  1204. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx16_LOAD(p)
  1205. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx16_STORE(p, r[i])
  1206. #define GGML_F16_VEC_FMA GGML_F32Cx16_FMA
  1207. #define GGML_F16_VEC_ADD GGML_F32Cx16_ADD
  1208. #define GGML_F16_VEC_MUL GGML_F32Cx16_MUL
  1209. #define GGML_F16_VEC_REDUCE GGML_F32Cx16_REDUCE
  1210. #elif defined(__AVX__)
  1211. #define GGML_SIMD
  1212. // F32 AVX
  1213. #define GGML_F32_STEP 32
  1214. #define GGML_F32_EPR 8
  1215. #define GGML_F32x8 __m256
  1216. #define GGML_F32x8_ZERO _mm256_setzero_ps()
  1217. #define GGML_F32x8_SET1(x) _mm256_set1_ps(x)
  1218. #define GGML_F32x8_LOAD _mm256_loadu_ps
  1219. #define GGML_F32x8_STORE _mm256_storeu_ps
  1220. #if defined(__FMA__)
  1221. #define GGML_F32x8_FMA(a, b, c) _mm256_fmadd_ps(b, c, a)
  1222. #else
  1223. #define GGML_F32x8_FMA(a, b, c) _mm256_add_ps(_mm256_mul_ps(b, c), a)
  1224. #endif
  1225. #define GGML_F32x8_ADD _mm256_add_ps
  1226. #define GGML_F32x8_MUL _mm256_mul_ps
  1227. #define GGML_F32x8_REDUCE(res, x) \
  1228. do { \
  1229. int offset = GGML_F32_ARR >> 1; \
  1230. for (int i = 0; i < offset; ++i) { \
  1231. x[i] = _mm256_add_ps(x[i], x[offset+i]); \
  1232. } \
  1233. offset >>= 1; \
  1234. for (int i = 0; i < offset; ++i) { \
  1235. x[i] = _mm256_add_ps(x[i], x[offset+i]); \
  1236. } \
  1237. offset >>= 1; \
  1238. for (int i = 0; i < offset; ++i) { \
  1239. x[i] = _mm256_add_ps(x[i], x[offset+i]); \
  1240. } \
  1241. const __m128 t0 = _mm_add_ps(_mm256_castps256_ps128(x[0]), \
  1242. _mm256_extractf128_ps(x[0], 1)); \
  1243. const __m128 t1 = _mm_hadd_ps(t0, t0); \
  1244. res = (ggml_float) _mm_cvtss_f32(_mm_hadd_ps(t1, t1)); \
  1245. } while (0)
  1246. // TODO: is this optimal ?
  1247. #define GGML_F32_VEC GGML_F32x8
  1248. #define GGML_F32_VEC_ZERO GGML_F32x8_ZERO
  1249. #define GGML_F32_VEC_SET1 GGML_F32x8_SET1
  1250. #define GGML_F32_VEC_LOAD GGML_F32x8_LOAD
  1251. #define GGML_F32_VEC_STORE GGML_F32x8_STORE
  1252. #define GGML_F32_VEC_FMA GGML_F32x8_FMA
  1253. #define GGML_F32_VEC_ADD GGML_F32x8_ADD
  1254. #define GGML_F32_VEC_MUL GGML_F32x8_MUL
  1255. #define GGML_F32_VEC_REDUCE GGML_F32x8_REDUCE
  1256. // F16 AVX
  1257. #define GGML_F16_STEP 32
  1258. #define GGML_F16_EPR 8
  1259. // F16 arithmetic is not supported by AVX, so we use F32 instead
  1260. #define GGML_F32Cx8 __m256
  1261. #define GGML_F32Cx8_ZERO _mm256_setzero_ps()
  1262. #define GGML_F32Cx8_SET1(x) _mm256_set1_ps(x)
  1263. #if defined(__F16C__)
  1264. // the _mm256_cvt intrinsics require F16C
  1265. #define GGML_F32Cx8_LOAD(x) _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *)(x)))
  1266. #define GGML_F32Cx8_STORE(x, y) _mm_storeu_si128((__m128i *)(x), _mm256_cvtps_ph(y, 0))
  1267. #else
  1268. static inline __m256 __avx_f32cx8_load(ggml_fp16_t *x) {
  1269. float tmp[8];
  1270. for (int i = 0; i < 8; i++) {
  1271. tmp[i] = GGML_FP16_TO_FP32(x[i]);
  1272. }
  1273. return _mm256_loadu_ps(tmp);
  1274. }
  1275. static inline void __avx_f32cx8_store(ggml_fp16_t *x, __m256 y) {
  1276. float arr[8];
  1277. _mm256_storeu_ps(arr, y);
  1278. for (int i = 0; i < 8; i++)
  1279. x[i] = GGML_FP32_TO_FP16(arr[i]);
  1280. }
  1281. #define GGML_F32Cx8_LOAD(x) __avx_f32cx8_load(x)
  1282. #define GGML_F32Cx8_STORE(x, y) __avx_f32cx8_store(x, y)
  1283. #endif
  1284. #define GGML_F32Cx8_FMA GGML_F32x8_FMA
  1285. #define GGML_F32Cx8_ADD _mm256_add_ps
  1286. #define GGML_F32Cx8_MUL _mm256_mul_ps
  1287. #define GGML_F32Cx8_REDUCE GGML_F32x8_REDUCE
  1288. #define GGML_F16_VEC GGML_F32Cx8
  1289. #define GGML_F16_VEC_ZERO GGML_F32Cx8_ZERO
  1290. #define GGML_F16_VEC_SET1 GGML_F32Cx8_SET1
  1291. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx8_LOAD(p)
  1292. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx8_STORE(p, r[i])
  1293. #define GGML_F16_VEC_FMA GGML_F32Cx8_FMA
  1294. #define GGML_F16_VEC_ADD GGML_F32Cx8_ADD
  1295. #define GGML_F16_VEC_MUL GGML_F32Cx8_MUL
  1296. #define GGML_F16_VEC_REDUCE GGML_F32Cx8_REDUCE
  1297. #elif defined(__POWER9_VECTOR__)
  1298. #define GGML_SIMD
  1299. // F32 POWER9
  1300. #define GGML_F32_STEP 32
  1301. #define GGML_F32_EPR 4
  1302. #define GGML_F32x4 vector float
  1303. #define GGML_F32x4_ZERO 0.0f
  1304. #define GGML_F32x4_SET1 vec_splats
  1305. #define GGML_F32x4_LOAD(p) vec_xl(0, p)
  1306. #define GGML_F32x4_STORE(p, r) vec_xst(r, 0, p)
  1307. #define GGML_F32x4_FMA(a, b, c) vec_madd(b, c, a)
  1308. #define GGML_F32x4_ADD vec_add
  1309. #define GGML_F32x4_MUL vec_mul
  1310. #define GGML_F32x4_REDUCE(res, x) \
  1311. { \
  1312. int offset = GGML_F32_ARR >> 1; \
  1313. for (int i = 0; i < offset; ++i) { \
  1314. x[i] = vec_add(x[i], x[offset+i]); \
  1315. } \
  1316. offset >>= 1; \
  1317. for (int i = 0; i < offset; ++i) { \
  1318. x[i] = vec_add(x[i], x[offset+i]); \
  1319. } \
  1320. offset >>= 1; \
  1321. for (int i = 0; i < offset; ++i) { \
  1322. x[i] = vec_add(x[i], x[offset+i]); \
  1323. } \
  1324. res = vec_extract(x[0], 0) + \
  1325. vec_extract(x[0], 1) + \
  1326. vec_extract(x[0], 2) + \
  1327. vec_extract(x[0], 3); \
  1328. }
  1329. #define GGML_F32_VEC GGML_F32x4
  1330. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1331. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1332. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1333. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1334. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1335. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1336. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1337. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1338. // F16 POWER9
  1339. #define GGML_F16_STEP GGML_F32_STEP
  1340. #define GGML_F16_EPR GGML_F32_EPR
  1341. #define GGML_F16_VEC GGML_F32x4
  1342. #define GGML_F16_VEC_ZERO GGML_F32x4_ZERO
  1343. #define GGML_F16_VEC_SET1 GGML_F32x4_SET1
  1344. #define GGML_F16_VEC_FMA GGML_F32x4_FMA
  1345. #define GGML_F16_VEC_ADD GGML_F32x4_ADD
  1346. #define GGML_F16_VEC_MUL GGML_F32x4_MUL
  1347. #define GGML_F16_VEC_REDUCE GGML_F32x4_REDUCE
  1348. // Use vec_xl, not vec_ld, in case the load address is not aligned.
  1349. #define GGML_F16_VEC_LOAD(p, i) (i & 0x1) ? \
  1350. vec_extract_fp32_from_shorth(vec_xl(0, p - GGML_F16_EPR)) : \
  1351. vec_extract_fp32_from_shortl(vec_xl(0, p))
  1352. #define GGML_ENDIAN_BYTE(i) ((unsigned char *)&(uint16_t){1})[i]
  1353. #define GGML_F16_VEC_STORE(p, r, i) \
  1354. if (i & 0x1) \
  1355. vec_xst(vec_pack_to_short_fp32(r[i - GGML_ENDIAN_BYTE(1)], \
  1356. r[i - GGML_ENDIAN_BYTE(0)]), \
  1357. 0, p - GGML_F16_EPR)
  1358. #elif defined(__wasm_simd128__)
  1359. #define GGML_SIMD
  1360. // F32 WASM
  1361. #define GGML_F32_STEP 16
  1362. #define GGML_F32_EPR 4
  1363. #define GGML_F32x4 v128_t
  1364. #define GGML_F32x4_ZERO wasm_f32x4_splat(0.0f)
  1365. #define GGML_F32x4_SET1(x) wasm_f32x4_splat(x)
  1366. #define GGML_F32x4_LOAD wasm_v128_load
  1367. #define GGML_F32x4_STORE wasm_v128_store
  1368. #define GGML_F32x4_FMA(a, b, c) wasm_f32x4_add(wasm_f32x4_mul(b, c), a)
  1369. #define GGML_F32x4_ADD wasm_f32x4_add
  1370. #define GGML_F32x4_MUL wasm_f32x4_mul
  1371. #define GGML_F32x4_REDUCE(res, x) \
  1372. { \
  1373. int offset = GGML_F32_ARR >> 1; \
  1374. for (int i = 0; i < offset; ++i) { \
  1375. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1376. } \
  1377. offset >>= 1; \
  1378. for (int i = 0; i < offset; ++i) { \
  1379. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1380. } \
  1381. offset >>= 1; \
  1382. for (int i = 0; i < offset; ++i) { \
  1383. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1384. } \
  1385. res = wasm_f32x4_extract_lane(x[0], 0) + \
  1386. wasm_f32x4_extract_lane(x[0], 1) + \
  1387. wasm_f32x4_extract_lane(x[0], 2) + \
  1388. wasm_f32x4_extract_lane(x[0], 3); \
  1389. }
  1390. #define GGML_F32_VEC GGML_F32x4
  1391. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1392. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1393. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1394. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1395. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1396. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1397. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1398. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1399. // F16 WASM
  1400. #define GGML_F16_STEP 16
  1401. #define GGML_F16_EPR 4
  1402. inline static v128_t __wasm_f16x4_load(const ggml_fp16_t * p) {
  1403. float tmp[4];
  1404. tmp[0] = GGML_FP16_TO_FP32(p[0]);
  1405. tmp[1] = GGML_FP16_TO_FP32(p[1]);
  1406. tmp[2] = GGML_FP16_TO_FP32(p[2]);
  1407. tmp[3] = GGML_FP16_TO_FP32(p[3]);
  1408. return wasm_v128_load(tmp);
  1409. }
  1410. inline static void __wasm_f16x4_store(ggml_fp16_t * p, v128_t x) {
  1411. float tmp[4];
  1412. wasm_v128_store(tmp, x);
  1413. p[0] = GGML_FP32_TO_FP16(tmp[0]);
  1414. p[1] = GGML_FP32_TO_FP16(tmp[1]);
  1415. p[2] = GGML_FP32_TO_FP16(tmp[2]);
  1416. p[3] = GGML_FP32_TO_FP16(tmp[3]);
  1417. }
  1418. #define GGML_F16x4 v128_t
  1419. #define GGML_F16x4_ZERO wasm_f32x4_splat(0.0f)
  1420. #define GGML_F16x4_SET1(x) wasm_f32x4_splat(x)
  1421. #define GGML_F16x4_LOAD(x) __wasm_f16x4_load(x)
  1422. #define GGML_F16x4_STORE(x, y) __wasm_f16x4_store(x, y)
  1423. #define GGML_F16x4_FMA GGML_F32x4_FMA
  1424. #define GGML_F16x4_ADD wasm_f32x4_add
  1425. #define GGML_F16x4_MUL wasm_f32x4_mul
  1426. #define GGML_F16x4_REDUCE(res, x) \
  1427. { \
  1428. int offset = GGML_F16_ARR >> 1; \
  1429. for (int i = 0; i < offset; ++i) { \
  1430. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1431. } \
  1432. offset >>= 1; \
  1433. for (int i = 0; i < offset; ++i) { \
  1434. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1435. } \
  1436. offset >>= 1; \
  1437. for (int i = 0; i < offset; ++i) { \
  1438. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1439. } \
  1440. res = wasm_f32x4_extract_lane(x[0], 0) + \
  1441. wasm_f32x4_extract_lane(x[0], 1) + \
  1442. wasm_f32x4_extract_lane(x[0], 2) + \
  1443. wasm_f32x4_extract_lane(x[0], 3); \
  1444. }
  1445. #define GGML_F16_VEC GGML_F16x4
  1446. #define GGML_F16_VEC_ZERO GGML_F16x4_ZERO
  1447. #define GGML_F16_VEC_SET1 GGML_F16x4_SET1
  1448. #define GGML_F16_VEC_LOAD(p, i) GGML_F16x4_LOAD(p)
  1449. #define GGML_F16_VEC_STORE(p, r, i) GGML_F16x4_STORE(p, r[i])
  1450. #define GGML_F16_VEC_FMA GGML_F16x4_FMA
  1451. #define GGML_F16_VEC_ADD GGML_F16x4_ADD
  1452. #define GGML_F16_VEC_MUL GGML_F16x4_MUL
  1453. #define GGML_F16_VEC_REDUCE GGML_F16x4_REDUCE
  1454. #elif defined(__SSE3__)
  1455. #define GGML_SIMD
  1456. // F32 SSE
  1457. #define GGML_F32_STEP 32
  1458. #define GGML_F32_EPR 4
  1459. #define GGML_F32x4 __m128
  1460. #define GGML_F32x4_ZERO _mm_setzero_ps()
  1461. #define GGML_F32x4_SET1(x) _mm_set1_ps(x)
  1462. #define GGML_F32x4_LOAD _mm_loadu_ps
  1463. #define GGML_F32x4_STORE _mm_storeu_ps
  1464. #if defined(__FMA__)
  1465. // TODO: Does this work?
  1466. #define GGML_F32x4_FMA(a, b, c) _mm_fmadd_ps(b, c, a)
  1467. #else
  1468. #define GGML_F32x4_FMA(a, b, c) _mm_add_ps(_mm_mul_ps(b, c), a)
  1469. #endif
  1470. #define GGML_F32x4_ADD _mm_add_ps
  1471. #define GGML_F32x4_MUL _mm_mul_ps
  1472. #define GGML_F32x4_REDUCE(res, x) \
  1473. { \
  1474. int offset = GGML_F32_ARR >> 1; \
  1475. for (int i = 0; i < offset; ++i) { \
  1476. x[i] = _mm_add_ps(x[i], x[offset+i]); \
  1477. } \
  1478. offset >>= 1; \
  1479. for (int i = 0; i < offset; ++i) { \
  1480. x[i] = _mm_add_ps(x[i], x[offset+i]); \
  1481. } \
  1482. offset >>= 1; \
  1483. for (int i = 0; i < offset; ++i) { \
  1484. x[i] = _mm_add_ps(x[i], x[offset+i]); \
  1485. } \
  1486. const __m128 t0 = _mm_hadd_ps(x[0], x[0]); \
  1487. res = (ggml_float) _mm_cvtss_f32(_mm_hadd_ps(t0, t0)); \
  1488. }
  1489. // TODO: is this optimal ?
  1490. #define GGML_F32_VEC GGML_F32x4
  1491. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1492. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1493. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1494. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1495. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1496. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1497. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1498. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1499. // F16 SSE
  1500. #define GGML_F16_STEP 32
  1501. #define GGML_F16_EPR 4
  1502. static inline __m128 __sse_f16x4_load(ggml_fp16_t *x) {
  1503. float tmp[4];
  1504. tmp[0] = GGML_FP16_TO_FP32(x[0]);
  1505. tmp[1] = GGML_FP16_TO_FP32(x[1]);
  1506. tmp[2] = GGML_FP16_TO_FP32(x[2]);
  1507. tmp[3] = GGML_FP16_TO_FP32(x[3]);
  1508. return _mm_loadu_ps(tmp);
  1509. }
  1510. static inline void __sse_f16x4_store(ggml_fp16_t *x, __m128 y) {
  1511. float arr[4];
  1512. _mm_storeu_ps(arr, y);
  1513. x[0] = GGML_FP32_TO_FP16(arr[0]);
  1514. x[1] = GGML_FP32_TO_FP16(arr[1]);
  1515. x[2] = GGML_FP32_TO_FP16(arr[2]);
  1516. x[3] = GGML_FP32_TO_FP16(arr[3]);
  1517. }
  1518. #define GGML_F32Cx4 __m128
  1519. #define GGML_F32Cx4_ZERO _mm_setzero_ps()
  1520. #define GGML_F32Cx4_SET1(x) _mm_set1_ps(x)
  1521. #define GGML_F32Cx4_LOAD(x) __sse_f16x4_load(x)
  1522. #define GGML_F32Cx4_STORE(x, y) __sse_f16x4_store(x, y)
  1523. #define GGML_F32Cx4_FMA GGML_F32x4_FMA
  1524. #define GGML_F32Cx4_ADD _mm_add_ps
  1525. #define GGML_F32Cx4_MUL _mm_mul_ps
  1526. #define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
  1527. #define GGML_F16_VEC GGML_F32Cx4
  1528. #define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
  1529. #define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
  1530. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
  1531. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE(p, r[i])
  1532. #define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
  1533. #define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
  1534. #define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
  1535. #define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
  1536. #elif defined(__loongarch_asx)
  1537. #define GGML_SIMD
  1538. // F32 LASX
  1539. #define GGML_F32_STEP 32
  1540. #define GGML_F32_EPR 8
  1541. #define GGML_F32x8 __m256
  1542. #define GGML_F32x8_ZERO (__m256)__lasx_xvldi(0)
  1543. #define GGML_F32x8_SET1(x) (__m256)__lasx_xvreplfr2vr_s((x))
  1544. #define GGML_F32x8_LOAD(x) (__m256)__lasx_xvld((x), 0)
  1545. #define GGML_F32x8_STORE(x,y) __lasx_xvst((y), (x), 0)
  1546. #define GGML_F32x8_FMA(a, b, c) __lasx_xvfmadd_s(b, c, a)
  1547. #define GGML_F32x8_ADD __lasx_xvfadd_s
  1548. #define GGML_F32x8_MUL __lasx_xvfmul_s
  1549. #define GGML_F32x8_REDUCE(res, x) \
  1550. do { \
  1551. int offset = GGML_F32_ARR >> 1; \
  1552. for (int i = 0; i < offset; ++i) { \
  1553. x[i] = __lasx_xvfadd_s(x[i], x[offset+i]); \
  1554. } \
  1555. offset >>= 1; \
  1556. for (int i = 0; i < offset; ++i) { \
  1557. x[i] = __lasx_xvfadd_s(x[i], x[offset+i]); \
  1558. } \
  1559. offset >>= 1; \
  1560. for (int i = 0; i < offset; ++i) { \
  1561. x[i] = __lasx_xvfadd_s(x[i], x[offset+i]); \
  1562. } \
  1563. float *tmp_p = (float *)&x[0]; \
  1564. res = tmp_p[0] + tmp_p[1] + tmp_p[2] + tmp_p[3] + tmp_p[4] + tmp_p[5] + tmp_p[6] + tmp_p[7]; \
  1565. } while (0)
  1566. // TODO: is this optimal ?
  1567. #define GGML_F32_VEC GGML_F32x8
  1568. #define GGML_F32_VEC_ZERO GGML_F32x8_ZERO
  1569. #define GGML_F32_VEC_SET1 GGML_F32x8_SET1
  1570. #define GGML_F32_VEC_LOAD GGML_F32x8_LOAD
  1571. #define GGML_F32_VEC_STORE GGML_F32x8_STORE
  1572. #define GGML_F32_VEC_FMA GGML_F32x8_FMA
  1573. #define GGML_F32_VEC_ADD GGML_F32x8_ADD
  1574. #define GGML_F32_VEC_MUL GGML_F32x8_MUL
  1575. #define GGML_F32_VEC_REDUCE GGML_F32x8_REDUCE
  1576. // F16 LASX
  1577. #define GGML_F16_STEP 32
  1578. #define GGML_F16_EPR 8
  1579. // F16 arithmetic is not supported by AVX, so we use F32 instead
  1580. #define GGML_F32Cx8 __m256
  1581. #define GGML_F32Cx8_ZERO (__m256)__lasx_xvldi(0)
  1582. #define GGML_F32Cx8_SET1(x) (__m256)__lasx_xvreplgr2vr_w((x))
  1583. static inline __m256 __lasx_f32cx8_load(const ggml_fp16_t * x) {
  1584. float tmp[8];
  1585. for (int i = 0; i < 8; i++) {
  1586. tmp[i] = GGML_FP16_TO_FP32(x[i]);
  1587. }
  1588. return (__m256)__lasx_xvld(tmp, 0);
  1589. }
  1590. static inline void __lasx_f32cx8_store(ggml_fp16_t * x, __m256 y) {
  1591. float arr[8];
  1592. __lasx_xvst(y, arr, 0);
  1593. for (int i = 0; i < 8; i++) {
  1594. x[i] = GGML_FP32_TO_FP16(arr[i]);
  1595. }
  1596. }
  1597. #define GGML_F32Cx8_LOAD(x) __lasx_f32cx8_load(x)
  1598. #define GGML_F32Cx8_STORE(x, y) __lasx_f32cx8_store(x, y)
  1599. #define GGML_F32Cx8_FMA GGML_F32x8_FMA
  1600. #define GGML_F32Cx8_ADD __lasx_xvfadd_s
  1601. #define GGML_F32Cx8_MUL __lasx_xvfmul_s
  1602. #define GGML_F32Cx8_REDUCE GGML_F32x8_REDUCE
  1603. #define GGML_F16_VEC GGML_F32Cx8
  1604. #define GGML_F16_VEC_ZERO GGML_F32Cx8_ZERO
  1605. #define GGML_F16_VEC_SET1 GGML_F32Cx8_SET1
  1606. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx8_LOAD(p)
  1607. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx8_STORE(p, r[i])
  1608. #define GGML_F16_VEC_FMA GGML_F32Cx8_FMA
  1609. #define GGML_F16_VEC_ADD GGML_F32Cx8_ADD
  1610. #define GGML_F16_VEC_MUL GGML_F32Cx8_MUL
  1611. #define GGML_F16_VEC_REDUCE GGML_F32Cx8_REDUCE
  1612. #elif defined(__loongarch_sx)
  1613. #define GGML_SIMD
  1614. // F32 LSX
  1615. #define GGML_F32_STEP 32
  1616. #define GGML_F32_EPR 4
  1617. #define GGML_F32x4 __m128
  1618. #define GGML_F32x4_ZERO __lsx_vldi(0)
  1619. #define GGML_F32x4_SET1(x) __lsx_vinsgr2vr_w(__lsx_vldi(0),(x), 0)
  1620. #define GGML_F32x4_LOAD(x) __lsx_vld((x), 0)
  1621. #define GGML_F32x4_STORE((x),(y)) __lsx_vst((y), (x), 0)
  1622. #define GGML_F32x4_FMA(a, b, c) __lsx_vfmadd_s(b, c, a)
  1623. #define GGML_F32x4_ADD __lsx_vfadd_s
  1624. #define GGML_F32x4_MUL __lsx_vfmul_s
  1625. #define GGML_F32x4_REDUCE(res, x) \
  1626. { \
  1627. int offset = GGML_F32_ARR >> 1; \
  1628. for (int i = 0; i < offset; ++i) { \
  1629. x[i] = __lsx_vfadd_s(x[i], x[offset+i]); \
  1630. } \
  1631. offset >>= 1; \
  1632. for (int i = 0; i < offset; ++i) { \
  1633. x[i] = __lsx_vfadd_s(x[i], x[offset+i]); \
  1634. } \
  1635. offset >>= 1; \
  1636. for (int i = 0; i < offset; ++i) { \
  1637. x[i] = __lsx_vfadd_s(x[i], x[offset+i]); \
  1638. } \
  1639. __m128i tmp = __lsx_vsrli_d((__m128i)x[0], 32); \
  1640. tmp = (__m128i)__lsx_vfadd_s((__m128)tmp, x[0]); \
  1641. tmp = __lsx_vpickev_w(__lsx_vldi(0), tmp); \
  1642. const __m128 t0 = __lsx_vshuf4i_w(tmp, 0x88); \
  1643. tmp = __lsx_vsrli_d((__m128i)t0, 32); \
  1644. tmp = (__m128i)__lsx_vfadd_s((__m128)tmp, t0); \
  1645. tmp = __lsx_vpickev_w(__lsx_vldi(0), tmp); \
  1646. res = (ggml_float) __lsx_vpickve2gr_w(__lsx_vshuf4i_w(tmp, 0x88), 0); \
  1647. }
  1648. #define GGML_F32_VEC GGML_F32x4
  1649. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1650. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1651. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1652. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1653. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1654. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1655. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1656. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1657. // F16 LSX
  1658. #define GGML_F16_STEP 32
  1659. #define GGML_F16_EPR 4
  1660. static inline __m128 __lsx_f16x4_load(const ggml_fp16_t * x) {
  1661. float tmp[4];
  1662. tmp[0] = GGML_FP16_TO_FP32(x[0]);
  1663. tmp[1] = GGML_FP16_TO_FP32(x[1]);
  1664. tmp[2] = GGML_FP16_TO_FP32(x[2]);
  1665. tmp[3] = GGML_FP16_TO_FP32(x[3]);
  1666. return __lsx_vld(tmp, 0);
  1667. }
  1668. static inline void __lsx_f16x4_store(ggml_fp16_t * x, __m128 y) {
  1669. float arr[4];
  1670. __lsx_vst(y, arr, 0);
  1671. x[0] = GGML_FP32_TO_FP16(arr[0]);
  1672. x[1] = GGML_FP32_TO_FP16(arr[1]);
  1673. x[2] = GGML_FP32_TO_FP16(arr[2]);
  1674. x[3] = GGML_FP32_TO_FP16(arr[3]);
  1675. }
  1676. #define GGML_F32Cx4 __m128
  1677. #define GGML_F32Cx4_ZERO __lsx_vldi(0)
  1678. #define GGML_F32Cx4_SET1(x) __lsx_vinsgr2vr_w(__lsx_vldi(0),(x), 0)
  1679. #define GGML_F32Cx4_LOAD(x) __lsx_f16x4_load(x)
  1680. #define GGML_F32Cx4_STORE(x, y) __lsx_f16x4_store(x, y)
  1681. #define GGML_F32Cx4_FMA GGML_F32x4_FMA
  1682. #define GGML_F32Cx4_ADD __lsx_vfadd_s
  1683. #define GGML_F32Cx4_MUL __lsx_vfmul_s
  1684. #define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
  1685. #define GGML_F16_VEC GGML_F32Cx4
  1686. #define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
  1687. #define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
  1688. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
  1689. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE(p, r[i])
  1690. #define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
  1691. #define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
  1692. #define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
  1693. #define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
  1694. #endif
  1695. // GGML_F32_ARR / GGML_F16_ARR
  1696. // number of registers to use per step
  1697. #ifdef GGML_SIMD
  1698. #define GGML_F32_ARR (GGML_F32_STEP/GGML_F32_EPR)
  1699. #define GGML_F16_ARR (GGML_F16_STEP/GGML_F16_EPR)
  1700. #endif
  1701. //
  1702. // ggml object
  1703. //
  1704. struct ggml_object {
  1705. size_t offs;
  1706. size_t size;
  1707. struct ggml_object * next;
  1708. enum ggml_object_type type;
  1709. char padding[4];
  1710. };
  1711. static const size_t GGML_OBJECT_SIZE = sizeof(struct ggml_object);
  1712. //
  1713. // ggml context
  1714. //
  1715. struct ggml_context {
  1716. size_t mem_size;
  1717. void* mem_buffer;
  1718. bool mem_buffer_owned;
  1719. bool no_alloc;
  1720. bool no_alloc_save; // this is used to save the no_alloc state when using scratch buffers
  1721. int n_objects;
  1722. struct ggml_object * objects_begin;
  1723. struct ggml_object * objects_end;
  1724. struct ggml_scratch scratch;
  1725. struct ggml_scratch scratch_save;
  1726. };
  1727. struct ggml_context_container {
  1728. bool used;
  1729. struct ggml_context context;
  1730. };
  1731. //
  1732. // Threading defs
  1733. //
  1734. typedef pthread_t ggml_thread_t;
  1735. #if defined(_WIN32)
  1736. typedef CONDITION_VARIABLE ggml_cond_t;
  1737. typedef SRWLOCK ggml_mutex_t;
  1738. #define ggml_mutex_init(m) InitializeSRWLock(m)
  1739. #define ggml_mutex_destroy(m)
  1740. #define ggml_mutex_lock(m) AcquireSRWLockExclusive(m)
  1741. #define ggml_mutex_unlock(m) ReleaseSRWLockExclusive(m)
  1742. #define ggml_mutex_lock_shared(m) AcquireSRWLockShared(m)
  1743. #define ggml_mutex_unlock_shared(m) ReleaseSRWLockShared(m)
  1744. #define ggml_cond_init(c) InitializeConditionVariable(c)
  1745. #define ggml_cond_destroy(c)
  1746. #define ggml_cond_wait(c, m) SleepConditionVariableSRW(c, m, INFINITE, CONDITION_VARIABLE_LOCKMODE_SHARED)
  1747. #define ggml_cond_broadcast(c) WakeAllConditionVariable(c)
  1748. #define ggml_thread_create pthread_create
  1749. #define ggml_thread_join pthread_join
  1750. #else
  1751. typedef pthread_cond_t ggml_cond_t;
  1752. typedef pthread_mutex_t ggml_mutex_t;
  1753. #define ggml_mutex_init(m) pthread_mutex_init(m, NULL)
  1754. #define ggml_mutex_destroy(m) pthread_mutex_destroy(m)
  1755. #define ggml_mutex_lock(m) pthread_mutex_lock(m)
  1756. #define ggml_mutex_unlock(m) pthread_mutex_unlock(m)
  1757. #define ggml_mutex_lock_shared(m) pthread_mutex_lock(m)
  1758. #define ggml_mutex_unlock_shared(m) pthread_mutex_unlock(m)
  1759. #define ggml_lock_init(x) UNUSED(x)
  1760. #define ggml_lock_destroy(x) UNUSED(x)
  1761. #if defined(__x86_64__) || (defined(_MSC_VER) && defined(_M_AMD64))
  1762. #define ggml_lock_lock(x) _mm_pause()
  1763. #else
  1764. #define ggml_lock_lock(x) UNUSED(x)
  1765. #endif
  1766. #define ggml_lock_unlock(x) UNUSED(x)
  1767. #define GGML_LOCK_INITIALIZER 0
  1768. #define ggml_cond_init(c) pthread_cond_init(c, NULL)
  1769. #define ggml_cond_destroy(c) pthread_cond_destroy(c)
  1770. #define ggml_cond_wait(c, m) pthread_cond_wait(c, m)
  1771. #define ggml_cond_broadcast(c) pthread_cond_broadcast(c)
  1772. #define ggml_thread_create pthread_create
  1773. #define ggml_thread_join pthread_join
  1774. #endif
  1775. // Threadpool def
  1776. struct ggml_threadpool {
  1777. ggml_mutex_t mutex; // mutex for cond.var
  1778. ggml_cond_t cond; // cond.var for waiting for new work
  1779. struct ggml_cgraph * cgraph;
  1780. struct ggml_cplan * cplan;
  1781. // synchronization primitives
  1782. atomic_int n_graph; // incremented when there is work to be done (i.e each graph)
  1783. atomic_int GGML_CACHE_ALIGN n_barrier;
  1784. atomic_int GGML_CACHE_ALIGN n_barrier_passed;
  1785. atomic_int current_chunk; // currently processing chunk during Mat_Mul, shared between all the threads.
  1786. // these are atomic as an annotation for thread-sanitizer
  1787. atomic_bool stop; // Used for stopping the threadpool altogether
  1788. atomic_bool pause; // Used for pausing the threadpool or individual threads
  1789. atomic_bool abort; // Used for aborting processing of a graph
  1790. struct ggml_compute_state * workers; // per thread state
  1791. int n_threads_max; // number of threads in the pool
  1792. atomic_int n_threads_cur; // number of threads used in the current graph
  1793. int32_t prio; // Scheduling priority
  1794. uint32_t poll; // Polling level (0 - no polling)
  1795. enum ggml_status ec;
  1796. };
  1797. // Per-thread state
  1798. struct ggml_compute_state {
  1799. #ifndef GGML_USE_OPENMP
  1800. ggml_thread_t thrd;
  1801. bool cpumask[GGML_MAX_N_THREADS];
  1802. int last_graph;
  1803. bool pending;
  1804. #endif
  1805. struct ggml_threadpool * threadpool;
  1806. int ith;
  1807. };
  1808. struct ggml_compute_params {
  1809. // ith = thread index, nth = number of threads
  1810. int ith, nth;
  1811. // work buffer for all threads
  1812. size_t wsize;
  1813. void * wdata;
  1814. struct ggml_threadpool * threadpool;
  1815. };
  1816. //
  1817. // fundamental operations
  1818. //
  1819. inline static void ggml_vec_set_i8(const int n, int8_t * x, const int8_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
  1820. inline static void ggml_vec_set_i16(const int n, int16_t * x, const int16_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
  1821. inline static void ggml_vec_set_i32(const int n, int32_t * x, const int32_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
  1822. inline static void ggml_vec_set_f16(const int n, ggml_fp16_t * x, const int32_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
  1823. inline static void ggml_vec_set_bf16(const int n, ggml_bf16_t * x, const ggml_bf16_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
  1824. inline static void ggml_vec_add_f32 (const int n, float * z, const float * x, const float * y) { for (int i = 0; i < n; ++i) z[i] = x[i] + y[i]; }
  1825. inline static void ggml_vec_add1_f32(const int n, float * z, const float * x, const float v) { for (int i = 0; i < n; ++i) z[i] = x[i] + v; }
  1826. inline static void ggml_vec_acc_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] += x[i]; }
  1827. inline static void ggml_vec_acc1_f32(const int n, float * y, const float v) { for (int i = 0; i < n; ++i) y[i] += v; }
  1828. inline static void ggml_vec_sub_f32 (const int n, float * z, const float * x, const float * y) { for (int i = 0; i < n; ++i) z[i] = x[i] - y[i]; }
  1829. inline static void ggml_vec_set_f32 (const int n, float * x, const float v) { for (int i = 0; i < n; ++i) x[i] = v; }
  1830. inline static void ggml_vec_cpy_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = x[i]; }
  1831. inline static void ggml_vec_neg_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = -x[i]; }
  1832. inline static void ggml_vec_mul_f32 (const int n, float * z, const float * x, const float * y) { for (int i = 0; i < n; ++i) z[i] = x[i]*y[i]; }
  1833. inline static void ggml_vec_div_f32 (const int n, float * z, const float * x, const float * y) { for (int i = 0; i < n; ++i) z[i] = x[i]/y[i]; }
  1834. static void ggml_vec_dot_f32(int n, float * restrict s, size_t bs, const float * restrict x, size_t bx, const float * restrict y, size_t by, int nrc) {
  1835. assert(nrc == 1);
  1836. UNUSED(nrc);
  1837. UNUSED(bx);
  1838. UNUSED(by);
  1839. UNUSED(bs);
  1840. #if defined(GGML_SIMD)
  1841. float sumf = 0.0f;
  1842. const int np = (n & ~(GGML_F32_STEP - 1));
  1843. GGML_F32_VEC sum[GGML_F32_ARR] = { GGML_F32_VEC_ZERO };
  1844. GGML_F32_VEC ax[GGML_F32_ARR];
  1845. GGML_F32_VEC ay[GGML_F32_ARR];
  1846. for (int i = 0; i < np; i += GGML_F32_STEP) {
  1847. for (int j = 0; j < GGML_F32_ARR; j++) {
  1848. ax[j] = GGML_F32_VEC_LOAD(x + i + j*GGML_F32_EPR);
  1849. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  1850. sum[j] = GGML_F32_VEC_FMA(sum[j], ax[j], ay[j]);
  1851. }
  1852. }
  1853. // reduce sum0..sum3 to sum0
  1854. GGML_F32_VEC_REDUCE(sumf, sum);
  1855. // leftovers
  1856. for (int i = np; i < n; ++i) {
  1857. sumf += x[i]*y[i];
  1858. }
  1859. #else
  1860. // scalar
  1861. ggml_float sumf = 0.0;
  1862. for (int i = 0; i < n; ++i) {
  1863. sumf += (ggml_float)(x[i]*y[i]);
  1864. }
  1865. #endif
  1866. *s = sumf;
  1867. }
  1868. static void ggml_vec_dot_bf16(int n, float * restrict s, size_t bs, ggml_bf16_t * restrict x, size_t bx, ggml_bf16_t * restrict y, size_t by, int nrc) {
  1869. assert(nrc == 1);
  1870. UNUSED(nrc);
  1871. UNUSED(bx);
  1872. UNUSED(by);
  1873. UNUSED(bs);
  1874. int i = 0;
  1875. ggml_float sumf = 0;
  1876. #if defined(__AVX512BF16__)
  1877. __m512 c1 = _mm512_setzero_ps();
  1878. __m512 c2 = _mm512_setzero_ps();
  1879. for (; i + 64 <= n; i += 64) {
  1880. c1 = _mm512_dpbf16_ps(c1, m512bh(_mm512_loadu_si512((x + i))),
  1881. m512bh(_mm512_loadu_si512((y + i))));
  1882. c2 = _mm512_dpbf16_ps(c2, m512bh(_mm512_loadu_si512((x + i + 32))),
  1883. m512bh(_mm512_loadu_si512((y + i + 32))));
  1884. }
  1885. sumf += (ggml_float)_mm512_reduce_add_ps(c1);
  1886. sumf += (ggml_float)_mm512_reduce_add_ps(c2);
  1887. #elif defined(__AVX512F__)
  1888. #define LOAD(p) _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(_mm256_loadu_si256((const __m256i *)(p))), 16))
  1889. __m512 c1 = _mm512_setzero_ps();
  1890. __m512 c2 = _mm512_setzero_ps();
  1891. for (; i + 32 <= n; i += 32) {
  1892. c1 = _mm512_add_ps(_mm512_mul_ps(LOAD(x + i), LOAD(y + i)), c1);
  1893. c2 = _mm512_add_ps(_mm512_mul_ps(LOAD(x + i + 16), LOAD(y + i + 16)), c2);
  1894. }
  1895. sumf += (ggml_float)_mm512_reduce_add_ps(c1);
  1896. sumf += (ggml_float)_mm512_reduce_add_ps(c2);
  1897. #undef LOAD
  1898. #elif defined(__AVX2__)
  1899. #define LOAD(p) _mm256_castsi256_ps(_mm256_slli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i *)(p))), 16))
  1900. __m256 c1 = _mm256_setzero_ps();
  1901. __m256 c2 = _mm256_setzero_ps();
  1902. __m256 c3 = _mm256_setzero_ps();
  1903. __m256 c4 = _mm256_setzero_ps();
  1904. for (; i + 32 <= n; i += 32) {
  1905. c1 = _mm256_add_ps(_mm256_mul_ps(LOAD(x + i), LOAD(y + i)), c1);
  1906. c2 = _mm256_add_ps(_mm256_mul_ps(LOAD(x + i + 8), LOAD(y + i + 8)), c2);
  1907. c3 = _mm256_add_ps(_mm256_mul_ps(LOAD(x + i + 16), LOAD(y + i + 16)), c3);
  1908. c4 = _mm256_add_ps(_mm256_mul_ps(LOAD(x + i + 24), LOAD(y + i + 24)), c4);
  1909. }
  1910. __m128 g;
  1911. c1 = _mm256_add_ps(_mm256_add_ps(c1, c3),
  1912. _mm256_add_ps(c2, c4));
  1913. g = _mm_add_ps(_mm256_extractf128_ps(c1, 1),
  1914. _mm256_castps256_ps128(c1));
  1915. g = _mm_add_ps(g, _mm_movehl_ps(g, g));
  1916. g = _mm_add_ss(g, _mm_movehdup_ps(g));
  1917. sumf += (ggml_float)_mm_cvtss_f32(g);
  1918. #undef LOAD
  1919. #endif
  1920. for (; i < n; ++i) {
  1921. sumf += (ggml_float)(GGML_BF16_TO_FP32(x[i]) *
  1922. GGML_BF16_TO_FP32(y[i]));
  1923. }
  1924. *s = sumf;
  1925. }
  1926. static void ggml_vec_dot_f16(int n, float * restrict s, size_t bs, ggml_fp16_t * restrict x, size_t bx, ggml_fp16_t * restrict y, size_t by, int nrc) {
  1927. assert(nrc == 1);
  1928. UNUSED(nrc);
  1929. UNUSED(bx);
  1930. UNUSED(by);
  1931. UNUSED(bs);
  1932. ggml_float sumf = 0.0;
  1933. #if defined(GGML_SIMD)
  1934. const int np = (n & ~(GGML_F16_STEP - 1));
  1935. GGML_F16_VEC sum[GGML_F16_ARR] = { GGML_F16_VEC_ZERO };
  1936. GGML_F16_VEC ax[GGML_F16_ARR];
  1937. GGML_F16_VEC ay[GGML_F16_ARR];
  1938. for (int i = 0; i < np; i += GGML_F16_STEP) {
  1939. for (int j = 0; j < GGML_F16_ARR; j++) {
  1940. ax[j] = GGML_F16_VEC_LOAD(x + i + j*GGML_F16_EPR, j);
  1941. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  1942. sum[j] = GGML_F16_VEC_FMA(sum[j], ax[j], ay[j]);
  1943. }
  1944. }
  1945. // reduce sum0..sum3 to sum0
  1946. GGML_F16_VEC_REDUCE(sumf, sum);
  1947. // leftovers
  1948. for (int i = np; i < n; ++i) {
  1949. sumf += (ggml_float)(GGML_FP16_TO_FP32(x[i])*GGML_FP16_TO_FP32(y[i]));
  1950. }
  1951. #else
  1952. for (int i = 0; i < n; ++i) {
  1953. sumf += (ggml_float)(GGML_FP16_TO_FP32(x[i])*GGML_FP16_TO_FP32(y[i]));
  1954. }
  1955. #endif
  1956. *s = sumf;
  1957. }
  1958. // compute GGML_VEC_DOT_UNROLL dot products at once
  1959. // xs - x row stride in bytes
  1960. inline static void ggml_vec_dot_f16_unroll(const int n, const int xs, float * restrict s, void * restrict xv, ggml_fp16_t * restrict y) {
  1961. ggml_float sumf[GGML_VEC_DOT_UNROLL] = { 0.0 };
  1962. ggml_fp16_t * restrict x[GGML_VEC_DOT_UNROLL];
  1963. for (int i = 0; i < GGML_VEC_DOT_UNROLL; ++i) {
  1964. x[i] = (ggml_fp16_t *) ((char *) xv + i*xs);
  1965. }
  1966. #if defined(GGML_SIMD)
  1967. const int np = (n & ~(GGML_F16_STEP - 1));
  1968. GGML_F16_VEC sum[GGML_VEC_DOT_UNROLL][GGML_F16_ARR] = { { GGML_F16_VEC_ZERO } };
  1969. GGML_F16_VEC ax[GGML_F16_ARR];
  1970. GGML_F16_VEC ay[GGML_F16_ARR];
  1971. for (int i = 0; i < np; i += GGML_F16_STEP) {
  1972. for (int j = 0; j < GGML_F16_ARR; j++) {
  1973. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  1974. for (int k = 0; k < GGML_VEC_DOT_UNROLL; ++k) {
  1975. ax[j] = GGML_F16_VEC_LOAD(x[k] + i + j*GGML_F16_EPR, j);
  1976. sum[k][j] = GGML_F16_VEC_FMA(sum[k][j], ax[j], ay[j]);
  1977. }
  1978. }
  1979. }
  1980. // reduce sum0..sum3 to sum0
  1981. for (int k = 0; k < GGML_VEC_DOT_UNROLL; ++k) {
  1982. GGML_F16_VEC_REDUCE(sumf[k], sum[k]);
  1983. }
  1984. // leftovers
  1985. for (int i = np; i < n; ++i) {
  1986. for (int j = 0; j < GGML_VEC_DOT_UNROLL; ++j) {
  1987. sumf[j] += (ggml_float)(GGML_FP16_TO_FP32(x[j][i])*GGML_FP16_TO_FP32(y[i]));
  1988. }
  1989. }
  1990. #else
  1991. for (int i = 0; i < n; ++i) {
  1992. for (int j = 0; j < GGML_VEC_DOT_UNROLL; ++j) {
  1993. sumf[j] += (ggml_float)(GGML_FP16_TO_FP32(x[j][i])*GGML_FP16_TO_FP32(y[i]));
  1994. }
  1995. }
  1996. #endif
  1997. for (int i = 0; i < GGML_VEC_DOT_UNROLL; ++i) {
  1998. s[i] = sumf[i];
  1999. }
  2000. }
  2001. inline static void ggml_vec_mad_f32(const int n, float * restrict y, const float * restrict x, const float v) {
  2002. #if defined(GGML_SIMD)
  2003. const int np = (n & ~(GGML_F32_STEP - 1));
  2004. GGML_F32_VEC vx = GGML_F32_VEC_SET1(v);
  2005. GGML_F32_VEC ax[GGML_F32_ARR];
  2006. GGML_F32_VEC ay[GGML_F32_ARR];
  2007. for (int i = 0; i < np; i += GGML_F32_STEP) {
  2008. for (int j = 0; j < GGML_F32_ARR; j++) {
  2009. ax[j] = GGML_F32_VEC_LOAD(x + i + j*GGML_F32_EPR);
  2010. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  2011. ay[j] = GGML_F32_VEC_FMA(ay[j], ax[j], vx);
  2012. GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
  2013. }
  2014. }
  2015. // leftovers
  2016. for (int i = np; i < n; ++i) {
  2017. y[i] += x[i]*v;
  2018. }
  2019. #else
  2020. // scalar
  2021. for (int i = 0; i < n; ++i) {
  2022. y[i] += x[i]*v;
  2023. }
  2024. #endif
  2025. }
  2026. inline static void ggml_vec_mad_f16(const int n, ggml_fp16_t * restrict y, const ggml_fp16_t * restrict x, const float v) {
  2027. #if defined(GGML_SIMD)
  2028. const int np = (n & ~(GGML_F16_STEP - 1));
  2029. GGML_F16_VEC vx = GGML_F16_VEC_SET1(v);
  2030. GGML_F16_VEC ax[GGML_F16_ARR];
  2031. GGML_F16_VEC ay[GGML_F16_ARR];
  2032. for (int i = 0; i < np; i += GGML_F16_STEP) {
  2033. for (int j = 0; j < GGML_F16_ARR; j++) {
  2034. ax[j] = GGML_F16_VEC_LOAD(x + i + j*GGML_F16_EPR, j);
  2035. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  2036. ay[j] = GGML_F16_VEC_FMA(ay[j], ax[j], vx);
  2037. GGML_F16_VEC_STORE(y + i + j*GGML_F16_EPR, ay, j);
  2038. }
  2039. }
  2040. // leftovers
  2041. for (int i = np; i < n; ++i) {
  2042. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i]) + GGML_FP16_TO_FP32(x[i])*v);
  2043. }
  2044. #else
  2045. // scalar
  2046. for (int i = 0; i < n; ++i) {
  2047. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i]) + GGML_FP16_TO_FP32(x[i])*v);
  2048. }
  2049. #endif
  2050. }
  2051. // xs and vs are byte strides of x and v
  2052. inline static void ggml_vec_mad_f32_unroll(const int n, const int xs, const int vs, float * restrict y, const float * restrict xv, const float * restrict vv) {
  2053. const float * restrict x[GGML_VEC_MAD_UNROLL];
  2054. const float * restrict v[GGML_VEC_MAD_UNROLL];
  2055. for (int i = 0; i < GGML_VEC_MAD_UNROLL; ++i) {
  2056. x[i] = (const float *) ((const char *) xv + i*xs);
  2057. v[i] = (const float *) ((const char *) vv + i*vs);
  2058. }
  2059. #if defined(GGML_SIMD)
  2060. const int np = (n & ~(GGML_F32_STEP - 1));
  2061. GGML_F32_VEC vx[GGML_VEC_MAD_UNROLL];
  2062. for (int k = 0; k < GGML_VEC_MAD_UNROLL; ++k) {
  2063. vx[k] = GGML_F32_VEC_SET1(v[k][0]);
  2064. }
  2065. GGML_F32_VEC ax[GGML_VEC_MAD_UNROLL][GGML_F32_ARR];
  2066. GGML_F32_VEC ay[GGML_F32_ARR];
  2067. for (int i = 0; i < np; i += GGML_F32_STEP) {
  2068. for (int j = 0; j < GGML_F32_ARR; j++) {
  2069. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  2070. for (int k = 0; k < GGML_VEC_MAD_UNROLL; ++k) {
  2071. ax[k][j] = GGML_F32_VEC_LOAD(x[k] + i + j*GGML_F32_EPR);
  2072. ay[j] = GGML_F32_VEC_FMA(ay[j], ax[k][j], vx[k]);
  2073. }
  2074. GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
  2075. }
  2076. }
  2077. // leftovers
  2078. for (int k = 0; k < GGML_VEC_MAD_UNROLL; ++k) {
  2079. for (int i = np; i < n; ++i) {
  2080. y[i] += x[k][i]*v[k][0];
  2081. }
  2082. }
  2083. #else
  2084. // scalar
  2085. for (int k = 0; k < GGML_VEC_MAD_UNROLL; ++k) {
  2086. for (int i = 0; i < n; ++i) {
  2087. y[i] += x[k][i]*v[k][0];
  2088. }
  2089. }
  2090. #endif
  2091. }
  2092. //inline static void ggml_vec_scale_f32(const int n, float * y, const float v) { for (int i = 0; i < n; ++i) y[i] *= v; }
  2093. inline static void ggml_vec_scale_f32(const int n, float * y, const float v) {
  2094. #if defined(GGML_USE_ACCELERATE)
  2095. vDSP_vsmul(y, 1, &v, y, 1, n);
  2096. #elif defined(GGML_SIMD)
  2097. const int np = (n & ~(GGML_F32_STEP - 1));
  2098. GGML_F32_VEC vx = GGML_F32_VEC_SET1(v);
  2099. GGML_F32_VEC ay[GGML_F32_ARR];
  2100. for (int i = 0; i < np; i += GGML_F32_STEP) {
  2101. for (int j = 0; j < GGML_F32_ARR; j++) {
  2102. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  2103. ay[j] = GGML_F32_VEC_MUL(ay[j], vx);
  2104. GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
  2105. }
  2106. }
  2107. // leftovers
  2108. for (int i = np; i < n; ++i) {
  2109. y[i] *= v;
  2110. }
  2111. #else
  2112. // scalar
  2113. for (int i = 0; i < n; ++i) {
  2114. y[i] *= v;
  2115. }
  2116. #endif
  2117. }
  2118. inline static void ggml_vec_scale_f16(const int n, ggml_fp16_t * y, const float v) {
  2119. #if defined(GGML_SIMD)
  2120. const int np = (n & ~(GGML_F16_STEP - 1));
  2121. GGML_F16_VEC vx = GGML_F16_VEC_SET1(v);
  2122. GGML_F16_VEC ay[GGML_F16_ARR];
  2123. for (int i = 0; i < np; i += GGML_F16_STEP) {
  2124. for (int j = 0; j < GGML_F16_ARR; j++) {
  2125. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  2126. ay[j] = GGML_F16_VEC_MUL(ay[j], vx);
  2127. GGML_F16_VEC_STORE(y + i + j*GGML_F16_EPR, ay, j);
  2128. }
  2129. }
  2130. // leftovers
  2131. for (int i = np; i < n; ++i) {
  2132. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i])*v);
  2133. }
  2134. #else
  2135. // scalar
  2136. for (int i = 0; i < n; ++i) {
  2137. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i])*v);
  2138. }
  2139. #endif
  2140. }
  2141. inline static void ggml_vec_norm_f32 (const int n, float * s, const float * x) { ggml_vec_dot_f32(n, s, 0, x, 0, x, 0, 1); *s = sqrtf(*s); }
  2142. inline static void ggml_vec_sqr_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = x[i]*x[i]; }
  2143. inline static void ggml_vec_sqrt_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = sqrtf(x[i]); }
  2144. inline static void ggml_vec_log_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = logf(x[i]); }
  2145. inline static void ggml_vec_sin_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = sinf(x[i]); }
  2146. inline static void ggml_vec_cos_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = cosf(x[i]); }
  2147. inline static void ggml_vec_abs_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = fabsf(x[i]); }
  2148. inline static void ggml_vec_sgn_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = (x[i] > 0.f) ? 1.f : ((x[i] < 0.f) ? -1.f : 0.f); }
  2149. inline static void ggml_vec_step_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = (x[i] > 0.f) ? 1.f : 0.f; }
  2150. inline static void ggml_vec_tanh_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = tanhf(x[i]); }
  2151. inline static void ggml_vec_elu_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = (x[i] > 0.f) ? x[i] : expm1f(x[i]); }
  2152. inline static void ggml_vec_relu_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = (x[i] > 0.f) ? x[i] : 0.f; }
  2153. inline static void ggml_vec_leaky_relu_f32 (const int n, float * y, const float * x, const float ns) { for (int i = 0; i < n; ++i) y[i] = ((x[i] > 0.f) ? x[i] : 0.f) + ns * ((x[i] < 0.0f) ? x[i] : 0.f); }
  2154. inline static void ggml_vec_sigmoid_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = 1.f / (1.f + expf(-x[i])); }
  2155. // TODO: optimize performance
  2156. inline static void ggml_vec_hardswish_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = x[i] * fminf(1.0f, fmaxf(0.0f, (x[i] + 3.0f) / 6.0f)); }
  2157. inline static void ggml_vec_hardsigmoid_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = fminf(1.0f, fmaxf(0.0f, (x[i] + 3.0f) / 6.0f)); }
  2158. inline static void ggml_vec_exp_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = expf(x[i]); }
  2159. static const float GELU_COEF_A = 0.044715f;
  2160. static const float GELU_QUICK_COEF = -1.702f;
  2161. static const float SQRT_2_OVER_PI = 0.79788456080286535587989211986876f;
  2162. inline static float ggml_gelu_f32(float x) {
  2163. return 0.5f*x*(1.0f + tanhf(SQRT_2_OVER_PI*x*(1.0f + GELU_COEF_A*x*x)));
  2164. }
  2165. inline static void ggml_vec_gelu_f16(const int n, ggml_fp16_t * y, const ggml_fp16_t * x) {
  2166. const uint16_t * i16 = (const uint16_t *) x;
  2167. for (int i = 0; i < n; ++i) {
  2168. y[i] = ggml_table_gelu_f16[i16[i]];
  2169. }
  2170. }
  2171. #ifdef GGML_GELU_FP16
  2172. inline static void ggml_vec_gelu_f32(const int n, float * y, const float * x) {
  2173. uint16_t t;
  2174. for (int i = 0; i < n; ++i) {
  2175. if (x[i] <= -10.0f) {
  2176. y[i] = 0.0f;
  2177. } else if (x[i] >= 10.0f) {
  2178. y[i] = x[i];
  2179. } else {
  2180. ggml_fp16_t fp16 = GGML_FP32_TO_FP16(x[i]);
  2181. memcpy(&t, &fp16, sizeof(uint16_t));
  2182. y[i] = GGML_FP16_TO_FP32(ggml_table_gelu_f16[t]);
  2183. }
  2184. }
  2185. }
  2186. #else
  2187. inline static void ggml_vec_gelu_f32(const int n, float * y, const float * x) {
  2188. for (int i = 0; i < n; ++i) {
  2189. y[i] = ggml_gelu_f32(x[i]);
  2190. }
  2191. }
  2192. #endif
  2193. inline static float ggml_gelu_quick_f32(float x) {
  2194. return x*(1.0f/(1.0f+expf(GELU_QUICK_COEF*x)));
  2195. }
  2196. //inline static void ggml_vec_gelu_quick_f16(const int n, ggml_fp16_t * y, const ggml_fp16_t * x) {
  2197. // const uint16_t * i16 = (const uint16_t *) x;
  2198. // for (int i = 0; i < n; ++i) {
  2199. // y[i] = ggml_table_gelu_quick_f16[i16[i]];
  2200. // }
  2201. //}
  2202. #ifdef GGML_GELU_QUICK_FP16
  2203. inline static void ggml_vec_gelu_quick_f32(const int n, float * y, const float * x) {
  2204. uint16_t t;
  2205. for (int i = 0; i < n; ++i) {
  2206. ggml_fp16_t fp16 = GGML_FP32_TO_FP16(x[i]);
  2207. memcpy(&t, &fp16, sizeof(uint16_t));
  2208. y[i] = GGML_FP16_TO_FP32(ggml_table_gelu_quick_f16[t]);
  2209. }
  2210. }
  2211. #else
  2212. inline static void ggml_vec_gelu_quick_f32(const int n, float * y, const float * x) {
  2213. for (int i = 0; i < n; ++i) {
  2214. y[i] = ggml_gelu_quick_f32(x[i]);
  2215. }
  2216. }
  2217. #endif
  2218. // Sigmoid Linear Unit (SiLU) function
  2219. inline static float ggml_silu_f32(float x) {
  2220. return x/(1.0f + expf(-x));
  2221. }
  2222. #if __FINITE_MATH_ONLY__
  2223. #error "some routines in ggml.c require non-finite math arithmetics -- pass -fno-finite-math-only to the compiler to fix"
  2224. #error "ref: https://github.com/ggerganov/llama.cpp/pull/7154#issuecomment-2143844461"
  2225. #endif
  2226. #if defined(__ARM_NEON) && defined(__aarch64__)
  2227. // adapted from arm limited optimized routine
  2228. // the maximum error is 1.45358 plus 0.5 ulps
  2229. // numbers above 88.38 will flush to infinity
  2230. // numbers beneath -103.97 will flush to zero
  2231. inline static float32x4_t ggml_v_expf(float32x4_t x) {
  2232. const float32x4_t r = vdupq_n_f32(0x1.8p23f);
  2233. const float32x4_t z = vfmaq_f32(r, x, vdupq_n_f32(0x1.715476p+0f));
  2234. const float32x4_t n = vsubq_f32(z, r);
  2235. const float32x4_t b = vfmsq_f32(vfmsq_f32(x, n, vdupq_n_f32(0x1.62e4p-1f)), n,
  2236. vdupq_n_f32(0x1.7f7d1cp-20f));
  2237. const uint32x4_t e = vshlq_n_u32(vreinterpretq_u32_f32(z), 23);
  2238. const float32x4_t k = vreinterpretq_f32_u32(vaddq_u32(e, vreinterpretq_u32_f32(vdupq_n_f32(1))));
  2239. const uint32x4_t c = vcagtq_f32(n, vdupq_n_f32(126));
  2240. const float32x4_t u = vmulq_f32(b, b);
  2241. const float32x4_t j = vfmaq_f32(
  2242. vmulq_f32(vdupq_n_f32(0x1.ffffecp-1f), b),
  2243. vfmaq_f32(vfmaq_f32(vdupq_n_f32(0x1.fffdb6p-2f), vdupq_n_f32(0x1.555e66p-3f), b),
  2244. vfmaq_f32(vdupq_n_f32(0x1.573e2ep-5f), vdupq_n_f32(0x1.0e4020p-7f), b), u), u);
  2245. if (!vpaddd_u64(vreinterpretq_u64_u32(c)))
  2246. return vfmaq_f32(k, j, k);
  2247. const uint32x4_t d = vandq_u32(vclezq_f32(n), vdupq_n_u32(0x82000000));
  2248. const float32x4_t s1 = vreinterpretq_f32_u32(vaddq_u32(d, vdupq_n_u32(0x7f000000)));
  2249. const float32x4_t s2 = vreinterpretq_f32_u32(vsubq_u32(e, d));
  2250. return vbslq_f32(vcagtq_f32(n, vdupq_n_f32(192)), vmulq_f32(s1, s1),
  2251. vbslq_f32(c, vmulq_f32(vfmaq_f32(s2, s2, j), s1), vfmaq_f32(k, k, j)));
  2252. }
  2253. // computes silu x/(1+exp(-x)) in single precision vector
  2254. inline static float32x4_t ggml_v_silu(float32x4_t x) {
  2255. const float32x4_t one = vdupq_n_f32(1.0f);
  2256. const float32x4_t zero = vdupq_n_f32(0.0f);
  2257. const float32x4_t neg_x = vsubq_f32(zero, x);
  2258. const float32x4_t exp_neg_x = ggml_v_expf(neg_x);
  2259. const float32x4_t one_plus_exp_neg_x = vaddq_f32(one, exp_neg_x);
  2260. return vdivq_f32(x, one_plus_exp_neg_x);
  2261. }
  2262. #elif defined(__AVX512F__) && defined(__AVX512DQ__)
  2263. // adapted from arm limited optimized routine
  2264. // the maximum error is 1.45358 plus 0.5 ulps
  2265. // numbers above 88.38 will flush to infinity
  2266. // numbers beneath -103.97 will flush to zero
  2267. inline static __m512 ggml_v_expf(__m512 x) {
  2268. const __m512 r = _mm512_set1_ps(0x1.8p23f);
  2269. const __m512 z = _mm512_fmadd_ps(x, _mm512_set1_ps(0x1.715476p+0f), r);
  2270. const __m512 n = _mm512_sub_ps(z, r);
  2271. const __m512 b =
  2272. _mm512_fnmadd_ps(n, _mm512_set1_ps(0x1.7f7d1cp-20f),
  2273. _mm512_fnmadd_ps(n, _mm512_set1_ps(0x1.62e4p-1f), x));
  2274. const __mmask16 d =
  2275. _mm512_cmp_ps_mask(_mm512_abs_ps(n), _mm512_set1_ps(192), _CMP_GT_OQ);
  2276. const __m512 u = _mm512_mul_ps(b, b);
  2277. const __m512 j = _mm512_fmadd_ps(
  2278. _mm512_fmadd_ps(_mm512_fmadd_ps(_mm512_set1_ps(0x1.0e4020p-7f), b,
  2279. _mm512_set1_ps(0x1.573e2ep-5f)),
  2280. u,
  2281. _mm512_fmadd_ps(_mm512_set1_ps(0x1.555e66p-3f), b,
  2282. _mm512_set1_ps(0x1.fffdb6p-2f))),
  2283. u,
  2284. _mm512_fmadd_ps(_mm512_set1_ps(0x1.ffffecp-1f), b, _mm512_set1_ps(1.0F)));
  2285. const __m512 res = _mm512_scalef_ps(j, n);
  2286. if (_mm512_kortestz(d, d))
  2287. return res;
  2288. const __m512 zero = _mm512_setzero_ps();
  2289. const __m512 alt = _mm512_mask_blend_ps(
  2290. _mm512_cmp_ps_mask(n, zero, _CMP_LE_OQ), _mm512_set1_ps(INFINITY), zero);
  2291. return _mm512_mask_blend_ps(d, res, alt);
  2292. }
  2293. // computes silu x/(1+exp(-x)) in single precision vector
  2294. inline static __m512 ggml_v_silu(__m512 x) {
  2295. const __m512 one = _mm512_set1_ps(1);
  2296. const __m512 zero = _mm512_setzero_ps();
  2297. const __m512 neg_x = _mm512_sub_ps(zero, x);
  2298. const __m512 exp_neg_x = ggml_v_expf(neg_x);
  2299. const __m512 one_plus_exp_neg_x = _mm512_add_ps(one, exp_neg_x);
  2300. return _mm512_div_ps(x, one_plus_exp_neg_x);
  2301. }
  2302. #elif defined(__AVX2__) && defined(__FMA__)
  2303. // adapted from arm limited optimized routine
  2304. // the maximum error is 1.45358 plus 0.5 ulps
  2305. // numbers above 88.38 will flush to infinity
  2306. // numbers beneath -103.97 will flush to zero
  2307. inline static __m256 ggml_v_expf(__m256 x) {
  2308. const __m256 r = _mm256_set1_ps(0x1.8p23f);
  2309. const __m256 z = _mm256_fmadd_ps(x, _mm256_set1_ps(0x1.715476p+0f), r);
  2310. const __m256 n = _mm256_sub_ps(z, r);
  2311. const __m256 b = _mm256_fnmadd_ps(n, _mm256_set1_ps(0x1.7f7d1cp-20f),
  2312. _mm256_fnmadd_ps(n, _mm256_set1_ps(0x1.62e4p-1f), x));
  2313. const __m256i e = _mm256_slli_epi32(_mm256_castps_si256(z), 23);
  2314. const __m256 k = _mm256_castsi256_ps(
  2315. _mm256_add_epi32(e, _mm256_castps_si256(_mm256_set1_ps(1))));
  2316. const __m256i c = _mm256_castps_si256(
  2317. _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.f), n),
  2318. _mm256_set1_ps(126), _CMP_GT_OQ));
  2319. const __m256 u = _mm256_mul_ps(b, b);
  2320. const __m256 j = _mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_set1_ps(0x1.0e4020p-7f), b,
  2321. _mm256_set1_ps(0x1.573e2ep-5f)), u,
  2322. _mm256_fmadd_ps(_mm256_set1_ps(0x1.555e66p-3f), b,
  2323. _mm256_set1_ps(0x1.fffdb6p-2f))),
  2324. u, _mm256_mul_ps(_mm256_set1_ps(0x1.ffffecp-1f), b));
  2325. if (!_mm256_movemask_ps(_mm256_castsi256_ps(c)))
  2326. return _mm256_fmadd_ps(j, k, k);
  2327. const __m256i g = _mm256_and_si256(
  2328. _mm256_castps_si256(_mm256_cmp_ps(n, _mm256_setzero_ps(), _CMP_LE_OQ)),
  2329. _mm256_set1_epi32(0x82000000u));
  2330. const __m256 s1 =
  2331. _mm256_castsi256_ps(_mm256_add_epi32(g, _mm256_set1_epi32(0x7f000000u)));
  2332. const __m256 s2 = _mm256_castsi256_ps(_mm256_sub_epi32(e, g));
  2333. const __m256i d = _mm256_castps_si256(
  2334. _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.f), n),
  2335. _mm256_set1_ps(192), _CMP_GT_OQ));
  2336. return _mm256_or_ps(
  2337. _mm256_and_ps(_mm256_castsi256_ps(d), _mm256_mul_ps(s1, s1)),
  2338. _mm256_andnot_ps(
  2339. _mm256_castsi256_ps(d),
  2340. _mm256_or_ps(
  2341. _mm256_and_ps(_mm256_castsi256_ps(c),
  2342. _mm256_mul_ps(_mm256_fmadd_ps(s2, j, s2), s1)),
  2343. _mm256_andnot_ps(_mm256_castsi256_ps(c), _mm256_fmadd_ps(k, j, k)))));
  2344. }
  2345. // computes silu x/(1+exp(-x)) in single precision vector
  2346. inline static __m256 ggml_v_silu(__m256 x) {
  2347. const __m256 one = _mm256_set1_ps(1);
  2348. const __m256 zero = _mm256_setzero_ps();
  2349. const __m256 neg_x = _mm256_sub_ps(zero, x);
  2350. const __m256 exp_neg_x = ggml_v_expf(neg_x);
  2351. const __m256 one_plus_exp_neg_x = _mm256_add_ps(one, exp_neg_x);
  2352. return _mm256_div_ps(x, one_plus_exp_neg_x);
  2353. }
  2354. #elif defined(__SSE2__) // __AVX2__ / __ARM_NEON
  2355. #if defined(__FMA__)
  2356. #define MADD128(x, y, z) _mm_fmadd_ps(x, y, z)
  2357. #define NMADD128(x, y, z) _mm_fnmadd_ps(x, y, z)
  2358. #else
  2359. #define MADD128(x, y, z) _mm_add_ps(_mm_mul_ps(x, y), z)
  2360. #define NMADD128(x, y, z) _mm_sub_ps(z, _mm_mul_ps(x, y))
  2361. #endif
  2362. // adapted from arm limited optimized routine
  2363. // the maximum error is 1.45358 plus 0.5 ulps
  2364. // numbers above 88.38 will flush to infinity
  2365. // numbers beneath -103.97 will flush to zero
  2366. inline static __m128 ggml_v_expf(__m128 x) {
  2367. const __m128 r = _mm_set1_ps(0x1.8p23f);
  2368. const __m128 z = MADD128(x, _mm_set1_ps(0x1.715476p+0f), r);
  2369. const __m128 n = _mm_sub_ps(z, r);
  2370. const __m128 b =
  2371. NMADD128(n, _mm_set1_ps(0x1.7f7d1cp-20f), NMADD128(n, _mm_set1_ps(0x1.62e4p-1f), x));
  2372. const __m128i e = _mm_slli_epi32(_mm_castps_si128(z), 23);
  2373. const __m128 k = _mm_castsi128_ps(_mm_add_epi32(e, _mm_castps_si128(_mm_set1_ps(1))));
  2374. const __m128i c =
  2375. _mm_castps_si128(_mm_cmpgt_ps(_mm_andnot_ps(_mm_set1_ps(-0.f), n), _mm_set1_ps(126)));
  2376. const __m128 u = _mm_mul_ps(b, b);
  2377. const __m128 j =
  2378. MADD128(MADD128(MADD128(_mm_set1_ps(0x1.0e4020p-7f), b, _mm_set1_ps(0x1.573e2ep-5f)), u,
  2379. MADD128(_mm_set1_ps(0x1.555e66p-3f), b, _mm_set1_ps(0x1.fffdb6p-2f))),
  2380. u, _mm_mul_ps(_mm_set1_ps(0x1.ffffecp-1f), b));
  2381. if (!_mm_movemask_epi8(c))
  2382. return MADD128(j, k, k);
  2383. const __m128i g = _mm_and_si128(_mm_castps_si128(_mm_cmple_ps(n, _mm_setzero_ps())),
  2384. _mm_set1_epi32(0x82000000u));
  2385. const __m128 s1 = _mm_castsi128_ps(_mm_add_epi32(g, _mm_set1_epi32(0x7f000000u)));
  2386. const __m128 s2 = _mm_castsi128_ps(_mm_sub_epi32(e, g));
  2387. const __m128i d =
  2388. _mm_castps_si128(_mm_cmpgt_ps(_mm_andnot_ps(_mm_set1_ps(-0.f), n), _mm_set1_ps(192)));
  2389. return _mm_or_ps(
  2390. _mm_and_ps(_mm_castsi128_ps(d), _mm_mul_ps(s1, s1)),
  2391. _mm_andnot_ps(_mm_castsi128_ps(d),
  2392. _mm_or_ps(_mm_and_ps(_mm_castsi128_ps(c), _mm_mul_ps(MADD128(s2, j, s2), s1)),
  2393. _mm_andnot_ps(_mm_castsi128_ps(c), MADD128(k, j, k)))));
  2394. }
  2395. // computes silu x/(1+exp(-x)) in single precision vector
  2396. inline static __m128 ggml_v_silu(__m128 x) {
  2397. const __m128 one = _mm_set1_ps(1);
  2398. const __m128 zero = _mm_setzero_ps();
  2399. const __m128 neg_x = _mm_sub_ps(zero, x);
  2400. const __m128 exp_neg_x = ggml_v_expf(neg_x);
  2401. const __m128 one_plus_exp_neg_x = _mm_add_ps(one, exp_neg_x);
  2402. return _mm_div_ps(x, one_plus_exp_neg_x);
  2403. }
  2404. #endif // __ARM_NEON / __AVX2__ / __SSE2__
  2405. static void ggml_vec_silu_f32(const int n, float * y, const float * x) {
  2406. int i = 0;
  2407. #if defined(__AVX512F__) && defined(__AVX512DQ__)
  2408. for (; i + 15 < n; i += 16) {
  2409. _mm512_storeu_ps(y + i, ggml_v_silu(_mm512_loadu_ps(x + i)));
  2410. }
  2411. #elif defined(__AVX2__) && defined(__FMA__)
  2412. for (; i + 7 < n; i += 8) {
  2413. _mm256_storeu_ps(y + i, ggml_v_silu(_mm256_loadu_ps(x + i)));
  2414. }
  2415. #elif defined(__SSE2__)
  2416. for (; i + 3 < n; i += 4) {
  2417. _mm_storeu_ps(y + i, ggml_v_silu(_mm_loadu_ps(x + i)));
  2418. }
  2419. #elif defined(__ARM_NEON) && defined(__aarch64__)
  2420. for (; i + 3 < n; i += 4) {
  2421. vst1q_f32(y + i, ggml_v_silu(vld1q_f32(x + i)));
  2422. }
  2423. #endif
  2424. for (; i < n; ++i) {
  2425. y[i] = ggml_silu_f32(x[i]);
  2426. }
  2427. }
  2428. static ggml_float ggml_vec_soft_max_f32(const int n, float * y, const float * x, float max) {
  2429. int i = 0;
  2430. ggml_float sum = 0;
  2431. #if defined(__AVX512F__) && defined(__AVX512DQ__)
  2432. for (; i + 15 < n; i += 16) {
  2433. __m512 val = ggml_v_expf(_mm512_sub_ps(_mm512_loadu_ps(x + i),
  2434. _mm512_set1_ps(max)));
  2435. _mm512_storeu_ps(y + i, val);
  2436. sum += (ggml_float)_mm512_reduce_add_ps(val);
  2437. }
  2438. #elif defined(__AVX2__) && defined(__FMA__)
  2439. for (; i + 7 < n; i += 8) {
  2440. __m256 val = ggml_v_expf(_mm256_sub_ps(_mm256_loadu_ps(x + i),
  2441. _mm256_set1_ps(max)));
  2442. _mm256_storeu_ps(y + i, val);
  2443. __m128 val2 = _mm_add_ps(_mm256_extractf128_ps(val, 1),
  2444. _mm256_castps256_ps128(val));
  2445. val2 = _mm_add_ps(val2, _mm_movehl_ps(val2, val2));
  2446. val2 = _mm_add_ss(val2, _mm_movehdup_ps(val2));
  2447. sum += (ggml_float)_mm_cvtss_f32(val2);
  2448. }
  2449. #elif defined(__SSE2__)
  2450. for (; i + 3 < n; i += 4) {
  2451. __m128 val = ggml_v_expf(_mm_sub_ps(_mm_loadu_ps(x + i),
  2452. _mm_set1_ps(max)));
  2453. _mm_storeu_ps(y + i, val);
  2454. #if defined(__AVX__) || defined(__AVX2__) || defined(__AVX512F__)
  2455. val = _mm_add_ps(val, _mm_movehl_ps(val, val));
  2456. val = _mm_add_ss(val, _mm_movehdup_ps(val));
  2457. #else
  2458. __m128 tmp = _mm_shuffle_ps(val, val, _MM_SHUFFLE(2, 3, 0, 1));
  2459. val = _mm_add_ps(val, tmp);
  2460. tmp = _mm_movehl_ps(tmp, val);
  2461. val = _mm_add_ss(val, tmp);
  2462. #endif
  2463. sum += (ggml_float)_mm_cvtss_f32(val);
  2464. }
  2465. #elif defined(__ARM_NEON) && defined(__aarch64__)
  2466. for (; i + 3 < n; i += 4) {
  2467. float32x4_t val = ggml_v_expf(vsubq_f32(vld1q_f32(x + i),
  2468. vdupq_n_f32(max)));
  2469. vst1q_f32(y + i, val);
  2470. sum += (ggml_float)vaddvq_f32(val);
  2471. }
  2472. #endif
  2473. for (; i < n; ++i) {
  2474. float val = expf(x[i] - max);
  2475. sum += (ggml_float)val;
  2476. y[i] = val;
  2477. }
  2478. return sum;
  2479. }
  2480. static ggml_float ggml_vec_log_soft_max_f32(const int n, float * y, const float * x, float max) {
  2481. // log(soft_max) = log(soft_max_i / soft_max_sum) = log(soft_max_i) - log(soft_max_sum) = (logit_i - max) - log(soft_max_i)
  2482. int i = 0;
  2483. ggml_float sum = 0;
  2484. for (; i < n; ++i) {
  2485. float val = x[i] - max;
  2486. y[i] = val;
  2487. sum += (ggml_float)expf(val);
  2488. }
  2489. return sum = (ggml_float)logf(sum);
  2490. }
  2491. inline static float ggml_silu_backward_f32(float x, float dy) {
  2492. const float s = 1.0f/(1.0f + expf(-x));
  2493. return dy*s*(1.0f + x*(1.0f - s));
  2494. }
  2495. inline static void ggml_vec_silu_backward_f32(const int n, float * dx, const float * x, const float * dy) {
  2496. for (int i = 0; i < n; ++i) {
  2497. dx[i] = ggml_silu_backward_f32(x[i], dy[i]);
  2498. }
  2499. }
  2500. inline static void ggml_vec_sum_f32(const int n, float * s, const float * x) {
  2501. #ifndef GGML_USE_ACCELERATE
  2502. ggml_float sum = 0.0;
  2503. for (int i = 0; i < n; ++i) {
  2504. sum += (ggml_float)x[i];
  2505. }
  2506. *s = sum;
  2507. #else
  2508. vDSP_sve(x, 1, s, n);
  2509. #endif
  2510. }
  2511. inline static void ggml_vec_sum_f32_ggf(const int n, ggml_float * s, const float * x) {
  2512. ggml_float sum = 0.0;
  2513. for (int i = 0; i < n; ++i) {
  2514. sum += (ggml_float)x[i];
  2515. }
  2516. *s = sum;
  2517. }
  2518. inline static void ggml_vec_sum_f16_ggf(const int n, float * s, const ggml_fp16_t * x) {
  2519. float sum = 0.0f;
  2520. for (int i = 0; i < n; ++i) {
  2521. sum += GGML_FP16_TO_FP32(x[i]);
  2522. }
  2523. *s = sum;
  2524. }
  2525. inline static void ggml_vec_sum_bf16_ggf(const int n, float * s, const ggml_bf16_t * x) {
  2526. float sum = 0.0f;
  2527. for (int i = 0; i < n; ++i) {
  2528. sum += GGML_BF16_TO_FP32(x[i]);
  2529. }
  2530. *s = sum;
  2531. }
  2532. inline static void ggml_vec_max_f32(const int n, float * s, const float * x) {
  2533. #ifndef GGML_USE_ACCELERATE
  2534. float max = -INFINITY;
  2535. for (int i = 0; i < n; ++i) {
  2536. max = MAX(max, x[i]);
  2537. }
  2538. *s = max;
  2539. #else
  2540. vDSP_maxv(x, 1, s, n);
  2541. #endif
  2542. }
  2543. inline static void ggml_vec_norm_inv_f32(const int n, float * s, const float * x) {
  2544. ggml_vec_norm_f32(n, s, x);
  2545. *s = 1.f/(*s);
  2546. }
  2547. inline static void ggml_vec_argmax_f32(const int n, int * s, const float * x) {
  2548. float max = -INFINITY;
  2549. int idx = 0;
  2550. for (int i = 0; i < n; ++i) {
  2551. max = MAX(max, x[i]);
  2552. if (max == x[i]) { idx = i; }
  2553. }
  2554. *s = idx;
  2555. }
  2556. //
  2557. // data types
  2558. //
  2559. static const char * GGML_OP_NAME[GGML_OP_COUNT] = {
  2560. "NONE",
  2561. "DUP",
  2562. "ADD",
  2563. "ADD1",
  2564. "ACC",
  2565. "SUB",
  2566. "MUL",
  2567. "DIV",
  2568. "SQR",
  2569. "SQRT",
  2570. "LOG",
  2571. "SIN",
  2572. "COS",
  2573. "SUM",
  2574. "SUM_ROWS",
  2575. "MEAN",
  2576. "ARGMAX",
  2577. "REPEAT",
  2578. "REPEAT_BACK",
  2579. "CONCAT",
  2580. "SILU_BACK",
  2581. "NORM",
  2582. "RMS_NORM",
  2583. "RMS_NORM_BACK",
  2584. "GROUP_NORM",
  2585. "MUL_MAT",
  2586. "MUL_MAT_ID",
  2587. "OUT_PROD",
  2588. "SCALE",
  2589. "SET",
  2590. "CPY",
  2591. "CONT",
  2592. "RESHAPE",
  2593. "VIEW",
  2594. "PERMUTE",
  2595. "TRANSPOSE",
  2596. "GET_ROWS",
  2597. "GET_ROWS_BACK",
  2598. "DIAG",
  2599. "DIAG_MASK_INF",
  2600. "DIAG_MASK_ZERO",
  2601. "SOFT_MAX",
  2602. "SOFT_MAX_BACK",
  2603. "ROPE",
  2604. "ROPE_BACK",
  2605. "CLAMP",
  2606. "CONV_TRANSPOSE_1D",
  2607. "IM2COL",
  2608. "IM2COL_BACK",
  2609. "CONV_TRANSPOSE_2D",
  2610. "POOL_1D",
  2611. "POOL_2D",
  2612. "POOL_2D_BACK",
  2613. "UPSCALE",
  2614. "PAD",
  2615. "ARANGE",
  2616. "TIMESTEP_EMBEDDING",
  2617. "ARGSORT",
  2618. "LEAKY_RELU",
  2619. "FLASH_ATTN_EXT",
  2620. "FLASH_ATTN_BACK",
  2621. "SSM_CONV",
  2622. "SSM_SCAN",
  2623. "WIN_PART",
  2624. "WIN_UNPART",
  2625. "GET_REL_POS",
  2626. "ADD_REL_POS",
  2627. "RWKV_WKV",
  2628. "UNARY",
  2629. "MAP_UNARY",
  2630. "MAP_BINARY",
  2631. "MAP_CUSTOM1_F32",
  2632. "MAP_CUSTOM2_F32",
  2633. "MAP_CUSTOM3_F32",
  2634. "MAP_CUSTOM1",
  2635. "MAP_CUSTOM2",
  2636. "MAP_CUSTOM3",
  2637. "CROSS_ENTROPY_LOSS",
  2638. "CROSS_ENTROPY_LOSS_BACK",
  2639. "OPT_STEP_ADAMW",
  2640. };
  2641. static_assert(GGML_OP_COUNT == 80, "GGML_OP_COUNT != 80");
  2642. static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = {
  2643. "none",
  2644. "x",
  2645. "x+y",
  2646. "x+y",
  2647. "view(x,nb,offset)+=y->x",
  2648. "x-y",
  2649. "x*y",
  2650. "x/y",
  2651. "x^2",
  2652. "√x",
  2653. "log(x)",
  2654. "sin(x)",
  2655. "cos(x)",
  2656. "Σx",
  2657. "Σx_k",
  2658. "Σx/n",
  2659. "argmax(x)",
  2660. "repeat(x)",
  2661. "repeat_back(x)",
  2662. "concat(x, y)",
  2663. "silu_back(x)",
  2664. "norm(x)",
  2665. "rms_norm(x)",
  2666. "rms_norm_back(x)",
  2667. "group_norm(x)",
  2668. "X*Y",
  2669. "X[i]*Y",
  2670. "X*Y",
  2671. "x*v",
  2672. "y-\\>view(x)",
  2673. "x-\\>y",
  2674. "cont(x)",
  2675. "reshape(x)",
  2676. "view(x)",
  2677. "permute(x)",
  2678. "transpose(x)",
  2679. "get_rows(x)",
  2680. "get_rows_back(x)",
  2681. "diag(x)",
  2682. "diag_mask_inf(x)",
  2683. "diag_mask_zero(x)",
  2684. "soft_max(x)",
  2685. "soft_max_back(x)",
  2686. "rope(x)",
  2687. "rope_back(x)",
  2688. "clamp(x)",
  2689. "conv_transpose_1d(x)",
  2690. "im2col(x)",
  2691. "im2col_back(x)",
  2692. "conv_transpose_2d(x)",
  2693. "pool_1d(x)",
  2694. "pool_2d(x)",
  2695. "pool_2d_back(x)",
  2696. "upscale(x)",
  2697. "pad(x)",
  2698. "arange(start, stop, step)",
  2699. "timestep_embedding(timesteps, dim, max_period)",
  2700. "argsort(x)",
  2701. "leaky_relu(x)",
  2702. "flash_attn_ext(x)",
  2703. "flash_attn_back(x)",
  2704. "ssm_conv(x)",
  2705. "ssm_scan(x)",
  2706. "win_part(x)",
  2707. "win_unpart(x)",
  2708. "get_rel_pos(x)",
  2709. "add_rel_pos(x)",
  2710. "rwkv_wkv(k, v, r, tf, td, s)",
  2711. "unary(x)",
  2712. "f(x)",
  2713. "f(x,y)",
  2714. "custom_f32(x)",
  2715. "custom_f32(x,y)",
  2716. "custom_f32(x,y,z)",
  2717. "custom(x)",
  2718. "custom(x,y)",
  2719. "custom(x,y,z)",
  2720. "cross_entropy_loss(x,y)",
  2721. "cross_entropy_loss_back(x,y)",
  2722. "adamw(x)",
  2723. };
  2724. static_assert(GGML_OP_COUNT == 80, "GGML_OP_COUNT != 80");
  2725. static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2");
  2726. static const char * GGML_UNARY_OP_NAME[GGML_UNARY_OP_COUNT] = {
  2727. "ABS",
  2728. "SGN",
  2729. "NEG",
  2730. "STEP",
  2731. "TANH",
  2732. "ELU",
  2733. "RELU",
  2734. "SIGMOID",
  2735. "GELU",
  2736. "GELU_QUICK",
  2737. "SILU",
  2738. "HARDSWISH",
  2739. "HARDSIGMOID",
  2740. "EXP",
  2741. };
  2742. static_assert(GGML_UNARY_OP_COUNT == 14, "GGML_UNARY_OP_COUNT != 14");
  2743. static_assert(sizeof(struct ggml_object)%GGML_MEM_ALIGN == 0, "ggml_object size must be a multiple of GGML_MEM_ALIGN");
  2744. static_assert(sizeof(struct ggml_tensor)%GGML_MEM_ALIGN == 0, "ggml_tensor size must be a multiple of GGML_MEM_ALIGN");
  2745. // Helpers for polling loops
  2746. #if defined(__aarch64__) && ( defined(__clang__) || defined(__GNUC__) )
  2747. static inline void ggml_thread_cpu_relax(void) {
  2748. __asm__ volatile("yield" ::: "memory");
  2749. }
  2750. #elif defined(__x86_64__)
  2751. static inline void ggml_thread_cpu_relax(void) {
  2752. _mm_pause();
  2753. }
  2754. #else
  2755. static inline void ggml_thread_cpu_relax(void) {;}
  2756. #endif
  2757. //
  2758. // NUMA support
  2759. //
  2760. #define GGML_NUMA_MAX_NODES 8
  2761. #define GGML_NUMA_MAX_CPUS 512
  2762. struct ggml_numa_node {
  2763. uint32_t cpus[GGML_NUMA_MAX_CPUS]; // hardware threads on this node
  2764. uint32_t n_cpus;
  2765. };
  2766. struct ggml_numa_nodes {
  2767. enum ggml_numa_strategy numa_strategy;
  2768. struct ggml_numa_node nodes[GGML_NUMA_MAX_NODES];
  2769. uint32_t n_nodes;
  2770. uint32_t total_cpus; // hardware threads on system
  2771. uint32_t current_node; // node on which main process is execting
  2772. #if defined(__gnu_linux__)
  2773. cpu_set_t cpuset; // cpuset from numactl
  2774. #else
  2775. uint32_t cpuset; // no NUMA support outside of Linux at this time. Use a portable datatype
  2776. #endif
  2777. };
  2778. //
  2779. // ggml state
  2780. //
  2781. struct ggml_state {
  2782. struct ggml_context_container contexts[GGML_MAX_CONTEXTS];
  2783. struct ggml_numa_nodes numa;
  2784. };
  2785. // global state
  2786. static struct ggml_state g_state;
  2787. static atomic_flag g_state_critical = ATOMIC_FLAG_INIT;
  2788. // critical section via spin lock
  2789. inline static void ggml_critical_section_start(void) {
  2790. while (atomic_flag_test_and_set(&g_state_critical)) {
  2791. // spin
  2792. sched_yield();
  2793. }
  2794. }
  2795. static void ggml_barrier(struct ggml_threadpool * tp) {
  2796. int n_threads = atomic_load_explicit(&tp->n_threads_cur, memory_order_relaxed);
  2797. if (n_threads == 1) {
  2798. return;
  2799. }
  2800. #ifdef GGML_USE_OPENMP
  2801. #pragma omp barrier
  2802. #else
  2803. int n_passed = atomic_load_explicit(&tp->n_barrier_passed, memory_order_relaxed);
  2804. // enter barrier (full seq-cst fence)
  2805. int n_barrier = atomic_fetch_add_explicit(&tp->n_barrier, 1, memory_order_seq_cst);
  2806. if (n_barrier == (n_threads - 1)) {
  2807. // last thread
  2808. atomic_store_explicit(&tp->n_barrier, 0, memory_order_relaxed);
  2809. // exit barrier (fill seq-cst fence)
  2810. atomic_fetch_add_explicit(&tp->n_barrier_passed, 1, memory_order_seq_cst);
  2811. return;
  2812. }
  2813. // wait for other threads
  2814. while (atomic_load_explicit(&tp->n_barrier_passed, memory_order_relaxed) == n_passed) {
  2815. ggml_thread_cpu_relax();
  2816. }
  2817. // exit barrier (full seq-cst fence)
  2818. // TSAN doesn't support standalone fence yet, we use a dummy read-modify-write instead
  2819. #ifdef GGML_TSAN_ENABLED
  2820. atomic_fetch_add_explicit(&tp->n_barrier_passed, 0, memory_order_seq_cst);
  2821. #else
  2822. atomic_thread_fence(memory_order_seq_cst);
  2823. #endif
  2824. #endif
  2825. }
  2826. // TODO: make this somehow automatically executed
  2827. // some sort of "sentry" mechanism
  2828. inline static void ggml_critical_section_end(void) {
  2829. atomic_flag_clear(&g_state_critical);
  2830. }
  2831. #if defined(__gnu_linux__)
  2832. static cpu_set_t ggml_get_numa_affinity(void) {
  2833. cpu_set_t cpuset;
  2834. pthread_t thread;
  2835. thread = pthread_self();
  2836. CPU_ZERO(&cpuset);
  2837. pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
  2838. return cpuset;
  2839. }
  2840. #else
  2841. static uint32_t ggml_get_numa_affinity(void) {
  2842. return 0; // no NUMA support
  2843. }
  2844. #endif
  2845. void ggml_numa_init(enum ggml_numa_strategy numa_flag) {
  2846. if (g_state.numa.n_nodes > 0) {
  2847. fprintf(stderr, "ggml_numa_init: NUMA already initialized\n");
  2848. return;
  2849. }
  2850. #if defined(__gnu_linux__)
  2851. struct stat st;
  2852. char path[256];
  2853. int rv;
  2854. // set numa scheme
  2855. g_state.numa.numa_strategy = numa_flag;
  2856. GGML_PRINT_DEBUG("numa strategy %u\n",g_state.numa.numa_strategy);
  2857. g_state.numa.cpuset = ggml_get_numa_affinity();
  2858. // enumerate nodes
  2859. while (g_state.numa.n_nodes < GGML_NUMA_MAX_NODES) {
  2860. rv = snprintf(path, sizeof(path), "/sys/devices/system/node/node%u", g_state.numa.n_nodes);
  2861. GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path));
  2862. if (stat(path, &st) != 0) { break; }
  2863. ++g_state.numa.n_nodes;
  2864. }
  2865. // enumerate CPUs
  2866. while (g_state.numa.total_cpus < GGML_NUMA_MAX_CPUS) {
  2867. rv = snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%u", g_state.numa.total_cpus);
  2868. GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path));
  2869. if (stat(path, &st) != 0) { break; }
  2870. ++g_state.numa.total_cpus;
  2871. }
  2872. GGML_PRINT_DEBUG("found %u numa nodes, %u CPUs\n", g_state.numa.n_nodes, g_state.numa.total_cpus);
  2873. // figure out which node we're on
  2874. uint current_cpu;
  2875. int getcpu_ret = 0;
  2876. #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 28) || defined(__COSMOPOLITAN__)
  2877. getcpu_ret = getcpu(&current_cpu, &g_state.numa.current_node);
  2878. #else
  2879. // old glibc doesn't have a wrapper for this call. Fall back on direct syscall
  2880. # if !defined(SYS_getcpu) && defined(SYS_get_cpu)
  2881. # define SYS_getcpu SYS_get_cpu // some older glibc versions use this name
  2882. # endif
  2883. getcpu_ret = syscall(SYS_getcpu, &current_cpu, &g_state.numa.current_node);
  2884. #endif
  2885. if (g_state.numa.n_nodes < 1 || g_state.numa.total_cpus < 1 || getcpu_ret != 0) {
  2886. g_state.numa.n_nodes = 0;
  2887. return;
  2888. }
  2889. GGML_PRINT_DEBUG("found our process on numa node %u, CPU %u\n", g_state.numa.current_node, current_cpu);
  2890. for (uint32_t n = 0; n < g_state.numa.n_nodes; ++n) {
  2891. struct ggml_numa_node * node = &g_state.numa.nodes[n];
  2892. GGML_PRINT_DEBUG("CPUs on node %u:", n);
  2893. node->n_cpus = 0;
  2894. for (uint32_t c = 0; c < g_state.numa.total_cpus; ++c) {
  2895. rv = snprintf(path, sizeof(path), "/sys/devices/system/node/node%u/cpu%u", n, c);
  2896. GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path));
  2897. if (stat(path, &st) == 0) {
  2898. node->cpus[node->n_cpus++] = c;
  2899. GGML_PRINT_DEBUG(" %u", c);
  2900. }
  2901. }
  2902. GGML_PRINT_DEBUG("\n");
  2903. }
  2904. if (ggml_is_numa()) {
  2905. FILE *fptr = fopen("/proc/sys/kernel/numa_balancing", "r");
  2906. if (fptr != NULL) {
  2907. char buf[42];
  2908. if (fgets(buf, sizeof(buf), fptr) && strncmp(buf, "0\n", sizeof(buf)) != 0) {
  2909. GGML_PRINT("WARNING: /proc/sys/kernel/numa_balancing is enabled, this has been observed to impair performance\n");
  2910. }
  2911. fclose(fptr);
  2912. }
  2913. }
  2914. #else
  2915. UNUSED(numa_flag);
  2916. // TODO
  2917. #endif
  2918. }
  2919. bool ggml_is_numa(void) {
  2920. return g_state.numa.n_nodes > 1;
  2921. }
  2922. ////////////////////////////////////////////////////////////////////////////////
  2923. void ggml_print_object(const struct ggml_object * obj) {
  2924. GGML_PRINT(" - ggml_object: type = %d, offset = %zu, size = %zu, next = %p\n",
  2925. obj->type, obj->offs, obj->size, (const void *) obj->next);
  2926. }
  2927. void ggml_print_objects(const struct ggml_context * ctx) {
  2928. struct ggml_object * obj = ctx->objects_begin;
  2929. GGML_PRINT("%s: objects in context %p:\n", __func__, (const void *) ctx);
  2930. while (obj != NULL) {
  2931. ggml_print_object(obj);
  2932. obj = obj->next;
  2933. }
  2934. GGML_PRINT("%s: --- end ---\n", __func__);
  2935. }
  2936. GGML_CALL int64_t ggml_nelements(const struct ggml_tensor * tensor) {
  2937. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2938. return tensor->ne[0]*tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
  2939. }
  2940. GGML_CALL int64_t ggml_nrows(const struct ggml_tensor * tensor) {
  2941. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2942. return tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
  2943. }
  2944. GGML_CALL size_t ggml_nbytes(const struct ggml_tensor * tensor) {
  2945. size_t nbytes;
  2946. size_t blck_size = ggml_blck_size(tensor->type);
  2947. if (blck_size == 1) {
  2948. nbytes = ggml_type_size(tensor->type);
  2949. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  2950. nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
  2951. }
  2952. }
  2953. else {
  2954. nbytes = tensor->ne[0]*tensor->nb[0]/blck_size;
  2955. for (int i = 1; i < GGML_MAX_DIMS; ++i) {
  2956. nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
  2957. }
  2958. }
  2959. return nbytes;
  2960. }
  2961. size_t ggml_nbytes_pad(const struct ggml_tensor * tensor) {
  2962. return GGML_PAD(ggml_nbytes(tensor), GGML_MEM_ALIGN);
  2963. }
  2964. GGML_CALL int64_t ggml_blck_size(enum ggml_type type) {
  2965. return type_traits[type].blck_size;
  2966. }
  2967. GGML_CALL size_t ggml_type_size(enum ggml_type type) {
  2968. return type_traits[type].type_size;
  2969. }
  2970. GGML_CALL size_t ggml_row_size(enum ggml_type type, int64_t ne) {
  2971. assert(ne % ggml_blck_size(type) == 0);
  2972. return ggml_type_size(type)*ne/ggml_blck_size(type);
  2973. }
  2974. double ggml_type_sizef(enum ggml_type type) {
  2975. return ((double)(type_traits[type].type_size))/type_traits[type].blck_size;
  2976. }
  2977. GGML_CALL const char * ggml_type_name(enum ggml_type type) {
  2978. return type < GGML_TYPE_COUNT ? type_traits[type].type_name : "NONE";
  2979. }
  2980. GGML_CALL bool ggml_is_quantized(enum ggml_type type) {
  2981. return type_traits[type].is_quantized;
  2982. }
  2983. GGML_CALL const char * ggml_op_name(enum ggml_op op) {
  2984. return GGML_OP_NAME[op];
  2985. }
  2986. const char * ggml_op_symbol(enum ggml_op op) {
  2987. return GGML_OP_SYMBOL[op];
  2988. }
  2989. const char * ggml_unary_op_name(enum ggml_unary_op op) {
  2990. return GGML_UNARY_OP_NAME[op];
  2991. }
  2992. GGML_CALL const char * ggml_op_desc(const struct ggml_tensor * t) {
  2993. if (t->op == GGML_OP_UNARY) {
  2994. enum ggml_unary_op uop = ggml_get_unary_op(t);
  2995. return ggml_unary_op_name(uop);
  2996. }
  2997. return ggml_op_name(t->op);
  2998. }
  2999. GGML_CALL size_t ggml_element_size(const struct ggml_tensor * tensor) {
  3000. return ggml_type_size(tensor->type);
  3001. }
  3002. bool ggml_is_scalar(const struct ggml_tensor * tensor) {
  3003. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3004. return tensor->ne[0] == 1 && tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  3005. }
  3006. bool ggml_is_vector(const struct ggml_tensor * tensor) {
  3007. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3008. return tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  3009. }
  3010. bool ggml_is_matrix(const struct ggml_tensor * tensor) {
  3011. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3012. return tensor->ne[2] == 1 && tensor->ne[3] == 1;
  3013. }
  3014. bool ggml_is_3d(const struct ggml_tensor * tensor) {
  3015. return tensor->ne[3] == 1;
  3016. }
  3017. int ggml_n_dims(const struct ggml_tensor * tensor) {
  3018. for (int i = GGML_MAX_DIMS - 1; i >= 1; --i) {
  3019. if (tensor->ne[i] > 1) {
  3020. return i + 1;
  3021. }
  3022. }
  3023. return 1;
  3024. }
  3025. static inline bool ggml_can_mul_mat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3026. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3027. return (t0->ne[0] == t1->ne[0]) &&
  3028. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  3029. (t1->ne[3]%t0->ne[3] == 0);
  3030. }
  3031. static inline bool ggml_can_out_prod(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3032. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3033. return (t0->ne[1] == t1->ne[1]) &&
  3034. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  3035. (t1->ne[3]%t0->ne[3] == 0);
  3036. }
  3037. enum ggml_type ggml_ftype_to_ggml_type(enum ggml_ftype ftype) {
  3038. enum ggml_type wtype = GGML_TYPE_COUNT;
  3039. switch (ftype) {
  3040. case GGML_FTYPE_ALL_F32: wtype = GGML_TYPE_F32; break;
  3041. case GGML_FTYPE_MOSTLY_F16: wtype = GGML_TYPE_F16; break;
  3042. case GGML_FTYPE_MOSTLY_BF16: wtype = GGML_TYPE_BF16; break;
  3043. case GGML_FTYPE_MOSTLY_Q4_0: wtype = GGML_TYPE_Q4_0; break;
  3044. case GGML_FTYPE_MOSTLY_Q4_1: wtype = GGML_TYPE_Q4_1; break;
  3045. case GGML_FTYPE_MOSTLY_Q5_0: wtype = GGML_TYPE_Q5_0; break;
  3046. case GGML_FTYPE_MOSTLY_Q5_1: wtype = GGML_TYPE_Q5_1; break;
  3047. case GGML_FTYPE_MOSTLY_Q8_0: wtype = GGML_TYPE_Q8_0; break;
  3048. case GGML_FTYPE_MOSTLY_Q2_K: wtype = GGML_TYPE_Q2_K; break;
  3049. case GGML_FTYPE_MOSTLY_Q3_K: wtype = GGML_TYPE_Q3_K; break;
  3050. case GGML_FTYPE_MOSTLY_Q4_K: wtype = GGML_TYPE_Q4_K; break;
  3051. case GGML_FTYPE_MOSTLY_Q5_K: wtype = GGML_TYPE_Q5_K; break;
  3052. case GGML_FTYPE_MOSTLY_Q6_K: wtype = GGML_TYPE_Q6_K; break;
  3053. case GGML_FTYPE_MOSTLY_IQ2_XXS: wtype = GGML_TYPE_IQ2_XXS; break;
  3054. case GGML_FTYPE_MOSTLY_IQ2_XS: wtype = GGML_TYPE_IQ2_XS; break;
  3055. case GGML_FTYPE_MOSTLY_IQ3_XXS: wtype = GGML_TYPE_IQ3_XXS; break;
  3056. case GGML_FTYPE_MOSTLY_IQ1_S: wtype = GGML_TYPE_IQ1_S; break;
  3057. case GGML_FTYPE_MOSTLY_IQ1_M: wtype = GGML_TYPE_IQ1_M; break;
  3058. case GGML_FTYPE_MOSTLY_IQ4_NL: wtype = GGML_TYPE_IQ4_NL; break;
  3059. case GGML_FTYPE_MOSTLY_IQ4_XS: wtype = GGML_TYPE_IQ4_XS; break;
  3060. case GGML_FTYPE_MOSTLY_IQ3_S: wtype = GGML_TYPE_IQ3_S; break;
  3061. case GGML_FTYPE_MOSTLY_IQ2_S: wtype = GGML_TYPE_IQ2_S; break;
  3062. case GGML_FTYPE_MOSTLY_Q4_0_4_4: wtype = GGML_TYPE_Q4_0_4_4; break;
  3063. case GGML_FTYPE_MOSTLY_Q4_0_4_8: wtype = GGML_TYPE_Q4_0_4_8; break;
  3064. case GGML_FTYPE_MOSTLY_Q4_0_8_8: wtype = GGML_TYPE_Q4_0_8_8; break;
  3065. case GGML_FTYPE_UNKNOWN: wtype = GGML_TYPE_COUNT; break;
  3066. case GGML_FTYPE_MOSTLY_Q4_1_SOME_F16: wtype = GGML_TYPE_COUNT; break;
  3067. }
  3068. GGML_ASSERT(wtype != GGML_TYPE_COUNT);
  3069. return wtype;
  3070. }
  3071. size_t ggml_tensor_overhead(void) {
  3072. return GGML_OBJECT_SIZE + GGML_TENSOR_SIZE;
  3073. }
  3074. GGML_CALL bool ggml_is_transposed(const struct ggml_tensor * tensor) {
  3075. return tensor->nb[0] > tensor->nb[1];
  3076. }
  3077. static bool ggml_is_contiguous_n(const struct ggml_tensor * tensor, int n) {
  3078. size_t next_nb = ggml_type_size(tensor->type);
  3079. if (tensor->ne[0] != ggml_blck_size(tensor->type) && tensor->nb[0] != next_nb) {
  3080. return false;
  3081. }
  3082. next_nb *= tensor->ne[0]/ggml_blck_size(tensor->type);
  3083. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3084. if (tensor->ne[i] != 1) {
  3085. if (i > n) {
  3086. if (tensor->nb[i] != next_nb) {
  3087. return false;
  3088. }
  3089. next_nb *= tensor->ne[i];
  3090. } else {
  3091. // this dimension does not need to be contiguous
  3092. next_nb = tensor->ne[i]*tensor->nb[i];
  3093. }
  3094. }
  3095. }
  3096. return true;
  3097. }
  3098. GGML_CALL bool ggml_is_contiguous(const struct ggml_tensor * tensor) {
  3099. return ggml_is_contiguous_0(tensor);
  3100. }
  3101. GGML_CALL bool ggml_is_contiguous_0(const struct ggml_tensor * tensor) {
  3102. return ggml_is_contiguous_n(tensor, 0);
  3103. }
  3104. GGML_CALL bool ggml_is_contiguous_1(const struct ggml_tensor * tensor) {
  3105. return ggml_is_contiguous_n(tensor, 1);
  3106. }
  3107. GGML_CALL bool ggml_is_contiguous_2(const struct ggml_tensor * tensor) {
  3108. return ggml_is_contiguous_n(tensor, 2);
  3109. }
  3110. GGML_CALL bool ggml_is_permuted(const struct ggml_tensor * tensor) {
  3111. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3112. return tensor->nb[0] > tensor->nb[1] || tensor->nb[1] > tensor->nb[2] || tensor->nb[2] > tensor->nb[3];
  3113. }
  3114. static inline bool ggml_is_padded_1d(const struct ggml_tensor * tensor) {
  3115. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3116. return
  3117. tensor->nb[0] == ggml_type_size(tensor->type) &&
  3118. tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
  3119. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  3120. }
  3121. GGML_CALL bool ggml_is_empty(const struct ggml_tensor * tensor) {
  3122. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  3123. if (tensor->ne[i] == 0) {
  3124. // empty if any dimension has no elements
  3125. return true;
  3126. }
  3127. }
  3128. return false;
  3129. }
  3130. bool ggml_are_same_shape(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3131. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3132. return
  3133. (t0->ne[0] == t1->ne[0]) &&
  3134. (t0->ne[1] == t1->ne[1]) &&
  3135. (t0->ne[2] == t1->ne[2]) &&
  3136. (t0->ne[3] == t1->ne[3]);
  3137. }
  3138. bool ggml_are_same_stride(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3139. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3140. return
  3141. (t0->nb[0] == t1->nb[0]) &&
  3142. (t0->nb[1] == t1->nb[1]) &&
  3143. (t0->nb[2] == t1->nb[2]) &&
  3144. (t0->nb[3] == t1->nb[3]);
  3145. }
  3146. // check if t1 can be represented as a repeatition of t0
  3147. bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3148. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3149. return ggml_is_empty(t0) ? ggml_is_empty(t1) :
  3150. (t1->ne[0]%t0->ne[0] == 0) &&
  3151. (t1->ne[1]%t0->ne[1] == 0) &&
  3152. (t1->ne[2]%t0->ne[2] == 0) &&
  3153. (t1->ne[3]%t0->ne[3] == 0);
  3154. }
  3155. static inline bool ggml_can_repeat_rows(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3156. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3157. return (t0->ne[0] == t1->ne[0]) && ggml_can_repeat(t0, t1);
  3158. }
  3159. static inline int ggml_up32(int n) {
  3160. return (n + 31) & ~31;
  3161. }
  3162. //static inline int ggml_up64(int n) {
  3163. // return (n + 63) & ~63;
  3164. //}
  3165. static inline int ggml_up(int n, int m) {
  3166. // assert m is a power of 2
  3167. GGML_ASSERT((m & (m - 1)) == 0);
  3168. return (n + m - 1) & ~(m - 1);
  3169. }
  3170. // assert that pointer is aligned to GGML_MEM_ALIGN
  3171. #define GGML_ASSERT_ALIGNED(ptr) \
  3172. GGML_ASSERT(((uintptr_t) (ptr))%GGML_MEM_ALIGN == 0)
  3173. ////////////////////////////////////////////////////////////////////////////////
  3174. #if defined(__ARM_ARCH)
  3175. #if defined(__linux__) && defined(__aarch64__)
  3176. #include <sys/auxv.h>
  3177. #elif defined(__APPLE__)
  3178. #include <sys/sysctl.h>
  3179. #endif
  3180. #if !defined(HWCAP2_I8MM)
  3181. #define HWCAP2_I8MM 0
  3182. #endif
  3183. static void ggml_init_arm_arch_features(void) {
  3184. #if defined(__linux__) && defined(__aarch64__)
  3185. uint32_t hwcap = getauxval(AT_HWCAP);
  3186. uint32_t hwcap2 = getauxval(AT_HWCAP2);
  3187. ggml_arm_arch_features.has_neon = !!(hwcap & HWCAP_ASIMD);
  3188. ggml_arm_arch_features.has_i8mm = !!(hwcap2 & HWCAP2_I8MM);
  3189. ggml_arm_arch_features.has_sve = !!(hwcap & HWCAP_SVE);
  3190. #if defined(__ARM_FEATURE_SVE)
  3191. ggml_arm_arch_features.sve_cnt = PR_SVE_VL_LEN_MASK & prctl(PR_SVE_GET_VL);
  3192. #endif
  3193. #elif defined(__APPLE__)
  3194. int oldp = 0;
  3195. size_t size = sizeof(oldp);
  3196. if (sysctlbyname("hw.optional.AdvSIMD", &oldp, &size, NULL, 0) != 0) {
  3197. oldp = 0;
  3198. }
  3199. ggml_arm_arch_features.has_neon = oldp;
  3200. if (sysctlbyname("hw.optional.arm.FEAT_I8MM", &oldp, &size, NULL, 0) != 0) {
  3201. oldp = 0;
  3202. }
  3203. ggml_arm_arch_features.has_i8mm = oldp;
  3204. ggml_arm_arch_features.has_sve = 0;
  3205. ggml_arm_arch_features.sve_cnt = 0;
  3206. #else
  3207. // Run-time CPU feature detection not implemented for this platform, fallback to compile time
  3208. #if defined(__ARM_NEON)
  3209. ggml_arm_arch_features.has_neon = 1;
  3210. #else
  3211. ggml_arm_arch_features.has_neon = 0;
  3212. #endif
  3213. #if defined(__ARM_FEATURE_MATMUL_INT8)
  3214. ggml_arm_arch_features.has_i8mm = 1;
  3215. #else
  3216. ggml_arm_arch_features.has_i8mm = 0;
  3217. #endif
  3218. #if defined(__ARM_FEATURE_SVE)
  3219. ggml_arm_arch_features.has_sve = 1;
  3220. ggml_arm_arch_features.sve_cnt = 16;
  3221. #else
  3222. ggml_arm_arch_features.has_sve = 0;
  3223. ggml_arm_arch_features.sve_cnt = 0;
  3224. #endif
  3225. #endif
  3226. }
  3227. #endif
  3228. struct ggml_context * ggml_init(struct ggml_init_params params) {
  3229. // make this function thread safe
  3230. ggml_critical_section_start();
  3231. static bool is_first_call = true;
  3232. if (is_first_call) {
  3233. // initialize time system (required on Windows)
  3234. ggml_time_init();
  3235. // initialize GELU, Quick GELU, SILU and EXP F32 tables
  3236. {
  3237. const uint64_t t_start = ggml_time_us(); UNUSED(t_start);
  3238. for (int i = 0; i < (1 << 16); ++i) {
  3239. union {
  3240. uint16_t u16;
  3241. ggml_fp16_t fp16;
  3242. } u = {i};
  3243. float f = ggml_table_f32_f16[i] = GGML_COMPUTE_FP16_TO_FP32(u.fp16);
  3244. ggml_table_gelu_f16[i] = GGML_FP32_TO_FP16(ggml_gelu_f32(f));
  3245. ggml_table_gelu_quick_f16[i] = GGML_FP32_TO_FP16(ggml_gelu_quick_f32(f));
  3246. }
  3247. const uint64_t t_end = ggml_time_us(); UNUSED(t_end);
  3248. GGML_PRINT_DEBUG("%s: GELU, Quick GELU, SILU and EXP tables initialized in %f ms\n", __func__, (t_end - t_start)/1000.0f);
  3249. }
  3250. // initialize g_state
  3251. {
  3252. const uint64_t t_start = ggml_time_us(); UNUSED(t_start);
  3253. g_state = (struct ggml_state) {
  3254. /*.contexts =*/ { { 0 } },
  3255. /*.numa =*/ {
  3256. .n_nodes = 0,
  3257. .total_cpus = 0,
  3258. },
  3259. };
  3260. for (int i = 0; i < GGML_MAX_CONTEXTS; ++i) {
  3261. g_state.contexts[i].used = false;
  3262. }
  3263. const uint64_t t_end = ggml_time_us(); UNUSED(t_end);
  3264. GGML_PRINT_DEBUG("%s: g_state initialized in %f ms\n", __func__, (t_end - t_start)/1000.0f);
  3265. }
  3266. #if defined(__ARM_ARCH)
  3267. ggml_init_arm_arch_features();
  3268. #endif
  3269. is_first_call = false;
  3270. }
  3271. // find non-used context in g_state
  3272. struct ggml_context * ctx = NULL;
  3273. for (int i = 0; i < GGML_MAX_CONTEXTS; i++) {
  3274. if (!g_state.contexts[i].used) {
  3275. g_state.contexts[i].used = true;
  3276. ctx = &g_state.contexts[i].context;
  3277. GGML_PRINT_DEBUG("%s: found unused context %d\n", __func__, i);
  3278. break;
  3279. }
  3280. }
  3281. if (ctx == NULL) {
  3282. GGML_PRINT_DEBUG("%s: no unused context found\n", __func__);
  3283. ggml_critical_section_end();
  3284. return NULL;
  3285. }
  3286. // allow to call ggml_init with 0 size
  3287. if (params.mem_size == 0) {
  3288. params.mem_size = GGML_MEM_ALIGN;
  3289. }
  3290. const size_t mem_size = params.mem_buffer ? params.mem_size : GGML_PAD(params.mem_size, GGML_MEM_ALIGN);
  3291. *ctx = (struct ggml_context) {
  3292. /*.mem_size =*/ mem_size,
  3293. /*.mem_buffer =*/ params.mem_buffer ? params.mem_buffer : GGML_ALIGNED_MALLOC(mem_size),
  3294. /*.mem_buffer_owned =*/ params.mem_buffer ? false : true,
  3295. /*.no_alloc =*/ params.no_alloc,
  3296. /*.no_alloc_save =*/ params.no_alloc,
  3297. /*.n_objects =*/ 0,
  3298. /*.objects_begin =*/ NULL,
  3299. /*.objects_end =*/ NULL,
  3300. /*.scratch =*/ { 0, 0, NULL, },
  3301. /*.scratch_save =*/ { 0, 0, NULL, },
  3302. };
  3303. GGML_ASSERT(ctx->mem_buffer != NULL);
  3304. GGML_ASSERT_ALIGNED(ctx->mem_buffer);
  3305. GGML_PRINT_DEBUG("%s: context initialized\n", __func__);
  3306. ggml_critical_section_end();
  3307. return ctx;
  3308. }
  3309. void ggml_free(struct ggml_context * ctx) {
  3310. if (ctx == NULL) {
  3311. return;
  3312. }
  3313. // make this function thread safe
  3314. ggml_critical_section_start();
  3315. bool found = false;
  3316. for (int i = 0; i < GGML_MAX_CONTEXTS; i++) {
  3317. if (&g_state.contexts[i].context == ctx) {
  3318. g_state.contexts[i].used = false;
  3319. GGML_PRINT_DEBUG("%s: context %d has been freed. memory used = %zu\n",
  3320. __func__, i, ggml_used_mem(ctx));
  3321. if (ctx->mem_buffer_owned) {
  3322. GGML_ALIGNED_FREE(ctx->mem_buffer);
  3323. }
  3324. found = true;
  3325. break;
  3326. }
  3327. }
  3328. if (!found) {
  3329. GGML_PRINT_DEBUG("%s: context not found\n", __func__);
  3330. }
  3331. ggml_critical_section_end();
  3332. }
  3333. size_t ggml_used_mem(const struct ggml_context * ctx) {
  3334. return ctx->objects_end == NULL ? 0 : ctx->objects_end->offs + ctx->objects_end->size;
  3335. }
  3336. size_t ggml_set_scratch(struct ggml_context * ctx, struct ggml_scratch scratch) {
  3337. const size_t result = ctx->scratch.data ? ctx->scratch.offs : 0;
  3338. ctx->scratch = scratch;
  3339. return result;
  3340. }
  3341. bool ggml_get_no_alloc(struct ggml_context * ctx) {
  3342. return ctx->no_alloc;
  3343. }
  3344. void ggml_set_no_alloc(struct ggml_context * ctx, bool no_alloc) {
  3345. ctx->no_alloc = no_alloc;
  3346. }
  3347. void * ggml_get_mem_buffer(const struct ggml_context * ctx) {
  3348. return ctx->mem_buffer;
  3349. }
  3350. size_t ggml_get_mem_size(const struct ggml_context * ctx) {
  3351. return ctx->mem_size;
  3352. }
  3353. size_t ggml_get_max_tensor_size(const struct ggml_context * ctx) {
  3354. size_t max_size = 0;
  3355. for (struct ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor != NULL; tensor = ggml_get_next_tensor(ctx, tensor)) {
  3356. size_t bytes = ggml_nbytes(tensor);
  3357. max_size = MAX(max_size, bytes);
  3358. }
  3359. return max_size;
  3360. }
  3361. // IMPORTANT:
  3362. // when creating "opt" tensors, always save and load the scratch buffer
  3363. // this is an error prone process, but it is necessary to support inplace
  3364. // operators when using scratch buffers
  3365. // TODO: implement a better way
  3366. static void ggml_scratch_save(struct ggml_context * ctx) {
  3367. // this is needed to allow opt tensors to store their data
  3368. // TODO: again, need to find a better way
  3369. ctx->no_alloc_save = ctx->no_alloc;
  3370. ctx->no_alloc = false;
  3371. ctx->scratch_save = ctx->scratch;
  3372. ctx->scratch.data = NULL;
  3373. }
  3374. static void ggml_scratch_load(struct ggml_context * ctx) {
  3375. ctx->no_alloc = ctx->no_alloc_save;
  3376. ctx->scratch = ctx->scratch_save;
  3377. }
  3378. ////////////////////////////////////////////////////////////////////////////////
  3379. static struct ggml_object * ggml_new_object(struct ggml_context * ctx, enum ggml_object_type type, size_t size) {
  3380. // always insert objects at the end of the context's memory pool
  3381. struct ggml_object * obj_cur = ctx->objects_end;
  3382. const size_t cur_offs = obj_cur == NULL ? 0 : obj_cur->offs;
  3383. const size_t cur_size = obj_cur == NULL ? 0 : obj_cur->size;
  3384. const size_t cur_end = cur_offs + cur_size;
  3385. // align to GGML_MEM_ALIGN
  3386. size_t size_needed = GGML_PAD(size, GGML_MEM_ALIGN);
  3387. char * const mem_buffer = ctx->mem_buffer;
  3388. struct ggml_object * const obj_new = (struct ggml_object *)(mem_buffer + cur_end);
  3389. if (cur_end + size_needed + GGML_OBJECT_SIZE > ctx->mem_size) {
  3390. GGML_PRINT("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
  3391. __func__, cur_end + size_needed + GGML_OBJECT_SIZE, ctx->mem_size);
  3392. assert(false);
  3393. return NULL;
  3394. }
  3395. *obj_new = (struct ggml_object) {
  3396. .offs = cur_end + GGML_OBJECT_SIZE,
  3397. .size = size_needed,
  3398. .next = NULL,
  3399. .type = type,
  3400. };
  3401. GGML_ASSERT_ALIGNED(mem_buffer + obj_new->offs);
  3402. if (obj_cur != NULL) {
  3403. obj_cur->next = obj_new;
  3404. } else {
  3405. // this is the first object in this context
  3406. ctx->objects_begin = obj_new;
  3407. }
  3408. ctx->objects_end = obj_new;
  3409. //printf("%s: inserted new object at %zu, size = %zu\n", __func__, cur_end, obj_new->size);
  3410. return obj_new;
  3411. }
  3412. static struct ggml_tensor * ggml_new_tensor_impl(
  3413. struct ggml_context * ctx,
  3414. enum ggml_type type,
  3415. int n_dims,
  3416. const int64_t * ne,
  3417. struct ggml_tensor * view_src,
  3418. size_t view_offs) {
  3419. GGML_ASSERT(type >= 0 && type < GGML_TYPE_COUNT);
  3420. GGML_ASSERT(n_dims >= 1 && n_dims <= GGML_MAX_DIMS);
  3421. // find the base tensor and absolute offset
  3422. if (view_src != NULL && view_src->view_src != NULL) {
  3423. view_offs += view_src->view_offs;
  3424. view_src = view_src->view_src;
  3425. }
  3426. size_t data_size = ggml_row_size(type, ne[0]);
  3427. for (int i = 1; i < n_dims; i++) {
  3428. data_size *= ne[i];
  3429. }
  3430. GGML_ASSERT(view_src == NULL || data_size == 0 || data_size + view_offs <= ggml_nbytes(view_src));
  3431. void * data = view_src != NULL ? view_src->data : NULL;
  3432. if (data != NULL) {
  3433. data = (char *) data + view_offs;
  3434. }
  3435. size_t obj_alloc_size = 0;
  3436. if (view_src == NULL && !ctx->no_alloc) {
  3437. if (ctx->scratch.data != NULL) {
  3438. // allocate tensor data in the scratch buffer
  3439. if (ctx->scratch.offs + data_size > ctx->scratch.size) {
  3440. GGML_PRINT("%s: not enough space in the scratch memory pool (needed %zu, available %zu)\n",
  3441. __func__, ctx->scratch.offs + data_size, ctx->scratch.size);
  3442. assert(false);
  3443. return NULL;
  3444. }
  3445. data = (char * const) ctx->scratch.data + ctx->scratch.offs;
  3446. ctx->scratch.offs += data_size;
  3447. } else {
  3448. // allocate tensor data in the context's memory pool
  3449. obj_alloc_size = data_size;
  3450. }
  3451. }
  3452. struct ggml_object * const obj_new = ggml_new_object(ctx, GGML_OBJECT_TYPE_TENSOR, GGML_TENSOR_SIZE + obj_alloc_size);
  3453. GGML_ASSERT(obj_new);
  3454. // TODO: for recoverable errors, we would need to free the data allocated from the scratch buffer here
  3455. struct ggml_tensor * const result = (struct ggml_tensor *)((char *)ctx->mem_buffer + obj_new->offs);
  3456. #ifdef __clang__
  3457. // temporary until ggml_tensor::backend is removed
  3458. #pragma clang diagnostic push
  3459. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  3460. #endif
  3461. *result = (struct ggml_tensor) {
  3462. /*.type =*/ type,
  3463. /*.backend =*/ GGML_BACKEND_TYPE_CPU,
  3464. /*.buffer =*/ NULL,
  3465. /*.ne =*/ { 1, 1, 1, 1 },
  3466. /*.nb =*/ { 0, 0, 0, 0 },
  3467. /*.op =*/ GGML_OP_NONE,
  3468. /*.op_params =*/ { 0 },
  3469. /*.flags =*/ 0,
  3470. /*.grad =*/ NULL,
  3471. /*.src =*/ { NULL },
  3472. /*.view_src =*/ view_src,
  3473. /*.view_offs =*/ view_offs,
  3474. /*.data =*/ obj_alloc_size > 0 ? (void *)(result + 1) : data,
  3475. /*.name =*/ { 0 },
  3476. /*.extra =*/ NULL,
  3477. ///*.padding =*/ { 0 },
  3478. };
  3479. #ifdef __clang__
  3480. #pragma clang diagnostic pop
  3481. #endif
  3482. // TODO: this should not be needed as long as we don't rely on aligned SIMD loads
  3483. //GGML_ASSERT_ALIGNED(result->data);
  3484. for (int i = 0; i < n_dims; i++) {
  3485. result->ne[i] = ne[i];
  3486. }
  3487. result->nb[0] = ggml_type_size(type);
  3488. result->nb[1] = result->nb[0]*(result->ne[0]/ggml_blck_size(type));
  3489. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  3490. result->nb[i] = result->nb[i - 1]*result->ne[i - 1];
  3491. }
  3492. ctx->n_objects++;
  3493. return result;
  3494. }
  3495. struct ggml_tensor * ggml_new_tensor(
  3496. struct ggml_context * ctx,
  3497. enum ggml_type type,
  3498. int n_dims,
  3499. const int64_t * ne) {
  3500. return ggml_new_tensor_impl(ctx, type, n_dims, ne, NULL, 0);
  3501. }
  3502. struct ggml_tensor * ggml_new_tensor_1d(
  3503. struct ggml_context * ctx,
  3504. enum ggml_type type,
  3505. int64_t ne0) {
  3506. return ggml_new_tensor(ctx, type, 1, &ne0);
  3507. }
  3508. struct ggml_tensor * ggml_new_tensor_2d(
  3509. struct ggml_context * ctx,
  3510. enum ggml_type type,
  3511. int64_t ne0,
  3512. int64_t ne1) {
  3513. const int64_t ne[2] = { ne0, ne1 };
  3514. return ggml_new_tensor(ctx, type, 2, ne);
  3515. }
  3516. struct ggml_tensor * ggml_new_tensor_3d(
  3517. struct ggml_context * ctx,
  3518. enum ggml_type type,
  3519. int64_t ne0,
  3520. int64_t ne1,
  3521. int64_t ne2) {
  3522. const int64_t ne[3] = { ne0, ne1, ne2 };
  3523. return ggml_new_tensor(ctx, type, 3, ne);
  3524. }
  3525. struct ggml_tensor * ggml_new_tensor_4d(
  3526. struct ggml_context * ctx,
  3527. enum ggml_type type,
  3528. int64_t ne0,
  3529. int64_t ne1,
  3530. int64_t ne2,
  3531. int64_t ne3) {
  3532. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  3533. return ggml_new_tensor(ctx, type, 4, ne);
  3534. }
  3535. struct ggml_tensor * ggml_new_i32(struct ggml_context * ctx, int32_t value) {
  3536. ggml_scratch_save(ctx);
  3537. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
  3538. ggml_scratch_load(ctx);
  3539. ggml_set_i32(result, value);
  3540. return result;
  3541. }
  3542. struct ggml_tensor * ggml_new_f32(struct ggml_context * ctx, float value) {
  3543. ggml_scratch_save(ctx);
  3544. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
  3545. ggml_scratch_load(ctx);
  3546. ggml_set_f32(result, value);
  3547. return result;
  3548. }
  3549. struct ggml_tensor * ggml_dup_tensor(struct ggml_context * ctx, const struct ggml_tensor * src) {
  3550. return ggml_new_tensor(ctx, src->type, GGML_MAX_DIMS, src->ne);
  3551. }
  3552. static void ggml_set_op_params(struct ggml_tensor * tensor, const void * params, size_t params_size) {
  3553. GGML_ASSERT(tensor != NULL); // silence -Warray-bounds warnings
  3554. assert(params_size <= GGML_MAX_OP_PARAMS);
  3555. memcpy(tensor->op_params, params, params_size);
  3556. }
  3557. static int32_t ggml_get_op_params_i32(const struct ggml_tensor * tensor, uint32_t i) {
  3558. assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
  3559. return ((const int32_t *)(tensor->op_params))[i];
  3560. }
  3561. static float ggml_get_op_params_f32(const struct ggml_tensor * tensor, uint32_t i) {
  3562. assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
  3563. return ((const float *)(tensor->op_params))[i];
  3564. }
  3565. static void ggml_set_op_params_i32(struct ggml_tensor * tensor, uint32_t i, int32_t value) {
  3566. assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
  3567. ((int32_t *)(tensor->op_params))[i] = value;
  3568. }
  3569. static void ggml_set_op_params_f32(struct ggml_tensor * tensor, uint32_t i, float value) {
  3570. assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
  3571. ((float *)(tensor->op_params))[i] = value;
  3572. }
  3573. struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor) {
  3574. if (tensor->buffer) {
  3575. ggml_backend_tensor_memset(tensor, 0, 0, ggml_nbytes(tensor));
  3576. } else {
  3577. memset(tensor->data, 0, ggml_nbytes(tensor));
  3578. }
  3579. return tensor;
  3580. }
  3581. struct ggml_tensor * ggml_set_i32 (struct ggml_tensor * tensor, int32_t value) {
  3582. const int n = ggml_nrows(tensor);
  3583. const int nc = tensor->ne[0];
  3584. const size_t n1 = tensor->nb[1];
  3585. char * const data = tensor->data;
  3586. switch (tensor->type) {
  3587. case GGML_TYPE_I8:
  3588. {
  3589. assert(tensor->nb[0] == sizeof(int8_t));
  3590. for (int i = 0; i < n; i++) {
  3591. ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
  3592. }
  3593. } break;
  3594. case GGML_TYPE_I16:
  3595. {
  3596. assert(tensor->nb[0] == sizeof(int16_t));
  3597. for (int i = 0; i < n; i++) {
  3598. ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
  3599. }
  3600. } break;
  3601. case GGML_TYPE_I32:
  3602. {
  3603. assert(tensor->nb[0] == sizeof(int32_t));
  3604. for (int i = 0; i < n; i++) {
  3605. ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
  3606. }
  3607. } break;
  3608. case GGML_TYPE_F16:
  3609. {
  3610. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  3611. for (int i = 0; i < n; i++) {
  3612. ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), GGML_FP32_TO_FP16(value));
  3613. }
  3614. } break;
  3615. case GGML_TYPE_BF16:
  3616. {
  3617. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  3618. for (int i = 0; i < n; i++) {
  3619. ggml_vec_set_bf16(nc, (ggml_bf16_t *)(data + i*n1), GGML_FP32_TO_BF16(value));
  3620. }
  3621. } break;
  3622. case GGML_TYPE_F32:
  3623. {
  3624. assert(tensor->nb[0] == sizeof(float));
  3625. for (int i = 0; i < n; i++) {
  3626. ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
  3627. }
  3628. } break;
  3629. default:
  3630. {
  3631. GGML_ABORT("fatal error");
  3632. }
  3633. }
  3634. return tensor;
  3635. }
  3636. struct ggml_tensor * ggml_set_f32(struct ggml_tensor * tensor, float value) {
  3637. const int n = ggml_nrows(tensor);
  3638. const int nc = tensor->ne[0];
  3639. const size_t n1 = tensor->nb[1];
  3640. char * const data = tensor->data;
  3641. switch (tensor->type) {
  3642. case GGML_TYPE_I8:
  3643. {
  3644. assert(tensor->nb[0] == sizeof(int8_t));
  3645. for (int i = 0; i < n; i++) {
  3646. ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
  3647. }
  3648. } break;
  3649. case GGML_TYPE_I16:
  3650. {
  3651. assert(tensor->nb[0] == sizeof(int16_t));
  3652. for (int i = 0; i < n; i++) {
  3653. ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
  3654. }
  3655. } break;
  3656. case GGML_TYPE_I32:
  3657. {
  3658. assert(tensor->nb[0] == sizeof(int32_t));
  3659. for (int i = 0; i < n; i++) {
  3660. ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
  3661. }
  3662. } break;
  3663. case GGML_TYPE_F16:
  3664. {
  3665. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  3666. for (int i = 0; i < n; i++) {
  3667. ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), GGML_FP32_TO_FP16(value));
  3668. }
  3669. } break;
  3670. case GGML_TYPE_BF16:
  3671. {
  3672. assert(tensor->nb[0] == sizeof(ggml_bf16_t));
  3673. for (int i = 0; i < n; i++) {
  3674. ggml_vec_set_bf16(nc, (ggml_bf16_t *)(data + i*n1), GGML_FP32_TO_BF16(value));
  3675. }
  3676. } break;
  3677. case GGML_TYPE_F32:
  3678. {
  3679. assert(tensor->nb[0] == sizeof(float));
  3680. for (int i = 0; i < n; i++) {
  3681. ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
  3682. }
  3683. } break;
  3684. default:
  3685. {
  3686. GGML_ABORT("fatal error");
  3687. }
  3688. }
  3689. return tensor;
  3690. }
  3691. void ggml_unravel_index(const struct ggml_tensor * tensor, int64_t i, int64_t * i0, int64_t * i1, int64_t * i2, int64_t * i3) {
  3692. const int64_t ne2 = tensor->ne[2];
  3693. const int64_t ne1 = tensor->ne[1];
  3694. const int64_t ne0 = tensor->ne[0];
  3695. const int64_t i3_ = (i/(ne2*ne1*ne0));
  3696. const int64_t i2_ = (i - i3_*ne2*ne1*ne0)/(ne1*ne0);
  3697. const int64_t i1_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0)/ne0;
  3698. const int64_t i0_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0 - i1_*ne0);
  3699. if (i0) {
  3700. * i0 = i0_;
  3701. }
  3702. if (i1) {
  3703. * i1 = i1_;
  3704. }
  3705. if (i2) {
  3706. * i2 = i2_;
  3707. }
  3708. if (i3) {
  3709. * i3 = i3_;
  3710. }
  3711. }
  3712. int32_t ggml_get_i32_1d(const struct ggml_tensor * tensor, int i) {
  3713. if (!ggml_is_contiguous(tensor)) {
  3714. int64_t id[4] = { 0, 0, 0, 0 };
  3715. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  3716. return ggml_get_i32_nd(tensor, id[0], id[1], id[2], id[3]);
  3717. }
  3718. switch (tensor->type) {
  3719. case GGML_TYPE_I8:
  3720. {
  3721. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  3722. return ((int8_t *)(tensor->data))[i];
  3723. }
  3724. case GGML_TYPE_I16:
  3725. {
  3726. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  3727. return ((int16_t *)(tensor->data))[i];
  3728. }
  3729. case GGML_TYPE_I32:
  3730. {
  3731. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  3732. return ((int32_t *)(tensor->data))[i];
  3733. }
  3734. case GGML_TYPE_F16:
  3735. {
  3736. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  3737. return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
  3738. }
  3739. case GGML_TYPE_BF16:
  3740. {
  3741. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_bf16_t));
  3742. return GGML_BF16_TO_FP32(((ggml_bf16_t *)(tensor->data))[i]);
  3743. }
  3744. case GGML_TYPE_F32:
  3745. {
  3746. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  3747. return ((float *)(tensor->data))[i];
  3748. }
  3749. default:
  3750. {
  3751. GGML_ABORT("fatal error");
  3752. }
  3753. }
  3754. }
  3755. void ggml_set_i32_1d(const struct ggml_tensor * tensor, int i, int32_t value) {
  3756. if (!ggml_is_contiguous(tensor)) {
  3757. int64_t id[4] = { 0, 0, 0, 0 };
  3758. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  3759. ggml_set_i32_nd(tensor, id[0], id[1], id[2], id[3], value);
  3760. return;
  3761. }
  3762. switch (tensor->type) {
  3763. case GGML_TYPE_I8:
  3764. {
  3765. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  3766. ((int8_t *)(tensor->data))[i] = value;
  3767. } break;
  3768. case GGML_TYPE_I16:
  3769. {
  3770. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  3771. ((int16_t *)(tensor->data))[i] = value;
  3772. } break;
  3773. case GGML_TYPE_I32:
  3774. {
  3775. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  3776. ((int32_t *)(tensor->data))[i] = value;
  3777. } break;
  3778. case GGML_TYPE_F16:
  3779. {
  3780. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  3781. ((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
  3782. } break;
  3783. case GGML_TYPE_BF16:
  3784. {
  3785. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_bf16_t));
  3786. ((ggml_bf16_t *)(tensor->data))[i] = GGML_FP32_TO_BF16(value);
  3787. } break;
  3788. case GGML_TYPE_F32:
  3789. {
  3790. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  3791. ((float *)(tensor->data))[i] = value;
  3792. } break;
  3793. default:
  3794. {
  3795. GGML_ABORT("fatal error");
  3796. }
  3797. }
  3798. }
  3799. int32_t ggml_get_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  3800. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  3801. switch (tensor->type) {
  3802. case GGML_TYPE_I8:
  3803. return ((int8_t *) data)[0];
  3804. case GGML_TYPE_I16:
  3805. return ((int16_t *) data)[0];
  3806. case GGML_TYPE_I32:
  3807. return ((int32_t *) data)[0];
  3808. case GGML_TYPE_F16:
  3809. return GGML_FP16_TO_FP32(((ggml_fp16_t *) data)[0]);
  3810. case GGML_TYPE_BF16:
  3811. return GGML_BF16_TO_FP32(((ggml_bf16_t *) data)[0]);
  3812. case GGML_TYPE_F32:
  3813. return ((float *) data)[0];
  3814. default:
  3815. GGML_ABORT("fatal error");
  3816. }
  3817. }
  3818. void ggml_set_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, int32_t value) {
  3819. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  3820. switch (tensor->type) {
  3821. case GGML_TYPE_I8:
  3822. {
  3823. ((int8_t *)(data))[0] = value;
  3824. } break;
  3825. case GGML_TYPE_I16:
  3826. {
  3827. ((int16_t *)(data))[0] = value;
  3828. } break;
  3829. case GGML_TYPE_I32:
  3830. {
  3831. ((int32_t *)(data))[0] = value;
  3832. } break;
  3833. case GGML_TYPE_F16:
  3834. {
  3835. ((ggml_fp16_t *)(data))[0] = GGML_FP32_TO_FP16(value);
  3836. } break;
  3837. case GGML_TYPE_BF16:
  3838. {
  3839. ((ggml_bf16_t *)(data))[0] = GGML_FP32_TO_BF16(value);
  3840. } break;
  3841. case GGML_TYPE_F32:
  3842. {
  3843. ((float *)(data))[0] = value;
  3844. } break;
  3845. default:
  3846. {
  3847. GGML_ABORT("fatal error");
  3848. }
  3849. }
  3850. }
  3851. float ggml_get_f32_1d(const struct ggml_tensor * tensor, int i) {
  3852. if (!ggml_is_contiguous(tensor)) {
  3853. int64_t id[4] = { 0, 0, 0, 0 };
  3854. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  3855. return ggml_get_f32_nd(tensor, id[0], id[1], id[2], id[3]);
  3856. }
  3857. switch (tensor->type) {
  3858. case GGML_TYPE_I8:
  3859. {
  3860. return ((int8_t *)(tensor->data))[i];
  3861. }
  3862. case GGML_TYPE_I16:
  3863. {
  3864. return ((int16_t *)(tensor->data))[i];
  3865. }
  3866. case GGML_TYPE_I32:
  3867. {
  3868. return ((int32_t *)(tensor->data))[i];
  3869. }
  3870. case GGML_TYPE_F16:
  3871. {
  3872. return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
  3873. }
  3874. case GGML_TYPE_BF16:
  3875. {
  3876. return GGML_BF16_TO_FP32(((ggml_bf16_t *)(tensor->data))[i]);
  3877. }
  3878. case GGML_TYPE_F32:
  3879. {
  3880. return ((float *)(tensor->data))[i];
  3881. }
  3882. default:
  3883. {
  3884. GGML_ABORT("fatal error");
  3885. }
  3886. }
  3887. }
  3888. void ggml_set_f32_1d(const struct ggml_tensor * tensor, int i, float value) {
  3889. if (!ggml_is_contiguous(tensor)) {
  3890. int64_t id[4] = { 0, 0, 0, 0 };
  3891. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  3892. ggml_set_f32_nd(tensor, id[0], id[1], id[2], id[3], value);
  3893. return;
  3894. }
  3895. switch (tensor->type) {
  3896. case GGML_TYPE_I8:
  3897. {
  3898. ((int8_t *)(tensor->data))[i] = value;
  3899. } break;
  3900. case GGML_TYPE_I16:
  3901. {
  3902. ((int16_t *)(tensor->data))[i] = value;
  3903. } break;
  3904. case GGML_TYPE_I32:
  3905. {
  3906. ((int32_t *)(tensor->data))[i] = value;
  3907. } break;
  3908. case GGML_TYPE_F16:
  3909. {
  3910. ((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
  3911. } break;
  3912. case GGML_TYPE_BF16:
  3913. {
  3914. ((ggml_bf16_t *)(tensor->data))[i] = GGML_FP32_TO_BF16(value);
  3915. } break;
  3916. case GGML_TYPE_F32:
  3917. {
  3918. ((float *)(tensor->data))[i] = value;
  3919. } break;
  3920. default:
  3921. {
  3922. GGML_ABORT("fatal error");
  3923. }
  3924. }
  3925. }
  3926. float ggml_get_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  3927. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  3928. switch (tensor->type) {
  3929. case GGML_TYPE_I8:
  3930. return ((int8_t *) data)[0];
  3931. case GGML_TYPE_I16:
  3932. return ((int16_t *) data)[0];
  3933. case GGML_TYPE_I32:
  3934. return ((int32_t *) data)[0];
  3935. case GGML_TYPE_F16:
  3936. return GGML_FP16_TO_FP32(((ggml_fp16_t *) data)[0]);
  3937. case GGML_TYPE_BF16:
  3938. return GGML_BF16_TO_FP32(((ggml_bf16_t *) data)[0]);
  3939. case GGML_TYPE_F32:
  3940. return ((float *) data)[0];
  3941. default:
  3942. GGML_ABORT("fatal error");
  3943. }
  3944. }
  3945. void ggml_set_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, float value) {
  3946. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  3947. switch (tensor->type) {
  3948. case GGML_TYPE_I8:
  3949. {
  3950. ((int8_t *)(data))[0] = value;
  3951. } break;
  3952. case GGML_TYPE_I16:
  3953. {
  3954. ((int16_t *)(data))[0] = value;
  3955. } break;
  3956. case GGML_TYPE_I32:
  3957. {
  3958. ((int32_t *)(data))[0] = value;
  3959. } break;
  3960. case GGML_TYPE_F16:
  3961. {
  3962. ((ggml_fp16_t *)(data))[0] = GGML_FP32_TO_FP16(value);
  3963. } break;
  3964. case GGML_TYPE_BF16:
  3965. {
  3966. ((ggml_bf16_t *)(data))[0] = GGML_FP32_TO_BF16(value);
  3967. } break;
  3968. case GGML_TYPE_F32:
  3969. {
  3970. ((float *)(data))[0] = value;
  3971. } break;
  3972. default:
  3973. {
  3974. GGML_ABORT("fatal error");
  3975. }
  3976. }
  3977. }
  3978. void * ggml_get_data(const struct ggml_tensor * tensor) {
  3979. return tensor->data;
  3980. }
  3981. float * ggml_get_data_f32(const struct ggml_tensor * tensor) {
  3982. assert(tensor->type == GGML_TYPE_F32);
  3983. return (float *)(tensor->data);
  3984. }
  3985. GGML_CALL enum ggml_unary_op ggml_get_unary_op(const struct ggml_tensor * tensor) {
  3986. GGML_ASSERT(tensor->op == GGML_OP_UNARY);
  3987. return (enum ggml_unary_op) ggml_get_op_params_i32(tensor, 0);
  3988. }
  3989. const char * ggml_get_name(const struct ggml_tensor * tensor) {
  3990. return tensor->name;
  3991. }
  3992. struct ggml_tensor * ggml_set_name(struct ggml_tensor * tensor, const char * name) {
  3993. size_t i;
  3994. for (i = 0; i < sizeof(tensor->name) - 1 && name[i] != '\0'; i++) {
  3995. tensor->name[i] = name[i];
  3996. }
  3997. tensor->name[i] = '\0';
  3998. return tensor;
  3999. }
  4000. struct ggml_tensor * ggml_format_name(struct ggml_tensor * tensor, const char * fmt, ...) {
  4001. va_list args;
  4002. va_start(args, fmt);
  4003. vsnprintf(tensor->name, sizeof(tensor->name), fmt, args);
  4004. va_end(args);
  4005. return tensor;
  4006. }
  4007. struct ggml_tensor * ggml_view_tensor(
  4008. struct ggml_context * ctx,
  4009. struct ggml_tensor * src) {
  4010. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, src->type, GGML_MAX_DIMS, src->ne, src, 0);
  4011. ggml_format_name(result, "%s (view)", src->name);
  4012. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  4013. result->nb[i] = src->nb[i];
  4014. }
  4015. return result;
  4016. }
  4017. struct ggml_tensor * ggml_get_first_tensor(const struct ggml_context * ctx) {
  4018. struct ggml_object * obj = ctx->objects_begin;
  4019. char * const mem_buffer = ctx->mem_buffer;
  4020. while (obj != NULL) {
  4021. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  4022. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  4023. }
  4024. obj = obj->next;
  4025. }
  4026. return NULL;
  4027. }
  4028. struct ggml_tensor * ggml_get_next_tensor(const struct ggml_context * ctx, struct ggml_tensor * tensor) {
  4029. struct ggml_object * obj = (struct ggml_object *) ((char *)tensor - GGML_OBJECT_SIZE);
  4030. obj = obj->next;
  4031. char * const mem_buffer = ctx->mem_buffer;
  4032. while (obj != NULL) {
  4033. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  4034. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  4035. }
  4036. obj = obj->next;
  4037. }
  4038. return NULL;
  4039. }
  4040. struct ggml_tensor * ggml_get_tensor(struct ggml_context * ctx, const char * name) {
  4041. struct ggml_object * obj = ctx->objects_begin;
  4042. char * const mem_buffer = ctx->mem_buffer;
  4043. while (obj != NULL) {
  4044. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  4045. struct ggml_tensor * cur = (struct ggml_tensor *)(mem_buffer + obj->offs);
  4046. if (strcmp(cur->name, name) == 0) {
  4047. return cur;
  4048. }
  4049. }
  4050. obj = obj->next;
  4051. }
  4052. return NULL;
  4053. }
  4054. ////////////////////////////////////////////////////////////////////////////////
  4055. // ggml_dup
  4056. static struct ggml_tensor * ggml_dup_impl(
  4057. struct ggml_context * ctx,
  4058. struct ggml_tensor * a,
  4059. bool inplace) {
  4060. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4061. result->op = GGML_OP_DUP;
  4062. result->src[0] = a;
  4063. return result;
  4064. }
  4065. struct ggml_tensor * ggml_dup(
  4066. struct ggml_context * ctx,
  4067. struct ggml_tensor * a) {
  4068. return ggml_dup_impl(ctx, a, false);
  4069. }
  4070. struct ggml_tensor * ggml_dup_inplace(
  4071. struct ggml_context * ctx,
  4072. struct ggml_tensor * a) {
  4073. return ggml_dup_impl(ctx, a, true);
  4074. }
  4075. // ggml_add
  4076. static struct ggml_tensor * ggml_add_impl(
  4077. struct ggml_context * ctx,
  4078. struct ggml_tensor * a,
  4079. struct ggml_tensor * b,
  4080. bool inplace) {
  4081. GGML_ASSERT(ggml_can_repeat(b, a));
  4082. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4083. result->op = GGML_OP_ADD;
  4084. result->src[0] = a;
  4085. result->src[1] = b;
  4086. return result;
  4087. }
  4088. struct ggml_tensor * ggml_add(
  4089. struct ggml_context * ctx,
  4090. struct ggml_tensor * a,
  4091. struct ggml_tensor * b) {
  4092. return ggml_add_impl(ctx, a, b, false);
  4093. }
  4094. struct ggml_tensor * ggml_add_inplace(
  4095. struct ggml_context * ctx,
  4096. struct ggml_tensor * a,
  4097. struct ggml_tensor * b) {
  4098. return ggml_add_impl(ctx, a, b, true);
  4099. }
  4100. // ggml_add_cast
  4101. static struct ggml_tensor * ggml_add_cast_impl(
  4102. struct ggml_context * ctx,
  4103. struct ggml_tensor * a,
  4104. struct ggml_tensor * b,
  4105. enum ggml_type type) {
  4106. // TODO: support less-strict constraint
  4107. // GGML_ASSERT(ggml_can_repeat(b, a));
  4108. GGML_ASSERT(ggml_can_repeat_rows(b, a));
  4109. // currently only supported for quantized input and f16
  4110. GGML_ASSERT(ggml_is_quantized(a->type) ||
  4111. a->type == GGML_TYPE_F16 ||
  4112. a->type == GGML_TYPE_BF16);
  4113. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  4114. result->op = GGML_OP_ADD;
  4115. result->src[0] = a;
  4116. result->src[1] = b;
  4117. return result;
  4118. }
  4119. struct ggml_tensor * ggml_add_cast(
  4120. struct ggml_context * ctx,
  4121. struct ggml_tensor * a,
  4122. struct ggml_tensor * b,
  4123. enum ggml_type type) {
  4124. return ggml_add_cast_impl(ctx, a, b, type);
  4125. }
  4126. // ggml_add1
  4127. static struct ggml_tensor * ggml_add1_impl(
  4128. struct ggml_context * ctx,
  4129. struct ggml_tensor * a,
  4130. struct ggml_tensor * b,
  4131. bool inplace) {
  4132. GGML_ASSERT(ggml_is_scalar(b));
  4133. GGML_ASSERT(ggml_is_padded_1d(a));
  4134. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4135. result->op = GGML_OP_ADD1;
  4136. result->src[0] = a;
  4137. result->src[1] = b;
  4138. return result;
  4139. }
  4140. struct ggml_tensor * ggml_add1(
  4141. struct ggml_context * ctx,
  4142. struct ggml_tensor * a,
  4143. struct ggml_tensor * b) {
  4144. return ggml_add1_impl(ctx, a, b, false);
  4145. }
  4146. struct ggml_tensor * ggml_add1_inplace(
  4147. struct ggml_context * ctx,
  4148. struct ggml_tensor * a,
  4149. struct ggml_tensor * b) {
  4150. return ggml_add1_impl(ctx, a, b, true);
  4151. }
  4152. // ggml_acc
  4153. static struct ggml_tensor * ggml_acc_impl(
  4154. struct ggml_context * ctx,
  4155. struct ggml_tensor * a,
  4156. struct ggml_tensor * b,
  4157. size_t nb1,
  4158. size_t nb2,
  4159. size_t nb3,
  4160. size_t offset,
  4161. bool inplace) {
  4162. GGML_ASSERT(ggml_nelements(b) <= ggml_nelements(a));
  4163. GGML_ASSERT(ggml_is_contiguous(a));
  4164. GGML_ASSERT(a->type == GGML_TYPE_F32);
  4165. GGML_ASSERT(b->type == GGML_TYPE_F32);
  4166. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4167. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  4168. ggml_set_op_params(result, params, sizeof(params));
  4169. result->op = GGML_OP_ACC;
  4170. result->src[0] = a;
  4171. result->src[1] = b;
  4172. return result;
  4173. }
  4174. struct ggml_tensor * ggml_acc(
  4175. struct ggml_context * ctx,
  4176. struct ggml_tensor * a,
  4177. struct ggml_tensor * b,
  4178. size_t nb1,
  4179. size_t nb2,
  4180. size_t nb3,
  4181. size_t offset) {
  4182. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  4183. }
  4184. struct ggml_tensor * ggml_acc_inplace(
  4185. struct ggml_context * ctx,
  4186. struct ggml_tensor * a,
  4187. struct ggml_tensor * b,
  4188. size_t nb1,
  4189. size_t nb2,
  4190. size_t nb3,
  4191. size_t offset) {
  4192. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  4193. }
  4194. // ggml_sub
  4195. static struct ggml_tensor * ggml_sub_impl(
  4196. struct ggml_context * ctx,
  4197. struct ggml_tensor * a,
  4198. struct ggml_tensor * b,
  4199. bool inplace) {
  4200. GGML_ASSERT(ggml_can_repeat(b, a));
  4201. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4202. result->op = GGML_OP_SUB;
  4203. result->src[0] = a;
  4204. result->src[1] = b;
  4205. return result;
  4206. }
  4207. struct ggml_tensor * ggml_sub(
  4208. struct ggml_context * ctx,
  4209. struct ggml_tensor * a,
  4210. struct ggml_tensor * b) {
  4211. return ggml_sub_impl(ctx, a, b, false);
  4212. }
  4213. struct ggml_tensor * ggml_sub_inplace(
  4214. struct ggml_context * ctx,
  4215. struct ggml_tensor * a,
  4216. struct ggml_tensor * b) {
  4217. return ggml_sub_impl(ctx, a, b, true);
  4218. }
  4219. // ggml_mul
  4220. static struct ggml_tensor * ggml_mul_impl(
  4221. struct ggml_context * ctx,
  4222. struct ggml_tensor * a,
  4223. struct ggml_tensor * b,
  4224. bool inplace) {
  4225. GGML_ASSERT(ggml_can_repeat(b, a));
  4226. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4227. result->op = GGML_OP_MUL;
  4228. result->src[0] = a;
  4229. result->src[1] = b;
  4230. return result;
  4231. }
  4232. struct ggml_tensor * ggml_mul(
  4233. struct ggml_context * ctx,
  4234. struct ggml_tensor * a,
  4235. struct ggml_tensor * b) {
  4236. return ggml_mul_impl(ctx, a, b, false);
  4237. }
  4238. struct ggml_tensor * ggml_mul_inplace(
  4239. struct ggml_context * ctx,
  4240. struct ggml_tensor * a,
  4241. struct ggml_tensor * b) {
  4242. return ggml_mul_impl(ctx, a, b, true);
  4243. }
  4244. // ggml_div
  4245. static struct ggml_tensor * ggml_div_impl(
  4246. struct ggml_context * ctx,
  4247. struct ggml_tensor * a,
  4248. struct ggml_tensor * b,
  4249. bool inplace) {
  4250. GGML_ASSERT(ggml_can_repeat(b, a));
  4251. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4252. result->op = GGML_OP_DIV;
  4253. result->src[0] = a;
  4254. result->src[1] = b;
  4255. return result;
  4256. }
  4257. struct ggml_tensor * ggml_div(
  4258. struct ggml_context * ctx,
  4259. struct ggml_tensor * a,
  4260. struct ggml_tensor * b) {
  4261. return ggml_div_impl(ctx, a, b, false);
  4262. }
  4263. struct ggml_tensor * ggml_div_inplace(
  4264. struct ggml_context * ctx,
  4265. struct ggml_tensor * a,
  4266. struct ggml_tensor * b) {
  4267. return ggml_div_impl(ctx, a, b, true);
  4268. }
  4269. // ggml_sqr
  4270. static struct ggml_tensor * ggml_sqr_impl(
  4271. struct ggml_context * ctx,
  4272. struct ggml_tensor * a,
  4273. bool inplace) {
  4274. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4275. result->op = GGML_OP_SQR;
  4276. result->src[0] = a;
  4277. return result;
  4278. }
  4279. struct ggml_tensor * ggml_sqr(
  4280. struct ggml_context * ctx,
  4281. struct ggml_tensor * a) {
  4282. return ggml_sqr_impl(ctx, a, false);
  4283. }
  4284. struct ggml_tensor * ggml_sqr_inplace(
  4285. struct ggml_context * ctx,
  4286. struct ggml_tensor * a) {
  4287. return ggml_sqr_impl(ctx, a, true);
  4288. }
  4289. // ggml_sqrt
  4290. static struct ggml_tensor * ggml_sqrt_impl(
  4291. struct ggml_context * ctx,
  4292. struct ggml_tensor * a,
  4293. bool inplace) {
  4294. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4295. result->op = GGML_OP_SQRT;
  4296. result->src[0] = a;
  4297. return result;
  4298. }
  4299. struct ggml_tensor * ggml_sqrt(
  4300. struct ggml_context * ctx,
  4301. struct ggml_tensor * a) {
  4302. return ggml_sqrt_impl(ctx, a, false);
  4303. }
  4304. struct ggml_tensor * ggml_sqrt_inplace(
  4305. struct ggml_context * ctx,
  4306. struct ggml_tensor * a) {
  4307. return ggml_sqrt_impl(ctx, a, true);
  4308. }
  4309. // ggml_log
  4310. static struct ggml_tensor * ggml_log_impl(
  4311. struct ggml_context * ctx,
  4312. struct ggml_tensor * a,
  4313. bool inplace) {
  4314. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4315. result->op = GGML_OP_LOG;
  4316. result->src[0] = a;
  4317. return result;
  4318. }
  4319. struct ggml_tensor * ggml_log(
  4320. struct ggml_context * ctx,
  4321. struct ggml_tensor * a) {
  4322. return ggml_log_impl(ctx, a, false);
  4323. }
  4324. struct ggml_tensor * ggml_log_inplace(
  4325. struct ggml_context * ctx,
  4326. struct ggml_tensor * a) {
  4327. return ggml_log_impl(ctx, a, true);
  4328. }
  4329. // ggml_sin
  4330. static struct ggml_tensor * ggml_sin_impl(
  4331. struct ggml_context * ctx,
  4332. struct ggml_tensor * a,
  4333. bool inplace) {
  4334. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4335. result->op = GGML_OP_SIN;
  4336. result->src[0] = a;
  4337. return result;
  4338. }
  4339. struct ggml_tensor * ggml_sin(
  4340. struct ggml_context * ctx,
  4341. struct ggml_tensor * a) {
  4342. return ggml_sin_impl(ctx, a, false);
  4343. }
  4344. struct ggml_tensor * ggml_sin_inplace(
  4345. struct ggml_context * ctx,
  4346. struct ggml_tensor * a) {
  4347. return ggml_sin_impl(ctx, a, true);
  4348. }
  4349. // ggml_cos
  4350. static struct ggml_tensor * ggml_cos_impl(
  4351. struct ggml_context * ctx,
  4352. struct ggml_tensor * a,
  4353. bool inplace) {
  4354. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4355. result->op = GGML_OP_COS;
  4356. result->src[0] = a;
  4357. return result;
  4358. }
  4359. struct ggml_tensor * ggml_cos(
  4360. struct ggml_context * ctx,
  4361. struct ggml_tensor * a) {
  4362. return ggml_cos_impl(ctx, a, false);
  4363. }
  4364. struct ggml_tensor * ggml_cos_inplace(
  4365. struct ggml_context * ctx,
  4366. struct ggml_tensor * a) {
  4367. return ggml_cos_impl(ctx, a, true);
  4368. }
  4369. // ggml_sum
  4370. struct ggml_tensor * ggml_sum(
  4371. struct ggml_context * ctx,
  4372. struct ggml_tensor * a) {
  4373. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  4374. result->op = GGML_OP_SUM;
  4375. result->src[0] = a;
  4376. return result;
  4377. }
  4378. // ggml_sum_rows
  4379. struct ggml_tensor * ggml_sum_rows(
  4380. struct ggml_context * ctx,
  4381. struct ggml_tensor * a) {
  4382. int64_t ne[GGML_MAX_DIMS] = { 1 };
  4383. for (int i = 1; i < GGML_MAX_DIMS; ++i) {
  4384. ne[i] = a->ne[i];
  4385. }
  4386. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  4387. result->op = GGML_OP_SUM_ROWS;
  4388. result->src[0] = a;
  4389. return result;
  4390. }
  4391. // ggml_mean
  4392. struct ggml_tensor * ggml_mean(
  4393. struct ggml_context * ctx,
  4394. struct ggml_tensor * a) {
  4395. int64_t ne[4] = { 1, a->ne[1], a->ne[2], a->ne[3] };
  4396. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  4397. result->op = GGML_OP_MEAN;
  4398. result->src[0] = a;
  4399. return result;
  4400. }
  4401. // ggml_argmax
  4402. struct ggml_tensor * ggml_argmax(
  4403. struct ggml_context * ctx,
  4404. struct ggml_tensor * a) {
  4405. GGML_ASSERT(ggml_is_matrix(a));
  4406. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, a->ne[1]);
  4407. result->op = GGML_OP_ARGMAX;
  4408. result->src[0] = a;
  4409. return result;
  4410. }
  4411. // ggml_repeat
  4412. struct ggml_tensor * ggml_repeat(
  4413. struct ggml_context * ctx,
  4414. struct ggml_tensor * a,
  4415. struct ggml_tensor * b) {
  4416. GGML_ASSERT(ggml_can_repeat(a, b));
  4417. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  4418. result->op = GGML_OP_REPEAT;
  4419. result->src[0] = a;
  4420. return result;
  4421. }
  4422. // ggml_repeat_back
  4423. struct ggml_tensor * ggml_repeat_back(
  4424. struct ggml_context * ctx,
  4425. struct ggml_tensor * a,
  4426. struct ggml_tensor * b) {
  4427. GGML_ASSERT(ggml_can_repeat(b, a));
  4428. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  4429. result->op = GGML_OP_REPEAT_BACK;
  4430. result->src[0] = a;
  4431. return result;
  4432. }
  4433. // ggml_concat
  4434. struct ggml_tensor * ggml_concat(
  4435. struct ggml_context * ctx,
  4436. struct ggml_tensor * a,
  4437. struct ggml_tensor * b,
  4438. int dim) {
  4439. GGML_ASSERT(dim >= 0 && dim < GGML_MAX_DIMS);
  4440. int64_t ne[GGML_MAX_DIMS];
  4441. for (int d = 0; d < GGML_MAX_DIMS; ++d) {
  4442. if (d == dim) {
  4443. ne[d] = a->ne[d] + b->ne[d];
  4444. continue;
  4445. }
  4446. GGML_ASSERT(a->ne[d] == b->ne[d]);
  4447. ne[d] = a->ne[d];
  4448. }
  4449. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  4450. ggml_set_op_params_i32(result, 0, dim);
  4451. result->op = GGML_OP_CONCAT;
  4452. result->src[0] = a;
  4453. result->src[1] = b;
  4454. return result;
  4455. }
  4456. // ggml_abs
  4457. struct ggml_tensor * ggml_abs(
  4458. struct ggml_context * ctx,
  4459. struct ggml_tensor * a) {
  4460. return ggml_unary(ctx, a, GGML_UNARY_OP_ABS);
  4461. }
  4462. struct ggml_tensor * ggml_abs_inplace(
  4463. struct ggml_context * ctx,
  4464. struct ggml_tensor * a) {
  4465. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ABS);
  4466. }
  4467. // ggml_sgn
  4468. struct ggml_tensor * ggml_sgn(
  4469. struct ggml_context * ctx,
  4470. struct ggml_tensor * a) {
  4471. return ggml_unary(ctx, a, GGML_UNARY_OP_SGN);
  4472. }
  4473. struct ggml_tensor * ggml_sgn_inplace(
  4474. struct ggml_context * ctx,
  4475. struct ggml_tensor * a) {
  4476. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SGN);
  4477. }
  4478. // ggml_neg
  4479. struct ggml_tensor * ggml_neg(
  4480. struct ggml_context * ctx,
  4481. struct ggml_tensor * a) {
  4482. return ggml_unary(ctx, a, GGML_UNARY_OP_NEG);
  4483. }
  4484. struct ggml_tensor * ggml_neg_inplace(
  4485. struct ggml_context * ctx,
  4486. struct ggml_tensor * a) {
  4487. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_NEG);
  4488. }
  4489. // ggml_step
  4490. struct ggml_tensor * ggml_step(
  4491. struct ggml_context * ctx,
  4492. struct ggml_tensor * a) {
  4493. return ggml_unary(ctx, a, GGML_UNARY_OP_STEP);
  4494. }
  4495. struct ggml_tensor * ggml_step_inplace(
  4496. struct ggml_context * ctx,
  4497. struct ggml_tensor * a) {
  4498. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_STEP);
  4499. }
  4500. // ggml_tanh
  4501. struct ggml_tensor * ggml_tanh(
  4502. struct ggml_context * ctx,
  4503. struct ggml_tensor * a) {
  4504. return ggml_unary(ctx, a, GGML_UNARY_OP_TANH);
  4505. }
  4506. struct ggml_tensor * ggml_tanh_inplace(
  4507. struct ggml_context * ctx,
  4508. struct ggml_tensor * a) {
  4509. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_TANH);
  4510. }
  4511. // ggml_elu
  4512. struct ggml_tensor * ggml_elu(
  4513. struct ggml_context * ctx,
  4514. struct ggml_tensor * a) {
  4515. return ggml_unary(ctx, a, GGML_UNARY_OP_ELU);
  4516. }
  4517. struct ggml_tensor * ggml_elu_inplace(
  4518. struct ggml_context * ctx,
  4519. struct ggml_tensor * a) {
  4520. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ELU);
  4521. }
  4522. // ggml_relu
  4523. struct ggml_tensor * ggml_relu(
  4524. struct ggml_context * ctx,
  4525. struct ggml_tensor * a) {
  4526. return ggml_unary(ctx, a, GGML_UNARY_OP_RELU);
  4527. }
  4528. struct ggml_tensor * ggml_relu_inplace(
  4529. struct ggml_context * ctx,
  4530. struct ggml_tensor * a) {
  4531. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_RELU);
  4532. }
  4533. // ggml_leaky_relu
  4534. struct ggml_tensor * ggml_leaky_relu(
  4535. struct ggml_context * ctx,
  4536. struct ggml_tensor * a,
  4537. float negative_slope,
  4538. bool inplace) {
  4539. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4540. ggml_set_op_params(result, &negative_slope, sizeof(negative_slope));
  4541. result->op = GGML_OP_LEAKY_RELU;
  4542. result->src[0] = a;
  4543. return result;
  4544. }
  4545. // ggml_sigmoid
  4546. struct ggml_tensor * ggml_sigmoid(
  4547. struct ggml_context * ctx,
  4548. struct ggml_tensor * a) {
  4549. return ggml_unary(ctx, a, GGML_UNARY_OP_SIGMOID);
  4550. }
  4551. struct ggml_tensor * ggml_sigmoid_inplace(
  4552. struct ggml_context * ctx,
  4553. struct ggml_tensor * a) {
  4554. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SIGMOID);
  4555. }
  4556. // ggml_gelu
  4557. struct ggml_tensor * ggml_gelu(
  4558. struct ggml_context * ctx,
  4559. struct ggml_tensor * a) {
  4560. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU);
  4561. }
  4562. struct ggml_tensor * ggml_gelu_inplace(
  4563. struct ggml_context * ctx,
  4564. struct ggml_tensor * a) {
  4565. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU);
  4566. }
  4567. // ggml_gelu_quick
  4568. struct ggml_tensor * ggml_gelu_quick(
  4569. struct ggml_context * ctx,
  4570. struct ggml_tensor * a) {
  4571. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  4572. }
  4573. struct ggml_tensor * ggml_gelu_quick_inplace(
  4574. struct ggml_context * ctx,
  4575. struct ggml_tensor * a) {
  4576. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  4577. }
  4578. // ggml_silu
  4579. struct ggml_tensor * ggml_silu(
  4580. struct ggml_context * ctx,
  4581. struct ggml_tensor * a) {
  4582. return ggml_unary(ctx, a, GGML_UNARY_OP_SILU);
  4583. }
  4584. struct ggml_tensor * ggml_silu_inplace(
  4585. struct ggml_context * ctx,
  4586. struct ggml_tensor * a) {
  4587. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SILU);
  4588. }
  4589. // ggml_silu_back
  4590. struct ggml_tensor * ggml_silu_back(
  4591. struct ggml_context * ctx,
  4592. struct ggml_tensor * a,
  4593. struct ggml_tensor * b) {
  4594. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  4595. result->op = GGML_OP_SILU_BACK;
  4596. result->src[0] = a;
  4597. result->src[1] = b;
  4598. return result;
  4599. }
  4600. // ggml hardswish
  4601. struct ggml_tensor * ggml_hardswish(
  4602. struct ggml_context * ctx,
  4603. struct ggml_tensor * a) {
  4604. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSWISH);
  4605. }
  4606. // ggml hardsigmoid
  4607. struct ggml_tensor * ggml_hardsigmoid(
  4608. struct ggml_context * ctx,
  4609. struct ggml_tensor * a) {
  4610. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSIGMOID);
  4611. }
  4612. // ggml exp
  4613. struct ggml_tensor * ggml_exp(
  4614. struct ggml_context * ctx,
  4615. struct ggml_tensor * a) {
  4616. return ggml_unary(ctx, a, GGML_UNARY_OP_EXP);
  4617. }
  4618. struct ggml_tensor * ggml_exp_inplace(
  4619. struct ggml_context * ctx,
  4620. struct ggml_tensor * a) {
  4621. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_EXP);
  4622. }
  4623. // ggml_norm
  4624. static struct ggml_tensor * ggml_norm_impl(
  4625. struct ggml_context * ctx,
  4626. struct ggml_tensor * a,
  4627. float eps,
  4628. bool inplace) {
  4629. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4630. ggml_set_op_params(result, &eps, sizeof(eps));
  4631. result->op = GGML_OP_NORM;
  4632. result->src[0] = a;
  4633. return result;
  4634. }
  4635. struct ggml_tensor * ggml_norm(
  4636. struct ggml_context * ctx,
  4637. struct ggml_tensor * a,
  4638. float eps) {
  4639. return ggml_norm_impl(ctx, a, eps, false);
  4640. }
  4641. struct ggml_tensor * ggml_norm_inplace(
  4642. struct ggml_context * ctx,
  4643. struct ggml_tensor * a,
  4644. float eps) {
  4645. return ggml_norm_impl(ctx, a, eps, true);
  4646. }
  4647. // ggml_rms_norm
  4648. static struct ggml_tensor * ggml_rms_norm_impl(
  4649. struct ggml_context * ctx,
  4650. struct ggml_tensor * a,
  4651. float eps,
  4652. bool inplace) {
  4653. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4654. ggml_set_op_params(result, &eps, sizeof(eps));
  4655. result->op = GGML_OP_RMS_NORM;
  4656. result->src[0] = a;
  4657. return result;
  4658. }
  4659. struct ggml_tensor * ggml_rms_norm(
  4660. struct ggml_context * ctx,
  4661. struct ggml_tensor * a,
  4662. float eps) {
  4663. return ggml_rms_norm_impl(ctx, a, eps, false);
  4664. }
  4665. struct ggml_tensor * ggml_rms_norm_inplace(
  4666. struct ggml_context * ctx,
  4667. struct ggml_tensor * a,
  4668. float eps) {
  4669. return ggml_rms_norm_impl(ctx, a, eps, true);
  4670. }
  4671. // ggml_rms_norm_back
  4672. struct ggml_tensor * ggml_rms_norm_back(
  4673. struct ggml_context * ctx,
  4674. struct ggml_tensor * a,
  4675. struct ggml_tensor * b,
  4676. float eps) {
  4677. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  4678. ggml_set_op_params(result, &eps, sizeof(eps));
  4679. result->op = GGML_OP_RMS_NORM_BACK;
  4680. result->src[0] = a;
  4681. result->src[1] = b;
  4682. return result;
  4683. }
  4684. // ggml_group_norm
  4685. static struct ggml_tensor * ggml_group_norm_impl(
  4686. struct ggml_context * ctx,
  4687. struct ggml_tensor * a,
  4688. int n_groups,
  4689. float eps,
  4690. bool inplace) {
  4691. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4692. ggml_set_op_params_i32(result, 0, n_groups);
  4693. ggml_set_op_params_f32(result, 1, eps);
  4694. result->op = GGML_OP_GROUP_NORM;
  4695. result->src[0] = a;
  4696. return result;
  4697. }
  4698. struct ggml_tensor * ggml_group_norm(
  4699. struct ggml_context * ctx,
  4700. struct ggml_tensor * a,
  4701. int n_groups,
  4702. float eps) {
  4703. return ggml_group_norm_impl(ctx, a, n_groups, eps, false);
  4704. }
  4705. struct ggml_tensor * ggml_group_norm_inplace(
  4706. struct ggml_context * ctx,
  4707. struct ggml_tensor * a,
  4708. int n_groups,
  4709. float eps) {
  4710. return ggml_group_norm_impl(ctx, a, n_groups, eps, true);
  4711. }
  4712. // ggml_mul_mat
  4713. struct ggml_tensor * ggml_mul_mat(
  4714. struct ggml_context * ctx,
  4715. struct ggml_tensor * a,
  4716. struct ggml_tensor * b) {
  4717. GGML_ASSERT(ggml_can_mul_mat(a, b));
  4718. GGML_ASSERT(!ggml_is_transposed(a));
  4719. const int64_t ne[4] = { a->ne[1], b->ne[1], b->ne[2], b->ne[3] };
  4720. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  4721. result->op = GGML_OP_MUL_MAT;
  4722. result->src[0] = a;
  4723. result->src[1] = b;
  4724. return result;
  4725. }
  4726. void ggml_mul_mat_set_prec(
  4727. struct ggml_tensor * a,
  4728. enum ggml_prec prec) {
  4729. GGML_ASSERT(a->op == GGML_OP_MUL_MAT);
  4730. const int32_t prec_i32 = (int32_t) prec;
  4731. ggml_set_op_params_i32(a, 0, prec_i32);
  4732. }
  4733. // ggml_mul_mat_id
  4734. /*
  4735. c = ggml_mul_mat_id(ctx, as, b, ids);
  4736. as -> [cols, rows, n_expert]
  4737. ids -> [n_experts_used, n_tokens] (i32)
  4738. b -> [cols, n_expert_used, n_tokens]
  4739. c -> [rows, n_expert_used, n_tokens]
  4740. in b, n_experts_used can be broadcasted to match the n_expert_used of ids
  4741. c ~= as[:,:,i] @ b[:,i%r,t], i = ids[e,t] for all e,t in ids
  4742. */
  4743. struct ggml_tensor * ggml_mul_mat_id(
  4744. struct ggml_context * ctx,
  4745. struct ggml_tensor * as,
  4746. struct ggml_tensor * b,
  4747. struct ggml_tensor * ids) {
  4748. GGML_ASSERT(!ggml_is_transposed(as));
  4749. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  4750. GGML_ASSERT(as->ne[3] == 1); // as is 3d (one matrix per expert)
  4751. GGML_ASSERT(b->ne[3] == 1); // b is 3d
  4752. GGML_ASSERT(ids->ne[2] == 1 && ids->ne[3] == 1); // ids is 2d
  4753. GGML_ASSERT(ids->ne[1] == b->ne[2]); // must have an expert list per b row
  4754. GGML_ASSERT(as->ne[0] == b->ne[0]); // can_mul_mat
  4755. GGML_ASSERT(ids->ne[0] % b->ne[1] == 0); // can broadcast
  4756. const int64_t ne[4] = { as->ne[1], ids->ne[0], b->ne[2], 1 };
  4757. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  4758. result->op = GGML_OP_MUL_MAT_ID;
  4759. result->src[0] = as;
  4760. result->src[1] = b;
  4761. result->src[2] = ids;
  4762. return result;
  4763. }
  4764. // ggml_out_prod
  4765. struct ggml_tensor * ggml_out_prod(
  4766. struct ggml_context * ctx,
  4767. struct ggml_tensor * a,
  4768. struct ggml_tensor * b) {
  4769. GGML_ASSERT(ggml_can_out_prod(a, b));
  4770. GGML_ASSERT(!ggml_is_transposed(a));
  4771. // a is broadcastable to b for ne[2] and ne[3] -> use b->ne[2] and b->ne[3]
  4772. const int64_t ne[4] = { a->ne[0], b->ne[0], b->ne[2], b->ne[3] };
  4773. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  4774. result->op = GGML_OP_OUT_PROD;
  4775. result->src[0] = a;
  4776. result->src[1] = b;
  4777. return result;
  4778. }
  4779. // ggml_scale
  4780. static struct ggml_tensor * ggml_scale_impl(
  4781. struct ggml_context * ctx,
  4782. struct ggml_tensor * a,
  4783. float s,
  4784. bool inplace) {
  4785. GGML_ASSERT(ggml_is_padded_1d(a));
  4786. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4787. ggml_set_op_params(result, &s, sizeof(s));
  4788. result->op = GGML_OP_SCALE;
  4789. result->src[0] = a;
  4790. return result;
  4791. }
  4792. struct ggml_tensor * ggml_scale(
  4793. struct ggml_context * ctx,
  4794. struct ggml_tensor * a,
  4795. float s) {
  4796. return ggml_scale_impl(ctx, a, s, false);
  4797. }
  4798. struct ggml_tensor * ggml_scale_inplace(
  4799. struct ggml_context * ctx,
  4800. struct ggml_tensor * a,
  4801. float s) {
  4802. return ggml_scale_impl(ctx, a, s, true);
  4803. }
  4804. // ggml_set
  4805. static struct ggml_tensor * ggml_set_impl(
  4806. struct ggml_context * ctx,
  4807. struct ggml_tensor * a,
  4808. struct ggml_tensor * b,
  4809. size_t nb1,
  4810. size_t nb2,
  4811. size_t nb3,
  4812. size_t offset,
  4813. bool inplace) {
  4814. GGML_ASSERT(ggml_nelements(a) >= ggml_nelements(b));
  4815. // make a view of the destination
  4816. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4817. GGML_ASSERT(offset < (size_t)(1 << 30));
  4818. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  4819. ggml_set_op_params(result, params, sizeof(params));
  4820. result->op = GGML_OP_SET;
  4821. result->src[0] = a;
  4822. result->src[1] = b;
  4823. return result;
  4824. }
  4825. struct ggml_tensor * ggml_set(
  4826. struct ggml_context * ctx,
  4827. struct ggml_tensor * a,
  4828. struct ggml_tensor * b,
  4829. size_t nb1,
  4830. size_t nb2,
  4831. size_t nb3,
  4832. size_t offset) {
  4833. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  4834. }
  4835. struct ggml_tensor * ggml_set_inplace(
  4836. struct ggml_context * ctx,
  4837. struct ggml_tensor * a,
  4838. struct ggml_tensor * b,
  4839. size_t nb1,
  4840. size_t nb2,
  4841. size_t nb3,
  4842. size_t offset) {
  4843. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  4844. }
  4845. struct ggml_tensor * ggml_set_1d(
  4846. struct ggml_context * ctx,
  4847. struct ggml_tensor * a,
  4848. struct ggml_tensor * b,
  4849. size_t offset) {
  4850. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, false);
  4851. }
  4852. struct ggml_tensor * ggml_set_1d_inplace(
  4853. struct ggml_context * ctx,
  4854. struct ggml_tensor * a,
  4855. struct ggml_tensor * b,
  4856. size_t offset) {
  4857. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, true);
  4858. }
  4859. struct ggml_tensor * ggml_set_2d(
  4860. struct ggml_context * ctx,
  4861. struct ggml_tensor * a,
  4862. struct ggml_tensor * b,
  4863. size_t nb1,
  4864. size_t offset) {
  4865. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, false);
  4866. }
  4867. struct ggml_tensor * ggml_set_2d_inplace(
  4868. struct ggml_context * ctx,
  4869. struct ggml_tensor * a,
  4870. struct ggml_tensor * b,
  4871. size_t nb1,
  4872. size_t offset) {
  4873. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, true);
  4874. }
  4875. // ggml_cpy
  4876. static struct ggml_tensor * ggml_cpy_impl(
  4877. struct ggml_context * ctx,
  4878. struct ggml_tensor * a,
  4879. struct ggml_tensor * b) {
  4880. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  4881. // make a view of the destination
  4882. struct ggml_tensor * result = ggml_view_tensor(ctx, b);
  4883. if (strlen(b->name) > 0) {
  4884. ggml_format_name(result, "%s (copy of %s)", b->name, a->name);
  4885. } else {
  4886. ggml_format_name(result, "%s (copy)", a->name);
  4887. }
  4888. result->op = GGML_OP_CPY;
  4889. result->src[0] = a;
  4890. result->src[1] = b;
  4891. return result;
  4892. }
  4893. struct ggml_tensor * ggml_cpy(
  4894. struct ggml_context * ctx,
  4895. struct ggml_tensor * a,
  4896. struct ggml_tensor * b) {
  4897. return ggml_cpy_impl(ctx, a, b);
  4898. }
  4899. struct ggml_tensor * ggml_cast(
  4900. struct ggml_context * ctx,
  4901. struct ggml_tensor * a,
  4902. enum ggml_type type) {
  4903. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  4904. ggml_format_name(result, "%s (copy)", a->name);
  4905. result->op = GGML_OP_CPY;
  4906. result->src[0] = a;
  4907. result->src[1] = result;
  4908. return result;
  4909. }
  4910. // ggml_cont
  4911. static struct ggml_tensor * ggml_cont_impl(
  4912. struct ggml_context * ctx,
  4913. struct ggml_tensor * a) {
  4914. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  4915. ggml_format_name(result, "%s (cont)", a->name);
  4916. result->op = GGML_OP_CONT;
  4917. result->src[0] = a;
  4918. return result;
  4919. }
  4920. struct ggml_tensor * ggml_cont(
  4921. struct ggml_context * ctx,
  4922. struct ggml_tensor * a) {
  4923. return ggml_cont_impl(ctx, a);
  4924. }
  4925. // make contiguous, with new shape
  4926. GGML_API struct ggml_tensor * ggml_cont_1d(
  4927. struct ggml_context * ctx,
  4928. struct ggml_tensor * a,
  4929. int64_t ne0) {
  4930. return ggml_cont_4d(ctx, a, ne0, 1, 1, 1);
  4931. }
  4932. GGML_API struct ggml_tensor * ggml_cont_2d(
  4933. struct ggml_context * ctx,
  4934. struct ggml_tensor * a,
  4935. int64_t ne0,
  4936. int64_t ne1) {
  4937. return ggml_cont_4d(ctx, a, ne0, ne1, 1, 1);
  4938. }
  4939. GGML_API struct ggml_tensor * ggml_cont_3d(
  4940. struct ggml_context * ctx,
  4941. struct ggml_tensor * a,
  4942. int64_t ne0,
  4943. int64_t ne1,
  4944. int64_t ne2) {
  4945. return ggml_cont_4d(ctx, a, ne0, ne1, ne2, 1);
  4946. }
  4947. struct ggml_tensor * ggml_cont_4d(
  4948. struct ggml_context * ctx,
  4949. struct ggml_tensor * a,
  4950. int64_t ne0,
  4951. int64_t ne1,
  4952. int64_t ne2,
  4953. int64_t ne3) {
  4954. GGML_ASSERT(ggml_nelements(a) == (ne0*ne1*ne2*ne3));
  4955. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  4956. ggml_format_name(result, "%s (cont)", a->name);
  4957. result->op = GGML_OP_CONT;
  4958. result->src[0] = a;
  4959. return result;
  4960. }
  4961. // ggml_reshape
  4962. struct ggml_tensor * ggml_reshape(
  4963. struct ggml_context * ctx,
  4964. struct ggml_tensor * a,
  4965. struct ggml_tensor * b) {
  4966. GGML_ASSERT(ggml_is_contiguous(a));
  4967. // as only the shape of b is relevant, and not its memory layout, b is allowed to be non contiguous.
  4968. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  4969. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, GGML_MAX_DIMS, b->ne, a, 0);
  4970. ggml_format_name(result, "%s (reshaped)", a->name);
  4971. result->op = GGML_OP_RESHAPE;
  4972. result->src[0] = a;
  4973. return result;
  4974. }
  4975. struct ggml_tensor * ggml_reshape_1d(
  4976. struct ggml_context * ctx,
  4977. struct ggml_tensor * a,
  4978. int64_t ne0) {
  4979. GGML_ASSERT(ggml_is_contiguous(a));
  4980. GGML_ASSERT(ggml_nelements(a) == ne0);
  4981. const int64_t ne[1] = { ne0 };
  4982. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 1, ne, a, 0);
  4983. ggml_format_name(result, "%s (reshaped)", a->name);
  4984. result->op = GGML_OP_RESHAPE;
  4985. result->src[0] = a;
  4986. return result;
  4987. }
  4988. struct ggml_tensor * ggml_reshape_2d(
  4989. struct ggml_context * ctx,
  4990. struct ggml_tensor * a,
  4991. int64_t ne0,
  4992. int64_t ne1) {
  4993. GGML_ASSERT(ggml_is_contiguous(a));
  4994. GGML_ASSERT(ggml_nelements(a) == ne0*ne1);
  4995. const int64_t ne[2] = { ne0, ne1 };
  4996. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, a, 0);
  4997. ggml_format_name(result, "%s (reshaped)", a->name);
  4998. result->op = GGML_OP_RESHAPE;
  4999. result->src[0] = a;
  5000. return result;
  5001. }
  5002. struct ggml_tensor * ggml_reshape_3d(
  5003. struct ggml_context * ctx,
  5004. struct ggml_tensor * a,
  5005. int64_t ne0,
  5006. int64_t ne1,
  5007. int64_t ne2) {
  5008. GGML_ASSERT(ggml_is_contiguous(a));
  5009. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2);
  5010. const int64_t ne[3] = { ne0, ne1, ne2 };
  5011. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 3, ne, a, 0);
  5012. ggml_format_name(result, "%s (reshaped)", a->name);
  5013. result->op = GGML_OP_RESHAPE;
  5014. result->src[0] = a;
  5015. return result;
  5016. }
  5017. struct ggml_tensor * ggml_reshape_4d(
  5018. struct ggml_context * ctx,
  5019. struct ggml_tensor * a,
  5020. int64_t ne0,
  5021. int64_t ne1,
  5022. int64_t ne2,
  5023. int64_t ne3) {
  5024. GGML_ASSERT(ggml_is_contiguous(a));
  5025. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2*ne3);
  5026. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  5027. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 4, ne, a, 0);
  5028. ggml_format_name(result, "%s (reshaped)", a->name);
  5029. result->op = GGML_OP_RESHAPE;
  5030. result->src[0] = a;
  5031. return result;
  5032. }
  5033. static struct ggml_tensor * ggml_view_impl(
  5034. struct ggml_context * ctx,
  5035. struct ggml_tensor * a,
  5036. int n_dims,
  5037. const int64_t * ne,
  5038. size_t offset) {
  5039. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, n_dims, ne, a, offset);
  5040. ggml_format_name(result, "%s (view)", a->name);
  5041. ggml_set_op_params(result, &offset, sizeof(offset));
  5042. result->op = GGML_OP_VIEW;
  5043. result->src[0] = a;
  5044. return result;
  5045. }
  5046. // ggml_view_1d
  5047. struct ggml_tensor * ggml_view_1d(
  5048. struct ggml_context * ctx,
  5049. struct ggml_tensor * a,
  5050. int64_t ne0,
  5051. size_t offset) {
  5052. struct ggml_tensor * result = ggml_view_impl(ctx, a, 1, &ne0, offset);
  5053. return result;
  5054. }
  5055. // ggml_view_2d
  5056. struct ggml_tensor * ggml_view_2d(
  5057. struct ggml_context * ctx,
  5058. struct ggml_tensor * a,
  5059. int64_t ne0,
  5060. int64_t ne1,
  5061. size_t nb1,
  5062. size_t offset) {
  5063. const int64_t ne[2] = { ne0, ne1 };
  5064. struct ggml_tensor * result = ggml_view_impl(ctx, a, 2, ne, offset);
  5065. result->nb[1] = nb1;
  5066. result->nb[2] = result->nb[1]*ne1;
  5067. result->nb[3] = result->nb[2];
  5068. return result;
  5069. }
  5070. // ggml_view_3d
  5071. struct ggml_tensor * ggml_view_3d(
  5072. struct ggml_context * ctx,
  5073. struct ggml_tensor * a,
  5074. int64_t ne0,
  5075. int64_t ne1,
  5076. int64_t ne2,
  5077. size_t nb1,
  5078. size_t nb2,
  5079. size_t offset) {
  5080. const int64_t ne[3] = { ne0, ne1, ne2 };
  5081. struct ggml_tensor * result = ggml_view_impl(ctx, a, 3, ne, offset);
  5082. result->nb[1] = nb1;
  5083. result->nb[2] = nb2;
  5084. result->nb[3] = result->nb[2]*ne2;
  5085. return result;
  5086. }
  5087. // ggml_view_4d
  5088. struct ggml_tensor * ggml_view_4d(
  5089. struct ggml_context * ctx,
  5090. struct ggml_tensor * a,
  5091. int64_t ne0,
  5092. int64_t ne1,
  5093. int64_t ne2,
  5094. int64_t ne3,
  5095. size_t nb1,
  5096. size_t nb2,
  5097. size_t nb3,
  5098. size_t offset) {
  5099. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  5100. struct ggml_tensor * result = ggml_view_impl(ctx, a, 4, ne, offset);
  5101. result->nb[1] = nb1;
  5102. result->nb[2] = nb2;
  5103. result->nb[3] = nb3;
  5104. return result;
  5105. }
  5106. // ggml_permute
  5107. struct ggml_tensor * ggml_permute(
  5108. struct ggml_context * ctx,
  5109. struct ggml_tensor * a,
  5110. int axis0,
  5111. int axis1,
  5112. int axis2,
  5113. int axis3) {
  5114. GGML_ASSERT(axis0 >= 0 && axis0 < GGML_MAX_DIMS);
  5115. GGML_ASSERT(axis1 >= 0 && axis1 < GGML_MAX_DIMS);
  5116. GGML_ASSERT(axis2 >= 0 && axis2 < GGML_MAX_DIMS);
  5117. GGML_ASSERT(axis3 >= 0 && axis3 < GGML_MAX_DIMS);
  5118. GGML_ASSERT(axis0 != axis1);
  5119. GGML_ASSERT(axis0 != axis2);
  5120. GGML_ASSERT(axis0 != axis3);
  5121. GGML_ASSERT(axis1 != axis2);
  5122. GGML_ASSERT(axis1 != axis3);
  5123. GGML_ASSERT(axis2 != axis3);
  5124. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  5125. ggml_format_name(result, "%s (permuted)", a->name);
  5126. int ne[GGML_MAX_DIMS];
  5127. int nb[GGML_MAX_DIMS];
  5128. ne[axis0] = a->ne[0];
  5129. ne[axis1] = a->ne[1];
  5130. ne[axis2] = a->ne[2];
  5131. ne[axis3] = a->ne[3];
  5132. nb[axis0] = a->nb[0];
  5133. nb[axis1] = a->nb[1];
  5134. nb[axis2] = a->nb[2];
  5135. nb[axis3] = a->nb[3];
  5136. result->ne[0] = ne[0];
  5137. result->ne[1] = ne[1];
  5138. result->ne[2] = ne[2];
  5139. result->ne[3] = ne[3];
  5140. result->nb[0] = nb[0];
  5141. result->nb[1] = nb[1];
  5142. result->nb[2] = nb[2];
  5143. result->nb[3] = nb[3];
  5144. result->op = GGML_OP_PERMUTE;
  5145. result->src[0] = a;
  5146. int32_t params[] = { axis0, axis1, axis2, axis3 };
  5147. ggml_set_op_params(result, params, sizeof(params));
  5148. return result;
  5149. }
  5150. // ggml_transpose
  5151. struct ggml_tensor * ggml_transpose(
  5152. struct ggml_context * ctx,
  5153. struct ggml_tensor * a) {
  5154. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  5155. ggml_format_name(result, "%s (transposed)", a->name);
  5156. result->ne[0] = a->ne[1];
  5157. result->ne[1] = a->ne[0];
  5158. result->nb[0] = a->nb[1];
  5159. result->nb[1] = a->nb[0];
  5160. result->op = GGML_OP_TRANSPOSE;
  5161. result->src[0] = a;
  5162. return result;
  5163. }
  5164. // ggml_get_rows
  5165. struct ggml_tensor * ggml_get_rows(
  5166. struct ggml_context * ctx,
  5167. struct ggml_tensor * a,
  5168. struct ggml_tensor * b) {
  5169. GGML_ASSERT(a->ne[2] == b->ne[1]);
  5170. GGML_ASSERT(b->ne[3] == 1);
  5171. GGML_ASSERT(b->type == GGML_TYPE_I32);
  5172. // TODO: implement non F32 return
  5173. enum ggml_type type = GGML_TYPE_F32;
  5174. if (a->type == GGML_TYPE_I32) {
  5175. type = a->type;
  5176. }
  5177. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, type, a->ne[0], b->ne[0], b->ne[1], b->ne[2]);
  5178. result->op = GGML_OP_GET_ROWS;
  5179. result->src[0] = a;
  5180. result->src[1] = b;
  5181. return result;
  5182. }
  5183. // ggml_get_rows_back
  5184. struct ggml_tensor * ggml_get_rows_back(
  5185. struct ggml_context * ctx,
  5186. struct ggml_tensor * a,
  5187. struct ggml_tensor * b,
  5188. struct ggml_tensor * c) {
  5189. GGML_ASSERT(ggml_is_matrix(a) && ggml_is_vector(b) && b->type == GGML_TYPE_I32);
  5190. GGML_ASSERT(ggml_is_matrix(c) && (a->ne[0] == c->ne[0]));
  5191. // TODO: implement non F32 return
  5192. //struct ggml_tensor * result = ggml_new_tensor_2d(ctx, a->type, a->ne[0], b->ne[0]);
  5193. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, c->ne[0], c->ne[1]);
  5194. result->op = GGML_OP_GET_ROWS_BACK;
  5195. result->src[0] = a;
  5196. result->src[1] = b;
  5197. return result;
  5198. }
  5199. // ggml_diag
  5200. struct ggml_tensor * ggml_diag(
  5201. struct ggml_context * ctx,
  5202. struct ggml_tensor * a) {
  5203. GGML_ASSERT(a->ne[1] == 1);
  5204. const int64_t ne[4] = { a->ne[0], a->ne[0], a->ne[2], a->ne[3] };
  5205. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, 4, ne);
  5206. result->op = GGML_OP_DIAG;
  5207. result->src[0] = a;
  5208. return result;
  5209. }
  5210. // ggml_diag_mask_inf
  5211. static struct ggml_tensor * ggml_diag_mask_inf_impl(
  5212. struct ggml_context * ctx,
  5213. struct ggml_tensor * a,
  5214. int n_past,
  5215. bool inplace) {
  5216. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5217. int32_t params[] = { n_past };
  5218. ggml_set_op_params(result, params, sizeof(params));
  5219. result->op = GGML_OP_DIAG_MASK_INF;
  5220. result->src[0] = a;
  5221. return result;
  5222. }
  5223. struct ggml_tensor * ggml_diag_mask_inf(
  5224. struct ggml_context * ctx,
  5225. struct ggml_tensor * a,
  5226. int n_past) {
  5227. return ggml_diag_mask_inf_impl(ctx, a, n_past, false);
  5228. }
  5229. struct ggml_tensor * ggml_diag_mask_inf_inplace(
  5230. struct ggml_context * ctx,
  5231. struct ggml_tensor * a,
  5232. int n_past) {
  5233. return ggml_diag_mask_inf_impl(ctx, a, n_past, true);
  5234. }
  5235. // ggml_diag_mask_zero
  5236. static struct ggml_tensor * ggml_diag_mask_zero_impl(
  5237. struct ggml_context * ctx,
  5238. struct ggml_tensor * a,
  5239. int n_past,
  5240. bool inplace) {
  5241. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5242. int32_t params[] = { n_past };
  5243. ggml_set_op_params(result, params, sizeof(params));
  5244. result->op = GGML_OP_DIAG_MASK_ZERO;
  5245. result->src[0] = a;
  5246. return result;
  5247. }
  5248. struct ggml_tensor * ggml_diag_mask_zero(
  5249. struct ggml_context * ctx,
  5250. struct ggml_tensor * a,
  5251. int n_past) {
  5252. return ggml_diag_mask_zero_impl(ctx, a, n_past, false);
  5253. }
  5254. struct ggml_tensor * ggml_diag_mask_zero_inplace(
  5255. struct ggml_context * ctx,
  5256. struct ggml_tensor * a,
  5257. int n_past) {
  5258. return ggml_diag_mask_zero_impl(ctx, a, n_past, true);
  5259. }
  5260. // ggml_soft_max
  5261. static struct ggml_tensor * ggml_soft_max_impl(
  5262. struct ggml_context * ctx,
  5263. struct ggml_tensor * a,
  5264. struct ggml_tensor * mask,
  5265. float scale,
  5266. float max_bias,
  5267. bool inplace) {
  5268. GGML_ASSERT(ggml_is_contiguous(a));
  5269. if (mask) {
  5270. GGML_ASSERT(mask->type == GGML_TYPE_F16 || mask->type == GGML_TYPE_F32);
  5271. GGML_ASSERT(ggml_is_contiguous(mask));
  5272. GGML_ASSERT(ggml_is_matrix(mask));
  5273. GGML_ASSERT(mask->ne[0] == a->ne[0]);
  5274. GGML_ASSERT(mask->ne[1] >= a->ne[1]);
  5275. }
  5276. if (max_bias > 0.0f) {
  5277. GGML_ASSERT(mask);
  5278. }
  5279. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5280. float params[] = { scale, max_bias };
  5281. ggml_set_op_params(result, params, sizeof(params));
  5282. result->op = GGML_OP_SOFT_MAX;
  5283. result->src[0] = a;
  5284. result->src[1] = mask;
  5285. return result;
  5286. }
  5287. struct ggml_tensor * ggml_soft_max(
  5288. struct ggml_context * ctx,
  5289. struct ggml_tensor * a) {
  5290. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, false);
  5291. }
  5292. struct ggml_tensor * ggml_soft_max_inplace(
  5293. struct ggml_context * ctx,
  5294. struct ggml_tensor * a) {
  5295. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, true);
  5296. }
  5297. struct ggml_tensor * ggml_soft_max_ext(
  5298. struct ggml_context * ctx,
  5299. struct ggml_tensor * a,
  5300. struct ggml_tensor * mask,
  5301. float scale,
  5302. float max_bias) {
  5303. return ggml_soft_max_impl(ctx, a, mask, scale, max_bias, false);
  5304. }
  5305. // ggml_soft_max_back
  5306. static struct ggml_tensor * ggml_soft_max_back_impl(
  5307. struct ggml_context * ctx,
  5308. struct ggml_tensor * a,
  5309. struct ggml_tensor * b,
  5310. bool inplace) {
  5311. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5312. result->op = GGML_OP_SOFT_MAX_BACK;
  5313. result->src[0] = a;
  5314. result->src[1] = b;
  5315. return result;
  5316. }
  5317. struct ggml_tensor * ggml_soft_max_back(
  5318. struct ggml_context * ctx,
  5319. struct ggml_tensor * a,
  5320. struct ggml_tensor * b) {
  5321. return ggml_soft_max_back_impl(ctx, a, b, false);
  5322. }
  5323. struct ggml_tensor * ggml_soft_max_back_inplace(
  5324. struct ggml_context * ctx,
  5325. struct ggml_tensor * a,
  5326. struct ggml_tensor * b) {
  5327. return ggml_soft_max_back_impl(ctx, a, b, true);
  5328. }
  5329. // ggml_rope
  5330. static struct ggml_tensor * ggml_rope_impl(
  5331. struct ggml_context * ctx,
  5332. struct ggml_tensor * a,
  5333. struct ggml_tensor * b,
  5334. struct ggml_tensor * c,
  5335. int n_dims,
  5336. int mode,
  5337. int n_ctx_orig,
  5338. float freq_base,
  5339. float freq_scale,
  5340. float ext_factor,
  5341. float attn_factor,
  5342. float beta_fast,
  5343. float beta_slow,
  5344. bool inplace) {
  5345. GGML_ASSERT((mode & 1) == 0 && "mode & 1 == 1 is no longer supported");
  5346. GGML_ASSERT(ggml_is_vector(b));
  5347. GGML_ASSERT(b->type == GGML_TYPE_I32);
  5348. GGML_ASSERT(a->ne[2] == b->ne[0]);
  5349. if (c) {
  5350. GGML_ASSERT(c->type == GGML_TYPE_F32);
  5351. GGML_ASSERT(c->ne[0] >= n_dims / 2);
  5352. }
  5353. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5354. int32_t params[11] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  5355. memcpy(params + 5, &freq_base, sizeof(float));
  5356. memcpy(params + 6, &freq_scale, sizeof(float));
  5357. memcpy(params + 7, &ext_factor, sizeof(float));
  5358. memcpy(params + 8, &attn_factor, sizeof(float));
  5359. memcpy(params + 9, &beta_fast, sizeof(float));
  5360. memcpy(params + 10, &beta_slow, sizeof(float));
  5361. ggml_set_op_params(result, params, sizeof(params));
  5362. result->op = GGML_OP_ROPE;
  5363. result->src[0] = a;
  5364. result->src[1] = b;
  5365. result->src[2] = c;
  5366. return result;
  5367. }
  5368. struct ggml_tensor * ggml_rope(
  5369. struct ggml_context * ctx,
  5370. struct ggml_tensor * a,
  5371. struct ggml_tensor * b,
  5372. int n_dims,
  5373. int mode) {
  5374. return ggml_rope_impl(
  5375. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, false
  5376. );
  5377. }
  5378. struct ggml_tensor * ggml_rope_inplace(
  5379. struct ggml_context * ctx,
  5380. struct ggml_tensor * a,
  5381. struct ggml_tensor * b,
  5382. int n_dims,
  5383. int mode) {
  5384. return ggml_rope_impl(
  5385. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, true
  5386. );
  5387. }
  5388. struct ggml_tensor * ggml_rope_ext(
  5389. struct ggml_context * ctx,
  5390. struct ggml_tensor * a,
  5391. struct ggml_tensor * b,
  5392. struct ggml_tensor * c,
  5393. int n_dims,
  5394. int mode,
  5395. int n_ctx_orig,
  5396. float freq_base,
  5397. float freq_scale,
  5398. float ext_factor,
  5399. float attn_factor,
  5400. float beta_fast,
  5401. float beta_slow) {
  5402. return ggml_rope_impl(
  5403. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  5404. ext_factor, attn_factor, beta_fast, beta_slow, false
  5405. );
  5406. }
  5407. struct ggml_tensor * ggml_rope_ext_inplace(
  5408. struct ggml_context * ctx,
  5409. struct ggml_tensor * a,
  5410. struct ggml_tensor * b,
  5411. struct ggml_tensor * c,
  5412. int n_dims,
  5413. int mode,
  5414. int n_ctx_orig,
  5415. float freq_base,
  5416. float freq_scale,
  5417. float ext_factor,
  5418. float attn_factor,
  5419. float beta_fast,
  5420. float beta_slow) {
  5421. return ggml_rope_impl(
  5422. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  5423. ext_factor, attn_factor, beta_fast, beta_slow, true
  5424. );
  5425. }
  5426. struct ggml_tensor * ggml_rope_custom(
  5427. struct ggml_context * ctx,
  5428. struct ggml_tensor * a,
  5429. struct ggml_tensor * b,
  5430. int n_dims,
  5431. int mode,
  5432. int n_ctx_orig,
  5433. float freq_base,
  5434. float freq_scale,
  5435. float ext_factor,
  5436. float attn_factor,
  5437. float beta_fast,
  5438. float beta_slow) {
  5439. return ggml_rope_impl(
  5440. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  5441. ext_factor, attn_factor, beta_fast, beta_slow, false
  5442. );
  5443. }
  5444. struct ggml_tensor * ggml_rope_custom_inplace(
  5445. struct ggml_context * ctx,
  5446. struct ggml_tensor * a,
  5447. struct ggml_tensor * b,
  5448. int n_dims,
  5449. int mode,
  5450. int n_ctx_orig,
  5451. float freq_base,
  5452. float freq_scale,
  5453. float ext_factor,
  5454. float attn_factor,
  5455. float beta_fast,
  5456. float beta_slow) {
  5457. return ggml_rope_impl(
  5458. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  5459. ext_factor, attn_factor, beta_fast, beta_slow, true
  5460. );
  5461. }
  5462. // ggml_rope_back
  5463. struct ggml_tensor * ggml_rope_back(
  5464. struct ggml_context * ctx,
  5465. struct ggml_tensor * a,
  5466. struct ggml_tensor * b,
  5467. struct ggml_tensor * c,
  5468. int n_dims,
  5469. int mode,
  5470. int n_ctx_orig,
  5471. float freq_base,
  5472. float freq_scale,
  5473. float ext_factor,
  5474. float attn_factor,
  5475. float beta_fast,
  5476. float beta_slow) {
  5477. GGML_ASSERT(ggml_is_vector(b));
  5478. GGML_ASSERT(b->type == GGML_TYPE_I32);
  5479. GGML_ASSERT(a->ne[2] == b->ne[0]);
  5480. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  5481. int32_t params[11] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  5482. memcpy(params + 5, &freq_base, sizeof(float));
  5483. memcpy(params + 6, &freq_scale, sizeof(float));
  5484. memcpy(params + 7, &ext_factor, sizeof(float));
  5485. memcpy(params + 8, &attn_factor, sizeof(float));
  5486. memcpy(params + 9, &beta_fast, sizeof(float));
  5487. memcpy(params + 10, &beta_slow, sizeof(float));
  5488. ggml_set_op_params(result, params, sizeof(params));
  5489. result->op = GGML_OP_ROPE_BACK;
  5490. result->src[0] = a;
  5491. result->src[1] = b;
  5492. result->src[2] = c;
  5493. return result;
  5494. }
  5495. // ggml_clamp
  5496. struct ggml_tensor * ggml_clamp(
  5497. struct ggml_context * ctx,
  5498. struct ggml_tensor * a,
  5499. float min,
  5500. float max) {
  5501. // TODO: when implement backward, fix this:
  5502. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  5503. float params[] = { min, max };
  5504. ggml_set_op_params(result, params, sizeof(params));
  5505. result->op = GGML_OP_CLAMP;
  5506. result->src[0] = a;
  5507. return result;
  5508. }
  5509. // ggml_conv_1d
  5510. static int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  5511. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  5512. }
  5513. GGML_API struct ggml_tensor * ggml_conv_1d(
  5514. struct ggml_context * ctx,
  5515. struct ggml_tensor * a,
  5516. struct ggml_tensor * b,
  5517. int s0,
  5518. int p0,
  5519. int d0) {
  5520. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, 0, p0, 0, d0, 0, false, GGML_TYPE_F16); // [N, OL, IC * K]
  5521. struct ggml_tensor * result =
  5522. ggml_mul_mat(ctx,
  5523. ggml_reshape_2d(ctx, im2col, im2col->ne[0], (im2col->ne[2] * im2col->ne[1])), // [N, OL, IC * K] => [N*OL, IC * K]
  5524. ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1]), a->ne[2])); // [OC,IC, K] => [OC, IC * K]
  5525. result = ggml_reshape_3d(ctx, result, im2col->ne[1], a->ne[2], im2col->ne[2]); // [N, OC, OL]
  5526. return result;
  5527. }
  5528. // ggml_conv_1d_ph
  5529. struct ggml_tensor* ggml_conv_1d_ph(
  5530. struct ggml_context * ctx,
  5531. struct ggml_tensor * a,
  5532. struct ggml_tensor * b,
  5533. int s,
  5534. int d) {
  5535. return ggml_conv_1d(ctx, a, b, s, a->ne[0] / 2, d);
  5536. }
  5537. // ggml_conv_transpose_1d
  5538. static int64_t ggml_calc_conv_transpose_1d_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  5539. return (ins - 1) * s - 2 * p + d * (ks - 1) + 1;
  5540. }
  5541. GGML_API struct ggml_tensor * ggml_conv_transpose_1d(
  5542. struct ggml_context * ctx,
  5543. struct ggml_tensor * a,
  5544. struct ggml_tensor * b,
  5545. int s0,
  5546. int p0,
  5547. int d0) {
  5548. GGML_ASSERT(ggml_is_matrix(b));
  5549. GGML_ASSERT(a->ne[2] == b->ne[1]);
  5550. GGML_ASSERT(a->ne[3] == 1);
  5551. GGML_ASSERT(p0 == 0);
  5552. GGML_ASSERT(d0 == 1);
  5553. const int64_t ne[4] = {
  5554. ggml_calc_conv_transpose_1d_output_size(b->ne[0], a->ne[0], s0, 0 /*p0*/, 1 /*d0*/),
  5555. a->ne[1], b->ne[2], 1,
  5556. };
  5557. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5558. int32_t params[] = { s0, p0, d0 };
  5559. ggml_set_op_params(result, params, sizeof(params));
  5560. result->op = GGML_OP_CONV_TRANSPOSE_1D;
  5561. result->src[0] = a;
  5562. result->src[1] = b;
  5563. return result;
  5564. }
  5565. // ggml_conv_depthwise
  5566. struct ggml_tensor * ggml_conv_depthwise_2d(
  5567. struct ggml_context * ctx,
  5568. struct ggml_tensor * a,
  5569. struct ggml_tensor * b,
  5570. int s0,
  5571. int s1,
  5572. int p0,
  5573. int p1,
  5574. int d0,
  5575. int d1) {
  5576. struct ggml_tensor * new_a = ggml_reshape_4d(ctx, a, a->ne[0], a->ne[1], 1, a->ne[2] * a->ne[3]);
  5577. struct ggml_tensor * im2col = ggml_im2col(ctx, new_a,
  5578. ggml_reshape_4d(ctx, b, b->ne[0], b->ne[1], 1, b->ne[2] * b->ne[3]),
  5579. s0, s1, p0, p1, d0, d1, true, GGML_TYPE_F16); // [N * IC, OH, OW, KH * KW]
  5580. struct ggml_tensor * new_b = ggml_reshape_4d(ctx, im2col, im2col->ne[0], im2col->ne[2] * im2col->ne[1], b->ne[2], b->ne[3]); // [N * IC, OH, OW, KH * KW] => [N, IC, OH * OW, KH * KW]
  5581. new_a = ggml_reshape_4d(ctx, new_a, (new_a->ne[0] * new_a->ne[1]), new_a->ne[2], new_a->ne[3], 1); // [OC,1, KH, KW] => [1, OC, 1, KH * KW]
  5582. struct ggml_tensor * result = ggml_mul_mat(ctx, new_a, new_b);
  5583. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], b->ne[2], b->ne[3]); // [N, OC, OH, OW]
  5584. return result;
  5585. }
  5586. // ggml_conv_2d
  5587. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  5588. // a: [OC,IC, KH, KW]
  5589. // b: [N, IC, IH, IW]
  5590. // result: [N, OH, OW, IC*KH*KW]
  5591. struct ggml_tensor * ggml_im2col(
  5592. struct ggml_context * ctx,
  5593. struct ggml_tensor * a,
  5594. struct ggml_tensor * b,
  5595. int s0,
  5596. int s1,
  5597. int p0,
  5598. int p1,
  5599. int d0,
  5600. int d1,
  5601. bool is_2D,
  5602. enum ggml_type dst_type) {
  5603. if(is_2D) {
  5604. GGML_ASSERT(a->ne[2] == b->ne[2]);
  5605. } else {
  5606. GGML_ASSERT(a->ne[1] == b->ne[1]);
  5607. GGML_ASSERT(b->ne[3] == 1);
  5608. }
  5609. const int64_t OH = is_2D ? ggml_calc_conv_output_size(b->ne[1], a->ne[1], s1, p1, d1) : 0;
  5610. const int64_t OW = ggml_calc_conv_output_size(b->ne[0], a->ne[0], s0, p0, d0);
  5611. GGML_ASSERT((!is_2D || OH > 0) && "b too small compared to a");
  5612. GGML_ASSERT((OW > 0) && "b too small compared to a");
  5613. const int64_t ne[4] = {
  5614. is_2D ? (a->ne[2] * a->ne[1] * a->ne[0]) : a->ne[1] * a->ne[0],
  5615. OW,
  5616. is_2D ? OH : b->ne[2],
  5617. is_2D ? b->ne[3] : 1,
  5618. };
  5619. struct ggml_tensor * result = ggml_new_tensor(ctx, dst_type, 4, ne);
  5620. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  5621. ggml_set_op_params(result, params, sizeof(params));
  5622. result->op = GGML_OP_IM2COL;
  5623. result->src[0] = a;
  5624. result->src[1] = b;
  5625. return result;
  5626. }
  5627. struct ggml_tensor * ggml_im2col_back(
  5628. struct ggml_context * ctx,
  5629. struct ggml_tensor * a,
  5630. struct ggml_tensor * b,
  5631. int64_t * ne,
  5632. int s0,
  5633. int s1,
  5634. int p0,
  5635. int p1,
  5636. int d0,
  5637. int d1,
  5638. bool is_2D) {
  5639. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5640. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  5641. ggml_set_op_params(result, params, sizeof(params));
  5642. result->op = GGML_OP_IM2COL_BACK;
  5643. result->src[0] = a;
  5644. result->src[1] = b;
  5645. return result;
  5646. }
  5647. // a: [OC,IC, KH, KW]
  5648. // b: [N, IC, IH, IW]
  5649. // result: [N, OC, OH, OW]
  5650. struct ggml_tensor * ggml_conv_2d(
  5651. struct ggml_context * ctx,
  5652. struct ggml_tensor * a,
  5653. struct ggml_tensor * b,
  5654. int s0,
  5655. int s1,
  5656. int p0,
  5657. int p1,
  5658. int d0,
  5659. int d1) {
  5660. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, s1, p0, p1, d0, d1, true, a->type); // [N, OH, OW, IC * KH * KW]
  5661. struct ggml_tensor * result =
  5662. ggml_mul_mat(ctx,
  5663. ggml_reshape_2d(ctx, im2col, im2col->ne[0], im2col->ne[3] * im2col->ne[2] * im2col->ne[1]), // [N, OH, OW, IC * KH * KW] => [N*OH*OW, IC * KH * KW]
  5664. ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1] * a->ne[2]), a->ne[3])); // [OC,IC, KH, KW] => [OC, IC * KH * KW]
  5665. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], im2col->ne[3], a->ne[3]); // [OC, N, OH, OW]
  5666. result = ggml_cont(ctx, ggml_permute(ctx, result, 0, 1, 3, 2)); // [N, OC, OH, OW]
  5667. return result;
  5668. }
  5669. // ggml_conv_2d_sk_p0
  5670. struct ggml_tensor * ggml_conv_2d_sk_p0(
  5671. struct ggml_context * ctx,
  5672. struct ggml_tensor * a,
  5673. struct ggml_tensor * b) {
  5674. return ggml_conv_2d(ctx, a, b, a->ne[0], a->ne[1], 0, 0, 1, 1);
  5675. }
  5676. // ggml_conv_2d_s1_ph
  5677. struct ggml_tensor * ggml_conv_2d_s1_ph(
  5678. struct ggml_context * ctx,
  5679. struct ggml_tensor * a,
  5680. struct ggml_tensor * b) {
  5681. return ggml_conv_2d(ctx, a, b, 1, 1, a->ne[0] / 2, a->ne[1] / 2, 1, 1);
  5682. }
  5683. // ggml_conv_transpose_2d_p0
  5684. static int64_t ggml_calc_conv_transpose_output_size(int64_t ins, int64_t ks, int s, int p) {
  5685. return (ins - 1) * s - 2 * p + ks;
  5686. }
  5687. struct ggml_tensor * ggml_conv_transpose_2d_p0(
  5688. struct ggml_context * ctx,
  5689. struct ggml_tensor * a,
  5690. struct ggml_tensor * b,
  5691. int stride) {
  5692. GGML_ASSERT(a->ne[3] == b->ne[2]);
  5693. const int64_t ne[4] = {
  5694. ggml_calc_conv_transpose_output_size(b->ne[0], a->ne[0], stride, 0 /*p0*/),
  5695. ggml_calc_conv_transpose_output_size(b->ne[1], a->ne[1], stride, 0 /*p1*/),
  5696. a->ne[2], b->ne[3],
  5697. };
  5698. struct ggml_tensor* result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5699. ggml_set_op_params_i32(result, 0, stride);
  5700. result->op = GGML_OP_CONV_TRANSPOSE_2D;
  5701. result->src[0] = a;
  5702. result->src[1] = b;
  5703. return result;
  5704. }
  5705. // ggml_pool_*
  5706. static int64_t ggml_calc_pool_output_size(int64_t ins, int ks, int s, float p) {
  5707. return (ins + 2 * p - ks) / s + 1;
  5708. }
  5709. // ggml_pool_1d
  5710. struct ggml_tensor * ggml_pool_1d(
  5711. struct ggml_context * ctx,
  5712. struct ggml_tensor * a,
  5713. enum ggml_op_pool op,
  5714. int k0,
  5715. int s0,
  5716. int p0) {
  5717. const int64_t ne[4] = {
  5718. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  5719. a->ne[1],
  5720. a->ne[2],
  5721. a->ne[3],
  5722. };
  5723. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5724. int32_t params[] = { op, k0, s0, p0 };
  5725. ggml_set_op_params(result, params, sizeof(params));
  5726. result->op = GGML_OP_POOL_1D;
  5727. result->src[0] = a;
  5728. return result;
  5729. }
  5730. // ggml_pool_2d
  5731. struct ggml_tensor * ggml_pool_2d(
  5732. struct ggml_context * ctx,
  5733. struct ggml_tensor * a,
  5734. enum ggml_op_pool op,
  5735. int k0,
  5736. int k1,
  5737. int s0,
  5738. int s1,
  5739. float p0,
  5740. float p1) {
  5741. struct ggml_tensor * result;
  5742. const int64_t ne[4] = {
  5743. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  5744. ggml_calc_pool_output_size(a->ne[1], k1, s1, p1),
  5745. a->ne[2],
  5746. a->ne[3],
  5747. };
  5748. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5749. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  5750. ggml_set_op_params(result, params, sizeof(params));
  5751. result->op = GGML_OP_POOL_2D;
  5752. result->src[0] = a;
  5753. return result;
  5754. }
  5755. struct ggml_tensor * ggml_pool_2d_back(
  5756. struct ggml_context * ctx,
  5757. struct ggml_tensor * a,
  5758. struct ggml_tensor * af,
  5759. enum ggml_op_pool op,
  5760. int k0,
  5761. int k1,
  5762. int s0,
  5763. int s1,
  5764. float p0,
  5765. float p1) {
  5766. struct ggml_tensor * result;
  5767. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, af->ne);
  5768. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  5769. ggml_set_op_params(result, params, sizeof(params));
  5770. result->op = GGML_OP_POOL_2D_BACK;
  5771. result->src[0] = a;
  5772. result->src[1] = af;
  5773. return result;
  5774. }
  5775. // ggml_upscale
  5776. static struct ggml_tensor * ggml_upscale_impl(
  5777. struct ggml_context * ctx,
  5778. struct ggml_tensor * a,
  5779. int ne0,
  5780. int ne1,
  5781. int ne2,
  5782. int ne3) {
  5783. GGML_ASSERT(a->ne[0] <= ne0);
  5784. GGML_ASSERT(a->ne[1] <= ne1);
  5785. GGML_ASSERT(a->ne[2] <= ne2);
  5786. GGML_ASSERT(a->ne[3] <= ne3);
  5787. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  5788. result->op = GGML_OP_UPSCALE;
  5789. result->src[0] = a;
  5790. return result;
  5791. }
  5792. struct ggml_tensor * ggml_upscale(
  5793. struct ggml_context * ctx,
  5794. struct ggml_tensor * a,
  5795. int scale_factor) {
  5796. return ggml_upscale_impl(ctx, a, a->ne[0] * scale_factor, a->ne[1] * scale_factor, a->ne[2], a->ne[3]);
  5797. }
  5798. struct ggml_tensor * ggml_upscale_ext(
  5799. struct ggml_context * ctx,
  5800. struct ggml_tensor * a,
  5801. int ne0,
  5802. int ne1,
  5803. int ne2,
  5804. int ne3) {
  5805. return ggml_upscale_impl(ctx, a, ne0, ne1, ne2, ne3);
  5806. }
  5807. // ggml_pad
  5808. struct ggml_tensor * ggml_pad(
  5809. struct ggml_context * ctx,
  5810. struct ggml_tensor * a,
  5811. int p0,
  5812. int p1,
  5813. int p2,
  5814. int p3) {
  5815. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  5816. a->ne[0] + p0,
  5817. a->ne[1] + p1,
  5818. a->ne[2] + p2,
  5819. a->ne[3] + p3);
  5820. result->op = GGML_OP_PAD;
  5821. result->src[0] = a;
  5822. return result;
  5823. }
  5824. // ggml_arange
  5825. struct ggml_tensor * ggml_arange(
  5826. struct ggml_context * ctx,
  5827. float start,
  5828. float stop,
  5829. float step) {
  5830. GGML_ASSERT(stop > start);
  5831. const int64_t steps = (int64_t) ceilf((stop - start) / step);
  5832. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, steps);
  5833. ggml_set_op_params_f32(result, 0, start);
  5834. ggml_set_op_params_f32(result, 1, stop);
  5835. ggml_set_op_params_f32(result, 2, step);
  5836. result->op = GGML_OP_ARANGE;
  5837. return result;
  5838. }
  5839. // ggml_timestep_embedding
  5840. struct ggml_tensor * ggml_timestep_embedding(
  5841. struct ggml_context * ctx,
  5842. struct ggml_tensor * timesteps,
  5843. int dim,
  5844. int max_period) {
  5845. int actual_dim = dim;
  5846. if (dim % 2 != 0) {
  5847. actual_dim = dim + 1;
  5848. }
  5849. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, actual_dim, timesteps->ne[0]);
  5850. ggml_set_op_params_i32(result, 0, dim);
  5851. ggml_set_op_params_i32(result, 1, max_period);
  5852. result->op = GGML_OP_TIMESTEP_EMBEDDING;
  5853. result->src[0] = timesteps;
  5854. return result;
  5855. }
  5856. // ggml_argsort
  5857. struct ggml_tensor * ggml_argsort(
  5858. struct ggml_context * ctx,
  5859. struct ggml_tensor * a,
  5860. enum ggml_sort_order order) {
  5861. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_I32, GGML_MAX_DIMS, a->ne);
  5862. ggml_set_op_params_i32(result, 0, (int32_t) order);
  5863. result->op = GGML_OP_ARGSORT;
  5864. result->src[0] = a;
  5865. return result;
  5866. }
  5867. // ggml_top_k
  5868. struct ggml_tensor * ggml_top_k(
  5869. struct ggml_context * ctx,
  5870. struct ggml_tensor * a,
  5871. int k) {
  5872. GGML_ASSERT(a->ne[0] >= k);
  5873. struct ggml_tensor * result = ggml_argsort(ctx, a, GGML_SORT_ORDER_DESC);
  5874. result = ggml_view_4d(ctx, result,
  5875. k, result->ne[1], result->ne[2], result->ne[3],
  5876. result->nb[1], result->nb[2], result->nb[3],
  5877. 0);
  5878. return result;
  5879. }
  5880. // ggml_flash_attn_ext
  5881. struct ggml_tensor * ggml_flash_attn_ext(
  5882. struct ggml_context * ctx,
  5883. struct ggml_tensor * q,
  5884. struct ggml_tensor * k,
  5885. struct ggml_tensor * v,
  5886. struct ggml_tensor * mask,
  5887. float scale,
  5888. float max_bias,
  5889. float logit_softcap) {
  5890. GGML_ASSERT(ggml_can_mul_mat(k, q));
  5891. // TODO: check if vT can be multiplied by (k*qT)
  5892. if (mask) {
  5893. GGML_ASSERT(ggml_is_contiguous(mask));
  5894. GGML_ASSERT(mask->ne[2] == 1);
  5895. GGML_ASSERT(mask->ne[3] == 1);
  5896. GGML_ASSERT(mask->ne[1] >= GGML_PAD(q->ne[1], GGML_KQ_MASK_PAD) &&
  5897. "the Flash-Attention kernel requires the mask to be padded to GGML_KQ_MASK_PAD and at least n_queries big");
  5898. //GGML_ASSERT(ggml_can_repeat_rows(mask, qk));
  5899. }
  5900. if (max_bias > 0.0f) {
  5901. GGML_ASSERT(mask);
  5902. }
  5903. bool is_node = false;
  5904. // permute(0, 2, 1, 3)
  5905. int64_t ne[4] = { q->ne[0], q->ne[2], q->ne[1], q->ne[3] };
  5906. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5907. float params[] = { scale, max_bias, logit_softcap };
  5908. ggml_set_op_params(result, params, sizeof(params));
  5909. result->op = GGML_OP_FLASH_ATTN_EXT;
  5910. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  5911. result->src[0] = q;
  5912. result->src[1] = k;
  5913. result->src[2] = v;
  5914. result->src[3] = mask;
  5915. return result;
  5916. }
  5917. void ggml_flash_attn_ext_set_prec(
  5918. struct ggml_tensor * a,
  5919. enum ggml_prec prec) {
  5920. GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
  5921. const int32_t prec_i32 = (int32_t) prec;
  5922. ggml_set_op_params_i32(a, 3, prec_i32); // scale is on first pos, max_bias on second
  5923. }
  5924. // ggml_flash_attn_back
  5925. struct ggml_tensor * ggml_flash_attn_back(
  5926. struct ggml_context * ctx,
  5927. struct ggml_tensor * q,
  5928. struct ggml_tensor * k,
  5929. struct ggml_tensor * v,
  5930. struct ggml_tensor * d,
  5931. bool masked) {
  5932. GGML_ABORT("TODO: adapt to ggml_flash_attn_ext() changes");
  5933. GGML_ASSERT(ggml_can_mul_mat(k, q));
  5934. // TODO: check if vT can be multiplied by (k*qT)
  5935. // d shape [D,N,ne2,ne3]
  5936. // q shape [D,N,ne2,ne3]
  5937. // k shape [D,M,kvne2,ne3]
  5938. // v shape [M,D,kvne2,ne3]
  5939. const int64_t D = q->ne[0];
  5940. const int64_t N = q->ne[1];
  5941. const int64_t M = k->ne[1];
  5942. const int64_t ne2 = q->ne[2];
  5943. const int64_t ne3 = q->ne[3];
  5944. const int64_t kvne2 = k->ne[2];
  5945. GGML_ASSERT(k->ne[0] == D);
  5946. GGML_ASSERT(v->ne[0] == M);
  5947. GGML_ASSERT(v->ne[1] == D);
  5948. GGML_ASSERT(d->ne[0] == D);
  5949. GGML_ASSERT(d->ne[1] == N);
  5950. GGML_ASSERT(k->ne[2] == kvne2);
  5951. GGML_ASSERT(k->ne[3] == ne3);
  5952. GGML_ASSERT(v->ne[2] == kvne2);
  5953. GGML_ASSERT(v->ne[3] == ne3);
  5954. GGML_ASSERT(d->ne[2] == ne2);
  5955. GGML_ASSERT(d->ne[3] == ne3);
  5956. GGML_ASSERT(ne2 % kvne2 == 0);
  5957. bool is_node = false;
  5958. if (q->grad || k->grad || v->grad) {
  5959. // when using this operation (in backwards pass) these grads are set.
  5960. // we don't want to create (big) grad of our result, so is_node is false.
  5961. is_node = false;
  5962. }
  5963. // store gradients of q, k and v as continuous tensors concatenated in result.
  5964. // note: v and gradv are actually transposed, i.e. v->ne[0] != D.
  5965. const int64_t elem_q = ggml_nelements(q);
  5966. const int64_t elem_k = ggml_nelements(k);
  5967. const int64_t elem_v = ggml_nelements(v);
  5968. enum ggml_type result_type = GGML_TYPE_F32;
  5969. GGML_ASSERT(ggml_blck_size(result_type) == 1);
  5970. const size_t tsize = ggml_type_size(result_type);
  5971. const size_t offs_q = 0;
  5972. const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
  5973. const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
  5974. const size_t end = offs_v + GGML_PAD(elem_v * tsize, GGML_MEM_ALIGN);
  5975. const size_t nelements = (end + tsize - 1)/tsize;
  5976. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nelements);
  5977. int32_t masked_i = masked ? 1 : 0;
  5978. ggml_set_op_params(result, &masked_i, sizeof(masked_i));
  5979. result->op = GGML_OP_FLASH_ATTN_BACK;
  5980. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  5981. result->src[0] = q;
  5982. result->src[1] = k;
  5983. result->src[2] = v;
  5984. result->src[3] = d;
  5985. return result;
  5986. }
  5987. // ggml_ssm_conv
  5988. struct ggml_tensor * ggml_ssm_conv(
  5989. struct ggml_context * ctx,
  5990. struct ggml_tensor * sx,
  5991. struct ggml_tensor * c) {
  5992. GGML_ASSERT(ggml_is_3d(sx));
  5993. GGML_ASSERT(ggml_is_matrix(c));
  5994. const int64_t d_conv = c->ne[0];
  5995. const int64_t d_inner = c->ne[1];
  5996. const int64_t n_t = sx->ne[0] - d_conv + 1; // tokens per sequence
  5997. const int64_t n_s = sx->ne[2];
  5998. // TODO: maybe support other strides than 1?
  5999. GGML_ASSERT(sx->ne[0] == d_conv - 1 + n_t);
  6000. GGML_ASSERT(sx->ne[1] == d_inner);
  6001. GGML_ASSERT(n_t >= 0);
  6002. struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_t, n_s);
  6003. result->op = GGML_OP_SSM_CONV;
  6004. result->src[0] = sx;
  6005. result->src[1] = c;
  6006. return result;
  6007. }
  6008. // ggml_ssm_scan
  6009. struct ggml_tensor * ggml_ssm_scan(
  6010. struct ggml_context * ctx,
  6011. struct ggml_tensor * s,
  6012. struct ggml_tensor * x,
  6013. struct ggml_tensor * dt,
  6014. struct ggml_tensor * A,
  6015. struct ggml_tensor * B,
  6016. struct ggml_tensor * C) {
  6017. GGML_ASSERT(ggml_is_contiguous(s));
  6018. GGML_ASSERT(ggml_is_contiguous(x));
  6019. GGML_ASSERT(ggml_is_contiguous(dt));
  6020. GGML_ASSERT(ggml_is_contiguous(A));
  6021. GGML_ASSERT(ggml_is_matrix(A));
  6022. GGML_ASSERT(ggml_is_3d(B));
  6023. GGML_ASSERT(ggml_is_3d(s));
  6024. GGML_ASSERT(B->nb[0] == ggml_type_size(B->type));
  6025. GGML_ASSERT(C->nb[0] == ggml_type_size(C->type));
  6026. GGML_ASSERT(ggml_are_same_shape(x, dt));
  6027. GGML_ASSERT(ggml_are_same_shape(B, C));
  6028. {
  6029. const int64_t d_state = s->ne[0];
  6030. const int64_t d_inner = s->ne[1];
  6031. const int64_t n_seq_tokens = x->ne[1];
  6032. const int64_t n_seqs = x->ne[2];
  6033. GGML_ASSERT(s->ne[2] == n_seqs);
  6034. GGML_ASSERT(x->ne[0] == d_inner);
  6035. GGML_ASSERT(A->ne[0] == d_state);
  6036. GGML_ASSERT(A->ne[1] == d_inner);
  6037. GGML_ASSERT(B->ne[0] == d_state);
  6038. GGML_ASSERT(B->ne[1] == n_seq_tokens);
  6039. GGML_ASSERT(B->ne[2] == n_seqs);
  6040. }
  6041. // concatenated y + ssm_states
  6042. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ggml_nelements(x) + ggml_nelements(s));
  6043. result->op = GGML_OP_SSM_SCAN;
  6044. result->src[0] = s;
  6045. result->src[1] = x;
  6046. result->src[2] = dt;
  6047. result->src[3] = A;
  6048. result->src[4] = B;
  6049. result->src[5] = C;
  6050. return result;
  6051. }
  6052. // ggml_win_part
  6053. struct ggml_tensor * ggml_win_part(
  6054. struct ggml_context * ctx,
  6055. struct ggml_tensor * a,
  6056. int w) {
  6057. GGML_ASSERT(a->ne[3] == 1);
  6058. GGML_ASSERT(a->type == GGML_TYPE_F32);
  6059. // padding
  6060. const int px = (w - a->ne[1]%w)%w;
  6061. const int py = (w - a->ne[2]%w)%w;
  6062. const int npx = (px + a->ne[1])/w;
  6063. const int npy = (py + a->ne[2])/w;
  6064. const int np = npx*npy;
  6065. const int64_t ne[4] = { a->ne[0], w, w, np, };
  6066. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  6067. int32_t params[] = { npx, npy, w };
  6068. ggml_set_op_params(result, params, sizeof(params));
  6069. result->op = GGML_OP_WIN_PART;
  6070. result->src[0] = a;
  6071. return result;
  6072. }
  6073. // ggml_win_unpart
  6074. struct ggml_tensor * ggml_win_unpart(
  6075. struct ggml_context * ctx,
  6076. struct ggml_tensor * a,
  6077. int w0,
  6078. int h0,
  6079. int w) {
  6080. GGML_ASSERT(a->type == GGML_TYPE_F32);
  6081. const int64_t ne[4] = { a->ne[0], w0, h0, 1, };
  6082. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 3, ne);
  6083. int32_t params[] = { w };
  6084. ggml_set_op_params(result, params, sizeof(params));
  6085. result->op = GGML_OP_WIN_UNPART;
  6086. result->src[0] = a;
  6087. return result;
  6088. }
  6089. // ggml_get_rel_pos
  6090. struct ggml_tensor * ggml_get_rel_pos(
  6091. struct ggml_context * ctx,
  6092. struct ggml_tensor * a,
  6093. int qh,
  6094. int kh) {
  6095. GGML_ASSERT(qh == kh);
  6096. GGML_ASSERT(2*MAX(qh, kh) - 1 == a->ne[1]);
  6097. const int64_t ne[4] = { a->ne[0], kh, qh, 1, };
  6098. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F16, 3, ne);
  6099. result->op = GGML_OP_GET_REL_POS;
  6100. result->src[0] = a;
  6101. return result;
  6102. }
  6103. // ggml_add_rel_pos
  6104. static struct ggml_tensor * ggml_add_rel_pos_impl(
  6105. struct ggml_context * ctx,
  6106. struct ggml_tensor * a,
  6107. struct ggml_tensor * pw,
  6108. struct ggml_tensor * ph,
  6109. bool inplace) {
  6110. GGML_ASSERT(ggml_are_same_shape(pw, ph));
  6111. GGML_ASSERT(ggml_is_contiguous(a));
  6112. GGML_ASSERT(ggml_is_contiguous(pw));
  6113. GGML_ASSERT(ggml_is_contiguous(ph));
  6114. GGML_ASSERT(ph->type == GGML_TYPE_F32);
  6115. GGML_ASSERT(pw->type == GGML_TYPE_F32);
  6116. GGML_ASSERT(pw->ne[3] == a->ne[2]);
  6117. GGML_ASSERT(pw->ne[0]*pw->ne[0] == a->ne[0]);
  6118. GGML_ASSERT(pw->ne[1]*pw->ne[2] == a->ne[1]);
  6119. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6120. ggml_set_op_params_i32(result, 0, inplace ? 1 : 0);
  6121. result->op = GGML_OP_ADD_REL_POS;
  6122. result->src[0] = a;
  6123. result->src[1] = pw;
  6124. result->src[2] = ph;
  6125. return result;
  6126. }
  6127. struct ggml_tensor * ggml_add_rel_pos(
  6128. struct ggml_context * ctx,
  6129. struct ggml_tensor * a,
  6130. struct ggml_tensor * pw,
  6131. struct ggml_tensor * ph) {
  6132. return ggml_add_rel_pos_impl(ctx, a, pw, ph, false);
  6133. }
  6134. struct ggml_tensor * ggml_add_rel_pos_inplace(
  6135. struct ggml_context * ctx,
  6136. struct ggml_tensor * a,
  6137. struct ggml_tensor * pw,
  6138. struct ggml_tensor * ph) {
  6139. return ggml_add_rel_pos_impl(ctx, a, pw, ph, true);
  6140. }
  6141. // ggml_rwkv_wkv
  6142. struct ggml_tensor * ggml_rwkv_wkv(
  6143. struct ggml_context * ctx,
  6144. struct ggml_tensor * k,
  6145. struct ggml_tensor * v,
  6146. struct ggml_tensor * r,
  6147. struct ggml_tensor * tf,
  6148. struct ggml_tensor * td,
  6149. struct ggml_tensor * state) {
  6150. GGML_ASSERT(ggml_is_contiguous(k));
  6151. GGML_ASSERT(ggml_is_contiguous(v));
  6152. GGML_ASSERT(ggml_is_contiguous(r));
  6153. GGML_ASSERT(ggml_is_contiguous(tf));
  6154. GGML_ASSERT(ggml_is_contiguous(td));
  6155. GGML_ASSERT(ggml_is_contiguous(state));
  6156. const int64_t S = k->ne[0];
  6157. const int64_t H = k->ne[2];
  6158. const int64_t n_tokens = k->ne[3];
  6159. const int64_t n_seqs = state->ne[1];
  6160. {
  6161. GGML_ASSERT(k->ne[1] == 1);
  6162. GGML_ASSERT(v->ne[0] == 1 && v->ne[1] == S && v->ne[2] == H && v->ne[3] == n_tokens);
  6163. GGML_ASSERT(r->ne[0] == 1 && r->ne[1] == S && r->ne[2] == H && r->ne[3] == n_tokens);
  6164. // TODO: RWKV v4 and v5
  6165. GGML_ASSERT(td->ne[0] == 1 && td->ne[1] == S && td->ne[2] == H && td->ne[3] == n_tokens);
  6166. GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
  6167. }
  6168. // concat output and new_state
  6169. const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
  6170. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  6171. result->op = GGML_OP_RWKV_WKV;
  6172. result->src[0] = k;
  6173. result->src[1] = v;
  6174. result->src[2] = r;
  6175. result->src[3] = tf;
  6176. result->src[4] = td;
  6177. result->src[5] = state;
  6178. return result;
  6179. }
  6180. // ggml_unary
  6181. static struct ggml_tensor * ggml_unary_impl(
  6182. struct ggml_context * ctx,
  6183. struct ggml_tensor * a,
  6184. enum ggml_unary_op op,
  6185. bool inplace) {
  6186. GGML_ASSERT(ggml_is_contiguous_1(a));
  6187. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6188. ggml_set_op_params_i32(result, 0, (int32_t) op);
  6189. result->op = GGML_OP_UNARY;
  6190. result->src[0] = a;
  6191. return result;
  6192. }
  6193. struct ggml_tensor * ggml_unary(
  6194. struct ggml_context * ctx,
  6195. struct ggml_tensor * a,
  6196. enum ggml_unary_op op) {
  6197. return ggml_unary_impl(ctx, a, op, false);
  6198. }
  6199. struct ggml_tensor * ggml_unary_inplace(
  6200. struct ggml_context * ctx,
  6201. struct ggml_tensor * a,
  6202. enum ggml_unary_op op) {
  6203. return ggml_unary_impl(ctx, a, op, true);
  6204. }
  6205. // ggml_map_unary
  6206. static struct ggml_tensor * ggml_map_unary_impl_f32(
  6207. struct ggml_context * ctx,
  6208. struct ggml_tensor * a,
  6209. const ggml_unary_op_f32_t fun,
  6210. bool inplace) {
  6211. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6212. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6213. result->op = GGML_OP_MAP_UNARY;
  6214. result->src[0] = a;
  6215. return result;
  6216. }
  6217. struct ggml_tensor * ggml_map_unary_f32(
  6218. struct ggml_context * ctx,
  6219. struct ggml_tensor * a,
  6220. const ggml_unary_op_f32_t fun) {
  6221. return ggml_map_unary_impl_f32(ctx, a, fun, false);
  6222. }
  6223. struct ggml_tensor * ggml_map_unary_inplace_f32(
  6224. struct ggml_context * ctx,
  6225. struct ggml_tensor * a,
  6226. const ggml_unary_op_f32_t fun) {
  6227. return ggml_map_unary_impl_f32(ctx, a, fun, true);
  6228. }
  6229. // ggml_map_binary
  6230. static struct ggml_tensor * ggml_map_binary_impl_f32(
  6231. struct ggml_context * ctx,
  6232. struct ggml_tensor * a,
  6233. struct ggml_tensor * b,
  6234. const ggml_binary_op_f32_t fun,
  6235. bool inplace) {
  6236. GGML_ASSERT(ggml_are_same_shape(a, b));
  6237. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6238. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6239. result->op = GGML_OP_MAP_BINARY;
  6240. result->src[0] = a;
  6241. result->src[1] = b;
  6242. return result;
  6243. }
  6244. struct ggml_tensor * ggml_map_binary_f32(
  6245. struct ggml_context * ctx,
  6246. struct ggml_tensor * a,
  6247. struct ggml_tensor * b,
  6248. const ggml_binary_op_f32_t fun) {
  6249. return ggml_map_binary_impl_f32(ctx, a, b, fun, false);
  6250. }
  6251. struct ggml_tensor * ggml_map_binary_inplace_f32(
  6252. struct ggml_context * ctx,
  6253. struct ggml_tensor * a,
  6254. struct ggml_tensor * b,
  6255. const ggml_binary_op_f32_t fun) {
  6256. return ggml_map_binary_impl_f32(ctx, a, b, fun, true);
  6257. }
  6258. // ggml_map_custom1_f32
  6259. static struct ggml_tensor * ggml_map_custom1_impl_f32(
  6260. struct ggml_context * ctx,
  6261. struct ggml_tensor * a,
  6262. const ggml_custom1_op_f32_t fun,
  6263. bool inplace) {
  6264. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6265. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6266. result->op = GGML_OP_MAP_CUSTOM1_F32;
  6267. result->src[0] = a;
  6268. return result;
  6269. }
  6270. struct ggml_tensor * ggml_map_custom1_f32(
  6271. struct ggml_context * ctx,
  6272. struct ggml_tensor * a,
  6273. const ggml_custom1_op_f32_t fun) {
  6274. return ggml_map_custom1_impl_f32(ctx, a, fun, false);
  6275. }
  6276. struct ggml_tensor * ggml_map_custom1_inplace_f32(
  6277. struct ggml_context * ctx,
  6278. struct ggml_tensor * a,
  6279. const ggml_custom1_op_f32_t fun) {
  6280. return ggml_map_custom1_impl_f32(ctx, a, fun, true);
  6281. }
  6282. // ggml_map_custom2_f32
  6283. static struct ggml_tensor * ggml_map_custom2_impl_f32(
  6284. struct ggml_context * ctx,
  6285. struct ggml_tensor * a,
  6286. struct ggml_tensor * b,
  6287. const ggml_custom2_op_f32_t fun,
  6288. bool inplace) {
  6289. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6290. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6291. result->op = GGML_OP_MAP_CUSTOM2_F32;
  6292. result->src[0] = a;
  6293. result->src[1] = b;
  6294. return result;
  6295. }
  6296. struct ggml_tensor * ggml_map_custom2_f32(
  6297. struct ggml_context * ctx,
  6298. struct ggml_tensor * a,
  6299. struct ggml_tensor * b,
  6300. const ggml_custom2_op_f32_t fun) {
  6301. return ggml_map_custom2_impl_f32(ctx, a, b, fun, false);
  6302. }
  6303. struct ggml_tensor * ggml_map_custom2_inplace_f32(
  6304. struct ggml_context * ctx,
  6305. struct ggml_tensor * a,
  6306. struct ggml_tensor * b,
  6307. const ggml_custom2_op_f32_t fun) {
  6308. return ggml_map_custom2_impl_f32(ctx, a, b, fun, true);
  6309. }
  6310. // ggml_map_custom3_f32
  6311. static struct ggml_tensor * ggml_map_custom3_impl_f32(
  6312. struct ggml_context * ctx,
  6313. struct ggml_tensor * a,
  6314. struct ggml_tensor * b,
  6315. struct ggml_tensor * c,
  6316. const ggml_custom3_op_f32_t fun,
  6317. bool inplace) {
  6318. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6319. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6320. result->op = GGML_OP_MAP_CUSTOM3_F32;
  6321. result->src[0] = a;
  6322. result->src[1] = b;
  6323. result->src[2] = c;
  6324. return result;
  6325. }
  6326. struct ggml_tensor * ggml_map_custom3_f32(
  6327. struct ggml_context * ctx,
  6328. struct ggml_tensor * a,
  6329. struct ggml_tensor * b,
  6330. struct ggml_tensor * c,
  6331. const ggml_custom3_op_f32_t fun) {
  6332. return ggml_map_custom3_impl_f32(ctx, a, b, c, fun, false);
  6333. }
  6334. struct ggml_tensor * ggml_map_custom3_inplace_f32(
  6335. struct ggml_context * ctx,
  6336. struct ggml_tensor * a,
  6337. struct ggml_tensor * b,
  6338. struct ggml_tensor * c,
  6339. const ggml_custom3_op_f32_t fun) {
  6340. return ggml_map_custom3_impl_f32(ctx, a, b, c, fun, true);
  6341. }
  6342. // ggml_map_custom1
  6343. struct ggml_map_custom1_op_params {
  6344. ggml_custom1_op_t fun;
  6345. int n_tasks;
  6346. void * userdata;
  6347. };
  6348. static struct ggml_tensor * ggml_map_custom1_impl(
  6349. struct ggml_context * ctx,
  6350. struct ggml_tensor * a,
  6351. const ggml_custom1_op_t fun,
  6352. int n_tasks,
  6353. void * userdata,
  6354. bool inplace) {
  6355. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  6356. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6357. struct ggml_map_custom1_op_params params = {
  6358. /*.fun =*/ fun,
  6359. /*.n_tasks =*/ n_tasks,
  6360. /*.userdata =*/ userdata
  6361. };
  6362. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  6363. result->op = GGML_OP_MAP_CUSTOM1;
  6364. result->src[0] = a;
  6365. return result;
  6366. }
  6367. struct ggml_tensor * ggml_map_custom1(
  6368. struct ggml_context * ctx,
  6369. struct ggml_tensor * a,
  6370. const ggml_custom1_op_t fun,
  6371. int n_tasks,
  6372. void * userdata) {
  6373. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, false);
  6374. }
  6375. struct ggml_tensor * ggml_map_custom1_inplace(
  6376. struct ggml_context * ctx,
  6377. struct ggml_tensor * a,
  6378. const ggml_custom1_op_t fun,
  6379. int n_tasks,
  6380. void * userdata) {
  6381. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, true);
  6382. }
  6383. // ggml_map_custom2
  6384. struct ggml_map_custom2_op_params {
  6385. ggml_custom2_op_t fun;
  6386. int n_tasks;
  6387. void * userdata;
  6388. };
  6389. static struct ggml_tensor * ggml_map_custom2_impl(
  6390. struct ggml_context * ctx,
  6391. struct ggml_tensor * a,
  6392. struct ggml_tensor * b,
  6393. const ggml_custom2_op_t fun,
  6394. int n_tasks,
  6395. void * userdata,
  6396. bool inplace) {
  6397. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  6398. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6399. struct ggml_map_custom2_op_params params = {
  6400. /*.fun =*/ fun,
  6401. /*.n_tasks =*/ n_tasks,
  6402. /*.userdata =*/ userdata
  6403. };
  6404. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  6405. result->op = GGML_OP_MAP_CUSTOM2;
  6406. result->src[0] = a;
  6407. result->src[1] = b;
  6408. return result;
  6409. }
  6410. struct ggml_tensor * ggml_map_custom2(
  6411. struct ggml_context * ctx,
  6412. struct ggml_tensor * a,
  6413. struct ggml_tensor * b,
  6414. const ggml_custom2_op_t fun,
  6415. int n_tasks,
  6416. void * userdata) {
  6417. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, false);
  6418. }
  6419. struct ggml_tensor * ggml_map_custom2_inplace(
  6420. struct ggml_context * ctx,
  6421. struct ggml_tensor * a,
  6422. struct ggml_tensor * b,
  6423. const ggml_custom2_op_t fun,
  6424. int n_tasks,
  6425. void * userdata) {
  6426. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, true);
  6427. }
  6428. // ggml_map_custom3
  6429. struct ggml_map_custom3_op_params {
  6430. ggml_custom3_op_t fun;
  6431. int n_tasks;
  6432. void * userdata;
  6433. };
  6434. static struct ggml_tensor * ggml_map_custom3_impl(
  6435. struct ggml_context * ctx,
  6436. struct ggml_tensor * a,
  6437. struct ggml_tensor * b,
  6438. struct ggml_tensor * c,
  6439. const ggml_custom3_op_t fun,
  6440. int n_tasks,
  6441. void * userdata,
  6442. bool inplace) {
  6443. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  6444. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6445. struct ggml_map_custom3_op_params params = {
  6446. /*.fun =*/ fun,
  6447. /*.n_tasks =*/ n_tasks,
  6448. /*.userdata =*/ userdata
  6449. };
  6450. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  6451. result->op = GGML_OP_MAP_CUSTOM3;
  6452. result->src[0] = a;
  6453. result->src[1] = b;
  6454. result->src[2] = c;
  6455. return result;
  6456. }
  6457. struct ggml_tensor * ggml_map_custom3(
  6458. struct ggml_context * ctx,
  6459. struct ggml_tensor * a,
  6460. struct ggml_tensor * b,
  6461. struct ggml_tensor * c,
  6462. const ggml_custom3_op_t fun,
  6463. int n_tasks,
  6464. void * userdata) {
  6465. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, false);
  6466. }
  6467. struct ggml_tensor * ggml_map_custom3_inplace(
  6468. struct ggml_context * ctx,
  6469. struct ggml_tensor * a,
  6470. struct ggml_tensor * b,
  6471. struct ggml_tensor * c,
  6472. const ggml_custom3_op_t fun,
  6473. int n_tasks,
  6474. void * userdata) {
  6475. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, true);
  6476. }
  6477. // ggml_cross_entropy_loss
  6478. struct ggml_tensor * ggml_cross_entropy_loss(
  6479. struct ggml_context * ctx,
  6480. struct ggml_tensor * a,
  6481. struct ggml_tensor * b) {
  6482. GGML_ASSERT(ggml_are_same_shape(a, b));
  6483. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  6484. result->op = GGML_OP_CROSS_ENTROPY_LOSS;
  6485. result->src[0] = a;
  6486. result->src[1] = b;
  6487. return result;
  6488. }
  6489. // ggml_cross_entropy_loss_back
  6490. struct ggml_tensor * ggml_cross_entropy_loss_back(
  6491. struct ggml_context * ctx,
  6492. struct ggml_tensor * a,
  6493. struct ggml_tensor * b,
  6494. struct ggml_tensor * c) {
  6495. GGML_ASSERT(ggml_are_same_shape(a, b));
  6496. GGML_ASSERT(ggml_is_scalar(c));
  6497. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  6498. result->op = GGML_OP_CROSS_ENTROPY_LOSS_BACK;
  6499. result->src[0] = a;
  6500. result->src[1] = b;
  6501. result->src[2] = c;
  6502. return result;
  6503. }
  6504. // opt_step_adamw
  6505. struct ggml_tensor * ggml_opt_step_adamw(
  6506. struct ggml_context * ctx,
  6507. struct ggml_tensor * a,
  6508. float alpha,
  6509. float beta1,
  6510. float beta2,
  6511. float eps,
  6512. float wd) {
  6513. GGML_ASSERT(a->flags & GGML_TENSOR_FLAG_PARAM);
  6514. GGML_ASSERT(alpha > 0.0f);
  6515. GGML_ASSERT(beta1 >= 0.0f && beta1 <= 1.0f);
  6516. GGML_ASSERT(beta2 >= 0.0f && beta2 <= 1.0f);
  6517. GGML_ASSERT(eps >= 0.0f);
  6518. GGML_ASSERT(wd >= 0.0f && wd <= 1.0f);
  6519. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  6520. const int64_t iter = 1;
  6521. memcpy(&result->op_params[0], &iter, sizeof(int64_t));
  6522. ggml_set_op_params_f32(result, 2, alpha);
  6523. ggml_set_op_params_f32(result, 3, beta1);
  6524. ggml_set_op_params_f32(result, 4, beta2);
  6525. ggml_set_op_params_f32(result, 5, eps);
  6526. ggml_set_op_params_f32(result, 6, wd);
  6527. result->op = GGML_OP_OPT_STEP_ADAMW;
  6528. result->src[0] = a;
  6529. result->src[1] = a->grad;
  6530. result->src[2] = ggml_dup_tensor(ctx, a);
  6531. result->src[3] = ggml_dup_tensor(ctx, a);
  6532. return result;
  6533. }
  6534. ////////////////////////////////////////////////////////////////////////////////
  6535. // ggml_compute_forward_dup
  6536. static void ggml_compute_forward_dup_same_cont(
  6537. const struct ggml_compute_params * params,
  6538. struct ggml_tensor * dst) {
  6539. const struct ggml_tensor * src0 = dst->src[0];
  6540. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  6541. GGML_ASSERT(ggml_is_contiguous(dst) && ggml_is_contiguous(src0));
  6542. GGML_ASSERT(src0->type == dst->type);
  6543. const size_t nb0 = ggml_type_size(src0->type);
  6544. const int ith = params->ith; // thread index
  6545. const int nth = params->nth; // number of threads
  6546. // parallelize by elements
  6547. const int ne = ggml_nelements(dst);
  6548. const int dr = (ne + nth - 1) / nth;
  6549. const int ie0 = dr * ith;
  6550. const int ie1 = MIN(ie0 + dr, ne);
  6551. if (ie0 < ie1) {
  6552. memcpy(
  6553. ((char *) dst->data + ie0*nb0),
  6554. ((char *) src0->data + ie0*nb0),
  6555. (ie1 - ie0) * nb0);
  6556. }
  6557. }
  6558. static void ggml_compute_forward_dup_f16(
  6559. const struct ggml_compute_params * params,
  6560. struct ggml_tensor * dst) {
  6561. const struct ggml_tensor * src0 = dst->src[0];
  6562. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  6563. GGML_TENSOR_UNARY_OP_LOCALS
  6564. const int ith = params->ith; // thread index
  6565. const int nth = params->nth; // number of threads
  6566. // parallelize by rows
  6567. const int nr = ne01;
  6568. // number of rows per thread
  6569. const int dr = (nr + nth - 1) / nth;
  6570. // row range for this thread
  6571. const int ir0 = dr * ith;
  6572. const int ir1 = MIN(ir0 + dr, nr);
  6573. if (src0->type == dst->type &&
  6574. ne00 == ne0 &&
  6575. nb00 == ggml_type_size(src0->type) && nb0 == ggml_type_size(dst->type)) {
  6576. // copy by rows
  6577. const size_t rs = ne00*nb00;
  6578. for (int64_t i03 = 0; i03 < ne03; i03++) {
  6579. for (int64_t i02 = 0; i02 < ne02; i02++) {
  6580. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  6581. memcpy(
  6582. ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  6583. ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03),
  6584. rs);
  6585. }
  6586. }
  6587. }
  6588. return;
  6589. }
  6590. // TODO: add more special-case implementations for tensor shapes/strides that can benefit from memcpy
  6591. if (ggml_is_contiguous(dst)) {
  6592. if (nb00 == sizeof(ggml_fp16_t)) {
  6593. if (dst->type == GGML_TYPE_F16) {
  6594. size_t id = 0;
  6595. const size_t rs = ne00 * nb00;
  6596. char * dst_ptr = (char *) dst->data;
  6597. for (int i03 = 0; i03 < ne03; i03++) {
  6598. for (int i02 = 0; i02 < ne02; i02++) {
  6599. id += rs * ir0;
  6600. for (int i01 = ir0; i01 < ir1; i01++) {
  6601. const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  6602. memcpy(dst_ptr + id, src0_ptr, rs);
  6603. id += rs;
  6604. }
  6605. id += rs * (ne01 - ir1);
  6606. }
  6607. }
  6608. } else if (dst->type == GGML_TYPE_F32) {
  6609. size_t id = 0;
  6610. float * dst_ptr = (float *) dst->data;
  6611. for (int i03 = 0; i03 < ne03; i03++) {
  6612. for (int i02 = 0; i02 < ne02; i02++) {
  6613. id += ne00 * ir0;
  6614. for (int i01 = ir0; i01 < ir1; i01++) {
  6615. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6616. for (int i00 = 0; i00 < ne00; i00++) {
  6617. dst_ptr[id] = GGML_FP16_TO_FP32(src0_ptr[i00]);
  6618. id++;
  6619. }
  6620. }
  6621. id += ne00 * (ne01 - ir1);
  6622. }
  6623. }
  6624. } else if (type_traits[dst->type].from_float) {
  6625. ggml_from_float_t const quantize_row_q = type_traits[dst->type].from_float;
  6626. float * src0_f32 = (float *) params->wdata + (ne00 + CACHE_LINE_SIZE_F32) * ith;
  6627. size_t id = 0;
  6628. size_t rs = nb0 * (ne00 / ggml_blck_size(dst->type));
  6629. char * dst_ptr = (char *) dst->data;
  6630. for (int i03 = 0; i03 < ne03; i03++) {
  6631. for (int i02 = 0; i02 < ne02; i02++) {
  6632. id += rs * ir0;
  6633. for (int i01 = ir0; i01 < ir1; i01++) {
  6634. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6635. for (int i00 = 0; i00 < ne00; i00++) {
  6636. src0_f32[i00] = GGML_FP16_TO_FP32(src0_ptr[i00]);
  6637. }
  6638. quantize_row_q(src0_f32, dst_ptr + id, ne00);
  6639. id += rs;
  6640. }
  6641. id += rs * (ne01 - ir1);
  6642. }
  6643. }
  6644. } else {
  6645. GGML_ABORT("fatal error"); // TODO: implement
  6646. }
  6647. } else {
  6648. //printf("%s: this is not optimal - fix me\n", __func__);
  6649. if (dst->type == GGML_TYPE_F32) {
  6650. size_t id = 0;
  6651. float * dst_ptr = (float *) dst->data;
  6652. for (int i03 = 0; i03 < ne03; i03++) {
  6653. for (int i02 = 0; i02 < ne02; i02++) {
  6654. id += ne00 * ir0;
  6655. for (int i01 = ir0; i01 < ir1; i01++) {
  6656. for (int i00 = 0; i00 < ne00; i00++) {
  6657. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6658. dst_ptr[id] = GGML_FP16_TO_FP32(*src0_ptr);
  6659. id++;
  6660. }
  6661. }
  6662. id += ne00 * (ne01 - ir1);
  6663. }
  6664. }
  6665. } else if (dst->type == GGML_TYPE_F16) {
  6666. size_t id = 0;
  6667. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  6668. for (int i03 = 0; i03 < ne03; i03++) {
  6669. for (int i02 = 0; i02 < ne02; i02++) {
  6670. id += ne00 * ir0;
  6671. for (int i01 = ir0; i01 < ir1; i01++) {
  6672. for (int i00 = 0; i00 < ne00; i00++) {
  6673. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6674. dst_ptr[id] = *src0_ptr;
  6675. id++;
  6676. }
  6677. }
  6678. id += ne00 * (ne01 - ir1);
  6679. }
  6680. }
  6681. } else {
  6682. GGML_ABORT("fatal error"); // TODO: implement
  6683. }
  6684. }
  6685. return;
  6686. }
  6687. // dst counters
  6688. int64_t i10 = 0;
  6689. int64_t i11 = 0;
  6690. int64_t i12 = 0;
  6691. int64_t i13 = 0;
  6692. if (dst->type == GGML_TYPE_F16) {
  6693. for (int64_t i03 = 0; i03 < ne03; i03++) {
  6694. for (int64_t i02 = 0; i02 < ne02; i02++) {
  6695. i10 += ne00 * ir0;
  6696. while (i10 >= ne0) {
  6697. i10 -= ne0;
  6698. if (++i11 == ne1) {
  6699. i11 = 0;
  6700. if (++i12 == ne2) {
  6701. i12 = 0;
  6702. if (++i13 == ne3) {
  6703. i13 = 0;
  6704. }
  6705. }
  6706. }
  6707. }
  6708. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  6709. for (int64_t i00 = 0; i00 < ne00; i00++) {
  6710. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6711. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  6712. memcpy(dst_ptr, src0_ptr, sizeof(ggml_fp16_t));
  6713. if (++i10 == ne00) {
  6714. i10 = 0;
  6715. if (++i11 == ne01) {
  6716. i11 = 0;
  6717. if (++i12 == ne02) {
  6718. i12 = 0;
  6719. if (++i13 == ne03) {
  6720. i13 = 0;
  6721. }
  6722. }
  6723. }
  6724. }
  6725. }
  6726. }
  6727. i10 += ne00 * (ne01 - ir1);
  6728. while (i10 >= ne0) {
  6729. i10 -= ne0;
  6730. if (++i11 == ne1) {
  6731. i11 = 0;
  6732. if (++i12 == ne2) {
  6733. i12 = 0;
  6734. if (++i13 == ne3) {
  6735. i13 = 0;
  6736. }
  6737. }
  6738. }
  6739. }
  6740. }
  6741. }
  6742. } else if (dst->type == GGML_TYPE_F32) {
  6743. for (int64_t i03 = 0; i03 < ne03; i03++) {
  6744. for (int64_t i02 = 0; i02 < ne02; i02++) {
  6745. i10 += ne00 * ir0;
  6746. while (i10 >= ne0) {
  6747. i10 -= ne0;
  6748. if (++i11 == ne1) {
  6749. i11 = 0;
  6750. if (++i12 == ne2) {
  6751. i12 = 0;
  6752. if (++i13 == ne3) {
  6753. i13 = 0;
  6754. }
  6755. }
  6756. }
  6757. }
  6758. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  6759. for (int64_t i00 = 0; i00 < ne00; i00++) {
  6760. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6761. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  6762. *(float *) dst_ptr = GGML_FP16_TO_FP32(*(const ggml_fp16_t *) src0_ptr);
  6763. if (++i10 == ne0) {
  6764. i10 = 0;
  6765. if (++i11 == ne1) {
  6766. i11 = 0;
  6767. if (++i12 == ne2) {
  6768. i12 = 0;
  6769. if (++i13 == ne3) {
  6770. i13 = 0;
  6771. }
  6772. }
  6773. }
  6774. }
  6775. }
  6776. }
  6777. i10 += ne00 * (ne01 - ir1);
  6778. while (i10 >= ne0) {
  6779. i10 -= ne0;
  6780. if (++i11 == ne1) {
  6781. i11 = 0;
  6782. if (++i12 == ne2) {
  6783. i12 = 0;
  6784. if (++i13 == ne3) {
  6785. i13 = 0;
  6786. }
  6787. }
  6788. }
  6789. }
  6790. }
  6791. }
  6792. } else {
  6793. GGML_ABORT("fatal error"); // TODO: implement
  6794. }
  6795. }
  6796. static void ggml_compute_forward_dup_bf16(
  6797. const struct ggml_compute_params * params,
  6798. struct ggml_tensor * dst) {
  6799. const struct ggml_tensor * src0 = dst->src[0];
  6800. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  6801. GGML_TENSOR_UNARY_OP_LOCALS
  6802. const int ith = params->ith; // thread index
  6803. const int nth = params->nth; // number of threads
  6804. // parallelize by rows
  6805. const int nr = ne01;
  6806. // number of rows per thread
  6807. const int dr = (nr + nth - 1) / nth;
  6808. // row range for this thread
  6809. const int ir0 = dr * ith;
  6810. const int ir1 = MIN(ir0 + dr, nr);
  6811. if (src0->type == dst->type &&
  6812. ne00 == ne0 &&
  6813. nb00 == ggml_type_size(src0->type) && nb0 == ggml_type_size(dst->type)) {
  6814. // copy by rows
  6815. const size_t rs = ne00*nb00;
  6816. for (int64_t i03 = 0; i03 < ne03; i03++) {
  6817. for (int64_t i02 = 0; i02 < ne02; i02++) {
  6818. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  6819. memcpy(
  6820. ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  6821. ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03),
  6822. rs);
  6823. }
  6824. }
  6825. }
  6826. return;
  6827. }
  6828. // TODO: add more special-case implementations for tensor shapes/strides that can benefit from memcpy
  6829. if (ggml_is_contiguous(dst)) {
  6830. if (nb00 == sizeof(ggml_bf16_t)) {
  6831. if (dst->type == GGML_TYPE_BF16) {
  6832. size_t id = 0;
  6833. const size_t rs = ne00 * nb00;
  6834. char * dst_ptr = (char *) dst->data;
  6835. for (int i03 = 0; i03 < ne03; i03++) {
  6836. for (int i02 = 0; i02 < ne02; i02++) {
  6837. id += rs * ir0;
  6838. for (int i01 = ir0; i01 < ir1; i01++) {
  6839. const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  6840. memcpy(dst_ptr + id, src0_ptr, rs);
  6841. id += rs;
  6842. }
  6843. id += rs * (ne01 - ir1);
  6844. }
  6845. }
  6846. } else if (dst->type == GGML_TYPE_F16) {
  6847. size_t id = 0;
  6848. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  6849. for (int i03 = 0; i03 < ne03; i03++) {
  6850. for (int i02 = 0; i02 < ne02; i02++) {
  6851. id += ne00 * ir0;
  6852. for (int i01 = ir0; i01 < ir1; i01++) {
  6853. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6854. for (int i00 = 0; i00 < ne00; i00++) {
  6855. dst_ptr[id] = GGML_FP32_TO_FP16(GGML_BF16_TO_FP32(src0_ptr[i00]));
  6856. id++;
  6857. }
  6858. }
  6859. id += ne00 * (ne01 - ir1);
  6860. }
  6861. }
  6862. } else if (dst->type == GGML_TYPE_F32) {
  6863. size_t id = 0;
  6864. float * dst_ptr = (float *) dst->data;
  6865. for (int i03 = 0; i03 < ne03; i03++) {
  6866. for (int i02 = 0; i02 < ne02; i02++) {
  6867. id += ne00 * ir0;
  6868. for (int i01 = ir0; i01 < ir1; i01++) {
  6869. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6870. for (int i00 = 0; i00 < ne00; i00++) {
  6871. dst_ptr[id] = GGML_BF16_TO_FP32(src0_ptr[i00]);
  6872. id++;
  6873. }
  6874. }
  6875. id += ne00 * (ne01 - ir1);
  6876. }
  6877. }
  6878. } else if (type_traits[dst->type].from_float) {
  6879. ggml_from_float_t const quantize_row_q = type_traits[dst->type].from_float;
  6880. float * src0_f32 = (float *) params->wdata + (ne00 + CACHE_LINE_SIZE_F32) * ith;
  6881. size_t id = 0;
  6882. size_t rs = nb0 * (ne00 / ggml_blck_size(dst->type));
  6883. char * dst_ptr = (char *) dst->data;
  6884. for (int i03 = 0; i03 < ne03; i03++) {
  6885. for (int i02 = 0; i02 < ne02; i02++) {
  6886. id += rs * ir0;
  6887. for (int i01 = ir0; i01 < ir1; i01++) {
  6888. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6889. for (int i00 = 0; i00 < ne00; i00++) {
  6890. src0_f32[i00] = GGML_BF16_TO_FP32(src0_ptr[i00]);
  6891. }
  6892. quantize_row_q(src0_f32, dst_ptr + id, ne00);
  6893. id += rs;
  6894. }
  6895. id += rs * (ne01 - ir1);
  6896. }
  6897. }
  6898. } else {
  6899. GGML_ABORT("fatal error"); // TODO: implement
  6900. }
  6901. } else {
  6902. //printf("%s: this is not optimal - fix me\n", __func__);
  6903. if (dst->type == GGML_TYPE_F32) {
  6904. size_t id = 0;
  6905. float * dst_ptr = (float *) dst->data;
  6906. for (int i03 = 0; i03 < ne03; i03++) {
  6907. for (int i02 = 0; i02 < ne02; i02++) {
  6908. id += ne00 * ir0;
  6909. for (int i01 = ir0; i01 < ir1; i01++) {
  6910. for (int i00 = 0; i00 < ne00; i00++) {
  6911. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6912. dst_ptr[id] = GGML_BF16_TO_FP32(*src0_ptr);
  6913. id++;
  6914. }
  6915. }
  6916. id += ne00 * (ne01 - ir1);
  6917. }
  6918. }
  6919. } else if (dst->type == GGML_TYPE_BF16) {
  6920. size_t id = 0;
  6921. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) dst->data;
  6922. for (int i03 = 0; i03 < ne03; i03++) {
  6923. for (int i02 = 0; i02 < ne02; i02++) {
  6924. id += ne00 * ir0;
  6925. for (int i01 = ir0; i01 < ir1; i01++) {
  6926. for (int i00 = 0; i00 < ne00; i00++) {
  6927. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6928. dst_ptr[id] = *src0_ptr;
  6929. id++;
  6930. }
  6931. }
  6932. id += ne00 * (ne01 - ir1);
  6933. }
  6934. }
  6935. } else if (dst->type == GGML_TYPE_F16) {
  6936. size_t id = 0;
  6937. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  6938. for (int i03 = 0; i03 < ne03; i03++) {
  6939. for (int i02 = 0; i02 < ne02; i02++) {
  6940. id += ne00 * ir0;
  6941. for (int i01 = ir0; i01 < ir1; i01++) {
  6942. for (int i00 = 0; i00 < ne00; i00++) {
  6943. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6944. dst_ptr[id] = GGML_FP32_TO_FP16(GGML_BF16_TO_FP32(*src0_ptr));
  6945. id++;
  6946. }
  6947. }
  6948. id += ne00 * (ne01 - ir1);
  6949. }
  6950. }
  6951. } else {
  6952. GGML_ABORT("fatal error"); // TODO: implement
  6953. }
  6954. }
  6955. return;
  6956. }
  6957. // dst counters
  6958. int64_t i10 = 0;
  6959. int64_t i11 = 0;
  6960. int64_t i12 = 0;
  6961. int64_t i13 = 0;
  6962. if (dst->type == GGML_TYPE_BF16) {
  6963. for (int64_t i03 = 0; i03 < ne03; i03++) {
  6964. for (int64_t i02 = 0; i02 < ne02; i02++) {
  6965. i10 += ne00 * ir0;
  6966. while (i10 >= ne0) {
  6967. i10 -= ne0;
  6968. if (++i11 == ne1) {
  6969. i11 = 0;
  6970. if (++i12 == ne2) {
  6971. i12 = 0;
  6972. if (++i13 == ne3) {
  6973. i13 = 0;
  6974. }
  6975. }
  6976. }
  6977. }
  6978. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  6979. for (int64_t i00 = 0; i00 < ne00; i00++) {
  6980. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6981. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  6982. memcpy(dst_ptr, src0_ptr, sizeof(ggml_bf16_t));
  6983. if (++i10 == ne00) {
  6984. i10 = 0;
  6985. if (++i11 == ne01) {
  6986. i11 = 0;
  6987. if (++i12 == ne02) {
  6988. i12 = 0;
  6989. if (++i13 == ne03) {
  6990. i13 = 0;
  6991. }
  6992. }
  6993. }
  6994. }
  6995. }
  6996. }
  6997. i10 += ne00 * (ne01 - ir1);
  6998. while (i10 >= ne0) {
  6999. i10 -= ne0;
  7000. if (++i11 == ne1) {
  7001. i11 = 0;
  7002. if (++i12 == ne2) {
  7003. i12 = 0;
  7004. if (++i13 == ne3) {
  7005. i13 = 0;
  7006. }
  7007. }
  7008. }
  7009. }
  7010. }
  7011. }
  7012. } else if (dst->type == GGML_TYPE_F16) {
  7013. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7014. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7015. i10 += ne00 * ir0;
  7016. while (i10 >= ne0) {
  7017. i10 -= ne0;
  7018. if (++i11 == ne1) {
  7019. i11 = 0;
  7020. if (++i12 == ne2) {
  7021. i12 = 0;
  7022. if (++i13 == ne3) {
  7023. i13 = 0;
  7024. }
  7025. }
  7026. }
  7027. }
  7028. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7029. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7030. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7031. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7032. *(ggml_fp16_t *) dst_ptr = GGML_FP32_TO_FP16(GGML_BF16_TO_FP32(*(const ggml_bf16_t *) src0_ptr));
  7033. if (++i10 == ne0) {
  7034. i10 = 0;
  7035. if (++i11 == ne1) {
  7036. i11 = 0;
  7037. if (++i12 == ne2) {
  7038. i12 = 0;
  7039. if (++i13 == ne3) {
  7040. i13 = 0;
  7041. }
  7042. }
  7043. }
  7044. }
  7045. }
  7046. }
  7047. i10 += ne00 * (ne01 - ir1);
  7048. while (i10 >= ne0) {
  7049. i10 -= ne0;
  7050. if (++i11 == ne1) {
  7051. i11 = 0;
  7052. if (++i12 == ne2) {
  7053. i12 = 0;
  7054. if (++i13 == ne3) {
  7055. i13 = 0;
  7056. }
  7057. }
  7058. }
  7059. }
  7060. }
  7061. }
  7062. } else if (dst->type == GGML_TYPE_F32) {
  7063. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7064. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7065. i10 += ne00 * ir0;
  7066. while (i10 >= ne0) {
  7067. i10 -= ne0;
  7068. if (++i11 == ne1) {
  7069. i11 = 0;
  7070. if (++i12 == ne2) {
  7071. i12 = 0;
  7072. if (++i13 == ne3) {
  7073. i13 = 0;
  7074. }
  7075. }
  7076. }
  7077. }
  7078. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7079. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7080. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7081. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7082. *(float *) dst_ptr = GGML_BF16_TO_FP32(*(const ggml_bf16_t *) src0_ptr);
  7083. if (++i10 == ne0) {
  7084. i10 = 0;
  7085. if (++i11 == ne1) {
  7086. i11 = 0;
  7087. if (++i12 == ne2) {
  7088. i12 = 0;
  7089. if (++i13 == ne3) {
  7090. i13 = 0;
  7091. }
  7092. }
  7093. }
  7094. }
  7095. }
  7096. }
  7097. i10 += ne00 * (ne01 - ir1);
  7098. while (i10 >= ne0) {
  7099. i10 -= ne0;
  7100. if (++i11 == ne1) {
  7101. i11 = 0;
  7102. if (++i12 == ne2) {
  7103. i12 = 0;
  7104. if (++i13 == ne3) {
  7105. i13 = 0;
  7106. }
  7107. }
  7108. }
  7109. }
  7110. }
  7111. }
  7112. } else {
  7113. GGML_ABORT("fatal error"); // TODO: implement
  7114. }
  7115. }
  7116. static void ggml_compute_forward_dup_f32(
  7117. const struct ggml_compute_params * params,
  7118. struct ggml_tensor * dst) {
  7119. const struct ggml_tensor * src0 = dst->src[0];
  7120. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  7121. GGML_TENSOR_UNARY_OP_LOCALS
  7122. const int ith = params->ith; // thread index
  7123. const int nth = params->nth; // number of threads
  7124. // parallelize by rows
  7125. const int nr = ne01;
  7126. // number of rows per thread
  7127. const int dr = (nr + nth - 1) / nth;
  7128. // row range for this thread
  7129. const int ir0 = dr * ith;
  7130. const int ir1 = MIN(ir0 + dr, nr);
  7131. if (src0->type == dst->type &&
  7132. ne00 == ne0 &&
  7133. nb00 == ggml_type_size(src0->type) && nb0 == ggml_type_size(dst->type)) {
  7134. // copy by rows
  7135. const size_t rs = ne00*nb00;
  7136. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7137. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7138. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7139. memcpy(
  7140. ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  7141. ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03),
  7142. rs);
  7143. }
  7144. }
  7145. }
  7146. return;
  7147. }
  7148. if (ggml_is_contiguous(dst)) {
  7149. // TODO: simplify
  7150. if (nb00 == sizeof(float)) {
  7151. if (dst->type == GGML_TYPE_F32) {
  7152. size_t id = 0;
  7153. const size_t rs = ne00 * nb00;
  7154. char * dst_ptr = (char *) dst->data;
  7155. for (int i03 = 0; i03 < ne03; i03++) {
  7156. for (int i02 = 0; i02 < ne02; i02++) {
  7157. id += rs * ir0;
  7158. for (int i01 = ir0; i01 < ir1; i01++) {
  7159. const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  7160. memcpy(dst_ptr + id, src0_ptr, rs);
  7161. id += rs;
  7162. }
  7163. id += rs * (ne01 - ir1);
  7164. }
  7165. }
  7166. } else if (type_traits[dst->type].from_float) {
  7167. ggml_from_float_t const quantize_row_q = type_traits[dst->type].from_float;
  7168. size_t id = 0;
  7169. size_t rs = nb0 * (ne00 / ggml_blck_size(dst->type));
  7170. char * dst_ptr = (char *) dst->data;
  7171. for (int i03 = 0; i03 < ne03; i03++) {
  7172. for (int i02 = 0; i02 < ne02; i02++) {
  7173. id += rs * ir0;
  7174. for (int i01 = ir0; i01 < ir1; i01++) {
  7175. const float * src0_ptr = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  7176. quantize_row_q(src0_ptr, dst_ptr + id, ne00);
  7177. id += rs;
  7178. }
  7179. id += rs * (ne01 - ir1);
  7180. }
  7181. }
  7182. } else {
  7183. GGML_ABORT("fatal error"); // TODO: implement
  7184. }
  7185. } else {
  7186. //printf("%s: this is not optimal - fix me\n", __func__);
  7187. if (dst->type == GGML_TYPE_F32) {
  7188. size_t id = 0;
  7189. float * dst_ptr = (float *) dst->data;
  7190. for (int i03 = 0; i03 < ne03; i03++) {
  7191. for (int i02 = 0; i02 < ne02; i02++) {
  7192. id += ne00 * ir0;
  7193. for (int i01 = ir0; i01 < ir1; i01++) {
  7194. for (int i00 = 0; i00 < ne00; i00++) {
  7195. const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7196. dst_ptr[id] = *src0_ptr;
  7197. id++;
  7198. }
  7199. }
  7200. id += ne00 * (ne01 - ir1);
  7201. }
  7202. }
  7203. } else if (dst->type == GGML_TYPE_F16) {
  7204. size_t id = 0;
  7205. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  7206. for (int i03 = 0; i03 < ne03; i03++) {
  7207. for (int i02 = 0; i02 < ne02; i02++) {
  7208. id += ne00 * ir0;
  7209. for (int i01 = ir0; i01 < ir1; i01++) {
  7210. for (int i00 = 0; i00 < ne00; i00++) {
  7211. const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7212. dst_ptr[id] = GGML_FP32_TO_FP16(*src0_ptr);
  7213. id++;
  7214. }
  7215. }
  7216. id += ne00 * (ne01 - ir1);
  7217. }
  7218. }
  7219. } else if (dst->type == GGML_TYPE_BF16) {
  7220. size_t id = 0;
  7221. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) dst->data;
  7222. for (int i03 = 0; i03 < ne03; i03++) {
  7223. for (int i02 = 0; i02 < ne02; i02++) {
  7224. id += ne00 * ir0;
  7225. for (int i01 = ir0; i01 < ir1; i01++) {
  7226. for (int i00 = 0; i00 < ne00; i00++) {
  7227. const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7228. dst_ptr[id] = GGML_FP32_TO_BF16(*src0_ptr);
  7229. id++;
  7230. }
  7231. }
  7232. id += ne00 * (ne01 - ir1);
  7233. }
  7234. }
  7235. } else {
  7236. GGML_ABORT("fatal error"); // TODO: implement
  7237. }
  7238. }
  7239. return;
  7240. }
  7241. // dst counters
  7242. int64_t i10 = 0;
  7243. int64_t i11 = 0;
  7244. int64_t i12 = 0;
  7245. int64_t i13 = 0;
  7246. if (dst->type == GGML_TYPE_F32) {
  7247. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7248. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7249. i10 += ne00 * ir0;
  7250. while (i10 >= ne0) {
  7251. i10 -= ne0;
  7252. if (++i11 == ne1) {
  7253. i11 = 0;
  7254. if (++i12 == ne2) {
  7255. i12 = 0;
  7256. if (++i13 == ne3) {
  7257. i13 = 0;
  7258. }
  7259. }
  7260. }
  7261. }
  7262. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7263. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7264. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7265. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7266. memcpy(dst_ptr, src0_ptr, sizeof(float));
  7267. if (++i10 == ne0) {
  7268. i10 = 0;
  7269. if (++i11 == ne1) {
  7270. i11 = 0;
  7271. if (++i12 == ne2) {
  7272. i12 = 0;
  7273. if (++i13 == ne3) {
  7274. i13 = 0;
  7275. }
  7276. }
  7277. }
  7278. }
  7279. }
  7280. }
  7281. i10 += ne00 * (ne01 - ir1);
  7282. while (i10 >= ne0) {
  7283. i10 -= ne0;
  7284. if (++i11 == ne1) {
  7285. i11 = 0;
  7286. if (++i12 == ne2) {
  7287. i12 = 0;
  7288. if (++i13 == ne3) {
  7289. i13 = 0;
  7290. }
  7291. }
  7292. }
  7293. }
  7294. }
  7295. }
  7296. } else if (dst->type == GGML_TYPE_F16) {
  7297. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7298. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7299. i10 += ne00 * ir0;
  7300. while (i10 >= ne0) {
  7301. i10 -= ne0;
  7302. if (++i11 == ne1) {
  7303. i11 = 0;
  7304. if (++i12 == ne2) {
  7305. i12 = 0;
  7306. if (++i13 == ne3) {
  7307. i13 = 0;
  7308. }
  7309. }
  7310. }
  7311. }
  7312. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7313. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7314. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7315. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7316. *(ggml_fp16_t *) dst_ptr = GGML_FP32_TO_FP16(*(const float *) src0_ptr);
  7317. if (++i10 == ne0) {
  7318. i10 = 0;
  7319. if (++i11 == ne1) {
  7320. i11 = 0;
  7321. if (++i12 == ne2) {
  7322. i12 = 0;
  7323. if (++i13 == ne3) {
  7324. i13 = 0;
  7325. }
  7326. }
  7327. }
  7328. }
  7329. }
  7330. }
  7331. i10 += ne00 * (ne01 - ir1);
  7332. while (i10 >= ne0) {
  7333. i10 -= ne0;
  7334. if (++i11 == ne1) {
  7335. i11 = 0;
  7336. if (++i12 == ne2) {
  7337. i12 = 0;
  7338. if (++i13 == ne3) {
  7339. i13 = 0;
  7340. }
  7341. }
  7342. }
  7343. }
  7344. }
  7345. }
  7346. } else if (dst->type == GGML_TYPE_BF16) {
  7347. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7348. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7349. i10 += ne00 * ir0;
  7350. while (i10 >= ne0) {
  7351. i10 -= ne0;
  7352. if (++i11 == ne1) {
  7353. i11 = 0;
  7354. if (++i12 == ne2) {
  7355. i12 = 0;
  7356. if (++i13 == ne3) {
  7357. i13 = 0;
  7358. }
  7359. }
  7360. }
  7361. }
  7362. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7363. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7364. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7365. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7366. *(ggml_bf16_t *) dst_ptr = GGML_FP32_TO_BF16(*(const float *) src0_ptr);
  7367. if (++i10 == ne0) {
  7368. i10 = 0;
  7369. if (++i11 == ne1) {
  7370. i11 = 0;
  7371. if (++i12 == ne2) {
  7372. i12 = 0;
  7373. if (++i13 == ne3) {
  7374. i13 = 0;
  7375. }
  7376. }
  7377. }
  7378. }
  7379. }
  7380. }
  7381. i10 += ne00 * (ne01 - ir1);
  7382. while (i10 >= ne0) {
  7383. i10 -= ne0;
  7384. if (++i11 == ne1) {
  7385. i11 = 0;
  7386. if (++i12 == ne2) {
  7387. i12 = 0;
  7388. if (++i13 == ne3) {
  7389. i13 = 0;
  7390. }
  7391. }
  7392. }
  7393. }
  7394. }
  7395. }
  7396. } else {
  7397. GGML_ABORT("fatal error"); // TODO: implement
  7398. }
  7399. }
  7400. // A simplified version of ggml_compute_forward_dup that doesn't do float upcasting, and just plain old memcpy.
  7401. static void ggml_compute_forward_dup_bytes(
  7402. const struct ggml_compute_params * params,
  7403. struct ggml_tensor * dst) {
  7404. const struct ggml_tensor * src0 = dst->src[0];
  7405. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  7406. GGML_ASSERT(src0->type == dst->type);
  7407. GGML_TENSOR_UNARY_OP_LOCALS;
  7408. if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) {
  7409. ggml_compute_forward_dup_same_cont(params, dst);
  7410. return;
  7411. }
  7412. const size_t type_size = ggml_type_size(src0->type);
  7413. const int ith = params->ith; // thread index
  7414. const int nth = params->nth; // number of threads
  7415. // parallelize by rows
  7416. const int nr = ne01;
  7417. // number of rows per thread
  7418. const int dr = (nr + nth - 1) / nth;
  7419. // row range for this thread
  7420. const int ir0 = dr * ith;
  7421. const int ir1 = MIN(ir0 + dr, nr);
  7422. if (src0->type == dst->type &&
  7423. ne00 == ne0 &&
  7424. nb00 == type_size && nb0 == type_size) {
  7425. // copy by rows
  7426. const size_t rs = ne00 * type_size;
  7427. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7428. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7429. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7430. memcpy(
  7431. ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  7432. ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03),
  7433. rs);
  7434. }
  7435. }
  7436. }
  7437. return;
  7438. }
  7439. if (ggml_is_contiguous(dst)) {
  7440. size_t id = 0;
  7441. char * dst_ptr = (char *) dst->data;
  7442. const size_t rs = ne00 * type_size;
  7443. if (nb00 == type_size) {
  7444. // src0 is contigous on first dimension, copy by rows
  7445. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7446. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7447. id += rs * ir0;
  7448. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7449. const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  7450. memcpy(dst_ptr + id, src0_ptr, rs);
  7451. id += rs;
  7452. }
  7453. id += rs * (ne01 - ir1);
  7454. }
  7455. }
  7456. } else {
  7457. //printf("%s: this is not optimal - fix me\n", __func__);
  7458. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7459. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7460. id += rs * ir0;
  7461. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7462. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7463. const char * src0_ptr = (char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03;
  7464. memcpy(dst_ptr + id, src0_ptr, type_size);
  7465. id += type_size;
  7466. }
  7467. }
  7468. id += rs * (ne01 - ir1);
  7469. }
  7470. }
  7471. }
  7472. return;
  7473. }
  7474. // dst counters
  7475. int64_t i10 = 0;
  7476. int64_t i11 = 0;
  7477. int64_t i12 = 0;
  7478. int64_t i13 = 0;
  7479. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7480. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7481. i10 += ne00 * ir0;
  7482. while (i10 >= ne0) {
  7483. i10 -= ne0;
  7484. if (++i11 == ne1) {
  7485. i11 = 0;
  7486. if (++i12 == ne2) {
  7487. i12 = 0;
  7488. if (++i13 == ne3) {
  7489. i13 = 0;
  7490. }
  7491. }
  7492. }
  7493. }
  7494. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7495. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7496. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7497. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7498. memcpy(dst_ptr, src0_ptr, type_size);
  7499. if (++i10 == ne0) {
  7500. i10 = 0;
  7501. if (++i11 == ne1) {
  7502. i11 = 0;
  7503. if (++i12 == ne2) {
  7504. i12 = 0;
  7505. if (++i13 == ne3) {
  7506. i13 = 0;
  7507. }
  7508. }
  7509. }
  7510. }
  7511. }
  7512. }
  7513. i10 += ne00 * (ne01 - ir1);
  7514. while (i10 >= ne0) {
  7515. i10 -= ne0;
  7516. if (++i11 == ne1) {
  7517. i11 = 0;
  7518. if (++i12 == ne2) {
  7519. i12 = 0;
  7520. if (++i13 == ne3) {
  7521. i13 = 0;
  7522. }
  7523. }
  7524. }
  7525. }
  7526. }
  7527. }
  7528. }
  7529. static void ggml_compute_forward_dup(
  7530. const struct ggml_compute_params * params,
  7531. struct ggml_tensor * dst) {
  7532. const struct ggml_tensor * src0 = dst->src[0];
  7533. if (src0->type == dst->type) {
  7534. ggml_compute_forward_dup_bytes(params, dst);
  7535. return;
  7536. }
  7537. switch (src0->type) {
  7538. case GGML_TYPE_F16:
  7539. {
  7540. ggml_compute_forward_dup_f16(params, dst);
  7541. } break;
  7542. case GGML_TYPE_BF16:
  7543. {
  7544. ggml_compute_forward_dup_bf16(params, dst);
  7545. } break;
  7546. case GGML_TYPE_F32:
  7547. {
  7548. ggml_compute_forward_dup_f32(params, dst);
  7549. } break;
  7550. default:
  7551. {
  7552. GGML_ABORT("fatal error");
  7553. }
  7554. }
  7555. }
  7556. // ggml_compute_forward_add
  7557. static void ggml_compute_forward_add_f32(
  7558. const struct ggml_compute_params * params,
  7559. struct ggml_tensor * dst) {
  7560. const struct ggml_tensor * src0 = dst->src[0];
  7561. const struct ggml_tensor * src1 = dst->src[1];
  7562. GGML_ASSERT(ggml_can_repeat(src1, src0) && ggml_are_same_shape(src0, dst));
  7563. const int ith = params->ith;
  7564. const int nth = params->nth;
  7565. const int nr = ggml_nrows(src0);
  7566. GGML_TENSOR_BINARY_OP_LOCALS
  7567. GGML_ASSERT( nb0 == sizeof(float));
  7568. GGML_ASSERT(nb00 == sizeof(float));
  7569. // rows per thread
  7570. const int dr = (nr + nth - 1)/nth;
  7571. // row range for this thread
  7572. const int ir0 = dr*ith;
  7573. const int ir1 = MIN(ir0 + dr, nr);
  7574. if (nb10 == sizeof(float)) {
  7575. for (int ir = ir0; ir < ir1; ++ir) {
  7576. // src1 is broadcastable across src0 and dst in i1, i2, i3
  7577. const int64_t i03 = ir/(ne02*ne01);
  7578. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  7579. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  7580. const int64_t i13 = i03 % ne13;
  7581. const int64_t i12 = i02 % ne12;
  7582. const int64_t i11 = i01 % ne11;
  7583. const int64_t nr0 = ne00 / ne10;
  7584. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  7585. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  7586. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11);
  7587. for (int64_t r = 0; r < nr0; ++r) {
  7588. #ifdef GGML_USE_ACCELERATE
  7589. vDSP_vadd(src0_ptr + r*ne10, 1, src1_ptr, 1, dst_ptr + r*ne10, 1, ne10);
  7590. #else
  7591. ggml_vec_add_f32(ne10, dst_ptr + r*ne10, src0_ptr + r*ne10, src1_ptr);
  7592. #endif
  7593. }
  7594. }
  7595. } else {
  7596. // src1 is not contiguous
  7597. for (int ir = ir0; ir < ir1; ++ir) {
  7598. // src1 is broadcastable across src0 and dst in i1, i2, i3
  7599. const int64_t i03 = ir/(ne02*ne01);
  7600. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  7601. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  7602. const int64_t i13 = i03 % ne13;
  7603. const int64_t i12 = i02 % ne12;
  7604. const int64_t i11 = i01 % ne11;
  7605. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  7606. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  7607. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  7608. const int64_t i10 = i0 % ne10;
  7609. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10);
  7610. dst_ptr[i0] = src0_ptr[i0] + *src1_ptr;
  7611. }
  7612. }
  7613. }
  7614. }
  7615. static void ggml_compute_forward_add_f16_f32(
  7616. const struct ggml_compute_params * params,
  7617. struct ggml_tensor * dst) {
  7618. const struct ggml_tensor * src0 = dst->src[0];
  7619. const struct ggml_tensor * src1 = dst->src[1];
  7620. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7621. const int ith = params->ith;
  7622. const int nth = params->nth;
  7623. const int nr = ggml_nrows(src0);
  7624. GGML_TENSOR_BINARY_OP_LOCALS
  7625. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  7626. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  7627. if (dst->type == GGML_TYPE_F32) {
  7628. GGML_ASSERT( nb0 == sizeof(float));
  7629. }
  7630. else {
  7631. GGML_ASSERT(dst->type == GGML_TYPE_F16);
  7632. GGML_ASSERT( nb0 == sizeof(ggml_fp16_t));
  7633. }
  7634. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  7635. // rows per thread
  7636. const int dr = (nr + nth - 1)/nth;
  7637. // row range for this thread
  7638. const int ir0 = dr*ith;
  7639. const int ir1 = MIN(ir0 + dr, nr);
  7640. if (nb10 == sizeof(float)) {
  7641. if (dst->type == GGML_TYPE_F16) {
  7642. for (int ir = ir0; ir < ir1; ++ir) {
  7643. // src0, src1 and dst are same shape => same indices
  7644. const int i3 = ir/(ne2*ne1);
  7645. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7646. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7647. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7648. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7649. float * src1_ptr = (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7650. for (int i = 0; i < ne0; i++) {
  7651. dst_ptr[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(src0_ptr[i]) + src1_ptr[i]);
  7652. }
  7653. }
  7654. } else {
  7655. for (int ir = ir0; ir < ir1; ++ir) {
  7656. // src0, src1 and dst are same shape => same indices
  7657. const int i3 = ir/(ne2*ne1);
  7658. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7659. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7660. float * dst_ptr = (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7661. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7662. float * src1_ptr = (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7663. for (int i = 0; i < ne0; i++) {
  7664. dst_ptr[i] = GGML_FP16_TO_FP32(src0_ptr[i]) + src1_ptr[i];
  7665. }
  7666. }
  7667. }
  7668. }
  7669. else {
  7670. // src1 is not contiguous
  7671. GGML_ABORT("fatal error");
  7672. }
  7673. }
  7674. static void ggml_compute_forward_add_bf16_f32(
  7675. const struct ggml_compute_params * params,
  7676. struct ggml_tensor * dst) {
  7677. const struct ggml_tensor * src0 = dst->src[0];
  7678. const struct ggml_tensor * src1 = dst->src[1];
  7679. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7680. const int ith = params->ith;
  7681. const int nth = params->nth;
  7682. const int nr = ggml_nrows(src0);
  7683. GGML_TENSOR_BINARY_OP_LOCALS
  7684. GGML_ASSERT(src0->type == GGML_TYPE_BF16);
  7685. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  7686. if (dst->type == GGML_TYPE_F32) {
  7687. GGML_ASSERT( nb0 == sizeof(float));
  7688. }
  7689. else {
  7690. GGML_ASSERT(dst->type == GGML_TYPE_BF16);
  7691. GGML_ASSERT( nb0 == sizeof(ggml_bf16_t));
  7692. }
  7693. GGML_ASSERT(nb00 == sizeof(ggml_bf16_t));
  7694. // rows per thread
  7695. const int dr = (nr + nth - 1)/nth;
  7696. // row range for this thread
  7697. const int ir0 = dr*ith;
  7698. const int ir1 = MIN(ir0 + dr, nr);
  7699. if (nb10 == sizeof(float)) {
  7700. if (dst->type == GGML_TYPE_BF16) {
  7701. for (int ir = ir0; ir < ir1; ++ir) {
  7702. // src0, src1 and dst are same shape => same indices
  7703. const int i3 = ir/(ne2*ne1);
  7704. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7705. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7706. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7707. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7708. float * src1_ptr = (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7709. for (int i = 0; i < ne0; i++) {
  7710. dst_ptr[i] = GGML_FP32_TO_BF16(GGML_BF16_TO_FP32(src0_ptr[i]) + src1_ptr[i]);
  7711. }
  7712. }
  7713. } else {
  7714. for (int ir = ir0; ir < ir1; ++ir) {
  7715. // src0, src1 and dst are same shape => same indices
  7716. const int i3 = ir/(ne2*ne1);
  7717. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7718. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7719. float * dst_ptr = (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7720. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7721. float * src1_ptr = (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7722. for (int i = 0; i < ne0; i++) {
  7723. dst_ptr[i] = GGML_BF16_TO_FP32(src0_ptr[i]) + src1_ptr[i];
  7724. }
  7725. }
  7726. }
  7727. }
  7728. else {
  7729. // src1 is not contiguous
  7730. GGML_ABORT("fatal error");
  7731. }
  7732. }
  7733. static void ggml_compute_forward_add_f16_f16(
  7734. const struct ggml_compute_params * params,
  7735. struct ggml_tensor * dst) {
  7736. const struct ggml_tensor * src0 = dst->src[0];
  7737. const struct ggml_tensor * src1 = dst->src[1];
  7738. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7739. const int ith = params->ith;
  7740. const int nth = params->nth;
  7741. const int nr = ggml_nrows(src0);
  7742. GGML_TENSOR_BINARY_OP_LOCALS
  7743. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  7744. GGML_ASSERT(src1->type == GGML_TYPE_F16);
  7745. GGML_ASSERT(dst->type == GGML_TYPE_F16);
  7746. GGML_ASSERT( nb0 == sizeof(ggml_fp16_t));
  7747. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  7748. // rows per thread
  7749. const int dr = (nr + nth - 1)/nth;
  7750. // row range for this thread
  7751. const int ir0 = dr*ith;
  7752. const int ir1 = MIN(ir0 + dr, nr);
  7753. if (nb10 == sizeof(ggml_fp16_t)) {
  7754. for (int ir = ir0; ir < ir1; ++ir) {
  7755. // src0, src1 and dst are same shape => same indices
  7756. const int i3 = ir/(ne2*ne1);
  7757. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7758. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7759. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7760. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7761. ggml_fp16_t * src1_ptr = (ggml_fp16_t *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7762. for (int i = 0; i < ne0; i++) {
  7763. dst_ptr[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(src0_ptr[i]) + GGML_FP16_TO_FP32(src1_ptr[i]));
  7764. }
  7765. }
  7766. }
  7767. else {
  7768. // src1 is not contiguous
  7769. GGML_ABORT("fatal error");
  7770. }
  7771. }
  7772. static void ggml_compute_forward_add_bf16_bf16(
  7773. const struct ggml_compute_params * params,
  7774. struct ggml_tensor * dst) {
  7775. const struct ggml_tensor * src0 = dst->src[0];
  7776. const struct ggml_tensor * src1 = dst->src[1];
  7777. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7778. const int ith = params->ith;
  7779. const int nth = params->nth;
  7780. const int nr = ggml_nrows(src0);
  7781. GGML_TENSOR_BINARY_OP_LOCALS
  7782. GGML_ASSERT(src0->type == GGML_TYPE_BF16);
  7783. GGML_ASSERT(src1->type == GGML_TYPE_BF16);
  7784. GGML_ASSERT(dst->type == GGML_TYPE_BF16);
  7785. GGML_ASSERT( nb0 == sizeof(ggml_bf16_t));
  7786. GGML_ASSERT(nb00 == sizeof(ggml_bf16_t));
  7787. // rows per thread
  7788. const int dr = (nr + nth - 1)/nth;
  7789. // row range for this thread
  7790. const int ir0 = dr*ith;
  7791. const int ir1 = MIN(ir0 + dr, nr);
  7792. if (nb10 == sizeof(ggml_bf16_t)) {
  7793. for (int ir = ir0; ir < ir1; ++ir) {
  7794. // src0, src1 and dst are same shape => same indices
  7795. const int i3 = ir/(ne2*ne1);
  7796. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7797. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7798. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7799. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7800. ggml_bf16_t * src1_ptr = (ggml_bf16_t *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7801. for (int i = 0; i < ne0; i++) {
  7802. dst_ptr[i] = GGML_FP32_TO_BF16(GGML_BF16_TO_FP32(src0_ptr[i]) + GGML_BF16_TO_FP32(src1_ptr[i]));
  7803. }
  7804. }
  7805. }
  7806. else {
  7807. // src1 is not contiguous
  7808. GGML_ABORT("fatal error");
  7809. }
  7810. }
  7811. static void ggml_compute_forward_add_q_f32(
  7812. const struct ggml_compute_params * params,
  7813. struct ggml_tensor * dst) {
  7814. const struct ggml_tensor * src0 = dst->src[0];
  7815. const struct ggml_tensor * src1 = dst->src[1];
  7816. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7817. const int nr = ggml_nrows(src0);
  7818. GGML_TENSOR_BINARY_OP_LOCALS
  7819. const int ith = params->ith;
  7820. const int nth = params->nth;
  7821. const enum ggml_type type = src0->type;
  7822. const enum ggml_type dtype = dst->type;
  7823. ggml_to_float_t const dequantize_row_q = type_traits[type].to_float;
  7824. ggml_from_float_t const quantize_row_q = type_traits[dtype].from_float;
  7825. // we don't support permuted src0 or src1
  7826. GGML_ASSERT(nb00 == ggml_type_size(type));
  7827. GGML_ASSERT(nb10 == sizeof(float));
  7828. // dst cannot be transposed or permuted
  7829. GGML_ASSERT(nb0 <= nb1);
  7830. GGML_ASSERT(nb1 <= nb2);
  7831. GGML_ASSERT(nb2 <= nb3);
  7832. GGML_ASSERT(ggml_is_quantized(src0->type));
  7833. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  7834. // rows per thread
  7835. const int dr = (nr + nth - 1)/nth;
  7836. // row range for this thread
  7837. const int ir0 = dr*ith;
  7838. const int ir1 = MIN(ir0 + dr, nr);
  7839. float * wdata = (float *) params->wdata + (ne00 + CACHE_LINE_SIZE_F32) * ith;
  7840. for (int ir = ir0; ir < ir1; ++ir) {
  7841. // src0 indices
  7842. const int i03 = ir/(ne02*ne01);
  7843. const int i02 = (ir - i03*ne02*ne01)/ne01;
  7844. const int i01 = (ir - i03*ne02*ne01 - i02*ne01);
  7845. // src1 and dst are same shape as src0 => same indices
  7846. const int i13 = i03;
  7847. const int i12 = i02;
  7848. const int i11 = i01;
  7849. const int i3 = i03;
  7850. const int i2 = i02;
  7851. const int i1 = i01;
  7852. void * src0_row = (void *) ((char *) src0->data + (i01*nb01 + i02*nb02 + i03*nb03));
  7853. float * src1_row = (float *)((char *) src1->data + (i11*nb11 + i12*nb12 + i13*nb13));
  7854. void * dst_row = (void *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  7855. assert(ne00 % 32 == 0);
  7856. // unquantize row from src0 to temp buffer
  7857. dequantize_row_q(src0_row, wdata, ne00);
  7858. // add src1
  7859. ggml_vec_acc_f32(ne00, wdata, src1_row);
  7860. // quantize row to dst
  7861. if (quantize_row_q != NULL) {
  7862. quantize_row_q(wdata, dst_row, ne00);
  7863. } else {
  7864. memcpy(dst_row, wdata, ne0*nb0);
  7865. }
  7866. }
  7867. }
  7868. static void ggml_compute_forward_add(
  7869. const struct ggml_compute_params * params,
  7870. struct ggml_tensor * dst) {
  7871. const struct ggml_tensor * src0 = dst->src[0];
  7872. const struct ggml_tensor * src1 = dst->src[1];
  7873. switch (src0->type) {
  7874. case GGML_TYPE_F32:
  7875. {
  7876. if (src1->type == GGML_TYPE_F32) {
  7877. ggml_compute_forward_add_f32(params, dst);
  7878. }
  7879. else {
  7880. GGML_ABORT("fatal error");
  7881. }
  7882. } break;
  7883. case GGML_TYPE_F16:
  7884. {
  7885. if (src1->type == GGML_TYPE_F16) {
  7886. ggml_compute_forward_add_f16_f16(params, dst);
  7887. }
  7888. else if (src1->type == GGML_TYPE_F32) {
  7889. ggml_compute_forward_add_f16_f32(params, dst);
  7890. }
  7891. else {
  7892. GGML_ABORT("fatal error");
  7893. }
  7894. } break;
  7895. case GGML_TYPE_BF16:
  7896. {
  7897. if (src1->type == GGML_TYPE_BF16) {
  7898. ggml_compute_forward_add_bf16_bf16(params, dst);
  7899. }
  7900. else if (src1->type == GGML_TYPE_F32) {
  7901. ggml_compute_forward_add_bf16_f32(params, dst);
  7902. }
  7903. else {
  7904. GGML_ABORT("fatal error");
  7905. }
  7906. } break;
  7907. case GGML_TYPE_Q4_0:
  7908. case GGML_TYPE_Q4_1:
  7909. case GGML_TYPE_Q5_0:
  7910. case GGML_TYPE_Q5_1:
  7911. case GGML_TYPE_Q8_0:
  7912. case GGML_TYPE_Q2_K:
  7913. case GGML_TYPE_Q3_K:
  7914. case GGML_TYPE_Q4_K:
  7915. case GGML_TYPE_Q5_K:
  7916. case GGML_TYPE_Q6_K:
  7917. case GGML_TYPE_TQ1_0:
  7918. case GGML_TYPE_TQ2_0:
  7919. case GGML_TYPE_IQ2_XXS:
  7920. case GGML_TYPE_IQ2_XS:
  7921. case GGML_TYPE_IQ3_XXS:
  7922. case GGML_TYPE_IQ1_S:
  7923. case GGML_TYPE_IQ1_M:
  7924. case GGML_TYPE_IQ4_NL:
  7925. case GGML_TYPE_IQ4_XS:
  7926. case GGML_TYPE_IQ3_S:
  7927. case GGML_TYPE_IQ2_S:
  7928. case GGML_TYPE_Q4_0_4_4:
  7929. case GGML_TYPE_Q4_0_4_8:
  7930. case GGML_TYPE_Q4_0_8_8:
  7931. {
  7932. ggml_compute_forward_add_q_f32(params, dst);
  7933. } break;
  7934. default:
  7935. {
  7936. GGML_ABORT("fatal error");
  7937. }
  7938. }
  7939. }
  7940. // ggml_compute_forward_add1
  7941. static void ggml_compute_forward_add1_f32(
  7942. const struct ggml_compute_params * params,
  7943. struct ggml_tensor * dst) {
  7944. const struct ggml_tensor * src0 = dst->src[0];
  7945. const struct ggml_tensor * src1 = dst->src[1];
  7946. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  7947. GGML_ASSERT(ggml_is_scalar(src1));
  7948. const int ith = params->ith;
  7949. const int nth = params->nth;
  7950. const int nr = ggml_nrows(src0);
  7951. GGML_TENSOR_UNARY_OP_LOCALS
  7952. GGML_ASSERT( nb0 == sizeof(float));
  7953. GGML_ASSERT(nb00 == sizeof(float));
  7954. // rows per thread
  7955. const int dr = (nr + nth - 1)/nth;
  7956. // row range for this thread
  7957. const int ir0 = dr*ith;
  7958. const int ir1 = MIN(ir0 + dr, nr);
  7959. for (int ir = ir0; ir < ir1; ++ir) {
  7960. // src0 and dst are same shape => same indices
  7961. const int i3 = ir/(ne2*ne1);
  7962. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7963. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7964. #ifdef GGML_USE_ACCELERATE
  7965. UNUSED(ggml_vec_add1_f32);
  7966. vDSP_vadd(
  7967. (float *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01), 1,
  7968. (float *) ((char *) src1->data), 0,
  7969. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 ), 1,
  7970. ne0);
  7971. #else
  7972. ggml_vec_add1_f32(ne0,
  7973. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 ),
  7974. (float *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01),
  7975. *(float *) src1->data);
  7976. #endif
  7977. }
  7978. }
  7979. static void ggml_compute_forward_add1_f16_f32(
  7980. const struct ggml_compute_params * params,
  7981. struct ggml_tensor * dst) {
  7982. const struct ggml_tensor * src0 = dst->src[0];
  7983. const struct ggml_tensor * src1 = dst->src[1];
  7984. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  7985. GGML_ASSERT(ggml_is_scalar(src1));
  7986. // scalar to add
  7987. const float v = *(float *) src1->data;
  7988. const int ith = params->ith;
  7989. const int nth = params->nth;
  7990. const int nr = ggml_nrows(src0);
  7991. GGML_TENSOR_UNARY_OP_LOCALS
  7992. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  7993. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  7994. GGML_ASSERT(dst->type == GGML_TYPE_F16);
  7995. GGML_ASSERT( nb0 == sizeof(ggml_fp16_t));
  7996. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  7997. // rows per thread
  7998. const int dr = (nr + nth - 1)/nth;
  7999. // row range for this thread
  8000. const int ir0 = dr*ith;
  8001. const int ir1 = MIN(ir0 + dr, nr);
  8002. for (int ir = ir0; ir < ir1; ++ir) {
  8003. // src0 and dst are same shape => same indices
  8004. const int i3 = ir/(ne2*ne1);
  8005. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8006. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8007. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 );
  8008. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  8009. for (int i = 0; i < ne0; i++) {
  8010. dst_ptr[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(src0_ptr[i]) + v);
  8011. }
  8012. }
  8013. }
  8014. static void ggml_compute_forward_add1_f16_f16(
  8015. const struct ggml_compute_params * params,
  8016. struct ggml_tensor * dst) {
  8017. const struct ggml_tensor * src0 = dst->src[0];
  8018. const struct ggml_tensor * src1 = dst->src[1];
  8019. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8020. GGML_ASSERT(ggml_is_scalar(src1));
  8021. // scalar to add
  8022. const float v = GGML_FP16_TO_FP32(*(ggml_fp16_t *) src1->data);
  8023. const int ith = params->ith;
  8024. const int nth = params->nth;
  8025. const int nr = ggml_nrows(src0);
  8026. GGML_TENSOR_UNARY_OP_LOCALS
  8027. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  8028. GGML_ASSERT(src1->type == GGML_TYPE_F16);
  8029. GGML_ASSERT(dst->type == GGML_TYPE_F16);
  8030. GGML_ASSERT( nb0 == sizeof(ggml_fp16_t));
  8031. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  8032. // rows per thread
  8033. const int dr = (nr + nth - 1)/nth;
  8034. // row range for this thread
  8035. const int ir0 = dr*ith;
  8036. const int ir1 = MIN(ir0 + dr, nr);
  8037. for (int ir = ir0; ir < ir1; ++ir) {
  8038. // src0 and dst are same shape => same indices
  8039. const int i3 = ir/(ne2*ne1);
  8040. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8041. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8042. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 );
  8043. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  8044. for (int i = 0; i < ne0; i++) {
  8045. dst_ptr[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(src0_ptr[i]) + v);
  8046. }
  8047. }
  8048. }
  8049. static void ggml_compute_forward_add1_q_f32(
  8050. const struct ggml_compute_params * params,
  8051. struct ggml_tensor * dst) {
  8052. const struct ggml_tensor * src0 = dst->src[0];
  8053. const struct ggml_tensor * src1 = dst->src[1];
  8054. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8055. GGML_ASSERT(ggml_is_scalar(src1));
  8056. // scalar to add
  8057. const float v = *(float *) src1->data;
  8058. const int ith = params->ith;
  8059. const int nth = params->nth;
  8060. const int nr = ggml_nrows(src0);
  8061. GGML_TENSOR_UNARY_OP_LOCALS
  8062. const enum ggml_type type = src0->type;
  8063. ggml_to_float_t const dequantize_row_q = type_traits[type].to_float;
  8064. ggml_from_float_t const quantize_row_q = type_traits[type].from_float;
  8065. // we don't support permuted src0
  8066. GGML_ASSERT(nb00 == ggml_type_size(type));
  8067. // dst cannot be transposed or permuted
  8068. GGML_ASSERT(nb0 <= nb1);
  8069. GGML_ASSERT(nb1 <= nb2);
  8070. GGML_ASSERT(nb2 <= nb3);
  8071. GGML_ASSERT(ggml_is_quantized(src0->type));
  8072. GGML_ASSERT(dst->type == src0->type);
  8073. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8074. // rows per thread
  8075. const int dr = (nr + nth - 1)/nth;
  8076. // row range for this thread
  8077. const int ir0 = dr*ith;
  8078. const int ir1 = MIN(ir0 + dr, nr);
  8079. float * wdata = (float *) params->wdata + (ne0 + CACHE_LINE_SIZE_F32) * ith;
  8080. for (int ir = ir0; ir < ir1; ++ir) {
  8081. // src0 and dst are same shape => same indices
  8082. const int i3 = ir/(ne2*ne1);
  8083. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8084. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8085. void * src0_row = (void *) ((char *) src0->data + (i1*nb01 + i2*nb02 + i3*nb03));
  8086. void * dst_row = (void *) ((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb0 ));
  8087. assert(ne0 % 32 == 0);
  8088. // unquantize row from src0 to temp buffer
  8089. dequantize_row_q(src0_row, wdata, ne0);
  8090. // add src1
  8091. ggml_vec_acc1_f32(ne0, wdata, v);
  8092. // quantize row to dst
  8093. quantize_row_q(wdata, dst_row, ne0);
  8094. }
  8095. }
  8096. static void ggml_compute_forward_add1_bf16_f32(
  8097. const struct ggml_compute_params * params,
  8098. struct ggml_tensor * dst) {
  8099. const struct ggml_tensor * src0 = dst->src[0];
  8100. const struct ggml_tensor * src1 = dst->src[1];
  8101. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8102. GGML_ASSERT(ggml_is_scalar(src1));
  8103. // scalar to add
  8104. const float v = *(float *) src1->data;
  8105. const int ith = params->ith;
  8106. const int nth = params->nth;
  8107. const int nr = ggml_nrows(src0);
  8108. GGML_TENSOR_UNARY_OP_LOCALS
  8109. GGML_ASSERT(src0->type == GGML_TYPE_BF16);
  8110. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8111. GGML_ASSERT(dst->type == GGML_TYPE_BF16);
  8112. GGML_ASSERT( nb0 == sizeof(ggml_bf16_t));
  8113. GGML_ASSERT(nb00 == sizeof(ggml_bf16_t));
  8114. // rows per thread
  8115. const int dr = (nr + nth - 1)/nth;
  8116. // row range for this thread
  8117. const int ir0 = dr*ith;
  8118. const int ir1 = MIN(ir0 + dr, nr);
  8119. for (int ir = ir0; ir < ir1; ++ir) {
  8120. // src0 and dst are same shape => same indices
  8121. const int i3 = ir/(ne2*ne1);
  8122. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8123. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8124. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 );
  8125. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  8126. for (int i = 0; i < ne0; i++) {
  8127. dst_ptr[i] = GGML_FP32_TO_BF16(GGML_BF16_TO_FP32(src0_ptr[i]) + v);
  8128. }
  8129. }
  8130. }
  8131. static void ggml_compute_forward_add1_bf16_bf16(
  8132. const struct ggml_compute_params * params,
  8133. struct ggml_tensor * dst) {
  8134. const struct ggml_tensor * src0 = dst->src[0];
  8135. const struct ggml_tensor * src1 = dst->src[1];
  8136. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8137. GGML_ASSERT(ggml_is_scalar(src1));
  8138. // scalar to add
  8139. const float v = GGML_BF16_TO_FP32(*(ggml_bf16_t *) src1->data);
  8140. const int ith = params->ith;
  8141. const int nth = params->nth;
  8142. const int nr = ggml_nrows(src0);
  8143. GGML_TENSOR_UNARY_OP_LOCALS
  8144. GGML_ASSERT(src0->type == GGML_TYPE_BF16);
  8145. GGML_ASSERT(src1->type == GGML_TYPE_BF16);
  8146. GGML_ASSERT(dst->type == GGML_TYPE_BF16);
  8147. GGML_ASSERT( nb0 == sizeof(ggml_bf16_t));
  8148. GGML_ASSERT(nb00 == sizeof(ggml_bf16_t));
  8149. // rows per thread
  8150. const int dr = (nr + nth - 1)/nth;
  8151. // row range for this thread
  8152. const int ir0 = dr*ith;
  8153. const int ir1 = MIN(ir0 + dr, nr);
  8154. for (int ir = ir0; ir < ir1; ++ir) {
  8155. // src0 and dst are same shape => same indices
  8156. const int i3 = ir/(ne2*ne1);
  8157. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8158. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8159. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 );
  8160. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  8161. for (int i = 0; i < ne0; i++) {
  8162. dst_ptr[i] = GGML_FP32_TO_BF16(GGML_BF16_TO_FP32(src0_ptr[i]) + v);
  8163. }
  8164. }
  8165. }
  8166. static void ggml_compute_forward_add1(
  8167. const struct ggml_compute_params * params,
  8168. struct ggml_tensor * dst) {
  8169. const struct ggml_tensor * src0 = dst->src[0];
  8170. const struct ggml_tensor * src1 = dst->src[1];
  8171. switch (src0->type) {
  8172. case GGML_TYPE_F32:
  8173. {
  8174. ggml_compute_forward_add1_f32(params, dst);
  8175. } break;
  8176. case GGML_TYPE_F16:
  8177. {
  8178. if (src1->type == GGML_TYPE_F16) {
  8179. ggml_compute_forward_add1_f16_f16(params, dst);
  8180. }
  8181. else if (src1->type == GGML_TYPE_F32) {
  8182. ggml_compute_forward_add1_f16_f32(params, dst);
  8183. }
  8184. else {
  8185. GGML_ABORT("fatal error");
  8186. }
  8187. } break;
  8188. case GGML_TYPE_BF16:
  8189. {
  8190. if (src1->type == GGML_TYPE_BF16) {
  8191. ggml_compute_forward_add1_bf16_bf16(params, dst);
  8192. }
  8193. else if (src1->type == GGML_TYPE_F32) {
  8194. ggml_compute_forward_add1_bf16_f32(params, dst);
  8195. }
  8196. else {
  8197. GGML_ABORT("fatal error");
  8198. }
  8199. } break;
  8200. case GGML_TYPE_Q4_0:
  8201. case GGML_TYPE_Q4_1:
  8202. case GGML_TYPE_Q5_0:
  8203. case GGML_TYPE_Q5_1:
  8204. case GGML_TYPE_Q8_0:
  8205. case GGML_TYPE_Q8_1:
  8206. case GGML_TYPE_Q2_K:
  8207. case GGML_TYPE_Q3_K:
  8208. case GGML_TYPE_Q4_K:
  8209. case GGML_TYPE_Q5_K:
  8210. case GGML_TYPE_Q6_K:
  8211. case GGML_TYPE_TQ1_0:
  8212. case GGML_TYPE_TQ2_0:
  8213. case GGML_TYPE_IQ2_XXS:
  8214. case GGML_TYPE_IQ2_XS:
  8215. case GGML_TYPE_IQ3_XXS:
  8216. case GGML_TYPE_IQ1_S:
  8217. case GGML_TYPE_IQ1_M:
  8218. case GGML_TYPE_IQ4_NL:
  8219. case GGML_TYPE_IQ4_XS:
  8220. case GGML_TYPE_IQ3_S:
  8221. case GGML_TYPE_IQ2_S:
  8222. case GGML_TYPE_Q4_0_4_4:
  8223. case GGML_TYPE_Q4_0_4_8:
  8224. case GGML_TYPE_Q4_0_8_8:
  8225. {
  8226. ggml_compute_forward_add1_q_f32(params, dst);
  8227. } break;
  8228. default:
  8229. {
  8230. GGML_ABORT("fatal error");
  8231. }
  8232. }
  8233. }
  8234. // ggml_compute_forward_acc
  8235. static void ggml_compute_forward_acc_f32(
  8236. const struct ggml_compute_params * params,
  8237. struct ggml_tensor * dst) {
  8238. const struct ggml_tensor * src0 = dst->src[0];
  8239. const struct ggml_tensor * src1 = dst->src[1];
  8240. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8241. GGML_ASSERT(ggml_is_contiguous(dst) && ggml_is_contiguous(src0));
  8242. // view src0 and dst with these strides and data offset inbytes during acc
  8243. // nb0 is implicitly element_size because src0 and dst are contiguous
  8244. size_t nb1 = ((int32_t *) dst->op_params)[0];
  8245. size_t nb2 = ((int32_t *) dst->op_params)[1];
  8246. size_t nb3 = ((int32_t *) dst->op_params)[2];
  8247. size_t offset = ((int32_t *) dst->op_params)[3];
  8248. bool inplace = (bool) ((int32_t *) dst->op_params)[4];
  8249. if (!inplace) {
  8250. if (params->ith == 0) {
  8251. // memcpy needs to be synchronized across threads to avoid race conditions.
  8252. // => do it in INIT phase
  8253. memcpy(
  8254. ((char *) dst->data),
  8255. ((char *) src0->data),
  8256. ggml_nbytes(dst));
  8257. }
  8258. ggml_barrier(params->threadpool);
  8259. }
  8260. const int ith = params->ith;
  8261. const int nth = params->nth;
  8262. const int nr = ggml_nrows(src1);
  8263. const int nc = src1->ne[0];
  8264. GGML_TENSOR_LOCALS(int64_t, ne1, src1, ne)
  8265. GGML_TENSOR_LOCALS(size_t, nb1, src1, nb)
  8266. // src0 and dst as viewed during acc
  8267. const size_t nb0 = ggml_element_size(src0);
  8268. const size_t nb00 = nb0;
  8269. const size_t nb01 = nb1;
  8270. const size_t nb02 = nb2;
  8271. const size_t nb03 = nb3;
  8272. GGML_ASSERT(offset + (ne10 == 0 ? 0 : ne10-1)*nb0 + (ne11 == 0 ? 0 : ne11-1)*nb1 + (ne12 == 0 ? 0 : ne12-1)*nb2 + (ne13 == 0 ? 0 : ne13-1)*nb3 < ggml_nbytes(dst));
  8273. GGML_ASSERT(offset + (ne10 == 0 ? 0 : ne10-1)*nb00 + (ne11 == 0 ? 0 : ne11-1)*nb01 + (ne12 == 0 ? 0 : ne12-1)*nb02 + (ne13 == 0 ? 0 : ne13-1)*nb03 < ggml_nbytes(src0));
  8274. GGML_ASSERT(nb10 == sizeof(float));
  8275. // rows per thread
  8276. const int dr = (nr + nth - 1)/nth;
  8277. // row range for this thread
  8278. const int ir0 = dr*ith;
  8279. const int ir1 = MIN(ir0 + dr, nr);
  8280. for (int ir = ir0; ir < ir1; ++ir) {
  8281. // src0 and dst are viewed with shape of src1 and offset
  8282. // => same indices
  8283. const int i3 = ir/(ne12*ne11);
  8284. const int i2 = (ir - i3*ne12*ne11)/ne11;
  8285. const int i1 = (ir - i3*ne12*ne11 - i2*ne11);
  8286. #ifdef GGML_USE_ACCELERATE
  8287. vDSP_vadd(
  8288. (float *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + offset), 1,
  8289. (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11), 1,
  8290. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + offset), 1, nc);
  8291. #else
  8292. ggml_vec_add_f32(nc,
  8293. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + offset),
  8294. (float *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + offset),
  8295. (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11));
  8296. #endif
  8297. }
  8298. }
  8299. static void ggml_compute_forward_acc(
  8300. const struct ggml_compute_params * params,
  8301. struct ggml_tensor * dst) {
  8302. const struct ggml_tensor * src0 = dst->src[0];
  8303. switch (src0->type) {
  8304. case GGML_TYPE_F32:
  8305. {
  8306. ggml_compute_forward_acc_f32(params, dst);
  8307. } break;
  8308. case GGML_TYPE_F16:
  8309. case GGML_TYPE_BF16:
  8310. case GGML_TYPE_Q4_0:
  8311. case GGML_TYPE_Q4_1:
  8312. case GGML_TYPE_Q5_0:
  8313. case GGML_TYPE_Q5_1:
  8314. case GGML_TYPE_Q8_0:
  8315. case GGML_TYPE_Q8_1:
  8316. case GGML_TYPE_Q2_K:
  8317. case GGML_TYPE_Q3_K:
  8318. case GGML_TYPE_Q4_K:
  8319. case GGML_TYPE_Q5_K:
  8320. case GGML_TYPE_Q6_K:
  8321. case GGML_TYPE_TQ1_0:
  8322. case GGML_TYPE_TQ2_0:
  8323. case GGML_TYPE_IQ2_XXS:
  8324. case GGML_TYPE_IQ2_XS:
  8325. case GGML_TYPE_IQ3_XXS:
  8326. case GGML_TYPE_IQ1_S:
  8327. case GGML_TYPE_IQ1_M:
  8328. case GGML_TYPE_IQ4_NL:
  8329. case GGML_TYPE_IQ4_XS:
  8330. case GGML_TYPE_IQ3_S:
  8331. case GGML_TYPE_IQ2_S:
  8332. case GGML_TYPE_Q4_0_4_4:
  8333. case GGML_TYPE_Q4_0_4_8:
  8334. case GGML_TYPE_Q4_0_8_8:
  8335. default:
  8336. {
  8337. GGML_ABORT("fatal error");
  8338. }
  8339. }
  8340. }
  8341. // ggml_compute_forward_sub
  8342. static void ggml_compute_forward_sub_f32(
  8343. const struct ggml_compute_params * params,
  8344. struct ggml_tensor * dst) {
  8345. const struct ggml_tensor * src0 = dst->src[0];
  8346. const struct ggml_tensor * src1 = dst->src[1];
  8347. assert(ggml_can_repeat(src1, src0) && ggml_are_same_shape(src0, dst));
  8348. const int ith = params->ith;
  8349. const int nth = params->nth;
  8350. const int nr = ggml_nrows(src0);
  8351. GGML_TENSOR_BINARY_OP_LOCALS
  8352. GGML_ASSERT( nb0 == sizeof(float));
  8353. GGML_ASSERT(nb00 == sizeof(float));
  8354. // rows per thread
  8355. const int dr = (nr + nth - 1)/nth;
  8356. // row range for this thread
  8357. const int ir0 = dr*ith;
  8358. const int ir1 = MIN(ir0 + dr, nr);
  8359. if (nb10 == sizeof(float)) {
  8360. for (int ir = ir0; ir < ir1; ++ir) {
  8361. // src1 is broadcastable across src0 and dst in i1, i2, i3
  8362. const int64_t i03 = ir/(ne02*ne01);
  8363. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8364. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8365. const int64_t i13 = i03 % ne13;
  8366. const int64_t i12 = i02 % ne12;
  8367. const int64_t i11 = i01 % ne11;
  8368. const int64_t nr0 = ne00 / ne10;
  8369. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8370. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8371. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11);
  8372. for (int64_t r = 0; r < nr0; ++r) {
  8373. #ifdef GGML_USE_ACCELERATE
  8374. vDSP_vsub(src1_ptr, 1, src0_ptr + r*ne10, 1, dst_ptr + r*ne10, 1, ne10);
  8375. #else
  8376. ggml_vec_sub_f32(ne10, dst_ptr + r*ne10, src0_ptr + r*ne10, src1_ptr);
  8377. #endif
  8378. }
  8379. }
  8380. } else {
  8381. // src1 is not contiguous
  8382. for (int ir = ir0; ir < ir1; ++ir) {
  8383. // src1 is broadcastable across src0 and dst in i1, i2, i3
  8384. const int64_t i03 = ir/(ne02*ne01);
  8385. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8386. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8387. const int64_t i13 = i03 % ne13;
  8388. const int64_t i12 = i02 % ne12;
  8389. const int64_t i11 = i01 % ne11;
  8390. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8391. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8392. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  8393. const int64_t i10 = i0 % ne10;
  8394. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10);
  8395. dst_ptr[i0] = src0_ptr[i0] - *src1_ptr;
  8396. }
  8397. }
  8398. }
  8399. }
  8400. static void ggml_compute_forward_sub(
  8401. const struct ggml_compute_params * params,
  8402. struct ggml_tensor * dst) {
  8403. const struct ggml_tensor * src0 = dst->src[0];
  8404. switch (src0->type) {
  8405. case GGML_TYPE_F32:
  8406. {
  8407. ggml_compute_forward_sub_f32(params, dst);
  8408. } break;
  8409. default:
  8410. {
  8411. GGML_ABORT("fatal error");
  8412. }
  8413. }
  8414. }
  8415. // ggml_compute_forward_mul
  8416. static void ggml_compute_forward_mul_f32(
  8417. const struct ggml_compute_params * params,
  8418. struct ggml_tensor * dst) {
  8419. const struct ggml_tensor * src0 = dst->src[0];
  8420. const struct ggml_tensor * src1 = dst->src[1];
  8421. GGML_ASSERT(ggml_can_repeat(src1, src0) && ggml_are_same_shape(src0, dst));
  8422. const int ith = params->ith;
  8423. const int nth = params->nth;
  8424. const int64_t nr = ggml_nrows(src0);
  8425. GGML_TENSOR_BINARY_OP_LOCALS
  8426. GGML_ASSERT( nb0 == sizeof(float));
  8427. GGML_ASSERT(nb00 == sizeof(float));
  8428. if (nb10 == sizeof(float)) {
  8429. for (int64_t ir = ith; ir < nr; ir += nth) {
  8430. // src0 and dst are same shape => same indices
  8431. const int64_t i03 = ir/(ne02*ne01);
  8432. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8433. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8434. const int64_t i13 = i03 % ne13;
  8435. const int64_t i12 = i02 % ne12;
  8436. const int64_t i11 = i01 % ne11;
  8437. const int64_t nr0 = ne00 / ne10;
  8438. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8439. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8440. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11);
  8441. for (int64_t r = 0 ; r < nr0; ++r) {
  8442. #ifdef GGML_USE_ACCELERATE
  8443. UNUSED(ggml_vec_mul_f32);
  8444. vDSP_vmul(src0_ptr + r*ne10, 1, src1_ptr, 1, dst_ptr + r*ne10, 1, ne10);
  8445. #else
  8446. ggml_vec_mul_f32(ne10, dst_ptr + r*ne10, src0_ptr + r*ne10, src1_ptr);
  8447. #endif
  8448. }
  8449. }
  8450. } else {
  8451. // src1 is not contiguous
  8452. for (int64_t ir = ith; ir < nr; ir += nth) {
  8453. // src0 and dst are same shape => same indices
  8454. // src1 is broadcastable across src0 and dst in i1, i2, i3
  8455. const int64_t i03 = ir/(ne02*ne01);
  8456. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8457. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8458. const int64_t i13 = i03 % ne13;
  8459. const int64_t i12 = i02 % ne12;
  8460. const int64_t i11 = i01 % ne11;
  8461. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8462. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8463. for (int64_t i0 = 0; i0 < ne00; ++i0) {
  8464. const int64_t i10 = i0 % ne10;
  8465. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10);
  8466. dst_ptr[i0] = src0_ptr[i0] * (*src1_ptr);
  8467. }
  8468. }
  8469. }
  8470. }
  8471. static void ggml_compute_forward_mul(
  8472. const struct ggml_compute_params * params,
  8473. struct ggml_tensor * dst) {
  8474. const struct ggml_tensor * src0 = dst->src[0];
  8475. const struct ggml_tensor * src1 = dst->src[1];
  8476. GGML_ASSERT(src1->type == GGML_TYPE_F32 && "only f32 src1 supported for now");
  8477. switch (src0->type) {
  8478. case GGML_TYPE_F32:
  8479. {
  8480. ggml_compute_forward_mul_f32(params, dst);
  8481. } break;
  8482. default:
  8483. {
  8484. GGML_ABORT("fatal error");
  8485. }
  8486. }
  8487. }
  8488. // ggml_compute_forward_div
  8489. static void ggml_compute_forward_div_f32(
  8490. const struct ggml_compute_params * params,
  8491. struct ggml_tensor * dst) {
  8492. const struct ggml_tensor * src0 = dst->src[0];
  8493. const struct ggml_tensor * src1 = dst->src[1];
  8494. GGML_ASSERT(ggml_can_repeat(src1, src0) && ggml_are_same_shape(src0, dst));
  8495. const int ith = params->ith;
  8496. const int nth = params->nth;
  8497. const int64_t nr = ggml_nrows(src0);
  8498. GGML_TENSOR_BINARY_OP_LOCALS
  8499. GGML_ASSERT( nb0 == sizeof(float));
  8500. GGML_ASSERT(nb00 == sizeof(float));
  8501. if (nb10 == sizeof(float)) {
  8502. for (int64_t ir = ith; ir < nr; ir += nth) {
  8503. // src0 and dst are same shape => same indices
  8504. const int64_t i03 = ir/(ne02*ne01);
  8505. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8506. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8507. const int64_t i13 = i03 % ne13;
  8508. const int64_t i12 = i02 % ne12;
  8509. const int64_t i11 = i01 % ne11;
  8510. const int64_t nr0 = ne00 / ne10;
  8511. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8512. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8513. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11);
  8514. for (int64_t r = 0; r < nr0; ++r) {
  8515. #ifdef GGML_USE_ACCELERATE
  8516. UNUSED(ggml_vec_div_f32);
  8517. vDSP_vdiv(src1_ptr, 1, src0_ptr + r*ne10, 1, dst_ptr + r*ne10, 1, ne10);
  8518. #else
  8519. ggml_vec_div_f32(ne10, dst_ptr + r*ne10, src0_ptr + r*ne10, src1_ptr);
  8520. #endif
  8521. }
  8522. }
  8523. } else {
  8524. // src1 is not contiguous
  8525. for (int64_t ir = ith; ir < nr; ir += nth) {
  8526. // src0 and dst are same shape => same indices
  8527. // src1 is broadcastable across src0 and dst in i1, i2, i3
  8528. const int64_t i03 = ir/(ne02*ne01);
  8529. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8530. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8531. const int64_t i13 = i03 % ne13;
  8532. const int64_t i12 = i02 % ne12;
  8533. const int64_t i11 = i01 % ne11;
  8534. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8535. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8536. for (int64_t i0 = 0; i0 < ne00; ++i0) {
  8537. const int64_t i10 = i0 % ne10;
  8538. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10);
  8539. dst_ptr[i0] = src0_ptr[i0] / (*src1_ptr);
  8540. }
  8541. }
  8542. }
  8543. }
  8544. static void ggml_compute_forward_div(
  8545. const struct ggml_compute_params * params,
  8546. struct ggml_tensor * dst) {
  8547. const struct ggml_tensor * src0 = dst->src[0];
  8548. switch (src0->type) {
  8549. case GGML_TYPE_F32:
  8550. {
  8551. ggml_compute_forward_div_f32(params, dst);
  8552. } break;
  8553. default:
  8554. {
  8555. GGML_ABORT("fatal error");
  8556. }
  8557. }
  8558. }
  8559. // ggml_compute_forward_sqr
  8560. static void ggml_compute_forward_sqr_f32(
  8561. const struct ggml_compute_params * params,
  8562. struct ggml_tensor * dst) {
  8563. const struct ggml_tensor * src0 = dst->src[0];
  8564. if (params->ith != 0) {
  8565. return;
  8566. }
  8567. assert(ggml_are_same_shape(src0, dst));
  8568. const int n = ggml_nrows(src0);
  8569. const int nc = src0->ne[0];
  8570. assert( dst->nb[0] == sizeof(float));
  8571. assert(src0->nb[0] == sizeof(float));
  8572. for (int i = 0; i < n; i++) {
  8573. ggml_vec_sqr_f32(nc,
  8574. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8575. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8576. }
  8577. }
  8578. static void ggml_compute_forward_sqr(
  8579. const struct ggml_compute_params * params,
  8580. struct ggml_tensor * dst) {
  8581. const struct ggml_tensor * src0 = dst->src[0];
  8582. switch (src0->type) {
  8583. case GGML_TYPE_F32:
  8584. {
  8585. ggml_compute_forward_sqr_f32(params, dst);
  8586. } break;
  8587. default:
  8588. {
  8589. GGML_ABORT("fatal error");
  8590. }
  8591. }
  8592. }
  8593. // ggml_compute_forward_sqrt
  8594. static void ggml_compute_forward_sqrt_f32(
  8595. const struct ggml_compute_params * params,
  8596. struct ggml_tensor * dst) {
  8597. const struct ggml_tensor * src0 = dst->src[0];
  8598. if (params->ith != 0) {
  8599. return;
  8600. }
  8601. assert(ggml_are_same_shape(src0, dst));
  8602. const int n = ggml_nrows(src0);
  8603. const int nc = src0->ne[0];
  8604. assert( dst->nb[0] == sizeof(float));
  8605. assert(src0->nb[0] == sizeof(float));
  8606. for (int i = 0; i < n; i++) {
  8607. ggml_vec_sqrt_f32(nc,
  8608. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8609. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8610. }
  8611. }
  8612. static void ggml_compute_forward_sqrt(
  8613. const struct ggml_compute_params * params,
  8614. struct ggml_tensor * dst) {
  8615. const struct ggml_tensor * src0 = dst->src[0];
  8616. switch (src0->type) {
  8617. case GGML_TYPE_F32:
  8618. {
  8619. ggml_compute_forward_sqrt_f32(params, dst);
  8620. } break;
  8621. default:
  8622. {
  8623. GGML_ABORT("fatal error");
  8624. }
  8625. }
  8626. }
  8627. // ggml_compute_forward_log
  8628. static void ggml_compute_forward_log_f32(
  8629. const struct ggml_compute_params * params,
  8630. struct ggml_tensor * dst) {
  8631. const struct ggml_tensor * src0 = dst->src[0];
  8632. if (params->ith != 0) {
  8633. return;
  8634. }
  8635. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8636. const int n = ggml_nrows(src0);
  8637. const int nc = src0->ne[0];
  8638. GGML_ASSERT( dst->nb[0] == sizeof(float));
  8639. GGML_ASSERT(src0->nb[0] == sizeof(float));
  8640. for (int i = 0; i < n; i++) {
  8641. ggml_vec_log_f32(nc,
  8642. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8643. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8644. }
  8645. }
  8646. static void ggml_compute_forward_log(
  8647. const struct ggml_compute_params * params,
  8648. struct ggml_tensor * dst) {
  8649. const struct ggml_tensor * src0 = dst->src[0];
  8650. switch (src0->type) {
  8651. case GGML_TYPE_F32:
  8652. {
  8653. ggml_compute_forward_log_f32(params, dst);
  8654. } break;
  8655. default:
  8656. {
  8657. GGML_ABORT("fatal error");
  8658. }
  8659. }
  8660. }
  8661. // ggml_compute_forward_sin
  8662. static void ggml_compute_forward_sin_f32(
  8663. const struct ggml_compute_params * params,
  8664. struct ggml_tensor * dst) {
  8665. const struct ggml_tensor * src0 = dst->src[0];
  8666. if (params->ith != 0) {
  8667. return;
  8668. }
  8669. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8670. const int n = ggml_nrows(src0);
  8671. const int nc = src0->ne[0];
  8672. GGML_ASSERT( dst->nb[0] == sizeof(float));
  8673. GGML_ASSERT(src0->nb[0] == sizeof(float));
  8674. for (int i = 0; i < n; i++) {
  8675. ggml_vec_sin_f32(nc,
  8676. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8677. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8678. }
  8679. }
  8680. static void ggml_compute_forward_sin(
  8681. const struct ggml_compute_params * params,
  8682. struct ggml_tensor * dst) {
  8683. const struct ggml_tensor * src0 = dst->src[0];
  8684. switch (src0->type) {
  8685. case GGML_TYPE_F32:
  8686. {
  8687. ggml_compute_forward_sin_f32(params, dst);
  8688. } break;
  8689. default:
  8690. {
  8691. GGML_ABORT("fatal error");
  8692. }
  8693. }
  8694. }
  8695. // ggml_compute_forward_cos
  8696. static void ggml_compute_forward_cos_f32(
  8697. const struct ggml_compute_params * params,
  8698. struct ggml_tensor * dst) {
  8699. const struct ggml_tensor * src0 = dst->src[0];
  8700. if (params->ith != 0) {
  8701. return;
  8702. }
  8703. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8704. const int n = ggml_nrows(src0);
  8705. const int nc = src0->ne[0];
  8706. GGML_ASSERT( dst->nb[0] == sizeof(float));
  8707. GGML_ASSERT(src0->nb[0] == sizeof(float));
  8708. for (int i = 0; i < n; i++) {
  8709. ggml_vec_cos_f32(nc,
  8710. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8711. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8712. }
  8713. }
  8714. static void ggml_compute_forward_cos(
  8715. const struct ggml_compute_params * params,
  8716. struct ggml_tensor * dst) {
  8717. const struct ggml_tensor * src0 = dst->src[0];
  8718. switch (src0->type) {
  8719. case GGML_TYPE_F32:
  8720. {
  8721. ggml_compute_forward_cos_f32(params, dst);
  8722. } break;
  8723. default:
  8724. {
  8725. GGML_ABORT("fatal error");
  8726. }
  8727. }
  8728. }
  8729. // ggml_compute_forward_sum
  8730. static void ggml_compute_forward_sum_f32(
  8731. const struct ggml_compute_params * params,
  8732. struct ggml_tensor * dst) {
  8733. const struct ggml_tensor * src0 = dst->src[0];
  8734. if (params->ith != 0) {
  8735. return;
  8736. }
  8737. assert(ggml_is_scalar(dst));
  8738. assert(src0->nb[0] == sizeof(float));
  8739. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  8740. GGML_TENSOR_LOCALS(size_t, nb0, src0, nb)
  8741. ggml_float sum = 0;
  8742. ggml_float row_sum = 0;
  8743. for (int64_t i03 = 0; i03 < ne03; i03++) {
  8744. for (int64_t i02 = 0; i02 < ne02; i02++) {
  8745. for (int64_t i01 = 0; i01 < ne01; i01++) {
  8746. ggml_vec_sum_f32_ggf(ne00,
  8747. &row_sum,
  8748. (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
  8749. sum += row_sum;
  8750. }
  8751. }
  8752. }
  8753. ((float *) dst->data)[0] = sum;
  8754. }
  8755. static void ggml_compute_forward_sum_f16(
  8756. const struct ggml_compute_params * params,
  8757. struct ggml_tensor * dst) {
  8758. const struct ggml_tensor * src0 = dst->src[0];
  8759. if (params->ith != 0) {
  8760. return;
  8761. }
  8762. assert(ggml_is_scalar(dst));
  8763. assert(src0->nb[0] == sizeof(ggml_fp16_t));
  8764. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  8765. GGML_TENSOR_LOCALS(size_t, nb0, src0, nb)
  8766. float sum = 0;
  8767. float row_sum = 0;
  8768. for (int64_t i03 = 0; i03 < ne03; i03++) {
  8769. for (int64_t i02 = 0; i02 < ne02; i02++) {
  8770. for (int64_t i01 = 0; i01 < ne01; i01++) {
  8771. ggml_vec_sum_f16_ggf(ne00,
  8772. &row_sum,
  8773. (ggml_fp16_t *) ((char *) src0->data + i01 * nb01 + i02 * nb02 + i03 * nb03));
  8774. sum += row_sum;
  8775. }
  8776. }
  8777. }
  8778. ((ggml_fp16_t *) dst->data)[0] = GGML_FP32_TO_FP16(sum);
  8779. }
  8780. static void ggml_compute_forward_sum_bf16(
  8781. const struct ggml_compute_params * params,
  8782. struct ggml_tensor * dst) {
  8783. const struct ggml_tensor * src0 = dst->src[0];
  8784. if (params->ith != 0) {
  8785. return;
  8786. }
  8787. assert(ggml_is_scalar(dst));
  8788. assert(src0->nb[0] == sizeof(ggml_bf16_t));
  8789. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  8790. GGML_TENSOR_LOCALS(size_t, nb0, src0, nb)
  8791. float sum = 0;
  8792. float row_sum = 0;
  8793. for (int64_t i03 = 0; i03 < ne03; i03++) {
  8794. for (int64_t i02 = 0; i02 < ne02; i02++) {
  8795. for (int64_t i01 = 0; i01 < ne01; i01++) {
  8796. ggml_vec_sum_bf16_ggf(ne00,
  8797. &row_sum,
  8798. (ggml_bf16_t *) ((char *) src0->data + i01 * nb01 + i02 * nb02 + i03 * nb03));
  8799. sum += row_sum;
  8800. }
  8801. }
  8802. }
  8803. ((ggml_bf16_t *) dst->data)[0] = GGML_FP32_TO_BF16(sum);
  8804. }
  8805. static void ggml_compute_forward_sum(
  8806. const struct ggml_compute_params * params,
  8807. struct ggml_tensor * dst) {
  8808. const struct ggml_tensor * src0 = dst->src[0];
  8809. switch (src0->type) {
  8810. case GGML_TYPE_F32:
  8811. {
  8812. ggml_compute_forward_sum_f32(params, dst);
  8813. } break;
  8814. case GGML_TYPE_F16:
  8815. {
  8816. ggml_compute_forward_sum_f16(params, dst);
  8817. } break;
  8818. case GGML_TYPE_BF16:
  8819. {
  8820. ggml_compute_forward_sum_bf16(params, dst);
  8821. } break;
  8822. default:
  8823. {
  8824. GGML_ABORT("fatal error");
  8825. }
  8826. }
  8827. }
  8828. // ggml_compute_forward_sum_rows
  8829. static void ggml_compute_forward_sum_rows_f32(
  8830. const struct ggml_compute_params * params,
  8831. struct ggml_tensor * dst) {
  8832. const struct ggml_tensor * src0 = dst->src[0];
  8833. if (params->ith != 0) {
  8834. return;
  8835. }
  8836. GGML_ASSERT(src0->nb[0] == sizeof(float));
  8837. GGML_ASSERT(dst->nb[0] == sizeof(float));
  8838. GGML_TENSOR_UNARY_OP_LOCALS
  8839. GGML_ASSERT(ne0 == 1);
  8840. GGML_ASSERT(ne1 == ne01);
  8841. GGML_ASSERT(ne2 == ne02);
  8842. GGML_ASSERT(ne3 == ne03);
  8843. for (int64_t i3 = 0; i3 < ne03; i3++) {
  8844. for (int64_t i2 = 0; i2 < ne02; i2++) {
  8845. for (int64_t i1 = 0; i1 < ne01; i1++) {
  8846. float * src_row = (float *) ((char *) src0->data + i1*nb01 + i2*nb02 + i3*nb03);
  8847. float * dst_row = (float *) ((char *) dst->data + i1*nb1 + i2*nb2 + i3*nb3);
  8848. float row_sum = 0;
  8849. ggml_vec_sum_f32(ne00, &row_sum, src_row);
  8850. dst_row[0] = row_sum;
  8851. }
  8852. }
  8853. }
  8854. }
  8855. static void ggml_compute_forward_sum_rows(
  8856. const struct ggml_compute_params * params,
  8857. struct ggml_tensor * dst) {
  8858. const struct ggml_tensor * src0 = dst->src[0];
  8859. switch (src0->type) {
  8860. case GGML_TYPE_F32:
  8861. {
  8862. ggml_compute_forward_sum_rows_f32(params, dst);
  8863. } break;
  8864. default:
  8865. {
  8866. GGML_ABORT("fatal error");
  8867. }
  8868. }
  8869. }
  8870. // ggml_compute_forward_mean
  8871. static void ggml_compute_forward_mean_f32(
  8872. const struct ggml_compute_params * params,
  8873. struct ggml_tensor * dst) {
  8874. const struct ggml_tensor * src0 = dst->src[0];
  8875. if (params->ith != 0) {
  8876. return;
  8877. }
  8878. assert(src0->nb[0] == sizeof(float));
  8879. GGML_TENSOR_UNARY_OP_LOCALS
  8880. assert(ne0 == 1);
  8881. assert(ne1 == ne01);
  8882. assert(ne2 == ne02);
  8883. assert(ne3 == ne03);
  8884. UNUSED(ne0);
  8885. UNUSED(ne1);
  8886. UNUSED(ne2);
  8887. UNUSED(ne3);
  8888. for (int64_t i03 = 0; i03 < ne03; i03++) {
  8889. for (int64_t i02 = 0; i02 < ne02; i02++) {
  8890. for (int64_t i01 = 0; i01 < ne01; i01++) {
  8891. ggml_vec_sum_f32(ne00,
  8892. (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  8893. (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
  8894. *(float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3) /= (float) ne00;
  8895. }
  8896. }
  8897. }
  8898. }
  8899. static void ggml_compute_forward_mean(
  8900. const struct ggml_compute_params * params,
  8901. struct ggml_tensor * dst) {
  8902. const struct ggml_tensor * src0 = dst->src[0];
  8903. switch (src0->type) {
  8904. case GGML_TYPE_F32:
  8905. {
  8906. ggml_compute_forward_mean_f32(params, dst);
  8907. } break;
  8908. default:
  8909. {
  8910. GGML_ABORT("fatal error");
  8911. }
  8912. }
  8913. }
  8914. // ggml_compute_forward_argmax
  8915. static void ggml_compute_forward_argmax_f32(
  8916. const struct ggml_compute_params * params,
  8917. struct ggml_tensor * dst) {
  8918. const struct ggml_tensor * src0 = dst->src[0];
  8919. if (params->ith != 0) {
  8920. return;
  8921. }
  8922. assert(src0->nb[0] == sizeof(float));
  8923. assert(dst->nb[0] == sizeof(float));
  8924. const int64_t ne00 = src0->ne[0];
  8925. const int64_t ne01 = src0->ne[1];
  8926. const size_t nb01 = src0->nb[1];
  8927. const size_t nb0 = dst->nb[0];
  8928. for (int64_t i1 = 0; i1 < ne01; i1++) {
  8929. float * src = (float *) ((char *) src0->data + i1*nb01);
  8930. int32_t * dst_ = (int32_t *) ((char *) dst->data + i1*nb0);
  8931. int v = 0;
  8932. ggml_vec_argmax_f32(ne00, &v, src);
  8933. dst_[0] = v;
  8934. }
  8935. }
  8936. static void ggml_compute_forward_argmax(
  8937. const struct ggml_compute_params * params,
  8938. struct ggml_tensor * dst) {
  8939. const struct ggml_tensor * src0 = dst->src[0];
  8940. switch (src0->type) {
  8941. case GGML_TYPE_F32:
  8942. {
  8943. ggml_compute_forward_argmax_f32(params, dst);
  8944. } break;
  8945. default:
  8946. {
  8947. GGML_ABORT("fatal error");
  8948. }
  8949. }
  8950. }
  8951. // ggml_compute_forward_repeat
  8952. static void ggml_compute_forward_repeat_f32(
  8953. const struct ggml_compute_params * params,
  8954. struct ggml_tensor * dst) {
  8955. const struct ggml_tensor * src0 = dst->src[0];
  8956. if (params->ith != 0) {
  8957. return;
  8958. }
  8959. GGML_ASSERT(ggml_can_repeat(src0, dst));
  8960. GGML_TENSOR_UNARY_OP_LOCALS
  8961. // guaranteed to be an integer due to the check in ggml_can_repeat
  8962. const int nr0 = (int)(ne0/ne00);
  8963. const int nr1 = (int)(ne1/ne01);
  8964. const int nr2 = (int)(ne2/ne02);
  8965. const int nr3 = (int)(ne3/ne03);
  8966. // TODO: support for transposed / permuted tensors
  8967. GGML_ASSERT(nb0 == sizeof(float));
  8968. GGML_ASSERT(nb00 == sizeof(float));
  8969. // TODO: maybe this is not optimal?
  8970. for (int i3 = 0; i3 < nr3; i3++) {
  8971. for (int k3 = 0; k3 < ne03; k3++) {
  8972. for (int i2 = 0; i2 < nr2; i2++) {
  8973. for (int k2 = 0; k2 < ne02; k2++) {
  8974. for (int i1 = 0; i1 < nr1; i1++) {
  8975. for (int k1 = 0; k1 < ne01; k1++) {
  8976. for (int i0 = 0; i0 < nr0; i0++) {
  8977. ggml_vec_cpy_f32(ne00,
  8978. (float *) ((char *) dst->data + (i3*ne03 + k3)*nb3 + (i2*ne02 + k2)*nb2 + (i1*ne01 + k1)*nb1 + (i0*ne00)*nb0),
  8979. (float *) ((char *) src0->data + ( k3)*nb03 + ( k2)*nb02 + ( k1)*nb01));
  8980. }
  8981. }
  8982. }
  8983. }
  8984. }
  8985. }
  8986. }
  8987. }
  8988. static void ggml_compute_forward_repeat_f16(
  8989. const struct ggml_compute_params * params,
  8990. struct ggml_tensor * dst) {
  8991. const struct ggml_tensor * src0 = dst->src[0];
  8992. if (params->ith != 0) {
  8993. return;
  8994. }
  8995. GGML_ASSERT(ggml_can_repeat(src0, dst));
  8996. GGML_TENSOR_UNARY_OP_LOCALS
  8997. // guaranteed to be an integer due to the check in ggml_can_repeat
  8998. const int nr0 = (int)(ne0/ne00);
  8999. const int nr1 = (int)(ne1/ne01);
  9000. const int nr2 = (int)(ne2/ne02);
  9001. const int nr3 = (int)(ne3/ne03);
  9002. // TODO: support for transposed / permuted tensors
  9003. GGML_ASSERT(nb0 == sizeof(ggml_fp16_t));
  9004. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  9005. // TODO: maybe this is not optimal?
  9006. for (int i3 = 0; i3 < nr3; i3++) {
  9007. for (int k3 = 0; k3 < ne03; k3++) {
  9008. for (int i2 = 0; i2 < nr2; i2++) {
  9009. for (int k2 = 0; k2 < ne02; k2++) {
  9010. for (int i1 = 0; i1 < nr1; i1++) {
  9011. for (int k1 = 0; k1 < ne01; k1++) {
  9012. for (int i0 = 0; i0 < nr0; i0++) {
  9013. ggml_fp16_t * y = (ggml_fp16_t *) ((char *) dst->data + (i3*ne03 + k3)*nb3 + (i2*ne02 + k2)*nb2 + (i1*ne01 + k1)*nb1 + (i0*ne00)*nb0);
  9014. ggml_fp16_t * x = (ggml_fp16_t *) ((char *) src0->data + ( k3)*nb03 + ( k2)*nb02 + ( k1)*nb01);
  9015. // ggml_vec_cpy_f16(ne00, y, x)
  9016. for (int i = 0; i < ne00; ++i) {
  9017. y[i] = x[i];
  9018. }
  9019. }
  9020. }
  9021. }
  9022. }
  9023. }
  9024. }
  9025. }
  9026. }
  9027. static void ggml_compute_forward_repeat(
  9028. const struct ggml_compute_params * params,
  9029. struct ggml_tensor * dst) {
  9030. const struct ggml_tensor * src0 = dst->src[0];
  9031. switch (src0->type) {
  9032. case GGML_TYPE_F16:
  9033. case GGML_TYPE_BF16:
  9034. case GGML_TYPE_I16:
  9035. {
  9036. ggml_compute_forward_repeat_f16(params, dst);
  9037. } break;
  9038. case GGML_TYPE_F32:
  9039. case GGML_TYPE_I32:
  9040. {
  9041. ggml_compute_forward_repeat_f32(params, dst);
  9042. } break;
  9043. default:
  9044. {
  9045. GGML_ABORT("fatal error");
  9046. }
  9047. }
  9048. }
  9049. // ggml_compute_forward_repeat_back
  9050. static void ggml_compute_forward_repeat_back_f32(
  9051. const struct ggml_compute_params * params,
  9052. struct ggml_tensor * dst) {
  9053. const struct ggml_tensor * src0 = dst->src[0];
  9054. if (params->ith != 0) {
  9055. return;
  9056. }
  9057. GGML_ASSERT(ggml_can_repeat(dst, src0));
  9058. GGML_TENSOR_UNARY_OP_LOCALS
  9059. // guaranteed to be an integer due to the check in ggml_can_repeat
  9060. const int nr0 = (int)(ne00/ne0);
  9061. const int nr1 = (int)(ne01/ne1);
  9062. const int nr2 = (int)(ne02/ne2);
  9063. const int nr3 = (int)(ne03/ne3);
  9064. // TODO: support for transposed / permuted tensors
  9065. GGML_ASSERT(nb0 == sizeof(float));
  9066. GGML_ASSERT(nb00 == sizeof(float));
  9067. if (ggml_is_contiguous(dst)) {
  9068. ggml_vec_set_f32(ne0*ne1*ne2*ne3, dst->data, 0);
  9069. } else {
  9070. for (int k3 = 0; k3 < ne3; k3++) {
  9071. for (int k2 = 0; k2 < ne2; k2++) {
  9072. for (int k1 = 0; k1 < ne1; k1++) {
  9073. ggml_vec_set_f32(ne0,
  9074. (float *) ((char *) dst->data + k1*nb1 + k2*nb2 + k3*nb3),
  9075. 0);
  9076. }
  9077. }
  9078. }
  9079. }
  9080. // TODO: maybe this is not optimal?
  9081. for (int i3 = 0; i3 < nr3; i3++) {
  9082. for (int k3 = 0; k3 < ne3; k3++) {
  9083. for (int i2 = 0; i2 < nr2; i2++) {
  9084. for (int k2 = 0; k2 < ne2; k2++) {
  9085. for (int i1 = 0; i1 < nr1; i1++) {
  9086. for (int k1 = 0; k1 < ne1; k1++) {
  9087. for (int i0 = 0; i0 < nr0; i0++) {
  9088. ggml_vec_acc_f32(ne0,
  9089. (float *) ((char *) dst->data + ( k3)*nb3 + ( k2)*nb2 + ( k1)*nb1),
  9090. (float *) ((char *) src0->data + (i3*ne3 + k3)*nb03 + (i2*ne2 + k2)*nb02 + (i1*ne1 + k1)*nb01 + (i0*ne0)*nb00));
  9091. }
  9092. }
  9093. }
  9094. }
  9095. }
  9096. }
  9097. }
  9098. }
  9099. static void ggml_compute_forward_repeat_back(
  9100. const struct ggml_compute_params * params,
  9101. struct ggml_tensor * dst) {
  9102. const struct ggml_tensor * src0 = dst->src[0];
  9103. switch (src0->type) {
  9104. case GGML_TYPE_F32:
  9105. {
  9106. ggml_compute_forward_repeat_back_f32(params, dst);
  9107. } break;
  9108. default:
  9109. {
  9110. GGML_ABORT("fatal error");
  9111. }
  9112. }
  9113. }
  9114. // ggml_compute_forward_concat
  9115. static void ggml_compute_forward_concat_f32(
  9116. const struct ggml_compute_params * params,
  9117. struct ggml_tensor * dst) {
  9118. const struct ggml_tensor * src0 = dst->src[0];
  9119. const struct ggml_tensor * src1 = dst->src[1];
  9120. GGML_ASSERT(src0->nb[0] == sizeof(float));
  9121. const int ith = params->ith;
  9122. const int nth = params->nth;
  9123. GGML_TENSOR_BINARY_OP_LOCALS
  9124. const int32_t dim = ggml_get_op_params_i32(dst, 0);
  9125. GGML_ASSERT(dim >= 0 && dim < 4);
  9126. int64_t o[4] = {0, 0, 0, 0};
  9127. o[dim] = src0->ne[dim];
  9128. const float * x;
  9129. // TODO: smarter multi-theading
  9130. for (int i3 = 0; i3 < ne3; i3++) {
  9131. for (int i2 = ith; i2 < ne2; i2 += nth) {
  9132. for (int i1 = 0; i1 < ne1; i1++) {
  9133. for (int i0 = 0; i0 < ne0; i0++) {
  9134. if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
  9135. x = (const float *) ((const char *)src0->data + (i0 )*nb00 + (i1 )*nb01 + (i2 )*nb02 + (i3 )*nb03);
  9136. } else {
  9137. x = (const float *) ((const char *)src1->data + (i0 - o[0])*nb10 + (i1 - o[1])*nb11 + (i2 - o[2])*nb12 + (i3 - o[3])*nb13);
  9138. }
  9139. float * y = (float *)((char *)dst->data + i0*nb0 + i1*nb1 + i2*nb2 + i3*nb3);
  9140. *y = *x;
  9141. }
  9142. }
  9143. }
  9144. }
  9145. }
  9146. static void ggml_compute_forward_concat(
  9147. const struct ggml_compute_params * params,
  9148. struct ggml_tensor * dst) {
  9149. const struct ggml_tensor * src0 = dst->src[0];
  9150. switch (src0->type) {
  9151. case GGML_TYPE_F32:
  9152. case GGML_TYPE_I32:
  9153. {
  9154. ggml_compute_forward_concat_f32(params, dst);
  9155. } break;
  9156. default:
  9157. {
  9158. GGML_ABORT("fatal error");
  9159. }
  9160. }
  9161. }
  9162. // ggml_compute_forward_abs
  9163. static void ggml_compute_forward_abs_f32(
  9164. const struct ggml_compute_params * params,
  9165. struct ggml_tensor * dst) {
  9166. const struct ggml_tensor * src0 = dst->src[0];
  9167. if (params->ith != 0) {
  9168. return;
  9169. }
  9170. assert(ggml_is_contiguous_1(src0));
  9171. assert(ggml_is_contiguous_1(dst));
  9172. assert(ggml_are_same_shape(src0, dst));
  9173. const int n = ggml_nrows(src0);
  9174. const int nc = src0->ne[0];
  9175. for (int i = 0; i < n; i++) {
  9176. ggml_vec_abs_f32(nc,
  9177. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9178. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9179. }
  9180. }
  9181. static void ggml_compute_forward_abs(
  9182. const struct ggml_compute_params * params,
  9183. struct ggml_tensor * dst) {
  9184. const struct ggml_tensor * src0 = dst->src[0];
  9185. switch (src0->type) {
  9186. case GGML_TYPE_F32:
  9187. {
  9188. ggml_compute_forward_abs_f32(params, dst);
  9189. } break;
  9190. default:
  9191. {
  9192. GGML_ABORT("fatal error");
  9193. }
  9194. }
  9195. }
  9196. // ggml_compute_forward_sgn
  9197. static void ggml_compute_forward_sgn_f32(
  9198. const struct ggml_compute_params * params,
  9199. struct ggml_tensor * dst) {
  9200. const struct ggml_tensor * src0 = dst->src[0];
  9201. if (params->ith != 0) {
  9202. return;
  9203. }
  9204. assert(ggml_is_contiguous_1(src0));
  9205. assert(ggml_is_contiguous_1(dst));
  9206. assert(ggml_are_same_shape(src0, dst));
  9207. const int n = ggml_nrows(src0);
  9208. const int nc = src0->ne[0];
  9209. for (int i = 0; i < n; i++) {
  9210. ggml_vec_sgn_f32(nc,
  9211. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9212. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9213. }
  9214. }
  9215. static void ggml_compute_forward_sgn(
  9216. const struct ggml_compute_params * params,
  9217. struct ggml_tensor * dst) {
  9218. const struct ggml_tensor * src0 = dst->src[0];
  9219. switch (src0->type) {
  9220. case GGML_TYPE_F32:
  9221. {
  9222. ggml_compute_forward_sgn_f32(params, dst);
  9223. } break;
  9224. default:
  9225. {
  9226. GGML_ABORT("fatal error");
  9227. }
  9228. }
  9229. }
  9230. // ggml_compute_forward_neg
  9231. static void ggml_compute_forward_neg_f32(
  9232. const struct ggml_compute_params * params,
  9233. struct ggml_tensor * dst) {
  9234. const struct ggml_tensor * src0 = dst->src[0];
  9235. if (params->ith != 0) {
  9236. return;
  9237. }
  9238. assert(ggml_is_contiguous_1(src0));
  9239. assert(ggml_is_contiguous_1(dst));
  9240. assert(ggml_are_same_shape(src0, dst));
  9241. const int n = ggml_nrows(src0);
  9242. const int nc = src0->ne[0];
  9243. for (int i = 0; i < n; i++) {
  9244. ggml_vec_neg_f32(nc,
  9245. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9246. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9247. }
  9248. }
  9249. static void ggml_compute_forward_neg(
  9250. const struct ggml_compute_params * params,
  9251. struct ggml_tensor * dst) {
  9252. const struct ggml_tensor * src0 = dst->src[0];
  9253. switch (src0->type) {
  9254. case GGML_TYPE_F32:
  9255. {
  9256. ggml_compute_forward_neg_f32(params, dst);
  9257. } break;
  9258. default:
  9259. {
  9260. GGML_ABORT("fatal error");
  9261. }
  9262. }
  9263. }
  9264. // ggml_compute_forward_step
  9265. static void ggml_compute_forward_step_f32(
  9266. const struct ggml_compute_params * params,
  9267. struct ggml_tensor * dst) {
  9268. const struct ggml_tensor * src0 = dst->src[0];
  9269. if (params->ith != 0) {
  9270. return;
  9271. }
  9272. assert(ggml_is_contiguous_1(src0));
  9273. assert(ggml_is_contiguous_1(dst));
  9274. assert(ggml_are_same_shape(src0, dst));
  9275. const int n = ggml_nrows(src0);
  9276. const int nc = src0->ne[0];
  9277. for (int i = 0; i < n; i++) {
  9278. ggml_vec_step_f32(nc,
  9279. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9280. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9281. }
  9282. }
  9283. static void ggml_compute_forward_step(
  9284. const struct ggml_compute_params * params,
  9285. struct ggml_tensor * dst) {
  9286. const struct ggml_tensor * src0 = dst->src[0];
  9287. switch (src0->type) {
  9288. case GGML_TYPE_F32:
  9289. {
  9290. ggml_compute_forward_step_f32(params, dst);
  9291. } break;
  9292. default:
  9293. {
  9294. GGML_ABORT("fatal error");
  9295. }
  9296. }
  9297. }
  9298. // ggml_compute_forward_tanh
  9299. static void ggml_compute_forward_tanh_f32(
  9300. const struct ggml_compute_params * params,
  9301. struct ggml_tensor * dst) {
  9302. const struct ggml_tensor * src0 = dst->src[0];
  9303. if (params->ith != 0) {
  9304. return;
  9305. }
  9306. assert(ggml_is_contiguous_1(src0));
  9307. assert(ggml_is_contiguous_1(dst));
  9308. assert(ggml_are_same_shape(src0, dst));
  9309. const int n = ggml_nrows(src0);
  9310. const int nc = src0->ne[0];
  9311. for (int i = 0; i < n; i++) {
  9312. ggml_vec_tanh_f32(nc,
  9313. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9314. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9315. }
  9316. }
  9317. static void ggml_compute_forward_tanh(
  9318. const struct ggml_compute_params * params,
  9319. struct ggml_tensor * dst) {
  9320. const struct ggml_tensor * src0 = dst->src[0];
  9321. switch (src0->type) {
  9322. case GGML_TYPE_F32:
  9323. {
  9324. ggml_compute_forward_tanh_f32(params, dst);
  9325. } break;
  9326. default:
  9327. {
  9328. GGML_ABORT("fatal error");
  9329. }
  9330. }
  9331. }
  9332. // ggml_compute_forward_elu
  9333. static void ggml_compute_forward_elu_f32(
  9334. const struct ggml_compute_params * params,
  9335. struct ggml_tensor * dst) {
  9336. const struct ggml_tensor * src0 = dst->src[0];
  9337. if (params->ith != 0) {
  9338. return;
  9339. }
  9340. assert(ggml_is_contiguous_1(src0));
  9341. assert(ggml_is_contiguous_1(dst));
  9342. assert(ggml_are_same_shape(src0, dst));
  9343. const int n = ggml_nrows(src0);
  9344. const int nc = src0->ne[0];
  9345. for (int i = 0; i < n; i++) {
  9346. ggml_vec_elu_f32(nc,
  9347. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9348. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9349. }
  9350. }
  9351. static void ggml_compute_forward_elu(
  9352. const struct ggml_compute_params * params,
  9353. struct ggml_tensor * dst) {
  9354. const struct ggml_tensor * src0 = dst->src[0];
  9355. switch (src0->type) {
  9356. case GGML_TYPE_F32:
  9357. {
  9358. ggml_compute_forward_elu_f32(params, dst);
  9359. } break;
  9360. default:
  9361. {
  9362. GGML_ABORT("fatal error");
  9363. }
  9364. }
  9365. }
  9366. // ggml_compute_forward_relu
  9367. static void ggml_compute_forward_relu_f32(
  9368. const struct ggml_compute_params * params,
  9369. struct ggml_tensor * dst) {
  9370. const struct ggml_tensor * src0 = dst->src[0];
  9371. if (params->ith != 0) {
  9372. return;
  9373. }
  9374. assert(ggml_is_contiguous_1(src0));
  9375. assert(ggml_is_contiguous_1(dst));
  9376. assert(ggml_are_same_shape(src0, dst));
  9377. const int n = ggml_nrows(src0);
  9378. const int nc = src0->ne[0];
  9379. for (int i = 0; i < n; i++) {
  9380. ggml_vec_relu_f32(nc,
  9381. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9382. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9383. }
  9384. }
  9385. static void ggml_compute_forward_relu(
  9386. const struct ggml_compute_params * params,
  9387. struct ggml_tensor * dst) {
  9388. const struct ggml_tensor * src0 = dst->src[0];
  9389. switch (src0->type) {
  9390. case GGML_TYPE_F32:
  9391. {
  9392. ggml_compute_forward_relu_f32(params, dst);
  9393. } break;
  9394. default:
  9395. {
  9396. GGML_ABORT("fatal error");
  9397. }
  9398. }
  9399. }
  9400. // ggml_compute_forward_sigmoid
  9401. static void ggml_compute_forward_sigmoid_f32(
  9402. const struct ggml_compute_params * params,
  9403. struct ggml_tensor * dst) {
  9404. const struct ggml_tensor * src0 = dst->src[0];
  9405. if (params->ith != 0) {
  9406. return;
  9407. }
  9408. assert(ggml_is_contiguous_1(src0));
  9409. assert(ggml_is_contiguous_1(dst));
  9410. assert(ggml_are_same_shape(src0, dst));
  9411. const int n = ggml_nrows(src0);
  9412. const int nc = src0->ne[0];
  9413. for (int i = 0; i < n; i++) {
  9414. ggml_vec_sigmoid_f32(nc,
  9415. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9416. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9417. }
  9418. }
  9419. static void ggml_compute_forward_sigmoid(
  9420. const struct ggml_compute_params * params,
  9421. struct ggml_tensor * dst) {
  9422. const struct ggml_tensor * src0 = dst->src[0];
  9423. switch (src0->type) {
  9424. case GGML_TYPE_F32:
  9425. {
  9426. ggml_compute_forward_sigmoid_f32(params, dst);
  9427. } break;
  9428. default:
  9429. {
  9430. GGML_ABORT("fatal error");
  9431. }
  9432. }
  9433. }
  9434. // ggml_compute_forward_gelu
  9435. static void ggml_compute_forward_gelu_f32(
  9436. const struct ggml_compute_params * params,
  9437. struct ggml_tensor * dst) {
  9438. const struct ggml_tensor * src0 = dst->src[0];
  9439. assert(ggml_is_contiguous_1(src0));
  9440. assert(ggml_is_contiguous_1(dst));
  9441. assert(ggml_are_same_shape(src0, dst));
  9442. const int ith = params->ith;
  9443. const int nth = params->nth;
  9444. const int nc = src0->ne[0];
  9445. const int nr = ggml_nrows(src0);
  9446. // rows per thread
  9447. const int dr = (nr + nth - 1)/nth;
  9448. // row range for this thread
  9449. const int ir0 = dr*ith;
  9450. const int ir1 = MIN(ir0 + dr, nr);
  9451. for (int i1 = ir0; i1 < ir1; i1++) {
  9452. ggml_vec_gelu_f32(nc,
  9453. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  9454. (float *) ((char *) src0->data + i1*(src0->nb[1])));
  9455. #ifndef NDEBUG
  9456. for (int k = 0; k < nc; k++) {
  9457. const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
  9458. UNUSED(x);
  9459. assert(!isnan(x));
  9460. assert(!isinf(x));
  9461. }
  9462. #endif
  9463. }
  9464. }
  9465. static void ggml_compute_forward_gelu(
  9466. const struct ggml_compute_params * params,
  9467. struct ggml_tensor * dst) {
  9468. const struct ggml_tensor * src0 = dst->src[0];
  9469. switch (src0->type) {
  9470. case GGML_TYPE_F32:
  9471. {
  9472. ggml_compute_forward_gelu_f32(params, dst);
  9473. } break;
  9474. default:
  9475. {
  9476. GGML_ABORT("fatal error");
  9477. }
  9478. }
  9479. }
  9480. // ggml_compute_forward_gelu_quick
  9481. static void ggml_compute_forward_gelu_quick_f32(
  9482. const struct ggml_compute_params * params,
  9483. struct ggml_tensor * dst) {
  9484. const struct ggml_tensor * src0 = dst->src[0];
  9485. assert(ggml_is_contiguous_1(src0));
  9486. assert(ggml_is_contiguous_1(dst));
  9487. assert(ggml_are_same_shape(src0, dst));
  9488. const int ith = params->ith;
  9489. const int nth = params->nth;
  9490. const int nc = src0->ne[0];
  9491. const int nr = ggml_nrows(src0);
  9492. // rows per thread
  9493. const int dr = (nr + nth - 1)/nth;
  9494. // row range for this thread
  9495. const int ir0 = dr*ith;
  9496. const int ir1 = MIN(ir0 + dr, nr);
  9497. for (int i1 = ir0; i1 < ir1; i1++) {
  9498. ggml_vec_gelu_quick_f32(nc,
  9499. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  9500. (float *) ((char *) src0->data + i1*(src0->nb[1])));
  9501. #ifndef NDEBUG
  9502. for (int k = 0; k < nc; k++) {
  9503. const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
  9504. UNUSED(x);
  9505. assert(!isnan(x));
  9506. assert(!isinf(x));
  9507. }
  9508. #endif
  9509. }
  9510. }
  9511. static void ggml_compute_forward_gelu_quick(
  9512. const struct ggml_compute_params * params,
  9513. struct ggml_tensor * dst) {
  9514. const struct ggml_tensor * src0 = dst->src[0];
  9515. switch (src0->type) {
  9516. case GGML_TYPE_F32:
  9517. {
  9518. ggml_compute_forward_gelu_quick_f32(params, dst);
  9519. } break;
  9520. default:
  9521. {
  9522. GGML_ABORT("fatal error");
  9523. }
  9524. }
  9525. }
  9526. // ggml_compute_forward_silu
  9527. static void ggml_compute_forward_silu_f32(
  9528. const struct ggml_compute_params * params,
  9529. struct ggml_tensor * dst) {
  9530. const struct ggml_tensor * src0 = dst->src[0];
  9531. assert(ggml_is_contiguous_1(src0));
  9532. assert(ggml_is_contiguous_1(dst));
  9533. assert(ggml_are_same_shape(src0, dst));
  9534. const int ith = params->ith;
  9535. const int nth = params->nth;
  9536. const int nc = src0->ne[0];
  9537. const int nr = ggml_nrows(src0);
  9538. // rows per thread
  9539. const int dr = (nr + nth - 1)/nth;
  9540. // row range for this thread
  9541. const int ir0 = dr*ith;
  9542. const int ir1 = MIN(ir0 + dr, nr);
  9543. for (int i1 = ir0; i1 < ir1; i1++) {
  9544. ggml_vec_silu_f32(nc,
  9545. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  9546. (float *) ((char *) src0->data + i1*(src0->nb[1])));
  9547. #ifndef NDEBUG
  9548. for (int k = 0; k < nc; k++) {
  9549. const float x = ((float *) ((char *) dst->data + i1*(dst->nb[1])))[k];
  9550. UNUSED(x);
  9551. assert(!isnan(x));
  9552. assert(!isinf(x));
  9553. }
  9554. #endif
  9555. }
  9556. }
  9557. static void ggml_compute_forward_silu(
  9558. const struct ggml_compute_params * params,
  9559. struct ggml_tensor * dst) {
  9560. const struct ggml_tensor * src0 = dst->src[0];
  9561. switch (src0->type) {
  9562. case GGML_TYPE_F32:
  9563. {
  9564. ggml_compute_forward_silu_f32(params, dst);
  9565. } break;
  9566. default:
  9567. {
  9568. GGML_ABORT("fatal error");
  9569. }
  9570. }
  9571. }
  9572. // ggml_compute_forward_leaky_relu
  9573. static void ggml_compute_forward_leaky_relu_f32(
  9574. const struct ggml_compute_params * params,
  9575. struct ggml_tensor * dst) {
  9576. const struct ggml_tensor * src0 = dst->src[0];
  9577. if (params->ith != 0) {
  9578. return;
  9579. }
  9580. assert(ggml_is_contiguous_1(src0));
  9581. assert(ggml_is_contiguous_1(dst));
  9582. assert(ggml_are_same_shape(src0, dst));
  9583. const int n = ggml_nrows(src0);
  9584. const int nc = src0->ne[0];
  9585. float negative_slope;
  9586. memcpy(&negative_slope, dst->op_params, sizeof(float));
  9587. assert(dst->nb[0] == sizeof(float));
  9588. assert(src0->nb[0] == sizeof(float));
  9589. for (int i = 0; i < n; i++) {
  9590. ggml_vec_leaky_relu_f32(nc,
  9591. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9592. (float *) ((char *) src0->data + i*(src0->nb[1])), negative_slope);
  9593. }
  9594. }
  9595. static void ggml_compute_forward_leaky_relu(
  9596. const struct ggml_compute_params * params,
  9597. struct ggml_tensor * dst) {
  9598. const struct ggml_tensor * src0 = dst->src[0];
  9599. switch (src0->type) {
  9600. case GGML_TYPE_F32:
  9601. {
  9602. ggml_compute_forward_leaky_relu_f32(params, dst);
  9603. } break;
  9604. default:
  9605. {
  9606. GGML_ABORT("fatal error");
  9607. }
  9608. }
  9609. }
  9610. // ggml_compute_forward_silu_back
  9611. static void ggml_compute_forward_silu_back_f32(
  9612. const struct ggml_compute_params * params,
  9613. struct ggml_tensor * dst) {
  9614. const struct ggml_tensor * src0 = dst->src[0];
  9615. const struct ggml_tensor * grad = dst->src[1];
  9616. assert(ggml_is_contiguous_1(grad));
  9617. assert(ggml_is_contiguous_1(src0));
  9618. assert(ggml_is_contiguous_1(dst));
  9619. assert(ggml_are_same_shape(src0, dst));
  9620. assert(ggml_are_same_shape(src0, grad));
  9621. const int ith = params->ith;
  9622. const int nth = params->nth;
  9623. const int nc = src0->ne[0];
  9624. const int nr = ggml_nrows(src0);
  9625. // rows per thread
  9626. const int dr = (nr + nth - 1)/nth;
  9627. // row range for this thread
  9628. const int ir0 = dr*ith;
  9629. const int ir1 = MIN(ir0 + dr, nr);
  9630. for (int i1 = ir0; i1 < ir1; i1++) {
  9631. ggml_vec_silu_backward_f32(nc,
  9632. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  9633. (float *) ((char *) src0->data + i1*(src0->nb[1])),
  9634. (float *) ((char *) grad->data + i1*(grad->nb[1])));
  9635. #ifndef NDEBUG
  9636. for (int k = 0; k < nc; k++) {
  9637. const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
  9638. UNUSED(x);
  9639. assert(!isnan(x));
  9640. assert(!isinf(x));
  9641. }
  9642. #endif
  9643. }
  9644. }
  9645. static void ggml_compute_forward_silu_back(
  9646. const struct ggml_compute_params * params,
  9647. struct ggml_tensor * dst) {
  9648. const struct ggml_tensor * src0 = dst->src[0];
  9649. switch (src0->type) {
  9650. case GGML_TYPE_F32:
  9651. {
  9652. ggml_compute_forward_silu_back_f32(params, dst);
  9653. } break;
  9654. default:
  9655. {
  9656. GGML_ABORT("fatal error");
  9657. }
  9658. }
  9659. }
  9660. static void ggml_compute_forward_hardswish_f32(
  9661. const struct ggml_compute_params * params,
  9662. struct ggml_tensor * dst) {
  9663. const struct ggml_tensor * src0 = dst->src[0];
  9664. if (params->ith != 0) {
  9665. return;
  9666. }
  9667. assert(ggml_is_contiguous_1(src0));
  9668. assert(ggml_is_contiguous_1(dst));
  9669. assert(ggml_are_same_shape(src0, dst));
  9670. const int n = ggml_nrows(src0);
  9671. const int nc = src0->ne[0];
  9672. for (int i = 0; i < n; i++) {
  9673. ggml_vec_hardswish_f32(nc,
  9674. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9675. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9676. }
  9677. }
  9678. static void ggml_compute_forward_hardswish(
  9679. const struct ggml_compute_params * params,
  9680. struct ggml_tensor * dst) {
  9681. const struct ggml_tensor * src0 = dst->src[0];
  9682. switch (src0->type) {
  9683. case GGML_TYPE_F32:
  9684. {
  9685. ggml_compute_forward_hardswish_f32(params, dst);
  9686. } break;
  9687. default:
  9688. {
  9689. GGML_ABORT("fatal error");
  9690. }
  9691. }
  9692. }
  9693. static void ggml_compute_forward_hardsigmoid_f32(
  9694. const struct ggml_compute_params * params,
  9695. struct ggml_tensor * dst) {
  9696. const struct ggml_tensor * src0 = dst->src[0];
  9697. if (params->ith != 0) {
  9698. return;
  9699. }
  9700. assert(ggml_is_contiguous_1(src0));
  9701. assert(ggml_is_contiguous_1(dst));
  9702. assert(ggml_are_same_shape(src0, dst));
  9703. const int n = ggml_nrows(src0);
  9704. const int nc = src0->ne[0];
  9705. for (int i = 0; i < n; i++) {
  9706. ggml_vec_hardsigmoid_f32(nc,
  9707. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9708. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9709. }
  9710. }
  9711. static void ggml_compute_forward_hardsigmoid(
  9712. const struct ggml_compute_params * params,
  9713. struct ggml_tensor * dst) {
  9714. const struct ggml_tensor * src0 = dst->src[0];
  9715. switch (src0->type) {
  9716. case GGML_TYPE_F32:
  9717. {
  9718. ggml_compute_forward_hardsigmoid_f32(params, dst);
  9719. } break;
  9720. default:
  9721. {
  9722. GGML_ABORT("fatal error");
  9723. }
  9724. }
  9725. }
  9726. static void ggml_compute_forward_exp_f32(
  9727. const struct ggml_compute_params * params,
  9728. struct ggml_tensor * dst) {
  9729. const struct ggml_tensor * src0 = dst->src[0];
  9730. if (params->ith != 0) {
  9731. return;
  9732. }
  9733. assert(ggml_is_contiguous_1(src0));
  9734. assert(ggml_is_contiguous_1(dst));
  9735. assert(ggml_are_same_shape(src0, dst));
  9736. const int n = ggml_nrows(src0);
  9737. const int nc = src0->ne[0];
  9738. for (int i = 0; i < n; i++) {
  9739. ggml_vec_exp_f32(nc,
  9740. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9741. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9742. }
  9743. }
  9744. static void ggml_compute_forward_exp(
  9745. const struct ggml_compute_params * params,
  9746. struct ggml_tensor * dst) {
  9747. const struct ggml_tensor * src0 = dst->src[0];
  9748. switch (src0->type) {
  9749. case GGML_TYPE_F32:
  9750. {
  9751. ggml_compute_forward_exp_f32(params, dst);
  9752. } break;
  9753. default:
  9754. {
  9755. GGML_ABORT("fatal error");
  9756. }
  9757. }
  9758. }
  9759. // ggml_compute_forward_norm
  9760. static void ggml_compute_forward_norm_f32(
  9761. const struct ggml_compute_params * params,
  9762. struct ggml_tensor * dst) {
  9763. const struct ggml_tensor * src0 = dst->src[0];
  9764. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  9765. GGML_ASSERT(src0->nb[0] == sizeof(float));
  9766. const int ith = params->ith;
  9767. const int nth = params->nth;
  9768. GGML_TENSOR_UNARY_OP_LOCALS
  9769. float eps;
  9770. memcpy(&eps, dst->op_params, sizeof(float));
  9771. GGML_ASSERT(eps > 0.0f);
  9772. // TODO: optimize
  9773. for (int64_t i03 = 0; i03 < ne03; i03++) {
  9774. for (int64_t i02 = 0; i02 < ne02; i02++) {
  9775. for (int64_t i01 = ith; i01 < ne01; i01 += nth) {
  9776. const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  9777. ggml_float sum = 0.0;
  9778. for (int64_t i00 = 0; i00 < ne00; i00++) {
  9779. sum += (ggml_float)x[i00];
  9780. }
  9781. float mean = sum/ne00;
  9782. float * y = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
  9783. ggml_float sum2 = 0.0;
  9784. for (int64_t i00 = 0; i00 < ne00; i00++) {
  9785. float v = x[i00] - mean;
  9786. y[i00] = v;
  9787. sum2 += (ggml_float)(v*v);
  9788. }
  9789. float variance = sum2/ne00;
  9790. const float scale = 1.0f/sqrtf(variance + eps);
  9791. ggml_vec_scale_f32(ne00, y, scale);
  9792. }
  9793. }
  9794. }
  9795. }
  9796. static void ggml_compute_forward_norm(
  9797. const struct ggml_compute_params * params,
  9798. struct ggml_tensor * dst) {
  9799. const struct ggml_tensor * src0 = dst->src[0];
  9800. switch (src0->type) {
  9801. case GGML_TYPE_F32:
  9802. {
  9803. ggml_compute_forward_norm_f32(params, dst);
  9804. } break;
  9805. default:
  9806. {
  9807. GGML_ABORT("fatal error");
  9808. }
  9809. }
  9810. }
  9811. // ggml_compute_forward_group_rms_norm
  9812. static void ggml_compute_forward_rms_norm_f32(
  9813. const struct ggml_compute_params * params,
  9814. struct ggml_tensor * dst) {
  9815. const struct ggml_tensor * src0 = dst->src[0];
  9816. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  9817. GGML_ASSERT(src0->nb[0] == sizeof(float));
  9818. const int ith = params->ith;
  9819. const int nth = params->nth;
  9820. GGML_TENSOR_UNARY_OP_LOCALS
  9821. float eps;
  9822. memcpy(&eps, dst->op_params, sizeof(float));
  9823. GGML_ASSERT(eps > 0.0f);
  9824. // TODO: optimize
  9825. for (int64_t i03 = 0; i03 < ne03; i03++) {
  9826. for (int64_t i02 = 0; i02 < ne02; i02++) {
  9827. for (int64_t i01 = ith; i01 < ne01; i01 += nth) {
  9828. const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  9829. ggml_float sum = 0.0;
  9830. for (int64_t i00 = 0; i00 < ne00; i00++) {
  9831. sum += (ggml_float)(x[i00] * x[i00]);
  9832. }
  9833. const float mean = sum/ne00;
  9834. float * y = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
  9835. memcpy(y, x, ne00 * sizeof(float));
  9836. // for (int i00 = 0; i00 < ne00; i00++) {
  9837. // y[i00] = x[i00];
  9838. // }
  9839. const float scale = 1.0f/sqrtf(mean + eps);
  9840. ggml_vec_scale_f32(ne00, y, scale);
  9841. }
  9842. }
  9843. }
  9844. }
  9845. static void ggml_compute_forward_rms_norm(
  9846. const struct ggml_compute_params * params,
  9847. struct ggml_tensor * dst) {
  9848. const struct ggml_tensor * src0 = dst->src[0];
  9849. switch (src0->type) {
  9850. case GGML_TYPE_F32:
  9851. {
  9852. ggml_compute_forward_rms_norm_f32(params, dst);
  9853. } break;
  9854. default:
  9855. {
  9856. GGML_ABORT("fatal error");
  9857. }
  9858. }
  9859. }
  9860. static void ggml_compute_forward_rms_norm_back_f32(
  9861. const struct ggml_compute_params * params,
  9862. struct ggml_tensor * dst) {
  9863. const struct ggml_tensor * src0 = dst->src[0];
  9864. const struct ggml_tensor * src1 = dst->src[1];
  9865. GGML_ASSERT(ggml_are_same_shape(src0, dst) && ggml_are_same_shape(src0, src1));
  9866. GGML_ASSERT(src0->nb[0] == sizeof(float));
  9867. const int ith = params->ith;
  9868. const int nth = params->nth;
  9869. GGML_TENSOR_BINARY_OP_LOCALS
  9870. float eps;
  9871. memcpy(&eps, dst->op_params, sizeof(float));
  9872. // TODO: optimize
  9873. for (int64_t i03 = 0; i03 < ne03; i03++) {
  9874. for (int64_t i02 = 0; i02 < ne02; i02++) {
  9875. for (int64_t i01 = ith; i01 < ne01; i01 += nth) {
  9876. // src1 is same shape as src0 => same indices
  9877. const int64_t i11 = i01;
  9878. const int64_t i12 = i02;
  9879. const int64_t i13 = i03;
  9880. const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  9881. const float * dz = (float *) ((char *) src1->data + i11*nb11 + i12*nb12 + i13*nb13);
  9882. ggml_float sum_xx = 0.0;
  9883. ggml_float sum_xdz = 0.0;
  9884. for (int64_t i00 = 0; i00 < ne00; i00++) {
  9885. sum_xx += (ggml_float)(x[i00] * x[i00]);
  9886. sum_xdz += (ggml_float)(x[i00] * dz[i00]);
  9887. }
  9888. //const float mean = (float)(sum_xx)/ne00;
  9889. const float mean_eps = (float)(sum_xx)/ne00 + eps;
  9890. const float sum_eps = (float)(sum_xx) + eps*ne00;
  9891. //const float mean_xdz = (float)(sum_xdz)/ne00;
  9892. // we could cache rms from forward pass to improve performance.
  9893. // to do this implement ggml_rms and compose ggml_rms_norm using ggml_rms.
  9894. //const float rms = sqrtf(mean_eps);
  9895. const float rrms = 1.0f / sqrtf(mean_eps);
  9896. //const float scale = -rrms/(ne00 * mean_eps); // -1/(n*rms**3)
  9897. {
  9898. // z = rms_norm(x)
  9899. //
  9900. // rms_norm(src0) =
  9901. // scale(
  9902. // src0,
  9903. // div(
  9904. // 1,
  9905. // sqrt(
  9906. // add(
  9907. // scale(
  9908. // sum(
  9909. // sqr(
  9910. // src0)),
  9911. // (1.0/N)),
  9912. // eps))));
  9913. // postorder:
  9914. // ## op args grad
  9915. // 00 param src0 grad[#00]
  9916. // 01 const 1
  9917. // 02 sqr (#00) grad[#02]
  9918. // 03 sum (#02) grad[#03]
  9919. // 04 const 1/N
  9920. // 05 scale (#03, #04) grad[#05]
  9921. // 06 const eps
  9922. // 07 add (#05, #06) grad[#07]
  9923. // 08 sqrt (#07) grad[#08]
  9924. // 09 div (#01,#08) grad[#09]
  9925. // 10 scale (#00,#09) grad[#10]
  9926. //
  9927. // backward pass, given grad[#10]
  9928. // #10: scale
  9929. // grad[#00] += scale(grad[#10],#09)
  9930. // grad[#09] += sum(mul(grad[#10],#00))
  9931. // #09: div
  9932. // grad[#08] += neg(mul(grad[#09], div(#09,#08)))
  9933. // #08: sqrt
  9934. // grad[#07] += mul(grad[#08], div(0.5, #08))
  9935. // #07: add
  9936. // grad[#05] += grad[#07]
  9937. // #05: scale
  9938. // grad[#03] += scale(grad[#05],#04)
  9939. // #03: sum
  9940. // grad[#02] += repeat(grad[#03], #02)
  9941. // #02:
  9942. // grad[#00] += scale(mul(#00, grad[#02]), 2.0)
  9943. //
  9944. // substitute and simplify:
  9945. // grad[#00] = scale(grad(#10), #09) + scale(mul(#00, grad[#02]), 2.0)
  9946. // grad[#02] = repeat(grad[#03], #02)
  9947. // grad[#02] = repeat(scale(grad[#05],#04), #02)
  9948. // grad[#02] = repeat(scale(grad[#07],#04), #02)
  9949. // grad[#02] = repeat(scale(mul(grad[#08], div(0.5, #08)),#04), #02)
  9950. // grad[#02] = repeat(scale(mul(neg(mul(grad[#09], div(#09,#08))), div(0.5, #08)),#04), #02)
  9951. // grad[#02] = repeat(scale(mul(neg(mul(sum(mul(grad[#10],#00)), div(#09,#08))), div(0.5, #08)),#04), #02)
  9952. // grad[#02] = repeat(-(sum(mul(grad[#10],#00)) * div(#09,#08) * div(0.5, #08) * (1/N)), #02)
  9953. // grad[#02] = repeat(-(sum(mul(grad[#10],#00)) * div(div(#01,#08),#08) * div(0.5, #08) * (1/N)), #02)
  9954. // grad[#02] = repeat(-(sum(mul(grad[#10],#00)) * div(1,#08*#08) * div(0.5, #08) * (1/N)), #02)
  9955. // grad[#02] = repeat(-(sum(mul(grad[#10],#00)) * div(1,#07) * div(0.5, #08) * (1/N)), #02)
  9956. // grad[#00] = scale(grad(#10), #09) + scale(mul(#00, grad[#02]), 2.0)
  9957. // grad[#00] = scale(grad(#10), #09) + scale(mul(#00, repeat(-(sum(mul(grad[#10],#00)) * div(1,#07) * div(0.5, #08) * (1/N)), #02)), 2.0)
  9958. // grad[#00] = scale(grad(#10), #09) + scale(scale(#00, -(sum(mul(grad[#10],#00)) * div(1,#07) * div(0.5, #08) * (1/N))), 2.0)
  9959. // grad[#00] = scale(grad(#10), #09) + scale(#00, -(sum(mul(grad[#10],#00)) * div(1,#07) * div(1,#08) * (1/N)))
  9960. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(1,#07*#08) * (-1/N))
  9961. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(1,#07*#08) * (-1/N))
  9962. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(1,mean_eps*rms) * (-1/N))
  9963. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(-1,rms*N*mean_eps))
  9964. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(-1,rms*N*(sum_xx/N+eps)))
  9965. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(-1,rms*N*sum_xx+rms*N*eps))
  9966. // grad[#00] = scale(dz, rrms) + scale(x, sum(mul(dz,x)) * div(-1,rms*N*mean_eps))
  9967. // grad[#00] = scale(dz, rrms) + scale(x, sum_xdz * div(-1,rms*N*mean_eps))
  9968. // a = b*c + d*e
  9969. // a = b*c*f/f + d*e*f/f
  9970. // a = (b*c*f + d*e*f)*(1/f)
  9971. // a = (b*c*(1/c) + d*e*(1/c))*(1/(1/c))
  9972. // a = (b + d*e/c)*c
  9973. // b = dz, c = rrms, d = x, e = sum_xdz * div(-1,rms*N*mean_eps)
  9974. // a = (dz + x*sum_xdz * div(-1,rms*N*mean_eps)/rrms)*rrms
  9975. // a = (dz + x*sum_xdz * div(-1,rms*N*mean_eps)*rms)*rrms
  9976. // a = (dz + x*sum_xdz * div(-rms,rms*N*mean_eps))*rrms
  9977. // a = (dz + x*sum_xdz * div(-1,N*mean_eps))*rrms
  9978. // a = (dz + x*div(-sum_xdz,N*mean_eps))*rrms
  9979. // a = (dz + x*div(-mean_xdz,mean_eps))*rrms
  9980. // grad[#00] = scale(dz + scale(x, div(-mean_xdz,mean_eps)),rrms)
  9981. // grad[#00] = scale(dz + scale(x, -mean_xdz/mean_eps),rrms)
  9982. // dx = scale(dz + scale(x, -mean_xdz/mean_eps),rrms)
  9983. }
  9984. // dx = scale(dz + scale(x, -mean_xdz/mean_eps),rrms)
  9985. // post-order:
  9986. // dx := x
  9987. // dx := scale(dx,-mean_xdz/mean_eps)
  9988. // dx := add(dx, dz)
  9989. // dx := scale(dx, rrms)
  9990. float * dx = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
  9991. ggml_vec_cpy_f32 (ne00, dx, x);
  9992. // ggml_vec_scale_f32(ne00, dx, -mean_xdz/mean_eps);
  9993. ggml_vec_scale_f32(ne00, dx, (float)(-sum_xdz)/sum_eps);
  9994. ggml_vec_acc_f32 (ne00, dx, dz);
  9995. ggml_vec_scale_f32(ne00, dx, rrms);
  9996. }
  9997. }
  9998. }
  9999. }
  10000. static void ggml_compute_forward_rms_norm_back(
  10001. const struct ggml_compute_params * params,
  10002. struct ggml_tensor * dst) {
  10003. const struct ggml_tensor * src0 = dst->src[0];
  10004. switch (src0->type) {
  10005. case GGML_TYPE_F32:
  10006. {
  10007. ggml_compute_forward_rms_norm_back_f32(params, dst);
  10008. } break;
  10009. default:
  10010. {
  10011. GGML_ABORT("fatal error");
  10012. }
  10013. }
  10014. }
  10015. // ggml_compute_forward_group_norm
  10016. static void ggml_compute_forward_group_norm_f32(
  10017. const struct ggml_compute_params * params,
  10018. struct ggml_tensor * dst) {
  10019. const struct ggml_tensor * src0 = dst->src[0];
  10020. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  10021. GGML_ASSERT(src0->nb[0] == sizeof(float));
  10022. const int ith = params->ith;
  10023. const int nth = params->nth;
  10024. GGML_TENSOR_UNARY_OP_LOCALS
  10025. // TODO: optimize
  10026. float eps;
  10027. memcpy(&eps, dst->op_params + 1, sizeof(float));
  10028. int n_channels = src0->ne[2];
  10029. int n_groups = dst->op_params[0];
  10030. int n_channels_per_group = (n_channels + n_groups - 1) / n_groups;
  10031. for (int i = ith; i < n_groups; i += nth) {
  10032. int start = i * n_channels_per_group;
  10033. int end = start + n_channels_per_group;
  10034. if (end > n_channels) {
  10035. end = n_channels;
  10036. }
  10037. int step = end - start;
  10038. for (int64_t i03 = 0; i03 < ne03; i03++) {
  10039. ggml_float sum = 0.0;
  10040. for (int64_t i02 = start; i02 < end; i02++) {
  10041. for (int64_t i01 = 0; i01 < ne01; i01++) {
  10042. const float * x = (float *)((char *) src0->data + i01 * nb01 + i02 * nb02 + i03 * nb03);
  10043. ggml_float sumr = 0.0;
  10044. for (int64_t i00 = 0; i00 < ne00; i00++) {
  10045. sumr += (ggml_float)x[i00];
  10046. }
  10047. sum += sumr;
  10048. }
  10049. }
  10050. const float mean = sum / (ne00 * ne01 * step);
  10051. ggml_float sum2 = 0.0;
  10052. for (int64_t i02 = start; i02 < end; i02++) {
  10053. for (int64_t i01 = 0; i01 < ne01; i01++) {
  10054. const float * x = (float *)((char *) src0->data + i01 * nb01 + i02 * nb02 + i03 * nb03);
  10055. float * y = (float *)((char *) dst->data + i01 * nb1 + i02 * nb2 + i03 * nb3);
  10056. ggml_float sumr = 0.0;
  10057. for (int64_t i00 = 0; i00 < ne00; i00++) {
  10058. float v = x[i00] - mean;
  10059. y[i00] = v;
  10060. sumr += (ggml_float)(v * v);
  10061. }
  10062. sum2 += sumr;
  10063. }
  10064. }
  10065. const float variance = sum2 / (ne00 * ne01 * step);
  10066. const float scale = 1.0f / sqrtf(variance + eps);
  10067. for (int64_t i02 = start; i02 < end; i02++) {
  10068. for (int64_t i01 = 0; i01 < ne01; i01++) {
  10069. float * y = (float *)((char *) dst->data + i01 * nb1 + i02 * nb2 + i03 * nb3);
  10070. ggml_vec_scale_f32(ne00, y, scale);
  10071. }
  10072. }
  10073. }
  10074. }
  10075. }
  10076. static void ggml_compute_forward_group_norm(
  10077. const struct ggml_compute_params * params,
  10078. struct ggml_tensor * dst) {
  10079. const struct ggml_tensor * src0 = dst->src[0];
  10080. switch (src0->type) {
  10081. case GGML_TYPE_F32:
  10082. {
  10083. ggml_compute_forward_group_norm_f32(params, dst);
  10084. } break;
  10085. default:
  10086. {
  10087. GGML_ABORT("fatal error");
  10088. }
  10089. }
  10090. }
  10091. // ggml_compute_forward_mul_mat
  10092. static void ggml_compute_forward_mul_mat_one_chunk(
  10093. const struct ggml_compute_params * params,
  10094. struct ggml_tensor * dst,
  10095. const int64_t num_rows_per_vec_dot,
  10096. const int64_t ir0_start,
  10097. const int64_t ir0_end,
  10098. const int64_t ir1_start,
  10099. const int64_t ir1_end) {
  10100. const struct ggml_tensor * src0 = dst->src[0];
  10101. const struct ggml_tensor * src1 = dst->src[1];
  10102. GGML_TENSOR_BINARY_OP_LOCALS
  10103. const enum ggml_type type = src0->type;
  10104. const bool src1_cont = ggml_is_contiguous(src1);
  10105. ggml_vec_dot_t const vec_dot = type_traits[type].vec_dot;
  10106. enum ggml_type const vec_dot_type = type_traits[type].vec_dot_type;
  10107. // broadcast factors
  10108. const int64_t r2 = ne12 / ne02;
  10109. const int64_t r3 = ne13 / ne03;
  10110. //printf("ir0_start = %6lld, ir0_end = %6lld, ir1_start = %6lld, ir1_end = %6lld\n", ir0_start, ir0_end, ir1_start, ir1_end);
  10111. // threads with no work simply yield (not sure if it helps)
  10112. if (ir0_start >= ir0_end || ir1_start >= ir1_end) {
  10113. return;
  10114. }
  10115. const void * wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  10116. const size_t row_size = ggml_row_size(vec_dot_type, ne10);
  10117. assert(ne12 % ne02 == 0);
  10118. assert(ne13 % ne03 == 0);
  10119. // block-tiling attempt
  10120. const int64_t blck_0 = 16;
  10121. const int64_t blck_1 = 16;
  10122. const size_t src1_col_stride = src1_cont || src1->type != vec_dot_type ? row_size : nb11;
  10123. // attempt to reduce false-sharing (does not seem to make a difference)
  10124. // 16 * 2, accounting for mmla kernels
  10125. float tmp[32];
  10126. for (int64_t iir1 = ir1_start; iir1 < ir1_end; iir1 += blck_1) {
  10127. for (int64_t iir0 = ir0_start; iir0 < ir0_end; iir0 += blck_0) {
  10128. for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir1_end; ir1 += num_rows_per_vec_dot) {
  10129. const int64_t i13 = (ir1 / (ne12 * ne1));
  10130. const int64_t i12 = (ir1 - i13 * ne12 * ne1) / ne1;
  10131. const int64_t i11 = (ir1 - i13 * ne12 * ne1 - i12 * ne1);
  10132. // broadcast src0 into src1
  10133. const int64_t i03 = i13 / r3;
  10134. const int64_t i02 = i12 / r2;
  10135. const int64_t i1 = i11;
  10136. const int64_t i2 = i12;
  10137. const int64_t i3 = i13;
  10138. const char * src0_row = (const char*)src0->data + (0 + i02 * nb02 + i03 * nb03);
  10139. // desc: when src1 is not a contiguous memory block we have to calculate the offset using the strides
  10140. // if it is, then we have either copied the data to params->wdata and made it contiguous or we are using
  10141. // the original src1 data pointer, so we should index using the indices directly
  10142. // TODO: this is a bit of a hack, we should probably have a better way to handle this
  10143. const char * src1_col = (const char*)wdata +
  10144. (src1_cont || src1->type != vec_dot_type
  10145. ? (i11 + i12 * ne11 + i13 * ne12 * ne11) * row_size
  10146. : (i11 * nb11 + i12 * nb12 + i13 * nb13));
  10147. float * dst_col = (float*)((char*)dst->data + (i1 * nb1 + i2 * nb2 + i3 * nb3));
  10148. //for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ++ir0) {
  10149. // vec_dot(ne00, &dst_col[ir0], src0_row + ir0*nb01, src1_col);
  10150. //}
  10151. for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ir0 += num_rows_per_vec_dot) {
  10152. vec_dot(ne00, &tmp[ir0 - iir0], (num_rows_per_vec_dot > 1 ? 16 : 0), src0_row + ir0 * nb01, (num_rows_per_vec_dot > 1 ? nb01 : 0), src1_col, (num_rows_per_vec_dot > 1 ? src1_col_stride : 0), num_rows_per_vec_dot);
  10153. }
  10154. for (int cn = 0; cn < num_rows_per_vec_dot; ++cn) {
  10155. memcpy(&dst_col[iir0 + cn * nb1 / nb0], tmp + (cn * 16), (MIN(iir0 + blck_0, ir0_end) - iir0) * sizeof(float));
  10156. }
  10157. }
  10158. }
  10159. }
  10160. }
  10161. static void ggml_compute_forward_mul_mat(
  10162. const struct ggml_compute_params * params,
  10163. struct ggml_tensor * dst) {
  10164. const struct ggml_tensor * src0 = dst->src[0];
  10165. const struct ggml_tensor * src1 = dst->src[1];
  10166. GGML_TENSOR_BINARY_OP_LOCALS
  10167. const int ith = params->ith;
  10168. const int nth = params->nth;
  10169. const enum ggml_type type = src0->type;
  10170. enum ggml_type const vec_dot_type = type_traits[type].vec_dot_type;
  10171. ggml_from_float_t const from_float = type_traits[vec_dot_type].from_float;
  10172. ggml_from_float_to_mat_t const from_float_to_mat = type_traits[vec_dot_type].from_float_to_mat;
  10173. int64_t const vec_dot_num_rows = type_traits[type].nrows;
  10174. int64_t const matmul_num_cols = type_traits[type].ncols;
  10175. int64_t const blck_size_interleave = type_traits[type].blck_size_interleave;
  10176. ggml_gemv_t const gemv = type_traits[type].gemv;
  10177. ggml_gemm_t const gemm = type_traits[type].gemm;
  10178. GGML_ASSERT(ne0 == ne01);
  10179. GGML_ASSERT(ne1 == ne11);
  10180. GGML_ASSERT(ne2 == ne12);
  10181. GGML_ASSERT(ne3 == ne13);
  10182. // we don't support permuted src0 or src1
  10183. GGML_ASSERT(nb00 == ggml_type_size(type));
  10184. GGML_ASSERT(nb10 == ggml_type_size(src1->type));
  10185. // dst cannot be transposed or permuted
  10186. GGML_ASSERT(nb0 == sizeof(float));
  10187. GGML_ASSERT(nb0 <= nb1);
  10188. GGML_ASSERT(nb1 <= nb2);
  10189. GGML_ASSERT(nb2 <= nb3);
  10190. // nb01 >= nb00 - src0 is not transposed
  10191. // compute by src0 rows
  10192. #if GGML_USE_LLAMAFILE
  10193. // broadcast factors
  10194. const int64_t r2 = ne12 / ne02;
  10195. const int64_t r3 = ne13 / ne03;
  10196. const bool src1_cont = ggml_is_contiguous(src1);
  10197. if (src1_cont) {
  10198. for (int64_t i13 = 0; i13 < ne13; i13++)
  10199. for (int64_t i12 = 0; i12 < ne12; i12++)
  10200. if (!llamafile_sgemm(ne01, ne11, ne00/ggml_blck_size(src0->type),
  10201. (const char *)src0->data + i12/r2*nb02 + i13/r3*nb03,
  10202. nb01/ggml_type_size(src0->type),
  10203. (const char *)src1->data + i12*nb12 + i13*nb13,
  10204. nb11/ggml_type_size(src1->type),
  10205. (char *)dst->data + i12*nb2 + i13*nb3,
  10206. nb1/ggml_type_size(dst->type),
  10207. ith, nth,
  10208. src0->type,
  10209. src1->type,
  10210. dst->type))
  10211. goto UseGgmlGemm1;
  10212. return;
  10213. }
  10214. UseGgmlGemm1:;
  10215. #endif
  10216. if (src1->type != vec_dot_type) {
  10217. char * wdata = params->wdata;
  10218. const size_t nbw1 = ggml_row_size(vec_dot_type, ne10);
  10219. const size_t nbw2 = nbw1*ne11;
  10220. const size_t nbw3 = nbw2*ne12;
  10221. assert(params->wsize >= ne13*nbw3);
  10222. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  10223. for (int64_t i13 = 0; i13 < ne13; ++i13) {
  10224. for (int64_t i12 = 0; i12 < ne12; ++i12) {
  10225. int64_t i11_processed = 0;
  10226. if ((ggml_n_dims(src1) == 2) && from_float_to_mat && gemm) {
  10227. for (int64_t i11 = ith * 4; i11 < ne11 - ne11 % 4; i11 += nth * 4) {
  10228. from_float_to_mat((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11),
  10229. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1),
  10230. 4, ne10, blck_size_interleave);
  10231. }
  10232. i11_processed = ne11 - ne11 % 4;
  10233. }
  10234. for (int64_t i11 = i11_processed + ith; i11 < ne11; i11 += nth) {
  10235. from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11),
  10236. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1),
  10237. ne10);
  10238. }
  10239. }
  10240. }
  10241. }
  10242. if (ith == 0) {
  10243. // Every thread starts at ith, so the first unprocessed chunk is nth. This save a bit of coordination right at the start.
  10244. atomic_store_explicit(&params->threadpool->current_chunk, nth, memory_order_relaxed);
  10245. }
  10246. ggml_barrier(params->threadpool);
  10247. #if GGML_USE_LLAMAFILE
  10248. if (src1->type != vec_dot_type) {
  10249. const void* wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  10250. const size_t row_size = ggml_row_size(vec_dot_type, ne10);
  10251. for (int64_t i13 = 0; i13 < ne13; i13++)
  10252. for (int64_t i12 = 0; i12 < ne12; i12++)
  10253. if (!llamafile_sgemm(ne01, ne11, ne00/ggml_blck_size(src0->type),
  10254. (const char *)src0->data + i12/r2*nb02 + i13/r3*nb03,
  10255. nb01/ggml_type_size(src0->type),
  10256. (const char *)wdata + (i12*ne11 + i13*ne12*ne11)*row_size,
  10257. row_size/ggml_type_size(vec_dot_type),
  10258. (char *)dst->data + i12*nb2 + i13*nb3,
  10259. nb1/ggml_type_size(dst->type),
  10260. ith, nth,
  10261. src0->type,
  10262. vec_dot_type,
  10263. dst->type))
  10264. goto UseGgmlGemm2;
  10265. return;
  10266. }
  10267. UseGgmlGemm2:;
  10268. #endif
  10269. // This is the size of the first dimension of the result, so we can iterate that way. (see the ASSERT above, these are the same numbers)
  10270. const int64_t nr0 = ne0;
  10271. // This is the size of the rest of the dimensions of the result
  10272. const int64_t nr1 = ne1 * ne2 * ne3;
  10273. // dot kernels can handle 1 row and col at a time, but mmla kernels can process 2 rows and cols
  10274. int64_t num_rows_per_vec_dot = vec_dot_num_rows;
  10275. // TODO: currently the mmla kernels support only even numbered rows/cols.
  10276. // this check can be removed once they are extended to support odd numbered rows/cols too
  10277. if ((nr0 % 2 != 0) || (ne11 % 2 != 0)) {
  10278. num_rows_per_vec_dot = 1;
  10279. }
  10280. // Now select a reasonable chunk size.
  10281. int chunk_size = 16;
  10282. // We need to step up the size if it's small
  10283. if (nr0 == 1 || nr1 == 1) {
  10284. chunk_size = 64;
  10285. }
  10286. // distribute the work across the inner or outer loop based on which one is larger
  10287. // The number of chunks in the 0/1 dim.
  10288. // CEIL(nr0/chunk_size)
  10289. int64_t nchunk0 = (nr0 + chunk_size - 1) / chunk_size;
  10290. int64_t nchunk1 = (nr1 + chunk_size - 1) / chunk_size;
  10291. // If the chunking is poor for the number of threads on this setup, scrap the whole plan. Re-chunk it by thread.
  10292. // Also, chunking by thread was measured to have perform better on NUMA systems. See https://github.com/ggerganov/llama.cpp/pull/6915
  10293. // In theory, chunking should be just as useful on NUMA and non NUMA systems, but testing disagreed with that.
  10294. if (nchunk0 * nchunk1 < nth * 4 || ggml_is_numa()) {
  10295. // distribute the thread work across the inner or outer loop based on which one is larger
  10296. nchunk0 = nr0 > nr1 ? nth : 1; // parallelize by src0 rows
  10297. nchunk1 = nr0 > nr1 ? 1 : nth; // parallelize by src1 rows
  10298. }
  10299. // The number of elements in each chunk
  10300. const int64_t dr0 = (nr0 + nchunk0 - 1) / nchunk0;
  10301. const int64_t dr1 = (nr1 + nchunk1 - 1) / nchunk1;
  10302. if ((ggml_n_dims(src0) == 2) && gemv) {
  10303. const void * src1_wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  10304. const size_t src1_col_stride = ggml_is_contiguous(src1) || src1->type != vec_dot_type ? ggml_row_size(vec_dot_type, ne10) : nb11;
  10305. int64_t src0_start = (ith * ne01) / nth;
  10306. int64_t src0_end = ((ith + 1) * ne01) / nth;
  10307. src0_start = (src0_start % matmul_num_cols) ? src0_start + matmul_num_cols - (src0_start % matmul_num_cols): src0_start;
  10308. src0_end = (src0_end % matmul_num_cols) ? src0_end + matmul_num_cols - (src0_end % matmul_num_cols): src0_end;
  10309. if (src0_start >= src0_end) return;
  10310. // If there are more than three rows in src1, use gemm; otherwise, use gemv.
  10311. if (gemm && (ne11 > 3)) {
  10312. gemm(ne00, (float *)((char *) dst->data) + src0_start, ne01, (const char *) src0->data + src0_start * nb01,
  10313. (const char *) src1_wdata, ne11 - ne11 % 4, src0_end - src0_start);
  10314. }
  10315. for (int iter = gemm ? ne11 - ne11 % 4 : 0; iter < ne11; iter++) {
  10316. gemv(ne00, (float *)((char *) dst->data + (iter * nb1)) + src0_start, ne01,
  10317. (const char *) src0->data + src0_start * nb01, (const char *) src1_wdata + (src1_col_stride * iter), 1,
  10318. src0_end - src0_start);
  10319. }
  10320. return;
  10321. }
  10322. // The first chunk comes from our thread_id, the rest will get auto-assigned.
  10323. int current_chunk = ith;
  10324. while (current_chunk < nchunk0 * nchunk1) {
  10325. const int64_t ith0 = current_chunk % nchunk0;
  10326. const int64_t ith1 = current_chunk / nchunk0;
  10327. const int64_t ir0_start = dr0 * ith0;
  10328. const int64_t ir0_end = MIN(ir0_start + dr0, nr0);
  10329. const int64_t ir1_start = dr1 * ith1;
  10330. const int64_t ir1_end = MIN(ir1_start + dr1, nr1);
  10331. ggml_compute_forward_mul_mat_one_chunk(params, dst, num_rows_per_vec_dot, ir0_start, ir0_end, ir1_start, ir1_end);
  10332. if (nth >= nchunk0 * nchunk1) {
  10333. break;
  10334. }
  10335. current_chunk = atomic_fetch_add_explicit(&params->threadpool->current_chunk, 1, memory_order_relaxed);
  10336. }
  10337. }
  10338. // ggml_compute_forward_mul_mat_id
  10339. static void ggml_compute_forward_mul_mat_id(
  10340. const struct ggml_compute_params * params,
  10341. struct ggml_tensor * dst) {
  10342. const struct ggml_tensor * src0 = dst->src[0];
  10343. const struct ggml_tensor * src1 = dst->src[1];
  10344. const struct ggml_tensor * ids = dst->src[2];
  10345. GGML_TENSOR_BINARY_OP_LOCALS
  10346. const int ith = params->ith;
  10347. const int nth = params->nth;
  10348. const enum ggml_type type = src0->type;
  10349. const bool src1_cont = ggml_is_contiguous(src1);
  10350. ggml_vec_dot_t const vec_dot = type_traits[type].vec_dot;
  10351. enum ggml_type const vec_dot_type = type_traits[type].vec_dot_type;
  10352. ggml_from_float_t const from_float = type_traits[vec_dot_type].from_float;
  10353. int64_t const matmul_num_cols = type_traits[type].ncols;
  10354. ggml_gemv_t const gemv = type_traits[type].gemv;
  10355. // we don't support permuted src0 or src1
  10356. GGML_ASSERT(nb00 == ggml_type_size(type));
  10357. GGML_ASSERT(nb10 == ggml_type_size(src1->type));
  10358. // dst cannot be transposed or permuted
  10359. GGML_ASSERT(nb0 == sizeof(float));
  10360. GGML_ASSERT(nb0 <= nb1);
  10361. GGML_ASSERT(nb1 <= nb2);
  10362. GGML_ASSERT(nb2 <= nb3);
  10363. // row groups
  10364. const int n_ids = ids->ne[0]; // n_expert_used
  10365. const int n_as = ne02; // n_expert
  10366. char * wdata_src1_end = (src1->type == vec_dot_type) ?
  10367. (char *) params->wdata :
  10368. (char *) params->wdata + GGML_PAD(ggml_row_size(vec_dot_type, ggml_nelements(src1)), sizeof(int64_t));
  10369. struct mmid_row_mapping {
  10370. int32_t i1;
  10371. int32_t i2;
  10372. };
  10373. int64_t * matrix_row_counts = (int64_t *) (wdata_src1_end); // [n_as]
  10374. struct mmid_row_mapping * matrix_rows = (struct mmid_row_mapping *)(matrix_row_counts + n_as); // [n_as][ne11]
  10375. if (src1->type != vec_dot_type) {
  10376. char * wdata = params->wdata;
  10377. const size_t nbw1 = ggml_row_size(vec_dot_type, ne10);
  10378. const size_t nbw2 = nbw1*ne11;
  10379. const size_t nbw3 = nbw2*ne12;
  10380. assert(params->wsize >= ne13*nbw3);
  10381. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  10382. for (int64_t i13 = 0; i13 < ne13; ++i13) {
  10383. for (int64_t i12 = 0; i12 < ne12; ++i12) {
  10384. for (int64_t i11 = ith; i11 < ne11; i11 += nth) {
  10385. from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11),
  10386. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1),
  10387. ne10);
  10388. }
  10389. }
  10390. }
  10391. }
  10392. #define MMID_MATRIX_ROW(row_id, i1) matrix_rows[(row_id)*ne12 + (i1)]
  10393. if (ith == 0) {
  10394. // initialize matrix_row_counts
  10395. memset(matrix_row_counts, 0, n_as*sizeof(int64_t));
  10396. // group rows by src0 matrix
  10397. for (int64_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) {
  10398. for (int id = 0; id < n_ids; ++id) {
  10399. const int32_t i02 = *(const int32_t *) ((const char *) ids->data + iid1*ids->nb[1] + id*ids->nb[0]);
  10400. assert(i02 >= 0 && i02 < n_as);
  10401. MMID_MATRIX_ROW(i02, matrix_row_counts[i02]) = (struct mmid_row_mapping) {id, iid1};
  10402. matrix_row_counts[i02] += 1;
  10403. }
  10404. }
  10405. }
  10406. ggml_barrier(params->threadpool);
  10407. // compute each matrix multiplication in sequence
  10408. for (int cur_a = 0; cur_a < n_as; ++cur_a) {
  10409. const int64_t cne1 = matrix_row_counts[cur_a];
  10410. if (cne1 == 0) {
  10411. continue;
  10412. }
  10413. const char * src0_cur = (const char *) src0->data + cur_a*nb02;
  10414. const void * wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  10415. const size_t row_size = ggml_row_size(vec_dot_type, ne10);
  10416. const int64_t nr0 = ne01; // src0 rows
  10417. const int64_t nr1 = cne1; // src1 rows
  10418. if (((ggml_n_dims(src0) - 1) == 2) && gemv) {
  10419. int64_t src0_cur_start = (ith * ne01) / nth;
  10420. int64_t src0_cur_end = ((ith + 1) * ne01) / nth;
  10421. src0_cur_start = (src0_cur_start % matmul_num_cols) ? src0_cur_start + matmul_num_cols - (src0_cur_start % matmul_num_cols): src0_cur_start;
  10422. src0_cur_end = (src0_cur_end % matmul_num_cols) ? src0_cur_end + matmul_num_cols - (src0_cur_end % matmul_num_cols): src0_cur_end;
  10423. if (src0_cur_start >= src0_cur_end) return;
  10424. for (int ir1 = 0; ir1 < nr1; ir1++) {
  10425. struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, ir1);
  10426. const int id = row_mapping.i1; // selected expert index
  10427. const int64_t i11 = id % ne11;
  10428. const int64_t i12 = row_mapping.i2; // row index in src1
  10429. const int64_t i1 = id; // selected expert index
  10430. const int64_t i2 = i12; // row
  10431. const char * src1_col = (const char *) wdata +
  10432. (src1_cont || src1->type != vec_dot_type
  10433. ? (i11 + i12 * ne11) * row_size
  10434. : (i11 * nb11 + i12 * nb12));
  10435. gemv(ne00, (float *)((char *) dst->data + (i1 * nb1 + i2 * nb2)) + src0_cur_start, ne01,
  10436. (const char *) src0_cur + src0_cur_start * nb01, src1_col, 1, src0_cur_end - src0_cur_start);
  10437. }
  10438. continue;
  10439. }
  10440. // distribute the thread work across the inner or outer loop based on which one is larger
  10441. const int64_t nth0 = nr0 > nr1 ? nth : 1; // parallelize by src0 rows
  10442. const int64_t nth1 = nr0 > nr1 ? 1 : nth; // parallelize by src1 rows
  10443. const int64_t ith0 = ith % nth0;
  10444. const int64_t ith1 = ith / nth0;
  10445. const int64_t dr0 = (nr0 + nth0 - 1)/nth0;
  10446. const int64_t dr1 = (nr1 + nth1 - 1)/nth1;
  10447. const int64_t ir010 = dr0*ith0;
  10448. const int64_t ir011 = MIN(ir010 + dr0, nr0);
  10449. const int64_t ir110 = dr1*ith1;
  10450. const int64_t ir111 = MIN(ir110 + dr1, nr1);
  10451. // threads with no work simply yield (not sure if it helps)
  10452. //if (ir010 >= ir011 || ir110 >= ir111) {
  10453. // sched_yield();
  10454. // continue;
  10455. //}
  10456. // block-tiling attempt
  10457. const int64_t blck_0 = 16;
  10458. const int64_t blck_1 = 16;
  10459. // attempt to reduce false-sharing (does not seem to make a difference)
  10460. float tmp[16];
  10461. for (int64_t iir1 = ir110; iir1 < ir111; iir1 += blck_1) {
  10462. for (int64_t iir0 = ir010; iir0 < ir011; iir0 += blck_0) {
  10463. for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir111; ++ir1) {
  10464. const int64_t _i12 = ir1; // logical row index for this expert
  10465. struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, _i12);
  10466. const int id = row_mapping.i1; // selected expert index
  10467. const int64_t i11 = id % ne11;
  10468. const int64_t i12 = row_mapping.i2; // row index in src1
  10469. const int64_t i1 = id; // selected expert index
  10470. const int64_t i2 = i12; // row
  10471. // desc: when src1 is not a contiguous memory block we have to calculate the offset using the strides
  10472. // if it is, then we have either copied the data to params->wdata and made it contiguous or we are using
  10473. // the original src1 data pointer, so we should index using the indices directly
  10474. // TODO: this is a bit of a hack, we should probably have a better way to handle this
  10475. const char * src1_col = (const char *) wdata +
  10476. (src1_cont || src1->type != vec_dot_type
  10477. ? (i11 + i12*ne11)*row_size
  10478. : (i11*nb11 + i12*nb12));
  10479. float * dst_col = (float *) ((char *) dst->data + (i1*nb1 + i2*nb2));
  10480. //for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir011; ++ir0) {
  10481. // vec_dot(ne00, &dst_col[ir0], src0_row + ir0*nb01, src1_col);
  10482. //}
  10483. for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir011; ++ir0) {
  10484. vec_dot(ne00, &tmp[ir0 - iir0], 0, src0_cur + ir0*nb01, 0, src1_col, 0, 1);
  10485. }
  10486. memcpy(&dst_col[iir0], tmp, (MIN(iir0 + blck_0, ir011) - iir0)*sizeof(float));
  10487. }
  10488. }
  10489. }
  10490. }
  10491. #undef MMID_MATRIX_ROW
  10492. }
  10493. // ggml_compute_forward_out_prod
  10494. static void ggml_compute_forward_out_prod_f32(
  10495. const struct ggml_compute_params * params,
  10496. struct ggml_tensor * dst) {
  10497. const struct ggml_tensor * src0 = dst->src[0];
  10498. const struct ggml_tensor * src1 = dst->src[1];
  10499. GGML_TENSOR_BINARY_OP_LOCALS
  10500. const int ith = params->ith;
  10501. const int nth = params->nth;
  10502. GGML_ASSERT(ne0 == ne00);
  10503. GGML_ASSERT(ne1 == ne10);
  10504. GGML_ASSERT(ne2 == ne02);
  10505. GGML_ASSERT(ne02 == ne12);
  10506. GGML_ASSERT(ne3 == ne13);
  10507. GGML_ASSERT(ne03 == ne13);
  10508. // we don't support permuted src0 or src1
  10509. GGML_ASSERT(nb00 == sizeof(float));
  10510. // dst cannot be transposed or permuted
  10511. GGML_ASSERT(nb0 == sizeof(float));
  10512. // GGML_ASSERT(nb0 <= nb1);
  10513. // GGML_ASSERT(nb1 <= nb2);
  10514. // GGML_ASSERT(nb2 <= nb3);
  10515. // nb01 >= nb00 - src0 is not transposed
  10516. // compute by src0 rows
  10517. if (ith == 0) {
  10518. ggml_vec_set_f32(ne0*ne1*ne2*ne3, dst->data, 0);
  10519. }
  10520. ggml_barrier(params->threadpool);
  10521. // dst[:,:,:,:] = 0
  10522. // for i2,i3:
  10523. // for i1:
  10524. // for i01:
  10525. // for i0:
  10526. // dst[i0,i1,i2,i3] += src0[i0,i01,i2,i3] * src1[i1,i01,i2,i3]
  10527. // parallelize by last three dimensions
  10528. // total rows in dst
  10529. const int64_t nr = ne1*ne2*ne3;
  10530. // rows per thread
  10531. const int64_t dr = (nr + nth - 1)/nth;
  10532. // row range for this thread
  10533. const int64_t ir0 = dr*ith;
  10534. const int64_t ir1 = MIN(ir0 + dr, nr);
  10535. // block-tiling attempt
  10536. const int64_t blck_0 = MAX(GGML_VEC_MAD_UNROLL, 32);
  10537. const int64_t blck_1 = 16;
  10538. for (int64_t bir = ir0; bir < ir1; bir += blck_1) {
  10539. const int64_t bir1 = MIN(bir + blck_1, ir1);
  10540. for (int64_t bi01 = 0; bi01 < ne01; bi01 += blck_0) {
  10541. const int64_t bne01 = MIN(bi01 + blck_0, ne01);
  10542. for (int64_t ir = bir; ir < bir1; ++ir) {
  10543. // dst indices
  10544. const int64_t i3 = ir/(ne2*ne1);
  10545. const int64_t i2 = (ir - i3*ne2*ne1)/ne1;
  10546. const int64_t i1 = (ir - i3*ne2*ne1 - i2*ne1);
  10547. const int64_t i02 = i2;
  10548. const int64_t i03 = i3;
  10549. //const int64_t i10 = i1;
  10550. const int64_t i12 = i2;
  10551. const int64_t i13 = i3;
  10552. #if GGML_VEC_MAD_UNROLL > 2
  10553. const int64_t bne01_unroll = bne01 - (bne01 % GGML_VEC_MAD_UNROLL);
  10554. for (int64_t i01 = bi01; i01 < bne01_unroll; i01 += GGML_VEC_MAD_UNROLL) {
  10555. const int64_t i11 = i01;
  10556. float * s0 = (float *) ((char *) src0->data + ( i01*nb01 + i02*nb02 + i03*nb03));
  10557. float * s1 = (float *) ((char *) src1->data + (i1*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  10558. float * d = (float *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  10559. ggml_vec_mad_f32_unroll(ne0, nb01, nb11, d, s0, s1);
  10560. }
  10561. for (int64_t i01 = bne01_unroll; i01 < bne01; ++i01) {
  10562. const int64_t i11 = i01;
  10563. float * s0 = (float *) ((char *) src0->data + ( i01*nb01 + i02*nb02 + i03*nb03));
  10564. float * s1 = (float *) ((char *) src1->data + (i1*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  10565. float * d = (float *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  10566. ggml_vec_mad_f32(ne0, d, s0, *s1);
  10567. }
  10568. #else
  10569. for (int64_t i01 = bi01; i01 < bne01; ++i01) {
  10570. const int64_t i11 = i01;
  10571. float * s0 = (float *) ((char *) src0->data + ( i01*nb01 + i02*nb02 + i03*nb03));
  10572. float * s1 = (float *) ((char *) src1->data + (i1*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  10573. float * d = (float *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  10574. ggml_vec_mad_f32(ne0, d, s0, *s1);
  10575. }
  10576. #endif
  10577. }
  10578. }
  10579. }
  10580. }
  10581. static void ggml_compute_forward_out_prod_q_f32(
  10582. const struct ggml_compute_params * params,
  10583. struct ggml_tensor * dst) {
  10584. const struct ggml_tensor * src0 = dst->src[0];
  10585. const struct ggml_tensor * src1 = dst->src[1];
  10586. GGML_TENSOR_BINARY_OP_LOCALS;
  10587. const int ith = params->ith;
  10588. const int nth = params->nth;
  10589. const enum ggml_type type = src0->type;
  10590. ggml_to_float_t const dequantize_row_q = type_traits[type].to_float;
  10591. GGML_ASSERT(ne02 == ne12);
  10592. GGML_ASSERT(ne03 == ne13);
  10593. GGML_ASSERT(ne2 == ne12);
  10594. GGML_ASSERT(ne3 == ne13);
  10595. // we don't support permuted src0 dim0
  10596. GGML_ASSERT(nb00 == ggml_type_size(type));
  10597. // dst dim0 cannot be transposed or permuted
  10598. GGML_ASSERT(nb0 == sizeof(float));
  10599. // GGML_ASSERT(nb0 <= nb1);
  10600. // GGML_ASSERT(nb1 <= nb2);
  10601. // GGML_ASSERT(nb2 <= nb3);
  10602. GGML_ASSERT(ne0 == ne00);
  10603. GGML_ASSERT(ne1 == ne10);
  10604. GGML_ASSERT(ne2 == ne02);
  10605. GGML_ASSERT(ne3 == ne03);
  10606. // nb01 >= nb00 - src0 is not transposed
  10607. // compute by src0 rows
  10608. if (ith == 0) {
  10609. ggml_vec_set_f32(ne0*ne1*ne2*ne3, dst->data, 0);
  10610. }
  10611. ggml_barrier(params->threadpool);
  10612. // parallelize by last three dimensions
  10613. // total rows in dst
  10614. const int64_t nr = ne1*ne2*ne3;
  10615. // rows per thread
  10616. const int64_t dr = (nr + nth - 1)/nth;
  10617. // row range for this thread
  10618. const int64_t ir0 = dr*ith;
  10619. const int64_t ir1 = MIN(ir0 + dr, nr);
  10620. // dst[:,:,:,:] = 0
  10621. // for i2,i3:
  10622. // for i1:
  10623. // for i01:
  10624. // for i0:
  10625. // dst[i0,i1,i2,i3] += src0[i0,i01,i2,i3] * src1[i1,i01,i2,i3]
  10626. float * wdata = (float *) params->wdata + (ne0 + CACHE_LINE_SIZE_F32) * ith;
  10627. for (int64_t ir = ir0; ir < ir1; ++ir) {
  10628. // dst indices
  10629. const int64_t i3 = ir/(ne2*ne1);
  10630. const int64_t i2 = (ir - i3*ne2*ne1)/ne1;
  10631. const int64_t i1 = (ir - i3*ne2*ne1 - i2*ne1);
  10632. const int64_t i02 = i2;
  10633. const int64_t i03 = i3;
  10634. //const int64_t i10 = i1;
  10635. const int64_t i12 = i2;
  10636. const int64_t i13 = i3;
  10637. for (int64_t i01 = 0; i01 < ne01; ++i01) {
  10638. const int64_t i11 = i01;
  10639. float * s0 = (float *) ((char *) src0->data + ( i01*nb01 + i02*nb02 + i03*nb03));
  10640. float * s1 = (float *) ((char *) src1->data + (i1*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  10641. float * d = (float *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  10642. dequantize_row_q(s0, wdata, ne0);
  10643. ggml_vec_mad_f32(ne0, d, wdata, *s1);
  10644. }
  10645. }
  10646. }
  10647. static void ggml_compute_forward_out_prod(
  10648. const struct ggml_compute_params * params,
  10649. struct ggml_tensor * dst) {
  10650. const struct ggml_tensor * src0 = dst->src[0];
  10651. switch (src0->type) {
  10652. case GGML_TYPE_Q4_0:
  10653. case GGML_TYPE_Q4_1:
  10654. case GGML_TYPE_Q5_0:
  10655. case GGML_TYPE_Q5_1:
  10656. case GGML_TYPE_Q8_0:
  10657. case GGML_TYPE_Q2_K:
  10658. case GGML_TYPE_Q3_K:
  10659. case GGML_TYPE_Q4_K:
  10660. case GGML_TYPE_Q5_K:
  10661. case GGML_TYPE_Q6_K:
  10662. case GGML_TYPE_TQ1_0:
  10663. case GGML_TYPE_TQ2_0:
  10664. case GGML_TYPE_IQ2_XXS:
  10665. case GGML_TYPE_IQ2_XS:
  10666. case GGML_TYPE_IQ3_XXS:
  10667. case GGML_TYPE_IQ1_S:
  10668. case GGML_TYPE_IQ1_M:
  10669. case GGML_TYPE_IQ4_NL:
  10670. case GGML_TYPE_IQ4_XS:
  10671. case GGML_TYPE_IQ3_S:
  10672. case GGML_TYPE_IQ2_S:
  10673. case GGML_TYPE_Q4_0_4_4:
  10674. case GGML_TYPE_Q4_0_4_8:
  10675. case GGML_TYPE_Q4_0_8_8:
  10676. {
  10677. ggml_compute_forward_out_prod_q_f32(params, dst);
  10678. } break;
  10679. case GGML_TYPE_F16:
  10680. {
  10681. GGML_ABORT("fatal error"); // todo
  10682. // ggml_compute_forward_out_prod_f16_f32(params, dst);
  10683. }
  10684. case GGML_TYPE_F32:
  10685. {
  10686. ggml_compute_forward_out_prod_f32(params, dst);
  10687. } break;
  10688. default:
  10689. {
  10690. GGML_ABORT("fatal error");
  10691. }
  10692. }
  10693. }
  10694. // ggml_compute_forward_scale
  10695. static void ggml_compute_forward_scale_f32(
  10696. const struct ggml_compute_params * params,
  10697. struct ggml_tensor * dst) {
  10698. const struct ggml_tensor * src0 = dst->src[0];
  10699. GGML_ASSERT(ggml_is_contiguous(src0));
  10700. GGML_ASSERT(ggml_is_contiguous(dst));
  10701. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  10702. // scale factor
  10703. float v;
  10704. memcpy(&v, dst->op_params, sizeof(float));
  10705. const int ith = params->ith;
  10706. const int nth = params->nth;
  10707. const int nc = src0->ne[0];
  10708. const int nr = ggml_nrows(src0);
  10709. // rows per thread
  10710. const int dr = (nr + nth - 1)/nth;
  10711. // row range for this thread
  10712. const int ir0 = dr*ith;
  10713. const int ir1 = MIN(ir0 + dr, nr);
  10714. const size_t nb01 = src0->nb[1];
  10715. const size_t nb1 = dst->nb[1];
  10716. for (int i1 = ir0; i1 < ir1; i1++) {
  10717. if (dst->data != src0->data) {
  10718. // src0 is same shape as dst => same indices
  10719. memcpy((char *)dst->data + i1*nb1, (char *)src0->data + i1*nb01, nc * sizeof(float));
  10720. }
  10721. ggml_vec_scale_f32(nc, (float *) ((char *) dst->data + i1*nb1), v);
  10722. }
  10723. }
  10724. static void ggml_compute_forward_scale(
  10725. const struct ggml_compute_params * params,
  10726. struct ggml_tensor * dst) {
  10727. const struct ggml_tensor * src0 = dst->src[0];
  10728. switch (src0->type) {
  10729. case GGML_TYPE_F32:
  10730. {
  10731. ggml_compute_forward_scale_f32(params, dst);
  10732. } break;
  10733. default:
  10734. {
  10735. GGML_ABORT("fatal error");
  10736. }
  10737. }
  10738. }
  10739. // ggml_compute_forward_set
  10740. static void ggml_compute_forward_set_f32(
  10741. const struct ggml_compute_params * params,
  10742. struct ggml_tensor * dst) {
  10743. const struct ggml_tensor * src0 = dst->src[0];
  10744. const struct ggml_tensor * src1 = dst->src[1];
  10745. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  10746. GGML_ASSERT(ggml_is_contiguous(dst) && ggml_is_contiguous(src0));
  10747. // view src0 and dst with these strides and data offset inbytes during set
  10748. // nb0 is implicitly element_size because src0 and dst are contiguous
  10749. size_t nb1 = ((int32_t *) dst->op_params)[0];
  10750. size_t nb2 = ((int32_t *) dst->op_params)[1];
  10751. size_t nb3 = ((int32_t *) dst->op_params)[2];
  10752. size_t offset = ((int32_t *) dst->op_params)[3];
  10753. bool inplace = (bool) ((int32_t *) dst->op_params)[4];
  10754. if (!inplace) {
  10755. if (params->ith == 0) {
  10756. // memcpy needs to be synchronized across threads to avoid race conditions.
  10757. // => do it in INIT phase
  10758. memcpy(
  10759. ((char *) dst->data),
  10760. ((char *) src0->data),
  10761. ggml_nbytes(dst));
  10762. }
  10763. ggml_barrier(params->threadpool);
  10764. }
  10765. const int ith = params->ith;
  10766. const int nth = params->nth;
  10767. const int nr = ggml_nrows(src1);
  10768. const int nc = src1->ne[0];
  10769. GGML_TENSOR_LOCALS(int64_t, ne1, src1, ne)
  10770. GGML_TENSOR_LOCALS(size_t, nb1, src1, nb)
  10771. // src0 and dst as viewed during set
  10772. const size_t nb0 = ggml_element_size(src0);
  10773. const int im0 = (ne10 == 0 ? 0 : ne10-1);
  10774. const int im1 = (ne11 == 0 ? 0 : ne11-1);
  10775. const int im2 = (ne12 == 0 ? 0 : ne12-1);
  10776. const int im3 = (ne13 == 0 ? 0 : ne13-1);
  10777. GGML_ASSERT(offset + im0*nb0 + im1*nb1 + im2*nb2 + im3*nb3 <= ggml_nbytes(dst));
  10778. GGML_ASSERT(nb10 == sizeof(float));
  10779. // rows per thread
  10780. const int dr = (nr + nth - 1)/nth;
  10781. // row range for this thread
  10782. const int ir0 = dr*ith;
  10783. const int ir1 = MIN(ir0 + dr, nr);
  10784. for (int ir = ir0; ir < ir1; ++ir) {
  10785. // src0 and dst are viewed with shape of src1 and offset
  10786. // => same indices
  10787. const int i3 = ir/(ne12*ne11);
  10788. const int i2 = (ir - i3*ne12*ne11)/ne11;
  10789. const int i1 = (ir - i3*ne12*ne11 - i2*ne11);
  10790. ggml_vec_cpy_f32(nc,
  10791. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + offset),
  10792. (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11));
  10793. }
  10794. }
  10795. static void ggml_compute_forward_set(
  10796. const struct ggml_compute_params * params,
  10797. struct ggml_tensor * dst) {
  10798. const struct ggml_tensor * src0 = dst->src[0];
  10799. switch (src0->type) {
  10800. case GGML_TYPE_F32:
  10801. {
  10802. ggml_compute_forward_set_f32(params, dst);
  10803. } break;
  10804. case GGML_TYPE_F16:
  10805. case GGML_TYPE_BF16:
  10806. case GGML_TYPE_Q4_0:
  10807. case GGML_TYPE_Q4_1:
  10808. case GGML_TYPE_Q5_0:
  10809. case GGML_TYPE_Q5_1:
  10810. case GGML_TYPE_Q8_0:
  10811. case GGML_TYPE_Q8_1:
  10812. case GGML_TYPE_Q2_K:
  10813. case GGML_TYPE_Q3_K:
  10814. case GGML_TYPE_Q4_K:
  10815. case GGML_TYPE_Q5_K:
  10816. case GGML_TYPE_Q6_K:
  10817. case GGML_TYPE_TQ1_0:
  10818. case GGML_TYPE_TQ2_0:
  10819. case GGML_TYPE_IQ2_XXS:
  10820. case GGML_TYPE_IQ2_XS:
  10821. case GGML_TYPE_IQ3_XXS:
  10822. case GGML_TYPE_IQ1_S:
  10823. case GGML_TYPE_IQ1_M:
  10824. case GGML_TYPE_IQ4_NL:
  10825. case GGML_TYPE_IQ4_XS:
  10826. case GGML_TYPE_IQ3_S:
  10827. case GGML_TYPE_IQ2_S:
  10828. case GGML_TYPE_Q4_0_4_4:
  10829. case GGML_TYPE_Q4_0_4_8:
  10830. case GGML_TYPE_Q4_0_8_8:
  10831. default:
  10832. {
  10833. GGML_ABORT("fatal error");
  10834. }
  10835. }
  10836. }
  10837. // ggml_compute_forward_cpy
  10838. static void ggml_compute_forward_cpy(
  10839. const struct ggml_compute_params * params,
  10840. struct ggml_tensor * dst) {
  10841. ggml_compute_forward_dup(params, dst);
  10842. }
  10843. // ggml_compute_forward_cont
  10844. static void ggml_compute_forward_cont(
  10845. const struct ggml_compute_params * params,
  10846. struct ggml_tensor * dst) {
  10847. ggml_compute_forward_dup(params, dst);
  10848. }
  10849. // ggml_compute_forward_reshape
  10850. static void ggml_compute_forward_reshape(
  10851. const struct ggml_compute_params * params,
  10852. struct ggml_tensor * dst) {
  10853. // NOP
  10854. UNUSED(params);
  10855. UNUSED(dst);
  10856. }
  10857. // ggml_compute_forward_view
  10858. static void ggml_compute_forward_view(
  10859. const struct ggml_compute_params * params,
  10860. const struct ggml_tensor * dst) {
  10861. // NOP
  10862. UNUSED(params);
  10863. UNUSED(dst);
  10864. }
  10865. // ggml_compute_forward_permute
  10866. static void ggml_compute_forward_permute(
  10867. const struct ggml_compute_params * params,
  10868. const struct ggml_tensor * dst) {
  10869. // NOP
  10870. UNUSED(params);
  10871. UNUSED(dst);
  10872. }
  10873. // ggml_compute_forward_transpose
  10874. static void ggml_compute_forward_transpose(
  10875. const struct ggml_compute_params * params,
  10876. const struct ggml_tensor * dst) {
  10877. // NOP
  10878. UNUSED(params);
  10879. UNUSED(dst);
  10880. }
  10881. // ggml_compute_forward_get_rows
  10882. static void ggml_compute_forward_get_rows_q(
  10883. const struct ggml_compute_params * params,
  10884. struct ggml_tensor * dst) {
  10885. const struct ggml_tensor * src0 = dst->src[0];
  10886. const struct ggml_tensor * src1 = dst->src[1];
  10887. GGML_TENSOR_BINARY_OP_LOCALS
  10888. const int64_t nc = ne00;
  10889. const int64_t nr = ggml_nelements(src1);
  10890. const enum ggml_type type = src0->type;
  10891. ggml_to_float_t const dequantize_row_q = type_traits[type].to_float;
  10892. assert(ne0 == nc);
  10893. assert(ne02 == ne11);
  10894. assert(nb00 == ggml_type_size(type));
  10895. assert(ggml_nrows(dst) == nr);
  10896. const int ith = params->ith;
  10897. const int nth = params->nth;
  10898. // rows per thread
  10899. const int dr = (nr + nth - 1)/nth;
  10900. // row range for this thread
  10901. const int ir0 = dr*ith;
  10902. const int ir1 = MIN(ir0 + dr, nr);
  10903. for (int64_t i = ir0; i < ir1; ++i) {
  10904. const int64_t i12 = i/(ne11*ne10);
  10905. const int64_t i11 = (i - i12*ne11*ne10)/ne10;
  10906. const int64_t i10 = (i - i12*ne11*ne10 - i11*ne10);
  10907. const int64_t i01 = *(int32_t *) ((char *) src1->data + i10*nb10 + i11*nb11 + i12*nb12);
  10908. GGML_ASSERT(i01 >= 0 && i01 < ne01);
  10909. dequantize_row_q(
  10910. (const void *) ((char *) src0->data + i01*nb01 + i11*nb02 + i12*nb03),
  10911. (float *) ((char *) dst->data + i10*nb1 + i11*nb2 + i12*nb3), nc);
  10912. }
  10913. }
  10914. static void ggml_compute_forward_get_rows_f16(
  10915. const struct ggml_compute_params * params,
  10916. struct ggml_tensor * dst) {
  10917. const struct ggml_tensor * src0 = dst->src[0];
  10918. const struct ggml_tensor * src1 = dst->src[1];
  10919. GGML_TENSOR_BINARY_OP_LOCALS
  10920. const int64_t nc = ne00;
  10921. const int64_t nr = ggml_nelements(src1);
  10922. assert(ne0 == nc);
  10923. assert(ne02 == ne11);
  10924. assert(nb00 == sizeof(ggml_fp16_t));
  10925. assert(ggml_nrows(dst) == nr);
  10926. const int ith = params->ith;
  10927. const int nth = params->nth;
  10928. // rows per thread
  10929. const int dr = (nr + nth - 1)/nth;
  10930. // row range for this thread
  10931. const int ir0 = dr*ith;
  10932. const int ir1 = MIN(ir0 + dr, nr);
  10933. for (int64_t i = ir0; i < ir1; ++i) {
  10934. const int64_t i12 = i/(ne11*ne10);
  10935. const int64_t i11 = (i - i12*ne11*ne10)/ne10;
  10936. const int64_t i10 = (i - i12*ne11*ne10 - i11*ne10);
  10937. const int64_t i01 = *(int32_t *) ((char *) src1->data + i10*nb10 + i11*nb11 + i12*nb12);
  10938. GGML_ASSERT(i01 >= 0 && i01 < ne01);
  10939. ggml_fp16_to_fp32_row(
  10940. (const void *) ((char *) src0->data + i01*nb01 + i11*nb02 + i12*nb03),
  10941. (float *) ((char *) dst->data + i10*nb1 + i11*nb2 + i12*nb3), nc);
  10942. }
  10943. }
  10944. static void ggml_compute_forward_get_rows_bf16(
  10945. const struct ggml_compute_params * params,
  10946. struct ggml_tensor * dst) {
  10947. const struct ggml_tensor * src0 = dst->src[0];
  10948. const struct ggml_tensor * src1 = dst->src[1];
  10949. GGML_TENSOR_BINARY_OP_LOCALS
  10950. const int64_t nc = ne00;
  10951. const int64_t nr = ggml_nelements(src1);
  10952. assert(ne0 == nc);
  10953. assert(ne02 == ne11);
  10954. assert(nb00 == sizeof(ggml_bf16_t));
  10955. assert(ggml_nrows(dst) == nr);
  10956. const int ith = params->ith;
  10957. const int nth = params->nth;
  10958. // rows per thread
  10959. const int dr = (nr + nth - 1)/nth;
  10960. // row range for this thread
  10961. const int ir0 = dr*ith;
  10962. const int ir1 = MIN(ir0 + dr, nr);
  10963. for (int64_t i = ir0; i < ir1; ++i) {
  10964. const int64_t i12 = i/(ne11*ne10);
  10965. const int64_t i11 = (i - i12*ne11*ne10)/ne10;
  10966. const int64_t i10 = (i - i12*ne11*ne10 - i11*ne10);
  10967. const int64_t i01 = *(int32_t *) ((char *) src1->data + i10*nb10 + i11*nb11 + i12*nb12);
  10968. GGML_ASSERT(i01 >= 0 && i01 < ne01);
  10969. ggml_bf16_to_fp32_row(
  10970. (const void *) ((char *) src0->data + i01*nb01 + i11*nb02 + i12*nb03),
  10971. (float *) ((char *) dst->data + i10*nb1 + i11*nb2 + i12*nb3), nc);
  10972. }
  10973. }
  10974. static void ggml_compute_forward_get_rows_f32(
  10975. const struct ggml_compute_params * params,
  10976. struct ggml_tensor * dst) {
  10977. const struct ggml_tensor * src0 = dst->src[0];
  10978. const struct ggml_tensor * src1 = dst->src[1];
  10979. GGML_TENSOR_BINARY_OP_LOCALS
  10980. const int64_t nc = ne00;
  10981. const int64_t nr = ggml_nelements(src1);
  10982. assert(ne0 == nc);
  10983. assert(ne02 == ne11);
  10984. assert(nb00 == sizeof(float));
  10985. assert(ggml_nrows(dst) == nr);
  10986. const int ith = params->ith;
  10987. const int nth = params->nth;
  10988. // rows per thread
  10989. const int dr = (nr + nth - 1)/nth;
  10990. // row range for this thread
  10991. const int ir0 = dr*ith;
  10992. const int ir1 = MIN(ir0 + dr, nr);
  10993. for (int64_t i = ir0; i < ir1; ++i) {
  10994. const int64_t i12 = i/(ne11*ne10);
  10995. const int64_t i11 = (i - i12*ne11*ne10)/ne10;
  10996. const int64_t i10 = (i - i12*ne11*ne10 - i11*ne10);
  10997. const int64_t i01 = *(int32_t *) ((char *) src1->data + i10*nb10 + i11*nb11 + i12*nb12);
  10998. GGML_ASSERT(i01 >= 0 && i01 < ne01);
  10999. ggml_vec_cpy_f32(nc,
  11000. (float *) ((char *) dst->data + i10*nb1 + i11*nb2 + i12*nb3),
  11001. (float *) ((char *) src0->data + i01*nb01 + i11*nb02 + i12*nb03));
  11002. }
  11003. }
  11004. static void ggml_compute_forward_get_rows(
  11005. const struct ggml_compute_params * params,
  11006. struct ggml_tensor * dst) {
  11007. const struct ggml_tensor * src0 = dst->src[0];
  11008. switch (src0->type) {
  11009. case GGML_TYPE_Q4_0:
  11010. case GGML_TYPE_Q4_1:
  11011. case GGML_TYPE_Q5_0:
  11012. case GGML_TYPE_Q5_1:
  11013. case GGML_TYPE_Q8_0:
  11014. case GGML_TYPE_Q8_1:
  11015. case GGML_TYPE_Q2_K:
  11016. case GGML_TYPE_Q3_K:
  11017. case GGML_TYPE_Q4_K:
  11018. case GGML_TYPE_Q5_K:
  11019. case GGML_TYPE_Q6_K:
  11020. case GGML_TYPE_TQ1_0:
  11021. case GGML_TYPE_TQ2_0:
  11022. case GGML_TYPE_IQ2_XXS:
  11023. case GGML_TYPE_IQ2_XS:
  11024. case GGML_TYPE_IQ3_XXS:
  11025. case GGML_TYPE_IQ1_S:
  11026. case GGML_TYPE_IQ1_M:
  11027. case GGML_TYPE_IQ4_NL:
  11028. case GGML_TYPE_IQ4_XS:
  11029. case GGML_TYPE_IQ3_S:
  11030. case GGML_TYPE_IQ2_S:
  11031. case GGML_TYPE_Q4_0_4_4:
  11032. case GGML_TYPE_Q4_0_4_8:
  11033. case GGML_TYPE_Q4_0_8_8:
  11034. {
  11035. ggml_compute_forward_get_rows_q(params, dst);
  11036. } break;
  11037. case GGML_TYPE_F16:
  11038. {
  11039. ggml_compute_forward_get_rows_f16(params, dst);
  11040. } break;
  11041. case GGML_TYPE_BF16:
  11042. {
  11043. ggml_compute_forward_get_rows_bf16(params, dst);
  11044. } break;
  11045. case GGML_TYPE_F32:
  11046. case GGML_TYPE_I32:
  11047. {
  11048. ggml_compute_forward_get_rows_f32(params, dst);
  11049. } break;
  11050. default:
  11051. {
  11052. GGML_ABORT("fatal error");
  11053. }
  11054. }
  11055. //static bool first = true;
  11056. //printf("ne0 = %d, ne1 = %d, ne2 = %d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
  11057. //if (first) {
  11058. // first = false;
  11059. //} else {
  11060. // for (int k = 0; k < dst->ne[1]; ++k) {
  11061. // for (int j = 0; j < dst->ne[0]/16; ++j) {
  11062. // for (int i = 0; i < 16; ++i) {
  11063. // printf("%8.4f ", ((float *) dst->data)[k*dst->ne[0] + j*16 + i]);
  11064. // }
  11065. // printf("\n");
  11066. // }
  11067. // printf("\n");
  11068. // }
  11069. // printf("\n");
  11070. // exit(0);
  11071. //}
  11072. }
  11073. // ggml_compute_forward_get_rows_back
  11074. static void ggml_compute_forward_get_rows_back_f32_f16(
  11075. const struct ggml_compute_params * params,
  11076. struct ggml_tensor * dst) {
  11077. const struct ggml_tensor * src0 = dst->src[0];
  11078. const struct ggml_tensor * src1 = dst->src[1];
  11079. if (params->ith != 0) {
  11080. return;
  11081. }
  11082. GGML_ASSERT(ggml_is_contiguous(dst));
  11083. // ggml_compute_forward_dup_same_cont(params, opt0, dst);
  11084. memset(dst->data, 0, ggml_nbytes(dst));
  11085. const int nc = src0->ne[0];
  11086. const int nr = ggml_nelements(src1);
  11087. GGML_ASSERT( dst->ne[0] == nc);
  11088. GGML_ASSERT(src0->nb[0] == sizeof(ggml_fp16_t));
  11089. for (int i = 0; i < nr; ++i) {
  11090. const int r = ((int32_t *) src1->data)[i];
  11091. for (int j = 0; j < nc; ++j) {
  11092. ggml_fp16_t v = ((ggml_fp16_t *) ((char *) src0->data + i*src0->nb[1]))[j];
  11093. ((float *) ((char *) dst->data + r*dst->nb[1]))[j] += GGML_FP16_TO_FP32(v);
  11094. }
  11095. }
  11096. }
  11097. static void ggml_compute_forward_get_rows_back_f32(
  11098. const struct ggml_compute_params * params,
  11099. struct ggml_tensor * dst) {
  11100. const struct ggml_tensor * src0 = dst->src[0];
  11101. const struct ggml_tensor * src1 = dst->src[1];
  11102. if (params->ith != 0) {
  11103. return;
  11104. }
  11105. GGML_ASSERT(ggml_is_contiguous(dst));
  11106. // ggml_compute_forward_dup_same_cont(params, opt0, dst);
  11107. memset(dst->data, 0, ggml_nbytes(dst));
  11108. const int nc = src0->ne[0];
  11109. const int nr = ggml_nelements(src1);
  11110. GGML_ASSERT( dst->ne[0] == nc);
  11111. GGML_ASSERT(src0->nb[0] == sizeof(float));
  11112. for (int i = 0; i < nr; ++i) {
  11113. const int r = ((int32_t *) src1->data)[i];
  11114. ggml_vec_add_f32(nc,
  11115. (float *) ((char *) dst->data + r*dst->nb[1]),
  11116. (float *) ((char *) dst->data + r*dst->nb[1]),
  11117. (float *) ((char *) src0->data + i*src0->nb[1]));
  11118. }
  11119. }
  11120. static void ggml_compute_forward_get_rows_back(
  11121. const struct ggml_compute_params * params,
  11122. struct ggml_tensor * dst) {
  11123. const struct ggml_tensor * src0 = dst->src[0];
  11124. switch (src0->type) {
  11125. case GGML_TYPE_F16:
  11126. {
  11127. ggml_compute_forward_get_rows_back_f32_f16(params, dst);
  11128. } break;
  11129. case GGML_TYPE_F32:
  11130. {
  11131. ggml_compute_forward_get_rows_back_f32(params, dst);
  11132. } break;
  11133. default:
  11134. {
  11135. GGML_ABORT("fatal error");
  11136. }
  11137. }
  11138. //static bool first = true;
  11139. //printf("ne0 = %d, ne1 = %d, ne2 = %d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
  11140. //if (first) {
  11141. // first = false;
  11142. //} else {
  11143. // for (int k = 0; k < dst->ne[1]; ++k) {
  11144. // for (int j = 0; j < dst->ne[0]/16; ++j) {
  11145. // for (int i = 0; i < 16; ++i) {
  11146. // printf("%8.4f ", ((float *) dst->data)[k*dst->ne[0] + j*16 + i]);
  11147. // }
  11148. // printf("\n");
  11149. // }
  11150. // printf("\n");
  11151. // }
  11152. // printf("\n");
  11153. // exit(0);
  11154. //}
  11155. }
  11156. // ggml_compute_forward_diag
  11157. static void ggml_compute_forward_diag_f32(
  11158. const struct ggml_compute_params * params,
  11159. struct ggml_tensor * dst) {
  11160. const struct ggml_tensor * src0 = dst->src[0];
  11161. if (params->ith != 0) {
  11162. return;
  11163. }
  11164. // TODO: handle transposed/permuted matrices
  11165. GGML_TENSOR_UNARY_OP_LOCALS
  11166. GGML_ASSERT(ne00 == ne0);
  11167. GGML_ASSERT(ne00 == ne1);
  11168. GGML_ASSERT(ne01 == 1);
  11169. GGML_ASSERT(ne02 == ne2);
  11170. GGML_ASSERT(ne03 == ne3);
  11171. GGML_ASSERT(nb00 == sizeof(float));
  11172. GGML_ASSERT(nb0 == sizeof(float));
  11173. for (int i3 = 0; i3 < ne3; i3++) {
  11174. for (int i2 = 0; i2 < ne2; i2++) {
  11175. for (int i1 = 0; i1 < ne1; i1++) {
  11176. float * d = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  11177. float * s = (float *)((char *) src0->data + i3*nb03 + i2*nb02);
  11178. for (int i0 = 0; i0 < i1; i0++) {
  11179. d[i0] = 0;
  11180. }
  11181. d[i1] = s[i1];
  11182. for (int i0 = i1+1; i0 < ne0; i0++) {
  11183. d[i0] = 0;
  11184. }
  11185. }
  11186. }
  11187. }
  11188. }
  11189. static void ggml_compute_forward_diag(
  11190. const struct ggml_compute_params * params,
  11191. struct ggml_tensor * dst) {
  11192. const struct ggml_tensor * src0 = dst->src[0];
  11193. switch (src0->type) {
  11194. case GGML_TYPE_F32:
  11195. {
  11196. ggml_compute_forward_diag_f32(params, dst);
  11197. } break;
  11198. default:
  11199. {
  11200. GGML_ABORT("fatal error");
  11201. }
  11202. }
  11203. }
  11204. // ggml_compute_forward_diag_mask_inf
  11205. static void ggml_compute_forward_diag_mask_f32(
  11206. const struct ggml_compute_params * params,
  11207. struct ggml_tensor * dst,
  11208. const float value) {
  11209. const struct ggml_tensor * src0 = dst->src[0];
  11210. const int ith = params->ith;
  11211. const int nth = params->nth;
  11212. const int n_past = ((int32_t *) dst->op_params)[0];
  11213. const bool inplace = src0->data == dst->data;
  11214. GGML_ASSERT(n_past >= 0);
  11215. if (!inplace) {
  11216. if (ith == 0) {
  11217. // memcpy needs to be synchronized across threads to avoid race conditions.
  11218. // => do it in INIT phase
  11219. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  11220. GGML_ASSERT(ggml_is_contiguous(dst) && ggml_is_contiguous(src0));
  11221. memcpy(
  11222. ((char *) dst->data),
  11223. ((char *) src0->data),
  11224. ggml_nbytes(dst));
  11225. }
  11226. ggml_barrier(params->threadpool);
  11227. }
  11228. // TODO: handle transposed/permuted matrices
  11229. const int n = ggml_nrows(src0);
  11230. const int nc = src0->ne[0];
  11231. const int nr = src0->ne[1];
  11232. const int nz = n/nr;
  11233. GGML_ASSERT( dst->nb[0] == sizeof(float));
  11234. GGML_ASSERT(src0->nb[0] == sizeof(float));
  11235. for (int k = 0; k < nz; k++) {
  11236. for (int j = ith; j < nr; j += nth) {
  11237. for (int i = n_past; i < nc; i++) {
  11238. if (i > n_past + j) {
  11239. *(float *)((char *) dst->data + k*dst->nb[2] + j*dst->nb[1] + i*dst->nb[0]) = value;
  11240. }
  11241. }
  11242. }
  11243. }
  11244. }
  11245. static void ggml_compute_forward_diag_mask_inf(
  11246. const struct ggml_compute_params * params,
  11247. struct ggml_tensor * dst) {
  11248. const struct ggml_tensor * src0 = dst->src[0];
  11249. switch (src0->type) {
  11250. case GGML_TYPE_F32:
  11251. {
  11252. ggml_compute_forward_diag_mask_f32(params, dst, -INFINITY);
  11253. } break;
  11254. default:
  11255. {
  11256. GGML_ABORT("fatal error");
  11257. }
  11258. }
  11259. }
  11260. static void ggml_compute_forward_diag_mask_zero(
  11261. const struct ggml_compute_params * params,
  11262. struct ggml_tensor * dst) {
  11263. const struct ggml_tensor * src0 = dst->src[0];
  11264. switch (src0->type) {
  11265. case GGML_TYPE_F32:
  11266. {
  11267. ggml_compute_forward_diag_mask_f32(params, dst, 0);
  11268. } break;
  11269. default:
  11270. {
  11271. GGML_ABORT("fatal error");
  11272. }
  11273. }
  11274. }
  11275. // ggml_compute_forward_soft_max
  11276. static void ggml_compute_forward_soft_max_f32(
  11277. const struct ggml_compute_params * params,
  11278. struct ggml_tensor * dst) {
  11279. const struct ggml_tensor * src0 = dst->src[0];
  11280. const struct ggml_tensor * src1 = dst->src[1];
  11281. assert(ggml_is_contiguous(dst));
  11282. assert(ggml_are_same_shape(src0, dst));
  11283. float scale = 1.0f;
  11284. float max_bias = 0.0f;
  11285. memcpy(&scale, (float *) dst->op_params + 0, sizeof(float));
  11286. memcpy(&max_bias, (float *) dst->op_params + 1, sizeof(float));
  11287. // TODO: handle transposed/permuted matrices
  11288. const int ith = params->ith;
  11289. const int nth = params->nth;
  11290. GGML_TENSOR_UNARY_OP_LOCALS
  11291. //const int64_t ne11 = src1 ? src1->ne[1] : 1;
  11292. // TODO: is this supposed to be ceil instead of floor?
  11293. // https://huggingface.co/mosaicml/mpt-7b/blob/main/attention.py#L370
  11294. const uint32_t n_head = ne02;
  11295. const uint32_t n_head_log2 = 1u << (uint32_t) floor(log2(n_head));
  11296. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  11297. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  11298. const int nc = src0->ne[0];
  11299. const int nr = ggml_nrows(src0);
  11300. // rows per thread
  11301. const int dr = (nr + nth - 1)/nth;
  11302. // row range for this thread
  11303. const int ir0 = dr*ith;
  11304. const int ir1 = MIN(ir0 + dr, nr);
  11305. float * wp = (float *) params->wdata + (nc + CACHE_LINE_SIZE_F32) * ith;
  11306. const bool use_f16 = (src1 && src1->type == GGML_TYPE_F16);
  11307. for (int i1 = ir0; i1 < ir1; i1++) {
  11308. // ALiBi
  11309. const uint32_t h = (i1/ne01)%ne02; // head
  11310. const float slope = (max_bias > 0.0f) ? h < n_head_log2 ? powf(m0, h + 1) : powf(m1, 2*(h - n_head_log2) + 1) : 1.0f;
  11311. float * sp = (float *)((char *) src0->data + i1*src0->nb[1]);
  11312. float * dp = (float *)((char *) dst->data + i1*dst->nb[1]);
  11313. // broadcast the mask across rows
  11314. ggml_fp16_t * mp_f16 = src1 ? (ggml_fp16_t *)((char *) src1->data) + (i1%ne01)*ne00 : NULL;
  11315. float * mp_f32 = src1 ? (float *)((char *) src1->data) + (i1%ne01)*ne00 : NULL;
  11316. ggml_vec_cpy_f32 (nc, wp, sp);
  11317. ggml_vec_scale_f32(nc, wp, scale);
  11318. if (mp_f32) {
  11319. if (use_f16) {
  11320. for (int i = 0; i < nc; ++i) {
  11321. wp[i] += slope*GGML_FP16_TO_FP32(mp_f16[i]);
  11322. }
  11323. } else {
  11324. for (int i = 0; i < nc; ++i) {
  11325. wp[i] += slope*mp_f32[i];
  11326. }
  11327. }
  11328. }
  11329. #ifndef NDEBUG
  11330. for (int i = 0; i < nc; ++i) {
  11331. //printf("p[%d] = %f\n", i, p[i]);
  11332. assert(!isnan(wp[i]));
  11333. }
  11334. #endif
  11335. float max = -INFINITY;
  11336. ggml_vec_max_f32(nc, &max, wp);
  11337. ggml_float sum = ggml_vec_soft_max_f32(nc, dp, wp, max);
  11338. assert(sum > 0.0);
  11339. sum = 1.0/sum;
  11340. ggml_vec_scale_f32(nc, dp, sum);
  11341. #ifndef NDEBUG
  11342. for (int i = 0; i < nc; ++i) {
  11343. assert(!isnan(dp[i]));
  11344. assert(!isinf(dp[i]));
  11345. }
  11346. #endif
  11347. }
  11348. }
  11349. static void ggml_compute_forward_soft_max(
  11350. const struct ggml_compute_params * params,
  11351. struct ggml_tensor * dst) {
  11352. const struct ggml_tensor * src0 = dst->src[0];
  11353. switch (src0->type) {
  11354. case GGML_TYPE_F32:
  11355. {
  11356. ggml_compute_forward_soft_max_f32(params, dst);
  11357. } break;
  11358. default:
  11359. {
  11360. GGML_ABORT("fatal error");
  11361. }
  11362. }
  11363. }
  11364. // ggml_compute_forward_soft_max_back
  11365. static void ggml_compute_forward_soft_max_back_f32(
  11366. const struct ggml_compute_params * params,
  11367. struct ggml_tensor * dst) {
  11368. const struct ggml_tensor * src0 = dst->src[0];
  11369. const struct ggml_tensor * src1 = dst->src[1];
  11370. GGML_ASSERT(ggml_is_contiguous(src0));
  11371. GGML_ASSERT(ggml_is_contiguous(src1));
  11372. GGML_ASSERT(ggml_is_contiguous(dst));
  11373. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  11374. GGML_ASSERT(ggml_are_same_shape(src1, dst));
  11375. // TODO: handle transposed/permuted matrices
  11376. const int ith = params->ith;
  11377. const int nth = params->nth;
  11378. const int nc = src0->ne[0];
  11379. const int nr = ggml_nrows(src0);
  11380. // rows per thread
  11381. const int dr = (nr + nth - 1)/nth;
  11382. // row range for this thread
  11383. const int ir0 = dr*ith;
  11384. const int ir1 = MIN(ir0 + dr, nr);
  11385. for (int i1 = ir0; i1 < ir1; i1++) {
  11386. float *dy = (float *)((char *) src0->data + i1*src0->nb[1]);
  11387. float *y = (float *)((char *) src1->data + i1*src1->nb[1]);
  11388. float *dx = (float *)((char *) dst->data + i1*dst->nb[1]);
  11389. #ifndef NDEBUG
  11390. for (int i = 0; i < nc; ++i) {
  11391. //printf("p[%d] = %f\n", i, p[i]);
  11392. assert(!isnan(dy[i]));
  11393. assert(!isnan(y[i]));
  11394. }
  11395. #endif
  11396. // Jii = yi - yi*yi
  11397. // Jij = -yi*yj
  11398. // J = diag(y)-y.T*y
  11399. // dx = J * dy
  11400. // dxk = sum_i(Jki * dyi)
  11401. // dxk = sum_i(-yk*yi * dyi) - (-yk*yk)*dyk + (yk - yk*yk)*dyk
  11402. // dxk = sum_i(-yk*yi * dyi) + yk*yk*dyk + yk*dyk - yk*yk*dyk
  11403. // dxk = sum_i(-yk*yi * dyi) + yk*dyk
  11404. // dxk = -yk * sum_i(yi * dyi) + yk*dyk
  11405. // dxk = -yk * dot(y, dy) + yk*dyk
  11406. // dxk = yk * (- dot(y, dy) + dyk)
  11407. // dxk = yk * (dyk - dot(y, dy))
  11408. //
  11409. // post-order:
  11410. // dot_y_dy := dot(y, dy)
  11411. // dx := dy
  11412. // dx := dx - dot_y_dy
  11413. // dx := dx * y
  11414. // linear runtime, no additional memory
  11415. float dot_y_dy = 0;
  11416. ggml_vec_dot_f32 (nc, &dot_y_dy, 0, y, 0, dy, 0, 1);
  11417. ggml_vec_cpy_f32 (nc, dx, dy);
  11418. ggml_vec_acc1_f32(nc, dx, -dot_y_dy);
  11419. ggml_vec_mul_f32 (nc, dx, dx, y);
  11420. #ifndef NDEBUG
  11421. for (int i = 0; i < nc; ++i) {
  11422. assert(!isnan(dx[i]));
  11423. assert(!isinf(dx[i]));
  11424. }
  11425. #endif
  11426. }
  11427. }
  11428. static void ggml_compute_forward_soft_max_back(
  11429. const struct ggml_compute_params * params,
  11430. struct ggml_tensor * dst) {
  11431. const struct ggml_tensor * src0 = dst->src[0];
  11432. switch (src0->type) {
  11433. case GGML_TYPE_F32:
  11434. {
  11435. ggml_compute_forward_soft_max_back_f32(params, dst);
  11436. } break;
  11437. default:
  11438. {
  11439. GGML_ABORT("fatal error");
  11440. }
  11441. }
  11442. }
  11443. // ggml_compute_forward_clamp
  11444. static void ggml_compute_forward_clamp_f32(
  11445. const struct ggml_compute_params * params,
  11446. struct ggml_tensor * dst) {
  11447. const struct ggml_tensor * src0 = dst->src[0];
  11448. if (params->ith != 0) {
  11449. return;
  11450. }
  11451. float min;
  11452. float max;
  11453. memcpy(&min, (float *) dst->op_params + 0, sizeof(float));
  11454. memcpy(&max, (float *) dst->op_params + 1, sizeof(float));
  11455. const int ith = params->ith;
  11456. const int nth = params->nth;
  11457. const int n = ggml_nrows(src0);
  11458. const int nc = src0->ne[0];
  11459. const size_t nb00 = src0->nb[0];
  11460. const size_t nb01 = src0->nb[1];
  11461. const size_t nb0 = dst->nb[0];
  11462. const size_t nb1 = dst->nb[1];
  11463. GGML_ASSERT( nb0 == sizeof(float));
  11464. GGML_ASSERT(nb00 == sizeof(float));
  11465. for (int j = ith; j < n; j += nth) {
  11466. float * dst_ptr = (float *) ((char *) dst->data + j*nb1);
  11467. float * src0_ptr = (float *) ((char *) src0->data + j*nb01);
  11468. for (int i = 0; i < nc; i++) {
  11469. dst_ptr[i] = MAX(MIN(src0_ptr[i], max), min);
  11470. }
  11471. }
  11472. }
  11473. static void ggml_compute_forward_clamp(
  11474. const struct ggml_compute_params * params,
  11475. struct ggml_tensor * dst) {
  11476. const struct ggml_tensor * src0 = dst->src[0];
  11477. switch (src0->type) {
  11478. case GGML_TYPE_F32:
  11479. {
  11480. ggml_compute_forward_clamp_f32(params, dst);
  11481. } break;
  11482. case GGML_TYPE_F16:
  11483. case GGML_TYPE_BF16:
  11484. case GGML_TYPE_Q4_0:
  11485. case GGML_TYPE_Q4_1:
  11486. case GGML_TYPE_Q5_0:
  11487. case GGML_TYPE_Q5_1:
  11488. case GGML_TYPE_Q8_0:
  11489. case GGML_TYPE_Q8_1:
  11490. case GGML_TYPE_Q2_K:
  11491. case GGML_TYPE_Q3_K:
  11492. case GGML_TYPE_Q4_K:
  11493. case GGML_TYPE_Q5_K:
  11494. case GGML_TYPE_Q6_K:
  11495. case GGML_TYPE_TQ1_0:
  11496. case GGML_TYPE_TQ2_0:
  11497. case GGML_TYPE_IQ2_XXS:
  11498. case GGML_TYPE_IQ2_XS:
  11499. case GGML_TYPE_IQ3_XXS:
  11500. case GGML_TYPE_IQ1_S:
  11501. case GGML_TYPE_IQ1_M:
  11502. case GGML_TYPE_IQ4_NL:
  11503. case GGML_TYPE_IQ4_XS:
  11504. case GGML_TYPE_IQ3_S:
  11505. case GGML_TYPE_IQ2_S:
  11506. case GGML_TYPE_Q8_K:
  11507. case GGML_TYPE_Q4_0_4_4:
  11508. case GGML_TYPE_Q4_0_4_8:
  11509. case GGML_TYPE_Q4_0_8_8:
  11510. case GGML_TYPE_I8:
  11511. case GGML_TYPE_I16:
  11512. case GGML_TYPE_I32:
  11513. case GGML_TYPE_I64:
  11514. case GGML_TYPE_F64:
  11515. case GGML_TYPE_COUNT:
  11516. {
  11517. GGML_ABORT("fatal error");
  11518. }
  11519. }
  11520. }
  11521. // ggml_compute_forward_rope
  11522. static float rope_yarn_ramp(const float low, const float high, const int i0) {
  11523. const float y = (i0 / 2 - low) / MAX(0.001f, high - low);
  11524. return 1 - MIN(1, MAX(0, y));
  11525. }
  11526. // YaRN algorithm based on LlamaYaRNScaledRotaryEmbedding.py from https://github.com/jquesnelle/yarn
  11527. // MIT licensed. Copyright (c) 2023 Jeffrey Quesnelle and Bowen Peng.
  11528. static void rope_yarn(
  11529. float theta_extrap, float freq_scale, float corr_dims[2], int64_t i0, float ext_factor, float mscale,
  11530. float * cos_theta, float * sin_theta) {
  11531. // Get n-d rotational scaling corrected for extrapolation
  11532. float theta_interp = freq_scale * theta_extrap;
  11533. float theta = theta_interp;
  11534. if (ext_factor != 0.0f) {
  11535. float ramp_mix = rope_yarn_ramp(corr_dims[0], corr_dims[1], i0) * ext_factor;
  11536. theta = theta_interp * (1 - ramp_mix) + theta_extrap * ramp_mix;
  11537. // Get n-d magnitude scaling corrected for interpolation
  11538. mscale *= 1.0f + 0.1f * logf(1.0f / freq_scale);
  11539. }
  11540. *cos_theta = cosf(theta) * mscale;
  11541. *sin_theta = sinf(theta) * mscale;
  11542. }
  11543. // Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` for x, we get
  11544. // `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`
  11545. static float ggml_rope_yarn_corr_dim(int n_dims, int n_ctx_orig, float n_rot, float base) {
  11546. return n_dims * logf(n_ctx_orig / (n_rot * 2 * (float)M_PI)) / (2 * logf(base));
  11547. }
  11548. static void ggml_rope_cache_init(
  11549. float theta_base, float freq_scale, const float * freq_factors, float corr_dims[2], int64_t ne0, float ext_factor, float mscale,
  11550. float * cache, float sin_sign, float theta_scale) {
  11551. // ref: https://github.com/jquesnelle/yarn/blob/master/scaled_rope/LlamaYaRNScaledRotaryEmbedding.py
  11552. float theta = theta_base;
  11553. for (int64_t i0 = 0; i0 < ne0; i0 += 2) {
  11554. const float ff = freq_factors ? freq_factors[i0/2] : 1.0f;
  11555. rope_yarn(
  11556. theta/ff, freq_scale, corr_dims, i0, ext_factor, mscale, &cache[i0 + 0], &cache[i0 + 1]
  11557. );
  11558. cache[i0 + 1] *= sin_sign;
  11559. theta *= theta_scale;
  11560. }
  11561. }
  11562. GGML_CALL void ggml_rope_yarn_corr_dims(
  11563. int n_dims, int n_ctx_orig, float freq_base, float beta_fast, float beta_slow, float dims[2]
  11564. ) {
  11565. // start and end correction dims
  11566. float start = floorf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_fast, freq_base));
  11567. float end = ceilf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_slow, freq_base));
  11568. dims[0] = MAX(0, start);
  11569. dims[1] = MIN(n_dims - 1, end);
  11570. }
  11571. static void ggml_compute_forward_rope_f32(
  11572. const struct ggml_compute_params * params,
  11573. struct ggml_tensor * dst,
  11574. const bool forward) {
  11575. const struct ggml_tensor * src0 = dst->src[0];
  11576. const struct ggml_tensor * src1 = dst->src[1];
  11577. const struct ggml_tensor * src2 = dst->src[2];
  11578. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  11579. //const int n_past = ((int32_t *) dst->op_params)[0];
  11580. const int n_dims = ((int32_t *) dst->op_params)[1];
  11581. const int mode = ((int32_t *) dst->op_params)[2];
  11582. //const int n_ctx = ((int32_t *) dst->op_params)[3];
  11583. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  11584. memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
  11585. memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
  11586. memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
  11587. memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
  11588. memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
  11589. memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
  11590. GGML_TENSOR_UNARY_OP_LOCALS
  11591. //printf("ne0: %d, ne1: %d, ne2: %d, ne3: %d\n", ne0, ne1, ne2, ne3);
  11592. //printf("n_past = %d, ne2 = %d\n", n_past, ne2);
  11593. GGML_ASSERT(nb00 == sizeof(float));
  11594. const int ith = params->ith;
  11595. const int nth = params->nth;
  11596. const int nr = ggml_nrows(dst);
  11597. GGML_ASSERT(n_dims <= ne0);
  11598. GGML_ASSERT(n_dims % 2 == 0);
  11599. // rows per thread
  11600. const int dr = (nr + nth - 1)/nth;
  11601. // row range for this thread
  11602. const int ir0 = dr*ith;
  11603. const int ir1 = MIN(ir0 + dr, nr);
  11604. // row index used to determine which thread to use
  11605. int ir = 0;
  11606. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  11607. float corr_dims[2];
  11608. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  11609. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  11610. const float * freq_factors = NULL;
  11611. if (src2 != NULL) {
  11612. GGML_ASSERT(src2->type == GGML_TYPE_F32);
  11613. GGML_ASSERT(src2->ne[0] >= n_dims / 2);
  11614. freq_factors = (const float *) src2->data;
  11615. }
  11616. // backward process uses inverse rotation by cos and sin.
  11617. // cos and sin build a rotation matrix, where the inverse is the transpose.
  11618. // this essentially just switches the sign of sin.
  11619. const float sin_sign = forward ? 1.0f : -1.0f;
  11620. const int32_t * pos = (const int32_t *) src1->data;
  11621. for (int64_t i3 = 0; i3 < ne3; i3++) {
  11622. for (int64_t i2 = 0; i2 < ne2; i2++) {
  11623. const int64_t p = pos[i2];
  11624. float * cache = (float *) params->wdata + (ne0 + CACHE_LINE_SIZE_F32)*ith;
  11625. ggml_rope_cache_init(p, freq_scale, freq_factors, corr_dims, ne0, ext_factor, attn_factor, cache, sin_sign, theta_scale);
  11626. for (int64_t i1 = 0; i1 < ne1; i1++) {
  11627. if (ir++ < ir0) continue;
  11628. if (ir > ir1) break;
  11629. if (!is_neox) {
  11630. for (int64_t i0 = 0; i0 < n_dims; i0 += 2) {
  11631. const float cos_theta = cache[i0 + 0];
  11632. const float sin_theta = cache[i0 + 1];
  11633. const float * const src = (float *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  11634. float * dst_data = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  11635. const float x0 = src[0];
  11636. const float x1 = src[1];
  11637. dst_data[0] = x0*cos_theta - x1*sin_theta;
  11638. dst_data[1] = x0*sin_theta + x1*cos_theta;
  11639. }
  11640. } else {
  11641. for (int64_t i0 = 0; i0 < n_dims; i0 += 2) {
  11642. const int64_t ic = i0/2;
  11643. const float cos_theta = cache[i0 + 0];
  11644. const float sin_theta = cache[i0 + 1];
  11645. const float * const src = (float *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + ic*nb00);
  11646. float * dst_data = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + ic*nb0);
  11647. const float x0 = src[0];
  11648. const float x1 = src[n_dims/2];
  11649. dst_data[0] = x0*cos_theta - x1*sin_theta;
  11650. dst_data[n_dims/2] = x0*sin_theta + x1*cos_theta;
  11651. }
  11652. }
  11653. for (int64_t i0 = n_dims; i0 < ne0; i0 += 2) {
  11654. const float * const src = (float *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  11655. float * dst_data = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  11656. dst_data[0] = src[0];
  11657. dst_data[1] = src[1];
  11658. }
  11659. }
  11660. }
  11661. }
  11662. }
  11663. // TODO: deduplicate f16/f32 code
  11664. static void ggml_compute_forward_rope_f16(
  11665. const struct ggml_compute_params * params,
  11666. struct ggml_tensor * dst,
  11667. const bool forward) {
  11668. const struct ggml_tensor * src0 = dst->src[0];
  11669. const struct ggml_tensor * src1 = dst->src[1];
  11670. const struct ggml_tensor * src2 = dst->src[2];
  11671. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  11672. //const int n_past = ((int32_t *) dst->op_params)[0];
  11673. const int n_dims = ((int32_t *) dst->op_params)[1];
  11674. const int mode = ((int32_t *) dst->op_params)[2];
  11675. //const int n_ctx = ((int32_t *) dst->op_params)[3];
  11676. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  11677. memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
  11678. memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
  11679. memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
  11680. memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
  11681. memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
  11682. memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
  11683. GGML_TENSOR_UNARY_OP_LOCALS
  11684. //printf("ne0: %d, ne1: %d, ne2: %d, ne3: %d\n", ne0, ne1, ne2, ne3);
  11685. //printf("n_past = %d, ne2 = %d\n", n_past, ne2);
  11686. GGML_ASSERT(nb0 == sizeof(ggml_fp16_t));
  11687. const int ith = params->ith;
  11688. const int nth = params->nth;
  11689. const int nr = ggml_nrows(dst);
  11690. GGML_ASSERT(n_dims <= ne0);
  11691. GGML_ASSERT(n_dims % 2 == 0);
  11692. // rows per thread
  11693. const int dr = (nr + nth - 1)/nth;
  11694. // row range for this thread
  11695. const int ir0 = dr*ith;
  11696. const int ir1 = MIN(ir0 + dr, nr);
  11697. // row index used to determine which thread to use
  11698. int ir = 0;
  11699. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  11700. float corr_dims[2];
  11701. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  11702. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  11703. const float * freq_factors = NULL;
  11704. if (src2 != NULL) {
  11705. GGML_ASSERT(src2->type == GGML_TYPE_F32);
  11706. GGML_ASSERT(src2->ne[0] >= n_dims / 2);
  11707. freq_factors = (const float *) src2->data;
  11708. }
  11709. // backward process uses inverse rotation by cos and sin.
  11710. // cos and sin build a rotation matrix, where the inverse is the transpose.
  11711. // this essentially just switches the sign of sin.
  11712. const float sin_sign = forward ? 1.0f : -1.0f;
  11713. const int32_t * pos = (const int32_t *) src1->data;
  11714. for (int64_t i3 = 0; i3 < ne3; i3++) {
  11715. for (int64_t i2 = 0; i2 < ne2; i2++) {
  11716. const int64_t p = pos[i2];
  11717. float * cache = (float *) params->wdata + (ne0 + CACHE_LINE_SIZE_F32)*ith;
  11718. ggml_rope_cache_init(p, freq_scale, freq_factors, corr_dims, ne0, ext_factor, attn_factor, cache, sin_sign, theta_scale);
  11719. for (int64_t i1 = 0; i1 < ne1; i1++) {
  11720. if (ir++ < ir0) continue;
  11721. if (ir > ir1) break;
  11722. if (!is_neox) {
  11723. for (int64_t i0 = 0; i0 < n_dims; i0 += 2) {
  11724. const float cos_theta = cache[i0 + 0];
  11725. const float sin_theta = cache[i0 + 1];
  11726. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  11727. ggml_fp16_t * dst_data = (ggml_fp16_t *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  11728. const float x0 = GGML_FP16_TO_FP32(src[0]);
  11729. const float x1 = GGML_FP16_TO_FP32(src[1]);
  11730. dst_data[0] = GGML_FP32_TO_FP16(x0*cos_theta - x1*sin_theta);
  11731. dst_data[1] = GGML_FP32_TO_FP16(x0*sin_theta + x1*cos_theta);
  11732. }
  11733. } else {
  11734. for (int64_t i0 = 0; i0 < n_dims; i0 += 2) {
  11735. const int64_t ic = i0/2;
  11736. const float cos_theta = cache[i0 + 0];
  11737. const float sin_theta = cache[i0 + 1];
  11738. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + ic*nb00);
  11739. ggml_fp16_t * dst_data = (ggml_fp16_t *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + ic*nb0);
  11740. const float x0 = GGML_FP16_TO_FP32(src[0]);
  11741. const float x1 = GGML_FP16_TO_FP32(src[n_dims/2]);
  11742. dst_data[0] = GGML_FP32_TO_FP16(x0*cos_theta - x1*sin_theta);
  11743. dst_data[n_dims/2] = GGML_FP32_TO_FP16(x0*sin_theta + x1*cos_theta);
  11744. }
  11745. }
  11746. for (int64_t i0 = n_dims; i0 < ne0; i0 += 2) {
  11747. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  11748. ggml_fp16_t * dst_data = (ggml_fp16_t *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  11749. dst_data[0] = src[0];
  11750. dst_data[1] = src[1];
  11751. }
  11752. }
  11753. }
  11754. }
  11755. }
  11756. static void ggml_compute_forward_rope(
  11757. const struct ggml_compute_params * params,
  11758. struct ggml_tensor * dst) {
  11759. const struct ggml_tensor * src0 = dst->src[0];
  11760. switch (src0->type) {
  11761. case GGML_TYPE_F16:
  11762. {
  11763. ggml_compute_forward_rope_f16(params, dst, true);
  11764. } break;
  11765. case GGML_TYPE_F32:
  11766. {
  11767. ggml_compute_forward_rope_f32(params, dst, true);
  11768. } break;
  11769. default:
  11770. {
  11771. GGML_ABORT("fatal error");
  11772. }
  11773. }
  11774. }
  11775. // ggml_compute_forward_rope_back
  11776. static void ggml_compute_forward_rope_back(
  11777. const struct ggml_compute_params * params,
  11778. struct ggml_tensor * dst) {
  11779. const struct ggml_tensor * src0 = dst->src[0];
  11780. switch (src0->type) {
  11781. case GGML_TYPE_F16:
  11782. {
  11783. ggml_compute_forward_rope_f16(params, dst, false);
  11784. } break;
  11785. case GGML_TYPE_F32:
  11786. {
  11787. ggml_compute_forward_rope_f32(params, dst, false);
  11788. } break;
  11789. default:
  11790. {
  11791. GGML_ABORT("fatal error");
  11792. }
  11793. }
  11794. }
  11795. // ggml_compute_forward_conv_transpose_1d
  11796. static void ggml_compute_forward_conv_transpose_1d_f16_f32(
  11797. const struct ggml_compute_params * params,
  11798. struct ggml_tensor * dst) {
  11799. const struct ggml_tensor * src0 = dst->src[0];
  11800. const struct ggml_tensor * src1 = dst->src[1];
  11801. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  11802. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  11803. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  11804. GGML_TENSOR_BINARY_OP_LOCALS
  11805. const int ith = params->ith;
  11806. const int nth = params->nth;
  11807. const int nk = ne00*ne01*ne02;
  11808. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  11809. GGML_ASSERT(nb10 == sizeof(float));
  11810. if (ith == 0) {
  11811. memset(params->wdata, 0, params->wsize);
  11812. // permute kernel data (src0) from (K x Cout x Cin) to (Cin x K x Cout)
  11813. {
  11814. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  11815. for (int64_t i02 = 0; i02 < ne02; i02++) {
  11816. for (int64_t i01 = 0; i01 < ne01; i01++) {
  11817. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i02*nb02 + i01*nb01);
  11818. ggml_fp16_t * dst_data = wdata + i01*ne00*ne02;
  11819. for (int64_t i00 = 0; i00 < ne00; i00++) {
  11820. dst_data[i00*ne02 + i02] = src[i00];
  11821. }
  11822. }
  11823. }
  11824. }
  11825. // permute source data (src1) from (L x Cin) to (Cin x L)
  11826. {
  11827. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + nk;
  11828. ggml_fp16_t * dst_data = wdata;
  11829. for (int64_t i11 = 0; i11 < ne11; i11++) {
  11830. const float * const src = (float *)((char *) src1->data + i11*nb11);
  11831. for (int64_t i10 = 0; i10 < ne10; i10++) {
  11832. dst_data[i10*ne11 + i11] = GGML_FP32_TO_FP16(src[i10]);
  11833. }
  11834. }
  11835. }
  11836. // need to zero dst since we are accumulating into it
  11837. memset(dst->data, 0, ggml_nbytes(dst));
  11838. }
  11839. ggml_barrier(params->threadpool);
  11840. const int32_t s0 = ((const int32_t*)(dst->op_params))[0];
  11841. // total rows in dst
  11842. const int nr = ne1;
  11843. // rows per thread
  11844. const int dr = (nr + nth - 1)/nth;
  11845. // row range for this thread
  11846. const int ir0 = dr*ith;
  11847. const int ir1 = MIN(ir0 + dr, nr);
  11848. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  11849. ggml_fp16_t * const wdata_src = wdata + nk;
  11850. for (int i1 = ir0; i1 < ir1; i1++) {
  11851. float * dst_data = (float *)((char *) dst->data + i1*nb1);
  11852. ggml_fp16_t * wdata_kernel = wdata + i1*ne02*ne00;
  11853. for (int i10 = 0; i10 < ne10; i10++) {
  11854. const int i1n = i10*ne11;
  11855. for (int i00 = 0; i00 < ne00; i00++) {
  11856. float v = 0;
  11857. ggml_vec_dot_f16(ne02, &v, 0,
  11858. (ggml_fp16_t *) wdata_src + i1n, 0,
  11859. (ggml_fp16_t *) wdata_kernel + i00*ne02, 0, 1);
  11860. dst_data[i10*s0 + i00] += v;
  11861. }
  11862. }
  11863. }
  11864. }
  11865. static void ggml_compute_forward_conv_transpose_1d_f32(
  11866. const struct ggml_compute_params * params,
  11867. struct ggml_tensor * dst) {
  11868. const struct ggml_tensor * src0 = dst->src[0];
  11869. const struct ggml_tensor * src1 = dst->src[1];
  11870. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  11871. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  11872. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  11873. GGML_TENSOR_BINARY_OP_LOCALS
  11874. const int ith = params->ith;
  11875. const int nth = params->nth;
  11876. const int nk = ne00*ne01*ne02;
  11877. GGML_ASSERT(nb00 == sizeof(float));
  11878. GGML_ASSERT(nb10 == sizeof(float));
  11879. if (ith == 0) {
  11880. memset(params->wdata, 0, params->wsize);
  11881. // prepare kernel data (src0) from (K x Cout x Cin) to (Cin x K x Cout)
  11882. {
  11883. float * const wdata = (float *) params->wdata + 0;
  11884. for (int64_t i02 = 0; i02 < ne02; i02++) {
  11885. for (int64_t i01 = 0; i01 < ne01; i01++) {
  11886. const float * const src = (float *)((char *) src0->data + i02*nb02 + i01*nb01);
  11887. float * dst_data = wdata + i01*ne00*ne02;
  11888. for (int64_t i00 = 0; i00 < ne00; i00++) {
  11889. dst_data[i00*ne02 + i02] = src[i00];
  11890. }
  11891. }
  11892. }
  11893. }
  11894. // prepare source data (src1)
  11895. {
  11896. float * const wdata = (float *) params->wdata + nk;
  11897. float * dst_data = wdata;
  11898. for (int64_t i11 = 0; i11 < ne11; i11++) {
  11899. const float * const src = (float *)((char *) src1->data + i11*nb11);
  11900. for (int64_t i10 = 0; i10 < ne10; i10++) {
  11901. dst_data[i10*ne11 + i11] = src[i10];
  11902. }
  11903. }
  11904. }
  11905. // need to zero dst since we are accumulating into it
  11906. memset(dst->data, 0, ggml_nbytes(dst));
  11907. }
  11908. ggml_barrier(params->threadpool);
  11909. const int32_t s0 = ((const int32_t*)(dst->op_params))[0];
  11910. // total rows in dst
  11911. const int nr = ne1;
  11912. // rows per thread
  11913. const int dr = (nr + nth - 1)/nth;
  11914. // row range for this thread
  11915. const int ir0 = dr*ith;
  11916. const int ir1 = MIN(ir0 + dr, nr);
  11917. float * const wdata = (float *) params->wdata + 0;
  11918. float * const wdata_src = wdata + nk;
  11919. for (int i1 = ir0; i1 < ir1; i1++) {
  11920. float * dst_data = (float *)((char *) dst->data + i1*nb1);
  11921. float * wdata_kernel = wdata + i1*ne02*ne00;
  11922. for (int i10 = 0; i10 < ne10; i10++) {
  11923. const int i1n = i10*ne11;
  11924. for (int i00 = 0; i00 < ne00; i00++) {
  11925. float v = 0;
  11926. ggml_vec_dot_f32(ne02, &v, 0,
  11927. wdata_src + i1n, 0,
  11928. wdata_kernel + i00*ne02, 0, 1);
  11929. dst_data[i10*s0 + i00] += v;
  11930. }
  11931. }
  11932. }
  11933. }
  11934. static void ggml_compute_forward_conv_transpose_1d(
  11935. const struct ggml_compute_params * params,
  11936. struct ggml_tensor * dst) {
  11937. const struct ggml_tensor * src0 = dst->src[0];
  11938. switch (src0->type) {
  11939. case GGML_TYPE_F16:
  11940. {
  11941. ggml_compute_forward_conv_transpose_1d_f16_f32(params, dst);
  11942. } break;
  11943. case GGML_TYPE_F32:
  11944. {
  11945. ggml_compute_forward_conv_transpose_1d_f32(params, dst);
  11946. } break;
  11947. default:
  11948. {
  11949. GGML_ABORT("fatal error");
  11950. }
  11951. }
  11952. }
  11953. // ggml_compute_forward_im2col_f32
  11954. // src0: kernel [OC, IC, KH, KW]
  11955. // src1: image [N, IC, IH, IW]
  11956. // dst: result [N, OH, OW, IC*KH*KW]
  11957. static void ggml_compute_forward_im2col_f32(
  11958. const struct ggml_compute_params * params,
  11959. struct ggml_tensor * dst) {
  11960. const struct ggml_tensor * src0 = dst->src[0];
  11961. const struct ggml_tensor * src1 = dst->src[1];
  11962. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  11963. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  11964. GGML_TENSOR_BINARY_OP_LOCALS;
  11965. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  11966. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  11967. const int32_t p0 = ((const int32_t *)(dst->op_params))[2];
  11968. const int32_t p1 = ((const int32_t *)(dst->op_params))[3];
  11969. const int32_t d0 = ((const int32_t *)(dst->op_params))[4];
  11970. const int32_t d1 = ((const int32_t *)(dst->op_params))[5];
  11971. const bool is_2D = ((const int32_t *)(dst->op_params))[6] == 1;
  11972. const int ith = params->ith;
  11973. const int nth = params->nth;
  11974. const int64_t N = is_2D ? ne13 : ne12;
  11975. const int64_t IC = is_2D ? ne12 : ne11;
  11976. const int64_t IH = is_2D ? ne11 : 1;
  11977. const int64_t IW = ne10;
  11978. const int64_t KH = is_2D ? ne01 : 1;
  11979. const int64_t KW = ne00;
  11980. const int64_t OH = is_2D ? ne2 : 1;
  11981. const int64_t OW = ne1;
  11982. int ofs0 = is_2D ? nb13 : nb12;
  11983. int ofs1 = is_2D ? nb12 : nb11;
  11984. GGML_ASSERT(nb10 == sizeof(float));
  11985. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  11986. {
  11987. float * const wdata = (float *) dst->data;
  11988. for (int64_t in = 0; in < N; in++) {
  11989. for (int64_t ioh = 0; ioh < OH; ioh++) { // 1
  11990. for (int64_t iow = 0; iow < OW; iow++) {
  11991. for (int64_t iic = ith; iic < IC; iic += nth) {
  11992. // micro kernel
  11993. float * dst_data = wdata + (in*OH*OW + ioh*OW + iow)*(IC*KH*KW); // [IC, KH, KW]
  11994. const float * const src_data = (float *)((char *) src1->data + in*ofs0 + iic*ofs1); // [IH, IW]
  11995. for (int64_t ikh = 0; ikh < KH; ikh++) { // 1
  11996. for (int64_t ikw = 0; ikw < KW; ikw++) {
  11997. const int64_t iiw = iow*s0 + ikw*d0 - p0;
  11998. const int64_t iih = ioh*s1 + ikh*d1 - p1;
  11999. if (iih < 0 || iih >= IH || iiw < 0 || iiw >= IW) {
  12000. dst_data[iic*(KH*KW) + ikh*KW + ikw] = 0;
  12001. } else {
  12002. dst_data[iic*(KH*KW) + ikh*KW + ikw] = (src_data[iih*IW + iiw]);
  12003. }
  12004. }
  12005. }
  12006. }
  12007. }
  12008. }
  12009. }
  12010. }
  12011. }
  12012. // ggml_compute_forward_im2col_f16
  12013. // src0: kernel [OC, IC, KH, KW]
  12014. // src1: image [N, IC, IH, IW]
  12015. // dst: result [N, OH, OW, IC*KH*KW]
  12016. static void ggml_compute_forward_im2col_f16(
  12017. const struct ggml_compute_params * params,
  12018. struct ggml_tensor * dst) {
  12019. const struct ggml_tensor * src0 = dst->src[0];
  12020. const struct ggml_tensor * src1 = dst->src[1];
  12021. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  12022. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  12023. GGML_ASSERT( dst->type == GGML_TYPE_F16);
  12024. GGML_TENSOR_BINARY_OP_LOCALS;
  12025. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  12026. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  12027. const int32_t p0 = ((const int32_t *)(dst->op_params))[2];
  12028. const int32_t p1 = ((const int32_t *)(dst->op_params))[3];
  12029. const int32_t d0 = ((const int32_t *)(dst->op_params))[4];
  12030. const int32_t d1 = ((const int32_t *)(dst->op_params))[5];
  12031. const bool is_2D = ((const int32_t *)(dst->op_params))[6] == 1;
  12032. const int ith = params->ith;
  12033. const int nth = params->nth;
  12034. const int64_t N = is_2D ? ne13 : ne12;
  12035. const int64_t IC = is_2D ? ne12 : ne11;
  12036. const int64_t IH = is_2D ? ne11 : 1;
  12037. const int64_t IW = ne10;
  12038. const int64_t KH = is_2D ? ne01 : 1;
  12039. const int64_t KW = ne00;
  12040. const int64_t OH = is_2D ? ne2 : 1;
  12041. const int64_t OW = ne1;
  12042. int ofs0 = is_2D ? nb13 : nb12;
  12043. int ofs1 = is_2D ? nb12 : nb11;
  12044. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  12045. GGML_ASSERT(nb10 == sizeof(float));
  12046. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  12047. {
  12048. ggml_fp16_t * const wdata = (ggml_fp16_t *) dst->data;
  12049. for (int64_t in = 0; in < N; in++) {
  12050. for (int64_t ioh = 0; ioh < OH; ioh++) { // 1
  12051. for (int64_t iow = 0; iow < OW; iow++) {
  12052. for (int64_t iic = ith; iic < IC; iic += nth) {
  12053. // micro kernel
  12054. ggml_fp16_t * dst_data = wdata + (in*OH*OW + ioh*OW + iow)*(IC*KH*KW); // [IC, KH, KW]
  12055. const float * const src_data = (float *)((char *) src1->data + in*ofs0 + iic*ofs1); // [IH, IW]
  12056. for (int64_t ikh = 0; ikh < KH; ikh++) { // 1
  12057. for (int64_t ikw = 0; ikw < KW; ikw++) {
  12058. const int64_t iiw = iow*s0 + ikw*d0 - p0;
  12059. const int64_t iih = ioh*s1 + ikh*d1 - p1;
  12060. if (iih < 0 || iih >= IH || iiw < 0 || iiw >= IW) {
  12061. dst_data[iic*(KH*KW) + ikh*KW + ikw] = 0;
  12062. } else {
  12063. dst_data[iic*(KH*KW) + ikh*KW + ikw] = GGML_FP32_TO_FP16(src_data[iih*IW + iiw]);
  12064. }
  12065. }
  12066. }
  12067. }
  12068. }
  12069. }
  12070. }
  12071. }
  12072. }
  12073. static void ggml_compute_forward_im2col(
  12074. const struct ggml_compute_params * params,
  12075. struct ggml_tensor * dst) {
  12076. switch (dst->type) {
  12077. case GGML_TYPE_F16:
  12078. {
  12079. ggml_compute_forward_im2col_f16(params, dst);
  12080. } break;
  12081. case GGML_TYPE_F32:
  12082. {
  12083. ggml_compute_forward_im2col_f32(params, dst);
  12084. } break;
  12085. default:
  12086. {
  12087. GGML_ABORT("fatal error");
  12088. }
  12089. }
  12090. }
  12091. // ggml_compute_forward_im2col_back_f32
  12092. static void ggml_compute_forward_im2col_back_f32(
  12093. const struct ggml_compute_params * params,
  12094. struct ggml_tensor * dst) {
  12095. const struct ggml_tensor * src0 = dst->src[0];
  12096. const struct ggml_tensor * src1 = dst->src[1];
  12097. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  12098. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  12099. GGML_TENSOR_BINARY_OP_LOCALS;
  12100. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  12101. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  12102. const int32_t p0 = ((const int32_t *)(dst->op_params))[2];
  12103. const int32_t p1 = ((const int32_t *)(dst->op_params))[3];
  12104. const int32_t d0 = ((const int32_t *)(dst->op_params))[4];
  12105. const int32_t d1 = ((const int32_t *)(dst->op_params))[5];
  12106. const bool is_2D = ((const int32_t *)(dst->op_params))[6] == 1;
  12107. const int ith = params->ith;
  12108. const int nth = params->nth;
  12109. const int64_t N = is_2D ? ne3 : ne2;
  12110. const int64_t IC = is_2D ? ne2 : ne1;
  12111. const int64_t IH = is_2D ? ne1 : 1;
  12112. const int64_t IW = ne0;
  12113. const int64_t KH = is_2D ? ne01 : 1;
  12114. const int64_t KW = ne00;
  12115. const int64_t OH = is_2D ? ne12 : 1;
  12116. const int64_t OW = ne11;
  12117. int ofs0 = is_2D ? nb3 : nb2;
  12118. int ofs1 = is_2D ? nb2 : nb1;
  12119. GGML_ASSERT(nb0 == sizeof(float));
  12120. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  12121. {
  12122. float * const wdata = (float *) dst->data;
  12123. for (int64_t in = 0; in < N; in++) {
  12124. for (int64_t iic = ith; iic < IC; iic += nth) {
  12125. for (int64_t iih = 0; iih < IH; iih++) {
  12126. for (int64_t iiw = 0; iiw < IW; iiw++) {
  12127. // micro kernel
  12128. float grad = 0.0f;
  12129. for (int64_t ikh = 0; ikh < KH; ikh++) {
  12130. for (int64_t ikw = 0; ikw < KW; ikw++) {
  12131. // For s0 > 1 some values were skipped over in the forward pass.
  12132. // These values have tmpw % s0 != 0 and need to be skipped in the backwards pass as well.
  12133. const int64_t tmpw = (iiw + p0 - ikw*d0);
  12134. if (tmpw % s0 != 0) {
  12135. continue;
  12136. }
  12137. const int64_t iow = tmpw / s0;
  12138. // Equivalent logic as above except for s1.
  12139. int64_t ioh;
  12140. if (is_2D) {
  12141. const int64_t tmph = iih + p1 - ikh*d1;
  12142. if (tmph % s1 != 0) {
  12143. continue;
  12144. }
  12145. ioh = tmph / s1;
  12146. } else {
  12147. ioh = 0;
  12148. }
  12149. if (iow < 0 || iow >= OW || ioh < 0 || ioh >= OH) {
  12150. continue;
  12151. }
  12152. const float * const src_data = (const float *) src1->data
  12153. + (in*OH*OW + ioh*OW + iow)*(IC*KH*KW); // [IC, KH, KW]
  12154. grad += src_data[iic*(KH*KW) + ikh*KW + ikw];
  12155. }
  12156. }
  12157. float * dst_data = (float *)((char *) wdata + (in*ofs0 + iic*ofs1)); // [IH, IW]
  12158. dst_data[iih*IW + iiw] = grad;
  12159. }
  12160. }
  12161. }
  12162. }
  12163. }
  12164. }
  12165. // ggml_compute_forward_conv_transpose_2d
  12166. static void ggml_compute_forward_conv_transpose_2d(
  12167. const struct ggml_compute_params * params,
  12168. struct ggml_tensor * dst) {
  12169. const struct ggml_tensor * src0 = dst->src[0];
  12170. const struct ggml_tensor * src1 = dst->src[1];
  12171. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  12172. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  12173. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  12174. GGML_TENSOR_BINARY_OP_LOCALS
  12175. const int ith = params->ith;
  12176. const int nth = params->nth;
  12177. const int nk = ne00*ne01*ne02*ne03;
  12178. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  12179. GGML_ASSERT(nb10 == sizeof(float));
  12180. if (ith == 0) {
  12181. memset(params->wdata, 0, params->wsize);
  12182. // permute kernel data (src0) from (Kw x Kh x Cout x Cin) to (Cin x Kw x Kh x Cout)
  12183. {
  12184. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  12185. for (int64_t i03 = 0; i03 < ne03; i03++) {
  12186. for (int64_t i02 = 0; i02 < ne02; i02++) {
  12187. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i03*nb03 + i02*nb02);
  12188. ggml_fp16_t * dst_data = wdata + i02*ne01*ne00*ne03;
  12189. for (int64_t i01 = 0; i01 < ne01; i01++) {
  12190. for (int64_t i00 = 0; i00 < ne00; i00++) {
  12191. dst_data[i01*ne00*ne03 + i00*ne03 + i03] = src[i01 * ne00 + i00];
  12192. }
  12193. }
  12194. }
  12195. }
  12196. }
  12197. // permute source data (src1) from (Sw x Sh x Cin) to (Cin x Sw x Sh)
  12198. {
  12199. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + nk;
  12200. for (int i12 = 0; i12 < ne12; i12++) {
  12201. for (int i11 = 0; i11 < ne11; i11++) {
  12202. const float * const src = (float *)((char *) src1->data + i12*nb12 + i11*nb11);
  12203. ggml_fp16_t * dst_data = wdata + i11*ne10*ne12;
  12204. for (int i10 = 0; i10 < ne10; i10++) {
  12205. dst_data[i10*ne12 + i12] = GGML_FP32_TO_FP16(src[i10]);
  12206. }
  12207. }
  12208. }
  12209. }
  12210. memset(dst->data, 0, ggml_nbytes(dst));
  12211. }
  12212. ggml_barrier(params->threadpool);
  12213. const int32_t stride = ggml_get_op_params_i32(dst, 0);
  12214. // total patches in dst
  12215. const int np = ne2;
  12216. // patches per thread
  12217. const int dp = (np + nth - 1)/nth;
  12218. // patch range for this thread
  12219. const int ip0 = dp*ith;
  12220. const int ip1 = MIN(ip0 + dp, np);
  12221. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  12222. ggml_fp16_t * const wdata_src = wdata + nk;
  12223. for (int i2 = ip0; i2 < ip1; i2++) { // Cout
  12224. float * dst_data = (float *)((char *) dst->data + i2*nb2);
  12225. ggml_fp16_t * wdata_kernel = wdata + i2*ne01*ne00*ne03;
  12226. for (int i11 = 0; i11 < ne11; i11++) {
  12227. for (int i10 = 0; i10 < ne10; i10++) {
  12228. const int i1n = i11*ne10*ne12 + i10*ne12;
  12229. for (int i01 = 0; i01 < ne01; i01++) {
  12230. for (int i00 = 0; i00 < ne00; i00++) {
  12231. float v = 0;
  12232. ggml_vec_dot_f16(ne03, &v, 0,
  12233. wdata_src + i1n, 0,
  12234. wdata_kernel + i01*ne00*ne03 + i00*ne03, 0, 1);
  12235. dst_data[(i11*stride + i01)*ne0 + i10*stride + i00] += v;
  12236. }
  12237. }
  12238. }
  12239. }
  12240. }
  12241. }
  12242. // ggml_compute_forward_pool_1d_sk_p0
  12243. static void ggml_compute_forward_pool_1d_sk_p0(
  12244. const struct ggml_compute_params * params,
  12245. const enum ggml_op_pool op,
  12246. const int k,
  12247. struct ggml_tensor * dst) {
  12248. const struct ggml_tensor * src = dst->src[0];
  12249. assert(src->type == GGML_TYPE_F32 || src->type == GGML_TYPE_F16);
  12250. if (params->ith != 0) {
  12251. return;
  12252. }
  12253. const char * cdata = (const char *)src->data;
  12254. const char * const data_end = cdata + ggml_nbytes(src);
  12255. float * drow = (float *)dst->data;
  12256. const int64_t rs = dst->ne[0];
  12257. while (cdata < data_end) {
  12258. const void * srow = (const void *)cdata;
  12259. int j = 0;
  12260. for (int64_t i = 0; i < rs; ++i) {
  12261. switch (op) {
  12262. case GGML_OP_POOL_AVG: drow[i] = 0; break;
  12263. case GGML_OP_POOL_MAX: drow[i] = -FLT_MAX; break;
  12264. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12265. }
  12266. for (int ki = 0; ki < k; ++ki) {
  12267. const float srow_j = (src->type == GGML_TYPE_F32) ? ((const float*)srow)[j] : GGML_FP16_TO_FP32(((const ggml_fp16_t*)srow)[j]);
  12268. switch (op) {
  12269. case GGML_OP_POOL_AVG: drow[i] += srow_j; break;
  12270. case GGML_OP_POOL_MAX: if (srow_j > drow[i]) drow[i] = srow_j; break;
  12271. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12272. }
  12273. ++j;
  12274. }
  12275. switch (op) {
  12276. case GGML_OP_POOL_AVG: drow[i] /= k; break;
  12277. case GGML_OP_POOL_MAX: break;
  12278. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12279. }
  12280. }
  12281. cdata += src->nb[1];
  12282. drow += rs;
  12283. }
  12284. }
  12285. // ggml_compute_forward_pool_1d
  12286. static void ggml_compute_forward_pool_1d(
  12287. const struct ggml_compute_params * params,
  12288. struct ggml_tensor * dst) {
  12289. const int32_t * opts = (const int32_t *)dst->op_params;
  12290. enum ggml_op_pool op = opts[0];
  12291. const int k0 = opts[1];
  12292. const int s0 = opts[2];
  12293. const int p0 = opts[3];
  12294. GGML_ASSERT(p0 == 0); // padding not supported
  12295. GGML_ASSERT(k0 == s0); // only s = k supported
  12296. ggml_compute_forward_pool_1d_sk_p0(params, op, k0, dst);
  12297. }
  12298. // ggml_compute_forward_pool_2d
  12299. static void ggml_compute_forward_pool_2d(
  12300. const struct ggml_compute_params * params,
  12301. struct ggml_tensor * dst) {
  12302. const struct ggml_tensor * src = dst->src[0];
  12303. assert(src->type == GGML_TYPE_F32 || src->type == GGML_TYPE_F16);
  12304. if (params->ith != 0) {
  12305. return;
  12306. }
  12307. const int32_t * opts = (const int32_t *)dst->op_params;
  12308. enum ggml_op_pool op = opts[0];
  12309. const int k0 = opts[1];
  12310. const int k1 = opts[2];
  12311. const int s0 = opts[3];
  12312. const int s1 = opts[4];
  12313. const int p0 = opts[5];
  12314. const int p1 = opts[6];
  12315. const char * cdata = (const char*)src->data;
  12316. const char * const data_end = cdata + ggml_nbytes(src);
  12317. const int64_t px = dst->ne[0];
  12318. const int64_t py = dst->ne[1];
  12319. const int64_t pa = px * py;
  12320. float * dplane = (float *)dst->data;
  12321. const int ka = k0 * k1;
  12322. const int offset0 = -p0;
  12323. const int offset1 = -p1;
  12324. while (cdata < data_end) {
  12325. for (int oy = 0; oy < py; ++oy) {
  12326. float * const drow = dplane + oy * px;
  12327. for (int ox = 0; ox < px; ++ox) {
  12328. float * const out = drow + ox;
  12329. switch (op) {
  12330. case GGML_OP_POOL_AVG: *out = 0; break;
  12331. case GGML_OP_POOL_MAX: *out = -FLT_MAX; break;
  12332. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12333. }
  12334. const int ix = offset0 + ox * s0;
  12335. const int iy = offset1 + oy * s1;
  12336. for (int ky = 0; ky < k1; ++ky) {
  12337. if (iy + ky < 0 || iy + ky >= src->ne[1]) continue;
  12338. const void * srow = (const void *)(cdata + src->nb[1] * (iy + ky));
  12339. for (int kx = 0; kx < k0; ++kx) {
  12340. int j = ix + kx;
  12341. if (j < 0 || j >= src->ne[0]) continue;
  12342. const float srow_j = (src->type == GGML_TYPE_F32) ? ((const float*)srow)[j] : GGML_FP16_TO_FP32(((const ggml_fp16_t*)srow)[j]);
  12343. switch (op) {
  12344. case GGML_OP_POOL_AVG: *out += srow_j; break;
  12345. case GGML_OP_POOL_MAX: if (srow_j > *out) *out = srow_j; break;
  12346. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12347. }
  12348. }
  12349. }
  12350. switch (op) {
  12351. case GGML_OP_POOL_AVG: *out /= ka; break;
  12352. case GGML_OP_POOL_MAX: break;
  12353. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12354. }
  12355. }
  12356. }
  12357. cdata += src->nb[2];
  12358. dplane += pa;
  12359. }
  12360. }
  12361. // ggml_compute_forward_pool_2d_back
  12362. static void ggml_compute_forward_pool_2d_back(
  12363. const struct ggml_compute_params * params,
  12364. struct ggml_tensor * dst) {
  12365. const struct ggml_tensor * src = dst->src[0];
  12366. const struct ggml_tensor * dstf = dst->src[1]; // forward tensor of dst
  12367. assert(dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16);
  12368. if (params->ith != 0) {
  12369. return;
  12370. }
  12371. const int32_t * opts = (const int32_t *)dst->op_params;
  12372. enum ggml_op_pool op = opts[0];
  12373. const int k0 = opts[1];
  12374. const int k1 = opts[2];
  12375. const int s0 = opts[3];
  12376. const int s1 = opts[4];
  12377. const int p0 = opts[5];
  12378. const int p1 = opts[6];
  12379. char * cdata = (char *) dst->data;
  12380. const char * cdataf = (const char *) dstf->data;
  12381. const char * const data_end = cdata + ggml_nbytes(dst);
  12382. GGML_ASSERT(params->ith == 0);
  12383. memset(cdata, 0, ggml_nbytes(dst));
  12384. const int64_t px = src->ne[0];
  12385. const int64_t py = src->ne[1];
  12386. const int64_t pa = px * py;
  12387. const float * splane = (const float *) src->data;
  12388. const int ka = k0 * k1;
  12389. const int offset0 = -p0;
  12390. const int offset1 = -p1;
  12391. while (cdata < data_end) {
  12392. for (int oy = 0; oy < py; ++oy) {
  12393. const float * const srow = splane + oy * px;
  12394. for (int ox = 0; ox < px; ++ox) {
  12395. const float grad0 = srow[ox];
  12396. const int ix = offset0 + ox * s0;
  12397. const int iy = offset1 + oy * s1;
  12398. if (op == GGML_OP_POOL_MAX) {
  12399. float maxval = -FLT_MAX;
  12400. int kxmax = -1;
  12401. int kymax = -1;
  12402. for (int ky = 0; ky < k1; ++ky) {
  12403. if (iy + ky < 0 || iy + ky >= dst->ne[1]) {
  12404. continue;
  12405. }
  12406. const void * drowf = (const void *)(cdataf + dst->nb[1] * (iy + ky));
  12407. for (int kx = 0; kx < k0; ++kx) {
  12408. int j = ix + kx;
  12409. if (j < 0 || j >= dst->ne[0]) {
  12410. continue;
  12411. }
  12412. const float val = dst->type == GGML_TYPE_F32 ?
  12413. ((const float *) drowf)[j] : GGML_FP16_TO_FP32(((const ggml_fp16_t *) drowf)[j]);
  12414. if (val <= maxval) {
  12415. continue;
  12416. }
  12417. maxval = val;
  12418. kxmax = kx;
  12419. kymax = ky;
  12420. }
  12421. }
  12422. if (kxmax == -1 || kymax == -1) {
  12423. continue;
  12424. }
  12425. void * drow = (void *)(cdata + dst->nb[1] * (iy + kymax));
  12426. const int j = ix + kxmax;
  12427. if (dst->type == GGML_TYPE_F32) {
  12428. ((float *) drow)[j] += grad0;
  12429. } else {
  12430. ((ggml_fp16_t *) drow)[j] = GGML_FP32_TO_FP16(grad0 + GGML_FP16_TO_FP32(((const ggml_fp16_t *) drow)[j]));
  12431. }
  12432. } else if (op == GGML_OP_POOL_AVG) {
  12433. const float grad = grad0 / ka;
  12434. for (int ky = 0; ky < k1; ++ky) {
  12435. if (iy + ky < 0 || iy + ky >= dst->ne[1]) {
  12436. continue;
  12437. }
  12438. void * drow = (void *)(cdata + dst->nb[1] * (iy + ky));
  12439. for (int kx = 0; kx < k0; ++kx) {
  12440. int j = ix + kx;
  12441. if (j < 0 || j >= dst->ne[0]) {
  12442. continue;
  12443. }
  12444. if (dst->type == GGML_TYPE_F32) {
  12445. ((float *) drow)[j] += grad;
  12446. } else {
  12447. ((ggml_fp16_t *) drow)[j] += GGML_FP32_TO_FP16(grad);
  12448. }
  12449. }
  12450. }
  12451. } else {
  12452. GGML_ASSERT(false);
  12453. }
  12454. }
  12455. }
  12456. cdata += dst->nb[2];
  12457. cdataf += dst->nb[2];
  12458. splane += pa;
  12459. }
  12460. }
  12461. // ggml_compute_forward_upscale
  12462. static void ggml_compute_forward_upscale_f32(
  12463. const struct ggml_compute_params * params,
  12464. struct ggml_tensor * dst) {
  12465. const struct ggml_tensor * src0 = dst->src[0];
  12466. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  12467. const int ith = params->ith;
  12468. const int nth = params->nth;
  12469. GGML_TENSOR_UNARY_OP_LOCALS
  12470. const float sf0 = (float)ne0/src0->ne[0];
  12471. const float sf1 = (float)ne1/src0->ne[1];
  12472. const float sf2 = (float)ne2/src0->ne[2];
  12473. const float sf3 = (float)ne3/src0->ne[3];
  12474. // TODO: optimize
  12475. for (int64_t i3 = 0; i3 < ne3; i3++) {
  12476. const int64_t i03 = i3 / sf3;
  12477. for (int64_t i2 = ith; i2 < ne2; i2 += nth) {
  12478. const int64_t i02 = i2 / sf2;
  12479. for (int64_t i1 = 0; i1 < ne1; i1++) {
  12480. const int64_t i01 = i1 / sf1;
  12481. for (int64_t i0 = 0; i0 < ne0; i0++) {
  12482. const int64_t i00 = i0 / sf0;
  12483. const float * x = (float *)((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  12484. float * y = (float *)((char *) dst->data + i0*nb0 + i1*nb1 + i2*nb2 + i3*nb3);
  12485. *y = *x;
  12486. }
  12487. }
  12488. }
  12489. }
  12490. }
  12491. static void ggml_compute_forward_upscale(
  12492. const struct ggml_compute_params * params,
  12493. struct ggml_tensor * dst) {
  12494. const struct ggml_tensor * src0 = dst->src[0];
  12495. switch (src0->type) {
  12496. case GGML_TYPE_F32:
  12497. {
  12498. ggml_compute_forward_upscale_f32(params, dst);
  12499. } break;
  12500. default:
  12501. {
  12502. GGML_ABORT("fatal error");
  12503. }
  12504. }
  12505. }
  12506. // ggml_compute_forward_pad
  12507. static void ggml_compute_forward_pad_f32(
  12508. const struct ggml_compute_params * params,
  12509. struct ggml_tensor * dst) {
  12510. const struct ggml_tensor * src0 = dst->src[0];
  12511. GGML_ASSERT(src0->nb[0] == sizeof(float));
  12512. GGML_ASSERT( dst->nb[0] == sizeof(float));
  12513. const int ith = params->ith;
  12514. const int nth = params->nth;
  12515. GGML_TENSOR_UNARY_OP_LOCALS
  12516. float * dst_ptr = (float *) dst->data;
  12517. // TODO: optimize
  12518. for (int64_t i2 = 0; i2 < ne2; ++i2) {
  12519. for (int64_t i1 = ith; i1 < ne1; i1 += nth) {
  12520. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  12521. for (int64_t i3 = 0; i3 < ne3; ++i3) {
  12522. const int64_t dst_idx = i3*(ne0*ne1*ne2) + i2*(ne0*ne1) + i1*ne0 + i0;
  12523. const float * src_ptr = (const float *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  12524. if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
  12525. dst_ptr[dst_idx] = *src_ptr;
  12526. } else {
  12527. dst_ptr[dst_idx] = 0;
  12528. }
  12529. }
  12530. }
  12531. }
  12532. }
  12533. }
  12534. static void ggml_compute_forward_pad(
  12535. const struct ggml_compute_params * params,
  12536. struct ggml_tensor * dst) {
  12537. const struct ggml_tensor * src0 = dst->src[0];
  12538. switch (src0->type) {
  12539. case GGML_TYPE_F32:
  12540. {
  12541. ggml_compute_forward_pad_f32(params, dst);
  12542. } break;
  12543. default:
  12544. {
  12545. GGML_ABORT("fatal error");
  12546. }
  12547. }
  12548. }
  12549. // ggml_compute_forward_arange
  12550. static void ggml_compute_forward_arange_f32(
  12551. const struct ggml_compute_params * params,
  12552. struct ggml_tensor * dst) {
  12553. GGML_ASSERT(dst->nb[0] == sizeof(float));
  12554. const int ith = params->ith;
  12555. const int nth = params->nth;
  12556. const float start = ggml_get_op_params_f32(dst, 0);
  12557. const float stop = ggml_get_op_params_f32(dst, 1);
  12558. const float step = ggml_get_op_params_f32(dst, 2);
  12559. const int64_t steps = (int64_t) ceilf((stop - start) / step);
  12560. GGML_ASSERT(ggml_nelements(dst) == steps);
  12561. for (int64_t i = ith; i < steps; i+= nth) {
  12562. float value = start + step * i;
  12563. ((float *)dst->data)[i] = value;
  12564. }
  12565. }
  12566. static void ggml_compute_forward_arange(
  12567. const struct ggml_compute_params * params,
  12568. struct ggml_tensor * dst) {
  12569. switch (dst->type) {
  12570. case GGML_TYPE_F32:
  12571. {
  12572. ggml_compute_forward_arange_f32(params, dst);
  12573. } break;
  12574. default:
  12575. {
  12576. GGML_ABORT("fatal error");
  12577. }
  12578. }
  12579. }
  12580. static void ggml_compute_forward_timestep_embedding_f32(
  12581. const struct ggml_compute_params * params,
  12582. struct ggml_tensor * dst) {
  12583. const struct ggml_tensor * src0 = dst->src[0];
  12584. GGML_ASSERT(src0->nb[0] == sizeof(float));
  12585. const int ith = params->ith;
  12586. const int nth = params->nth;
  12587. GGML_TENSOR_UNARY_OP_LOCALS
  12588. const int dim = ggml_get_op_params_i32(dst, 0);
  12589. const int max_period = ggml_get_op_params_i32(dst, 1);
  12590. int half = dim / 2;
  12591. for (int64_t i = 0; i < ne00; i++) {
  12592. float * embed_data = (float *)((char *) dst->data + i*nb1);
  12593. for (int64_t j = ith; j < half; j += nth) {
  12594. float timestep = ((float *)src0->data)[i];
  12595. float freq = (float)expf(-logf(max_period) * j / half);
  12596. float arg = timestep * freq;
  12597. embed_data[j] = cosf(arg);
  12598. embed_data[j + half] = sinf(arg);
  12599. }
  12600. if (dim % 2 != 0 && ith == 0) {
  12601. embed_data[dim] = 0.f;
  12602. }
  12603. }
  12604. }
  12605. static void ggml_compute_forward_timestep_embedding(
  12606. const struct ggml_compute_params * params,
  12607. struct ggml_tensor * dst) {
  12608. const struct ggml_tensor * src0 = dst->src[0];
  12609. switch (src0->type) {
  12610. case GGML_TYPE_F32:
  12611. {
  12612. ggml_compute_forward_timestep_embedding_f32(params, dst);
  12613. } break;
  12614. default:
  12615. {
  12616. GGML_ABORT("fatal error");
  12617. }
  12618. }
  12619. }
  12620. // ggml_compute_forward_argsort
  12621. static void ggml_compute_forward_argsort_f32(
  12622. const struct ggml_compute_params * params,
  12623. struct ggml_tensor * dst) {
  12624. const struct ggml_tensor * src0 = dst->src[0];
  12625. GGML_TENSOR_UNARY_OP_LOCALS
  12626. GGML_ASSERT(nb0 == sizeof(float));
  12627. const int ith = params->ith;
  12628. const int nth = params->nth;
  12629. const int64_t nr = ggml_nrows(src0);
  12630. enum ggml_sort_order order = (enum ggml_sort_order) ggml_get_op_params_i32(dst, 0);
  12631. for (int64_t i = ith; i < nr; i += nth) {
  12632. int32_t * dst_data = (int32_t *)((char *) dst->data + i*nb1);
  12633. const float * src_data = (float *)((char *) src0->data + i*nb01);
  12634. for (int64_t j = 0; j < ne0; j++) {
  12635. dst_data[j] = j;
  12636. }
  12637. // C doesn't have a functional sort, so we do a bubble sort instead
  12638. for (int64_t j = 0; j < ne0; j++) {
  12639. for (int64_t k = j + 1; k < ne0; k++) {
  12640. if ((order == GGML_SORT_ORDER_ASC && src_data[dst_data[j]] > src_data[dst_data[k]]) ||
  12641. (order == GGML_SORT_ORDER_DESC && src_data[dst_data[j]] < src_data[dst_data[k]])) {
  12642. int32_t tmp = dst_data[j];
  12643. dst_data[j] = dst_data[k];
  12644. dst_data[k] = tmp;
  12645. }
  12646. }
  12647. }
  12648. }
  12649. }
  12650. static void ggml_compute_forward_argsort(
  12651. const struct ggml_compute_params * params,
  12652. struct ggml_tensor * dst) {
  12653. const struct ggml_tensor * src0 = dst->src[0];
  12654. switch (src0->type) {
  12655. case GGML_TYPE_F32:
  12656. {
  12657. ggml_compute_forward_argsort_f32(params, dst);
  12658. } break;
  12659. default:
  12660. {
  12661. GGML_ABORT("fatal error");
  12662. }
  12663. }
  12664. }
  12665. // ggml_compute_forward_flash_attn_ext
  12666. static void ggml_compute_forward_flash_attn_ext_f16(
  12667. const struct ggml_compute_params * params,
  12668. const struct ggml_tensor * q,
  12669. const struct ggml_tensor * k,
  12670. const struct ggml_tensor * v,
  12671. const struct ggml_tensor * mask,
  12672. struct ggml_tensor * dst) {
  12673. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  12674. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  12675. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  12676. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  12677. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  12678. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  12679. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  12680. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  12681. const int ith = params->ith;
  12682. const int nth = params->nth;
  12683. const int64_t D = neq0;
  12684. const int64_t N = neq1;
  12685. GGML_ASSERT(ne0 == D);
  12686. GGML_ASSERT(ne2 == N);
  12687. // input tensor rows must be contiguous
  12688. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  12689. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  12690. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  12691. GGML_ASSERT(neq0 == D);
  12692. GGML_ASSERT(nek0 == D);
  12693. GGML_ASSERT(nev0 == D);
  12694. GGML_ASSERT(neq1 == N);
  12695. GGML_ASSERT(nev0 == D);
  12696. // dst cannot be transposed or permuted
  12697. GGML_ASSERT(nb0 == sizeof(float));
  12698. GGML_ASSERT(nb0 <= nb1);
  12699. GGML_ASSERT(nb1 <= nb2);
  12700. GGML_ASSERT(nb2 <= nb3);
  12701. // broadcast factors
  12702. const int64_t rk2 = neq2/nek2;
  12703. const int64_t rk3 = neq3/nek3;
  12704. const int64_t rv2 = neq2/nev2;
  12705. const int64_t rv3 = neq3/nev3;
  12706. // parallelize by q rows using ggml_vec_dot_f32
  12707. // total rows in q
  12708. const int nr = neq1*neq2*neq3;
  12709. // rows per thread
  12710. const int dr = (nr + nth - 1)/nth;
  12711. // row range for this thread
  12712. const int ir0 = dr*ith;
  12713. const int ir1 = MIN(ir0 + dr, nr);
  12714. float scale = 1.0f;
  12715. float max_bias = 0.0f;
  12716. float logit_softcap = 0.0f;
  12717. memcpy(&scale, (float *) dst->op_params + 0, sizeof(float));
  12718. memcpy(&max_bias, (float *) dst->op_params + 1, sizeof(float));
  12719. memcpy(&logit_softcap, (float *) dst->op_params + 2, sizeof(float));
  12720. if (logit_softcap != 0) {
  12721. scale /= logit_softcap;
  12722. }
  12723. const uint32_t n_head = neq2;
  12724. const uint32_t n_head_log2 = 1u << (uint32_t) floor(log2(n_head));
  12725. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  12726. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  12727. enum ggml_type const k_vec_dot_type = type_traits[k->type].vec_dot_type;
  12728. ggml_from_float_t const q_to_vec_dot = type_traits[k_vec_dot_type].from_float;
  12729. ggml_vec_dot_t const kq_vec_dot = type_traits[k->type].vec_dot;
  12730. ggml_to_float_t const v_to_float = type_traits[v->type].to_float;
  12731. // loop over n_batch and n_head
  12732. for (int ir = ir0; ir < ir1; ++ir) {
  12733. // q indices
  12734. const int iq3 = ir/(neq2*neq1);
  12735. const int iq2 = (ir - iq3*neq2*neq1)/neq1;
  12736. const int iq1 = (ir - iq3*neq2*neq1 - iq2*neq1);
  12737. const uint32_t h = iq2; // head index
  12738. const float slope = (max_bias > 0.0f) ? h < n_head_log2 ? powf(m0, h + 1) : powf(m1, 2*(h - n_head_log2) + 1) : 1.0f;
  12739. float S = 0.0f; // sum
  12740. float M = -INFINITY; // maximum KQ value
  12741. float * VKQ32 = (float *) params->wdata + ith*(3*D + CACHE_LINE_SIZE_F32); // FP32 VKQ accumulator
  12742. float * V32 = (VKQ32 + 1*D); // (temporary) FP32 V buffer
  12743. ggml_fp16_t * VKQ16 = (ggml_fp16_t *) (VKQ32 + 1*D); // (temporary) FP16 VKQ accumulator
  12744. ggml_fp16_t * Q_q = (ggml_fp16_t *) (VKQ32 + 2*D); // (temporary) buffer for Q converted to quantized/FP16
  12745. if (v->type == GGML_TYPE_F16) {
  12746. memset(VKQ16, 0, D*sizeof(ggml_fp16_t));
  12747. } else {
  12748. memset(VKQ32, 0, D*sizeof(float));
  12749. }
  12750. const ggml_fp16_t * mp = mask ? (ggml_fp16_t *)((char *) mask->data + iq1*mask->nb[1]) : NULL;
  12751. // k indices
  12752. const int ik3 = iq3 / rk3;
  12753. const int ik2 = iq2 / rk2;
  12754. // v indices
  12755. const int iv3 = iq3 / rv3;
  12756. const int iv2 = iq2 / rv2;
  12757. const float * pq = (const float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3));
  12758. q_to_vec_dot(pq, Q_q, D);
  12759. // online softmax / attention
  12760. // loop over n_kv and n_head_kv
  12761. // ref: https://arxiv.org/pdf/2112.05682.pdf
  12762. for (int64_t ic = 0; ic < nek1; ++ic) {
  12763. const float mv = mp ? slope*GGML_FP16_TO_FP32(mp[ic]) : 0.0f;
  12764. if (mv == -INFINITY) {
  12765. continue;
  12766. }
  12767. float s; // KQ value
  12768. const char * k_data = (const char *) k->data + ( ic*nbk1 + ik2*nbk2 + ik3*nbk3);
  12769. kq_vec_dot(D, &s, 0, k_data, 0, Q_q, 0, 1);
  12770. s = s*scale; // scale KQ value
  12771. if (logit_softcap != 0.0f) {
  12772. s = logit_softcap*tanhf(s);
  12773. }
  12774. s += mv; // apply mask
  12775. const float Mold = M;
  12776. float ms = 1.0f; // upon new higher max val, scale VKQ and KQ sum with this value
  12777. float vs = 1.0f; // post-softmax KQ value, expf(s - M)
  12778. const char * v_data = ((const char *) v->data + (ic*nbv1 + iv2*nbv2 + iv3*nbv3));
  12779. if (v->type == GGML_TYPE_F16) {
  12780. if (s > M) {
  12781. // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f
  12782. M = s;
  12783. ms = expf(Mold - M);
  12784. // V = V*expf(Mold - M)
  12785. ggml_vec_scale_f16(D, VKQ16, ms);
  12786. } else {
  12787. // no new maximum, ms == 1.0f, vs != 1.0f
  12788. vs = expf(s - M);
  12789. }
  12790. // V += v*expf(s - M)
  12791. ggml_vec_mad_f16(D, VKQ16, (const ggml_fp16_t *) v_data, vs);
  12792. } else {
  12793. if (s > M) {
  12794. // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f
  12795. M = s;
  12796. ms = expf(Mold - M);
  12797. // V = V*expf(Mold - M)
  12798. ggml_vec_scale_f32(D, VKQ32, ms);
  12799. } else {
  12800. // no new maximum, ms == 1.0f, vs != 1.0f
  12801. vs = expf(s - M);
  12802. }
  12803. v_to_float(v_data, V32, D);
  12804. // V += v*expf(s - M)
  12805. ggml_vec_mad_f32(D, VKQ32, V32, vs);
  12806. }
  12807. S = S*ms + vs; // scale and increment sum with partial sum
  12808. }
  12809. if (v->type == GGML_TYPE_F16) {
  12810. for (int64_t d = 0; d < D; ++d) {
  12811. VKQ32[d] = GGML_FP16_TO_FP32(VKQ16[d]);
  12812. }
  12813. }
  12814. // V /= S
  12815. const float S_inv = 1.0f/S;
  12816. ggml_vec_scale_f32(D, VKQ32, S_inv);
  12817. // dst indices
  12818. const int i1 = iq1;
  12819. const int i2 = iq2;
  12820. const int i3 = iq3;
  12821. // original
  12822. //memcpy((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb3), V, nev0*sizeof(float));
  12823. // permute(0, 2, 1, 3)
  12824. memcpy((char *) dst->data + (i3*ne2*ne1 + i2 + i1*ne1)*nb1, VKQ32, nb1);
  12825. }
  12826. }
  12827. static void ggml_compute_forward_flash_attn_ext(
  12828. const struct ggml_compute_params * params,
  12829. const struct ggml_tensor * q,
  12830. const struct ggml_tensor * k,
  12831. const struct ggml_tensor * v,
  12832. const struct ggml_tensor * mask,
  12833. struct ggml_tensor * dst) {
  12834. switch (dst->op_params[3]) {
  12835. case GGML_PREC_DEFAULT:
  12836. case GGML_PREC_F32:
  12837. {
  12838. // uses F32 accumulators
  12839. ggml_compute_forward_flash_attn_ext_f16(params, q, k, v, mask, dst);
  12840. } break;
  12841. default:
  12842. {
  12843. GGML_ABORT("fatal error");
  12844. }
  12845. }
  12846. }
  12847. // ggml_compute_forward_flash_attn_back
  12848. static void ggml_compute_forward_flash_attn_back_f32(
  12849. const struct ggml_compute_params * params,
  12850. const bool masked,
  12851. struct ggml_tensor * dst) {
  12852. const struct ggml_tensor * q = dst->src[0];
  12853. const struct ggml_tensor * k = dst->src[1];
  12854. const struct ggml_tensor * v = dst->src[2];
  12855. const struct ggml_tensor * d = dst->src[3];
  12856. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  12857. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  12858. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  12859. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  12860. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  12861. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  12862. GGML_TENSOR_LOCALS(int64_t, ned, d, ne)
  12863. GGML_TENSOR_LOCALS(size_t, nbd, d, nb)
  12864. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  12865. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  12866. const int ith = params->ith;
  12867. const int nth = params->nth;
  12868. const int64_t D = neq0;
  12869. const int64_t N = neq1;
  12870. const int64_t P = nek1 - N;
  12871. const int64_t M = P + N;
  12872. const int Mup = ggml_up(M, GGML_SOFT_MAX_UNROLL);
  12873. const int mxDM = MAX(D, Mup);
  12874. // GGML_ASSERT(ne0 == D);
  12875. // GGML_ASSERT(ne1 == N);
  12876. GGML_ASSERT(P >= 0);
  12877. GGML_ASSERT(nbq0 == sizeof(float));
  12878. GGML_ASSERT(nbk0 == sizeof(float));
  12879. GGML_ASSERT(nbv0 == sizeof(float));
  12880. GGML_ASSERT(neq0 == D);
  12881. GGML_ASSERT(nek0 == D);
  12882. GGML_ASSERT(nev1 == D);
  12883. GGML_ASSERT(ned0 == D);
  12884. GGML_ASSERT(neq1 == N);
  12885. GGML_ASSERT(nek1 == N + P);
  12886. GGML_ASSERT(nev1 == D);
  12887. GGML_ASSERT(ned1 == N);
  12888. // dst cannot be transposed or permuted
  12889. GGML_ASSERT(nb0 == sizeof(float));
  12890. GGML_ASSERT(nb0 <= nb1);
  12891. GGML_ASSERT(nb1 <= nb2);
  12892. GGML_ASSERT(nb2 <= nb3);
  12893. if (ith == 0) {
  12894. memset(dst->data, 0, nb0*ne0*ne1*ne2*ne3);
  12895. }
  12896. ggml_barrier(params->threadpool);
  12897. const int64_t elem_q = ggml_nelements(q);
  12898. const int64_t elem_k = ggml_nelements(k);
  12899. enum ggml_type result_type = dst->type;
  12900. GGML_ASSERT(ggml_blck_size(result_type) == 1);
  12901. const size_t tsize = ggml_type_size(result_type);
  12902. const size_t offs_q = 0;
  12903. const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
  12904. const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
  12905. void * grad_q = (char *) dst->data;
  12906. void * grad_k = (char *) dst->data + offs_k;
  12907. void * grad_v = (char *) dst->data + offs_v;
  12908. const size_t nbgq1 = nb0*neq0;
  12909. const size_t nbgq2 = nb0*neq0*neq1;
  12910. const size_t nbgq3 = nb0*neq0*neq1*neq2;
  12911. const size_t nbgk1 = nb0*nek0;
  12912. const size_t nbgk2 = nb0*nek0*nek1;
  12913. const size_t nbgk3 = nb0*nek0*nek1*neq2;
  12914. const size_t nbgv1 = nb0*nev0;
  12915. const size_t nbgv2 = nb0*nev0*nev1;
  12916. const size_t nbgv3 = nb0*nev0*nev1*neq2;
  12917. // parallelize by k rows using ggml_vec_dot_f32
  12918. // total rows in k
  12919. const int nr = nek2*nek3;
  12920. // rows per thread
  12921. const int dr = (nr + nth - 1)/nth;
  12922. // row range for this thread
  12923. const int ir0 = dr*ith;
  12924. const int ir1 = MIN(ir0 + dr, nr);
  12925. const float scale = 1.0f/sqrtf(D);
  12926. //printf("P=%d N=%d D=%d ir0=%d ir1=%d scale = %f\n", P, N, D, ir0, ir1, scale);
  12927. // how often k2 (and v2) is repeated in q2
  12928. int nrep = neq2/nek2;
  12929. for (int ir = ir0; ir < ir1; ++ir) {
  12930. // q indices
  12931. const int ik3 = ir/(nek2);
  12932. const int ik2 = ir - ik3*nek2;
  12933. const int iq3 = ik3;
  12934. const int id3 = ik3;
  12935. const int iv3 = ik3;
  12936. const int iv2 = ik2;
  12937. for (int irep = 0; irep < nrep; ++irep) {
  12938. const int iq2 = ik2 + irep*nek2;
  12939. const int id2 = iq2;
  12940. // (ik2 + irep*nek2) % nek2 == ik2
  12941. for (int iq1 = 0; iq1 < neq1; ++iq1) {
  12942. const int id1 = iq1;
  12943. // not sure about CACHE_LINE_SIZE_F32..
  12944. // - maybe it must not be multiplied by 2 and excluded from .. in SM 1*(..) offset?
  12945. float * S = (float *) params->wdata + ith*2*(mxDM + CACHE_LINE_SIZE_F32) + 0*(mxDM+CACHE_LINE_SIZE_F32);
  12946. float * SM = (float *) params->wdata + ith*2*(mxDM + CACHE_LINE_SIZE_F32) + 1*(mxDM+CACHE_LINE_SIZE_F32);
  12947. for (int i = M; i < Mup; ++i) {
  12948. S[i] = -INFINITY;
  12949. }
  12950. const int64_t masked_begin = masked ? (P + iq1 + 1) : M;
  12951. for (int64_t ic = 0; ic < masked_begin; ++ic) {
  12952. // k indices
  12953. const int ik1 = ic;
  12954. // S indices
  12955. const int i1 = ik1;
  12956. ggml_vec_dot_f32(neq0,
  12957. S + i1, 0,
  12958. (float *) ((char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3)), 0,
  12959. (float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)), 0, 1);
  12960. }
  12961. // scale
  12962. ggml_vec_scale_f32(masked_begin, S, scale);
  12963. for (int64_t i = masked_begin; i < M; i++) {
  12964. S[i] = -INFINITY;
  12965. }
  12966. // softmax
  12967. // exclude known -INF S[..] values from max and loop
  12968. // dont forget to set their SM values to zero
  12969. {
  12970. float max = -INFINITY;
  12971. ggml_vec_max_f32(masked_begin, &max, S);
  12972. ggml_float sum = 0.0;
  12973. {
  12974. #ifdef GGML_SOFT_MAX_ACCELERATE
  12975. max = -max;
  12976. vDSP_vsadd(SM, 1, &max, SM, 1, Mup);
  12977. vvexpf(SM, SM, &Mup);
  12978. ggml_vec_sum_f32(Mup, &sum, SM);
  12979. #else
  12980. sum = ggml_vec_soft_max_f32(Mup, SM, S, max);
  12981. #endif
  12982. }
  12983. assert(sum > 0.0);
  12984. sum = 1.0/sum;
  12985. ggml_vec_scale_f32(masked_begin, SM, sum);
  12986. }
  12987. // step-by-step explanation
  12988. {
  12989. // forward-process shape grads from backward process
  12990. // parallel_for ik2,ik3:
  12991. // for irep:
  12992. // iq2 = ik2 + irep*nek2
  12993. // k[:D,:M,:,:] [D,M,:,:] grad[k][:D,:M,ik2,ik3] += grad[kcur]
  12994. // q[:D,:N,:,:] [D,N,:,:] grad[q][:D,iq1,iq2,iq3] += grad[qcur]
  12995. // v[:M,:D,:,:] [M,D,:,:] grad[v][:M,:D,iv2,iv3] += grad[vcur]
  12996. // for iq1:
  12997. // kcur = k[:D,:M,ik2,ik3] [D,M,1,1] grad[kcur] = grad[S1].T @ qcur
  12998. // qcur = q[:D,iq1,iq2,iq3] [D,1,1,1] grad[qcur] = grad[S1] @ kcur
  12999. // vcur = v[:M,:D,iv2,iv3] [M,D,1,1] grad[vcur] = grad[S5].T @ S4
  13000. // S0 = -Inf [D,1,1,1]
  13001. // ~S1[i] = dot(kcur[:D,i], qcur)
  13002. // S1 = qcur @ kcur.T [M,1,1,1] grad[S1] = grad[S2] * scale
  13003. // S2 = S1 * scale [M,1,1,1] grad[S2] = diag_mask_zero(grad[S3], P)
  13004. // S3 = diag_mask_inf(S2, P) [M,1,1,1] grad[S3] = S4 * (grad[S4] - dot(S4, grad[S4]))
  13005. // S4 = softmax(S3) [M,1,1,1] grad[S4] = grad[S5] @ vcur
  13006. // ~S5[i] = dot(vcur[:,i], S4)
  13007. // S5 = S4 @ vcur.T [D,1,1,1] grad[S5] = d[:D,id1,id2,id3]
  13008. // ~dst[i,iq1,iq2,iq3] = S5[i] ^
  13009. // dst[:D,iq1,iq2,iq3] = S5 | grad[dst[:D,iq1,iq2,iq3]] = d[:D,id1,id2,id3]
  13010. // dst backward-/ grad[dst] = d
  13011. //
  13012. // output gradients with their dependencies:
  13013. //
  13014. // grad[kcur] = grad[S1].T @ qcur
  13015. // grad[S1] = diag_mask_zero(grad[S3], P) * scale
  13016. // grad[S3] = S4 * (grad[S4] - dot(S4, grad[S4]))
  13017. // grad[S4] = grad[S5] @ vcur
  13018. // grad[S4] = d[:D,id1,id2,id3] @ vcur
  13019. // grad[qcur] = grad[S1] @ kcur
  13020. // grad[vcur] = grad[S5].T @ S4
  13021. // grad[vcur] = d[:D,id1,id2,id3].T @ S4
  13022. //
  13023. // in post-order:
  13024. //
  13025. // S1 = qcur @ kcur.T
  13026. // S2 = S1 * scale
  13027. // S3 = diag_mask_inf(S2, P)
  13028. // S4 = softmax(S3)
  13029. // grad[S4] = d[:D,id1,id2,id3] @ vcur
  13030. // grad[S3] = S4 * (grad[S4] - dot(S4, grad[S4]))
  13031. // grad[S1] = diag_mask_zero(grad[S3], P) * scale
  13032. // grad[qcur] = grad[S1] @ kcur
  13033. // grad[kcur] = grad[S1].T @ qcur
  13034. // grad[vcur] = d[:D,id1,id2,id3].T @ S4
  13035. //
  13036. // using less variables (SM=S4):
  13037. //
  13038. // S = diag_mask_inf(qcur @ kcur.T * scale, P)
  13039. // SM = softmax(S)
  13040. // S = d[:D,iq1,iq2,iq3] @ vcur
  13041. // dot_SM_gradSM = dot(SM, S)
  13042. // S = SM * (S - dot(SM, S))
  13043. // S = diag_mask_zero(S, P) * scale
  13044. //
  13045. // grad[q][:D,iq1,iq2,iq3] += S @ kcur
  13046. // grad[k][:D,:M,ik2,ik3] += S.T @ qcur
  13047. // grad[v][:M,:D,iv2,iv3] += d[:D,id1,id2,id3].T @ SM
  13048. }
  13049. // S = gradSM = d[:D,id1,id2,id3] @ vcur[:,:,iv2,iv3]
  13050. // S = d[:D,id1,id2,id3] @ vcur[:,:,iv2,iv3]
  13051. // for ic:
  13052. // S[:M] += vcur[:M,ic,iv2,iv3] * d[ic,id1,id2,id3]
  13053. // exclude known future zero S[..] values from operation
  13054. ggml_vec_set_f32(masked_begin, S, 0);
  13055. for (int64_t ic = 0; ic < D; ++ic) {
  13056. ggml_vec_mad_f32(masked_begin,
  13057. S,
  13058. (float *) ((char *) v->data + ( ic*nbv1 + iv2*nbv2 + iv3*nbv3)),
  13059. *(float *) ((char *) d->data + (ic*nbd0 + id1*nbd1 + id2*nbd2 + id3*nbd3)));
  13060. }
  13061. // S = SM * (S - dot(SM, S))
  13062. float dot_SM_gradSM = 0;
  13063. ggml_vec_dot_f32 (masked_begin, &dot_SM_gradSM, 0, SM, 0, S, 0, 1);
  13064. ggml_vec_acc1_f32(M, S, -dot_SM_gradSM);
  13065. ggml_vec_mul_f32 (masked_begin, S, S, SM);
  13066. // S = diag_mask_zero(S, P) * scale
  13067. // already done by above ggml_vec_set_f32
  13068. // exclude known zero S[..] values from operation
  13069. ggml_vec_scale_f32(masked_begin, S, scale);
  13070. // S shape [M,1]
  13071. // SM shape [M,1]
  13072. // kcur shape [D,M]
  13073. // qcur shape [D,1]
  13074. // vcur shape [M,D]
  13075. // grad[q][:D,iq1,iq2,iq3] += S @ kcur
  13076. // grad[q][:D,iq1,iq2,iq3] += shape[M,1] @ shape[D,M]
  13077. // for ic:
  13078. // grad[q][:D,iq1,iq2,iq3] += S[ic] * kcur[:D,ic,ik2,ik3]
  13079. // exclude known zero S[..] values from loop
  13080. for (int64_t ic = 0; ic < masked_begin; ++ic) {
  13081. ggml_vec_mad_f32(D,
  13082. (float *) ((char *) grad_q + (iq1*nbgq1 + iq2*nbgq2 + iq3*nbgq3)),
  13083. (float *) ((char *) k->data + (ic*nbk1 + ik2*nbk2 + ik3*nbk3)),
  13084. S[ic]);
  13085. }
  13086. // grad[k][:D,:M,iq2,iq3] += S.T @ qcur
  13087. // for ic:
  13088. // grad[k][:D,ic,iq2,iq3] += S.T[0,ic] * qcur[:D,0]
  13089. // grad[k][:D,ic,iq2,iq3] += S[ic] * qcur[:D,0]
  13090. // exclude known zero S[..] values from loop
  13091. for (int64_t ic = 0; ic < masked_begin; ++ic) {
  13092. ggml_vec_mad_f32(D,
  13093. (float *) ((char *) grad_k + (ic*nbgk1 + ik2*nbgk2 + ik3*nbgk3)),
  13094. (float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)),
  13095. S[ic]);
  13096. }
  13097. // grad[v][:M,:D,iv2,iv3] += d[:D,id1,id2,id3].T @ SM
  13098. // for ic:
  13099. // grad[v][:M,ic,iv2,iv3] += d[:D,id1,id2,id3].T[0,ic] * SM[:M]
  13100. // grad[v][:M,ic,iv2,iv3] += d[ic,id1,id2,id3] * SM[:M]
  13101. // exclude known zero SM[..] values from mad
  13102. for (int64_t ic = 0; ic < D; ++ic) {
  13103. ggml_vec_mad_f32(masked_begin,
  13104. (float *) ((char *) grad_v + ( ic*nbgv1 + iv2*nbgv2 + iv3*nbgv3)),
  13105. SM,
  13106. *(float *) ((char *) d->data + (ic*nbd0 + id1*nbd1 + id2*nbd2 + id3*nbd3)));
  13107. }
  13108. }
  13109. }
  13110. }
  13111. }
  13112. static void ggml_compute_forward_flash_attn_back(
  13113. const struct ggml_compute_params * params,
  13114. const bool masked,
  13115. struct ggml_tensor * dst) {
  13116. const struct ggml_tensor * q = dst->src[0];
  13117. switch (q->type) {
  13118. case GGML_TYPE_F32:
  13119. {
  13120. ggml_compute_forward_flash_attn_back_f32(params, masked, dst);
  13121. } break;
  13122. default:
  13123. {
  13124. GGML_ABORT("fatal error");
  13125. }
  13126. }
  13127. }
  13128. // ggml_compute_forward_ssm_conv
  13129. static void ggml_compute_forward_ssm_conv_f32(
  13130. const struct ggml_compute_params * params,
  13131. struct ggml_tensor * dst) {
  13132. const struct ggml_tensor * src0 = dst->src[0]; // conv_x
  13133. const struct ggml_tensor * src1 = dst->src[1]; // conv1d.weight
  13134. const int ith = params->ith;
  13135. const int nth = params->nth;
  13136. const int nc = src1->ne[0]; // d_conv
  13137. const int ncs = src0->ne[0]; // d_conv - 1 + n_t
  13138. const int nr = src0->ne[1]; // d_inner
  13139. const int n_t = dst->ne[1]; // tokens per sequence
  13140. const int n_s = dst->ne[2]; // number of sequences in the batch
  13141. GGML_ASSERT( dst->ne[0] == nr);
  13142. GGML_ASSERT(src0->nb[0] == sizeof(float));
  13143. GGML_ASSERT(src1->nb[0] == sizeof(float));
  13144. GGML_ASSERT(src0->nb[1] == src0->ne[0]*sizeof(float));
  13145. // rows per thread
  13146. const int dr = (nr + nth - 1)/nth;
  13147. // row range for this thread
  13148. const int ir0 = dr*ith;
  13149. const int ir1 = MIN(ir0 + dr, nr);
  13150. const int ir = ir1 - ir0;
  13151. for (int i3 = 0; i3 < n_s; ++i3) {
  13152. for (int i2 = 0; i2 < n_t; ++i2) {
  13153. // {d_conv - 1 + n_t, d_inner, n_seqs}
  13154. // sliding window
  13155. const float * s = (const float *) ((const char *) src0->data + ir0*(src0->nb[1]) + i2*(src0->nb[0]) + i3*(src0->nb[2])); // {d_conv, d_inner, n_s}
  13156. const float * c = (const float *) ((const char *) src1->data + ir0*(src1->nb[1])); // {d_conv, d_inner}
  13157. float * x = (float *) ((char *) dst->data + ir0*(dst->nb[0]) + i2*(dst->nb[1]) + i3*(dst->nb[2])); // {d_inner, n_t, n_s}
  13158. // TODO: transpose the output for smaller strides for big batches?
  13159. // d_inner
  13160. for (int i1 = 0; i1 < ir; ++i1) {
  13161. // rowwise dot product
  13162. // NOTE: not using ggml_vec_dot_f32, because its sum is in double precision
  13163. float sumf = 0.0f;
  13164. // d_conv
  13165. for (int i0 = 0; i0 < nc; ++i0) {
  13166. sumf += s[i0 + i1*ncs] * c[i0 + i1*nc];
  13167. }
  13168. x[i1] = sumf;
  13169. }
  13170. }
  13171. }
  13172. }
  13173. static void ggml_compute_forward_ssm_conv(
  13174. const struct ggml_compute_params * params,
  13175. struct ggml_tensor * dst) {
  13176. switch (dst->src[0]->type) {
  13177. case GGML_TYPE_F32:
  13178. {
  13179. ggml_compute_forward_ssm_conv_f32(params, dst);
  13180. } break;
  13181. default:
  13182. {
  13183. GGML_ABORT("fatal error");
  13184. }
  13185. }
  13186. }
  13187. // ggml_compute_forward_ssm_scan
  13188. static void ggml_compute_forward_ssm_scan_f32(
  13189. const struct ggml_compute_params * params,
  13190. struct ggml_tensor * dst) {
  13191. const struct ggml_tensor * src0 = dst->src[0]; // s
  13192. const struct ggml_tensor * src1 = dst->src[1]; // x
  13193. const struct ggml_tensor * src2 = dst->src[2]; // dt
  13194. const struct ggml_tensor * src3 = dst->src[3]; // A
  13195. const struct ggml_tensor * src4 = dst->src[4]; // B
  13196. const struct ggml_tensor * src5 = dst->src[5]; // C
  13197. const int ith = params->ith;
  13198. const int nth = params->nth;
  13199. const int64_t nc = src0->ne[0]; // d_state
  13200. const int64_t nr = src0->ne[1]; // d_inner
  13201. const int64_t n_t = src1->ne[1]; // number of tokens per sequence
  13202. const int64_t n_s = src0->ne[2]; // number of sequences in the batch
  13203. GGML_ASSERT(ggml_nelements(src1) + ggml_nelements(src0) == ggml_nelements(dst));
  13204. GGML_ASSERT(src0->nb[0] == sizeof(float));
  13205. GGML_ASSERT(src1->nb[0] == sizeof(float));
  13206. GGML_ASSERT(src2->nb[0] == sizeof(float));
  13207. GGML_ASSERT(src3->nb[0] == sizeof(float));
  13208. GGML_ASSERT(src4->nb[0] == sizeof(float));
  13209. GGML_ASSERT(src5->nb[0] == sizeof(float));
  13210. // required for the dot product between s and C
  13211. GGML_ASSERT(src0->nb[1] == src0->ne[0]*sizeof(float));
  13212. // required for per-sequence offsets for states
  13213. GGML_ASSERT(src0->nb[2] == src0->ne[0]*src0->ne[1]*sizeof(float));
  13214. // required to get correct offset for state destination (i.e. src1->nb[3])
  13215. GGML_ASSERT(src1->nb[3] == src1->ne[0]*src1->ne[1]*src1->ne[2]*sizeof(float));
  13216. // rows per thread
  13217. const int dr = (nr + nth - 1)/nth;
  13218. // row range for this thread
  13219. const int ir0 = dr*ith;
  13220. const int ir1 = MIN(ir0 + dr, nr);
  13221. const int ir = ir1 - ir0;
  13222. for (int i3 = 0; i3 < n_s; ++i3) {
  13223. for (int i2 = 0; i2 < n_t; ++i2) {
  13224. const float * s0 = (const float *) ((const char *) src0->data + ir0*(src0->nb[1]) + i3*(src0->nb[2])); // {d_state, d_inner, n_s}
  13225. const float * x = (const float *) ((const char *) src1->data + ir0*(src1->nb[0]) + i2*(src1->nb[1]) + i3*(src1->nb[2])); // {d_inner, n_t, n_s}
  13226. const float * dt = (const float *) ((const char *) src2->data + ir0*(src2->nb[0]) + i2*(src2->nb[1]) + i3*(src2->nb[2])); // {d_inner, n_t, n_s}
  13227. const float * A = (const float *) ((const char *) src3->data + ir0*(src3->nb[1])); // {d_state, d_inner}
  13228. const float * B = (const float *) ((const char *) src4->data + i2*(src4->nb[1]) + i3*(src4->nb[2])); // {d_state, n_t, n_s}
  13229. const float * C = (const float *) ((const char *) src5->data + i2*(src5->nb[1]) + i3*(src5->nb[2])); // {d_state, n_t, n_s}
  13230. float * y = ( float *) (( char *) dst->data + ir0*(src1->nb[0]) + i2*(src1->nb[1]) + i3*(src1->nb[2])); // {d_inner, n_t, n_s}
  13231. float * s = ( float *) (( char *) dst->data + ir0*(src0->nb[1]) + i3*(src0->nb[2]) + src1->nb[3]); // {d_state, d_inner, n_s}
  13232. // use the output as the source for the next token-wise iterations
  13233. if (i2 > 0) { s0 = s; }
  13234. // d_inner
  13235. for (int i1 = 0; i1 < ir; ++i1) {
  13236. // ref: https://github.com/state-spaces/mamba/blob/34076d664838588a3c97727b263478ab9f621a07/mamba_ssm/ops/triton/selective_state_update.py#L78
  13237. float dt_soft_plus = dt[i1] <= 20.0f ? log1pf(expf(dt[i1])) : dt[i1];
  13238. float x_dt = x[i1] * dt_soft_plus;
  13239. float sumf = 0.0f;
  13240. // d_state
  13241. for (int i0 = 0; i0 < nc; ++i0) {
  13242. int i = i0 + i1*nc;
  13243. // state = prev_state * dA + dB * x
  13244. float state = (s0[i] * expf(dt_soft_plus * A[i])) + (B[i0] * x_dt);
  13245. // y = rowwise_dotprod(state, C)
  13246. sumf += state * C[i0];
  13247. s[i] = state;
  13248. }
  13249. y[i1] = sumf;
  13250. }
  13251. }
  13252. }
  13253. }
  13254. static void ggml_compute_forward_ssm_scan(
  13255. const struct ggml_compute_params * params,
  13256. struct ggml_tensor * dst) {
  13257. switch (dst->src[0]->type) {
  13258. case GGML_TYPE_F32:
  13259. {
  13260. ggml_compute_forward_ssm_scan_f32(params, dst);
  13261. } break;
  13262. default:
  13263. {
  13264. GGML_ABORT("fatal error");
  13265. }
  13266. }
  13267. }
  13268. // ggml_compute_forward_win_part
  13269. static void ggml_compute_forward_win_part_f32(
  13270. const struct ggml_compute_params * params,
  13271. struct ggml_tensor * dst) {
  13272. UNUSED(params);
  13273. const struct ggml_tensor * src0 = dst->src[0];
  13274. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  13275. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  13276. const int32_t nep0 = ((const int32_t *)(dst->op_params))[0];
  13277. const int32_t nep1 = ((const int32_t *)(dst->op_params))[1];
  13278. const int32_t w = ((const int32_t *)(dst->op_params))[2];
  13279. assert(ne00 == ne0);
  13280. assert(ne3 == nep0*nep1);
  13281. // TODO: optimize / multi-thread
  13282. for (int py = 0; py < nep1; ++py) {
  13283. for (int px = 0; px < nep0; ++px) {
  13284. const int64_t i3 = py*nep0 + px;
  13285. for (int64_t i2 = 0; i2 < ne2; ++i2) {
  13286. for (int64_t i1 = 0; i1 < ne1; ++i1) {
  13287. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  13288. const int64_t i02 = py*w + i2;
  13289. const int64_t i01 = px*w + i1;
  13290. const int64_t i00 = i0;
  13291. const int64_t i = i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0 + i0;
  13292. const int64_t j = i02*ne01*ne00 + i01*ne00 + i00;
  13293. if (py*w + i2 >= ne02 || px*w + i1 >= ne01) {
  13294. ((float *) dst->data)[i] = 0.0f;
  13295. } else {
  13296. ((float *) dst->data)[i] = ((float *) src0->data)[j];
  13297. }
  13298. }
  13299. }
  13300. }
  13301. }
  13302. }
  13303. }
  13304. static void ggml_compute_forward_win_part(
  13305. const struct ggml_compute_params * params,
  13306. struct ggml_tensor * dst) {
  13307. const struct ggml_tensor * src0 = dst->src[0];
  13308. switch (src0->type) {
  13309. case GGML_TYPE_F32:
  13310. {
  13311. ggml_compute_forward_win_part_f32(params, dst);
  13312. } break;
  13313. default:
  13314. {
  13315. GGML_ABORT("fatal error");
  13316. }
  13317. }
  13318. }
  13319. // ggml_compute_forward_win_unpart
  13320. static void ggml_compute_forward_win_unpart_f32(
  13321. const struct ggml_compute_params * params,
  13322. struct ggml_tensor * dst) {
  13323. UNUSED(params);
  13324. const struct ggml_tensor * src0 = dst->src[0];
  13325. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  13326. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  13327. const int32_t w = ((const int32_t *)(dst->op_params))[0];
  13328. // padding
  13329. const int px = (w - ne1%w)%w;
  13330. //const int py = (w - ne2%w)%w;
  13331. const int npx = (px + ne1)/w;
  13332. //const int npy = (py + ne2)/w;
  13333. assert(ne0 == ne00);
  13334. // TODO: optimize / multi-thread
  13335. for (int64_t i2 = 0; i2 < ne2; ++i2) {
  13336. for (int64_t i1 = 0; i1 < ne1; ++i1) {
  13337. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  13338. const int ip2 = i2/w;
  13339. const int ip1 = i1/w;
  13340. const int64_t i02 = i2%w;
  13341. const int64_t i01 = i1%w;
  13342. const int64_t i00 = i0;
  13343. const int64_t i = (ip2*npx + ip1)*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00 + i00;
  13344. const int64_t j = i2*ne1*ne0 + i1*ne0 + i0;
  13345. ((float *) dst->data)[j] = ((float *) src0->data)[i];
  13346. }
  13347. }
  13348. }
  13349. }
  13350. static void ggml_compute_forward_win_unpart(
  13351. const struct ggml_compute_params * params,
  13352. struct ggml_tensor * dst) {
  13353. const struct ggml_tensor * src0 = dst->src[0];
  13354. switch (src0->type) {
  13355. case GGML_TYPE_F32:
  13356. {
  13357. ggml_compute_forward_win_unpart_f32(params, dst);
  13358. } break;
  13359. default:
  13360. {
  13361. GGML_ABORT("fatal error");
  13362. }
  13363. }
  13364. }
  13365. //gmml_compute_forward_unary
  13366. static void ggml_compute_forward_unary(
  13367. const struct ggml_compute_params * params,
  13368. struct ggml_tensor * dst) {
  13369. const enum ggml_unary_op op = ggml_get_unary_op(dst);
  13370. switch (op) {
  13371. case GGML_UNARY_OP_ABS:
  13372. {
  13373. ggml_compute_forward_abs(params, dst);
  13374. } break;
  13375. case GGML_UNARY_OP_SGN:
  13376. {
  13377. ggml_compute_forward_sgn(params, dst);
  13378. } break;
  13379. case GGML_UNARY_OP_NEG:
  13380. {
  13381. ggml_compute_forward_neg(params, dst);
  13382. } break;
  13383. case GGML_UNARY_OP_STEP:
  13384. {
  13385. ggml_compute_forward_step(params, dst);
  13386. } break;
  13387. case GGML_UNARY_OP_TANH:
  13388. {
  13389. ggml_compute_forward_tanh(params, dst);
  13390. } break;
  13391. case GGML_UNARY_OP_ELU:
  13392. {
  13393. ggml_compute_forward_elu(params, dst);
  13394. } break;
  13395. case GGML_UNARY_OP_RELU:
  13396. {
  13397. ggml_compute_forward_relu(params, dst);
  13398. } break;
  13399. case GGML_UNARY_OP_SIGMOID:
  13400. {
  13401. ggml_compute_forward_sigmoid(params, dst);
  13402. } break;
  13403. case GGML_UNARY_OP_GELU:
  13404. {
  13405. ggml_compute_forward_gelu(params, dst);
  13406. } break;
  13407. case GGML_UNARY_OP_GELU_QUICK:
  13408. {
  13409. ggml_compute_forward_gelu_quick(params, dst);
  13410. } break;
  13411. case GGML_UNARY_OP_SILU:
  13412. {
  13413. ggml_compute_forward_silu(params, dst);
  13414. } break;
  13415. case GGML_UNARY_OP_HARDSWISH:
  13416. {
  13417. ggml_compute_forward_hardswish(params, dst);
  13418. } break;
  13419. case GGML_UNARY_OP_HARDSIGMOID:
  13420. {
  13421. ggml_compute_forward_hardsigmoid(params, dst);
  13422. } break;
  13423. case GGML_UNARY_OP_EXP:
  13424. {
  13425. ggml_compute_forward_exp(params, dst);
  13426. } break;
  13427. default:
  13428. {
  13429. GGML_ABORT("fatal error");
  13430. }
  13431. }
  13432. }
  13433. // ggml_compute_forward_get_rel_pos
  13434. static void ggml_compute_forward_get_rel_pos_f16(
  13435. const struct ggml_compute_params * params,
  13436. struct ggml_tensor * dst) {
  13437. UNUSED(params);
  13438. const struct ggml_tensor * src0 = dst->src[0];
  13439. // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L292-L322
  13440. GGML_TENSOR_UNARY_OP_LOCALS
  13441. const int64_t w = ne1;
  13442. ggml_fp16_t * src0_data = (ggml_fp16_t *) src0->data;
  13443. ggml_fp16_t * dst_data = (ggml_fp16_t *) dst->data;
  13444. for (int64_t i2 = 0; i2 < ne2; ++i2) {
  13445. for (int64_t i1 = 0; i1 < ne1; ++i1) {
  13446. const int64_t pos = (w - i1 - 1) + i2;
  13447. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  13448. dst_data[i2*ne1*ne0 + i1*ne0 + i0] = src0_data[pos*ne00 + i0];
  13449. }
  13450. }
  13451. }
  13452. }
  13453. static void ggml_compute_forward_get_rel_pos(
  13454. const struct ggml_compute_params * params,
  13455. struct ggml_tensor * dst) {
  13456. const struct ggml_tensor * src0 = dst->src[0];
  13457. switch (src0->type) {
  13458. case GGML_TYPE_F16:
  13459. case GGML_TYPE_BF16:
  13460. {
  13461. ggml_compute_forward_get_rel_pos_f16(params, dst);
  13462. } break;
  13463. default:
  13464. {
  13465. GGML_ABORT("fatal error");
  13466. }
  13467. }
  13468. }
  13469. // ggml_compute_forward_add_rel_pos
  13470. static void ggml_compute_forward_add_rel_pos_f32(
  13471. const struct ggml_compute_params * params,
  13472. struct ggml_tensor * dst) {
  13473. const struct ggml_tensor * src0 = dst->src[0];
  13474. const struct ggml_tensor * src1 = dst->src[1];
  13475. const struct ggml_tensor * src2 = dst->src[2];
  13476. const bool inplace = (bool) ((int32_t *) dst->op_params)[0];
  13477. if (!inplace) {
  13478. if (params->ith == 0) {
  13479. memcpy((char *) dst->data, (char *) src0->data, ggml_nbytes(dst));
  13480. }
  13481. ggml_barrier(params->threadpool);
  13482. }
  13483. // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L357-L359
  13484. float * src1_data = (float *) src1->data;
  13485. float * src2_data = (float *) src2->data;
  13486. float * dst_data = (float *) dst->data;
  13487. const int64_t ne10 = src1->ne[0];
  13488. const int64_t ne11 = src1->ne[1];
  13489. const int64_t ne12 = src1->ne[2];
  13490. const int64_t ne13 = src1->ne[3];
  13491. const int ith = params->ith;
  13492. const int nth = params->nth;
  13493. // total patches in dst
  13494. const int np = ne13;
  13495. // patches per thread
  13496. const int dp = (np + nth - 1)/nth;
  13497. // patch range for this thread
  13498. const int ip0 = dp*ith;
  13499. const int ip1 = MIN(ip0 + dp, np);
  13500. for (int64_t i13 = ip0; i13 < ip1; ++i13) {
  13501. for (int64_t i12 = 0; i12 < ne12; ++i12) {
  13502. for (int64_t i11 = 0; i11 < ne11; ++i11) {
  13503. const int64_t jp1 = i13*ne12*ne11*ne10 + i12*ne11*ne10 + i11*ne10;
  13504. for (int64_t i10 = 0; i10 < ne10; ++i10) {
  13505. const int64_t jp0 = jp1 + i10;
  13506. const float src1_e = src1_data[jp0];
  13507. const float src2_e = src2_data[jp0];
  13508. const int64_t jdh = jp0 * ne10;
  13509. const int64_t jdw = jdh - (ne10 - 1) * i10;
  13510. for (int64_t j = 0; j < ne10; ++j) {
  13511. dst_data[jdh + j ] += src2_e;
  13512. dst_data[jdw + j*ne10] += src1_e;
  13513. }
  13514. }
  13515. }
  13516. }
  13517. }
  13518. }
  13519. static void ggml_compute_forward_add_rel_pos(
  13520. const struct ggml_compute_params * params,
  13521. struct ggml_tensor * dst) {
  13522. const struct ggml_tensor * src0 = dst->src[0];
  13523. switch (src0->type) {
  13524. case GGML_TYPE_F32:
  13525. {
  13526. ggml_compute_forward_add_rel_pos_f32(params, dst);
  13527. } break;
  13528. default:
  13529. {
  13530. GGML_ABORT("fatal error");
  13531. }
  13532. }
  13533. }
  13534. // ggml_compute_forward_rwkv_wkv
  13535. static void ggml_compute_forward_rwkv_wkv_f32(
  13536. const struct ggml_compute_params * params,
  13537. struct ggml_tensor * dst) {
  13538. const size_t T = dst->src[1]->ne[3];
  13539. const size_t C = dst->ne[0];
  13540. const size_t H = dst->src[1]->ne[2];
  13541. const size_t n_seqs = dst->src[5]->ne[1];
  13542. float * dst_data = (float *) dst->data;
  13543. float * state = ((float *) dst->data) + C * T;
  13544. if (params->ith != 0) {
  13545. return;
  13546. }
  13547. memset(dst_data, 0, T * C * sizeof(float));
  13548. float * k = (float *) dst->src[0]->data;
  13549. float * v = (float *) dst->src[1]->data;
  13550. float * r = (float *) dst->src[2]->data;
  13551. float * time_faaaa = (float *) dst->src[3]->data;
  13552. float * time_decay = (float *) dst->src[4]->data;
  13553. size_t t_stride = H * (C / H);
  13554. size_t h_stride = C / H;
  13555. size_t h_stride_2d = (C / H) * (C / H);
  13556. // basically fused operations:
  13557. // dst = r @ (time_faaaa * (k @ v) + state),
  13558. // state = time_decay * state + (k @ v),
  13559. // recursive through each token
  13560. for (size_t t = 0; t < T; t++) {
  13561. size_t t_offset = t * t_stride;
  13562. size_t state_offset = (C / H) * C * (t / (T / n_seqs));
  13563. float * state_cur = state + state_offset;
  13564. float * state_prev = t % (T / n_seqs) ? state_cur : (float*)dst->src[5]->data + state_offset;
  13565. for (size_t h = 0; h < H; h++) {
  13566. size_t h_offset = h * h_stride;
  13567. size_t t_h_offset = t_offset + h_offset;
  13568. size_t h_2d_offset = h * h_stride_2d;
  13569. for (size_t i = 0; i < C / H; i++) {
  13570. size_t t_h_i_offset = t_h_offset + i;
  13571. size_t h_i_offset = h_offset + i;
  13572. size_t h_2d_i_offset = h_2d_offset + i * h_stride;
  13573. float k_val = k[t_h_i_offset];
  13574. float r_val = r[t_h_i_offset];
  13575. float time_faaaa_val = time_faaaa[h_i_offset];
  13576. // RWKV v6: different time_decay for each token.
  13577. float time_decay_val = time_decay[t_h_i_offset];
  13578. for (size_t j = 0; j < C / H; j ++) {
  13579. size_t t_h_j_offset = t_h_offset + j;
  13580. size_t h_2d_i_j_offset = h_2d_i_offset + j;
  13581. float v_val = v[t_h_j_offset];
  13582. float kv_val = v_val * k_val;
  13583. float prev_state_val = state_prev[h_2d_i_j_offset];
  13584. float temp_val = kv_val * time_faaaa_val + prev_state_val;
  13585. dst_data[t_h_j_offset] += temp_val * r_val;
  13586. state_cur[h_2d_i_j_offset] = prev_state_val * time_decay_val + kv_val;
  13587. }
  13588. }
  13589. }
  13590. }
  13591. }
  13592. static void ggml_compute_forward_rwkv_wkv(
  13593. const struct ggml_compute_params * params,
  13594. struct ggml_tensor * dst) {
  13595. const struct ggml_tensor * src0 = dst->src[0];
  13596. switch (src0->type) {
  13597. case GGML_TYPE_F32:
  13598. {
  13599. ggml_compute_forward_rwkv_wkv_f32(params, dst);
  13600. } break;
  13601. default:
  13602. {
  13603. GGML_ABORT("fatal error");
  13604. }
  13605. }
  13606. }
  13607. // ggml_compute_forward_map_unary
  13608. static void ggml_compute_forward_map_unary_f32(
  13609. const struct ggml_compute_params * params,
  13610. struct ggml_tensor * dst,
  13611. const ggml_unary_op_f32_t fun) {
  13612. const struct ggml_tensor * src0 = dst->src[0];
  13613. if (params->ith != 0) {
  13614. return;
  13615. }
  13616. assert(ggml_is_contiguous_1(src0));
  13617. assert(ggml_is_contiguous_1(dst));
  13618. assert(ggml_are_same_shape(src0, dst));
  13619. const int n = ggml_nrows(src0);
  13620. const int nc = src0->ne[0];
  13621. for (int i = 0; i < n; i++) {
  13622. fun(nc,
  13623. (float *) ((char *) dst->data + i*( dst->nb[1])),
  13624. (float *) ((char *) src0->data + i*(src0->nb[1])));
  13625. }
  13626. }
  13627. static void ggml_compute_forward_map_unary(
  13628. const struct ggml_compute_params * params,
  13629. struct ggml_tensor * dst,
  13630. const ggml_unary_op_f32_t fun) {
  13631. const struct ggml_tensor * src0 = dst->src[0];
  13632. switch (src0->type) {
  13633. case GGML_TYPE_F32:
  13634. {
  13635. ggml_compute_forward_map_unary_f32(params, dst, fun);
  13636. } break;
  13637. default:
  13638. {
  13639. GGML_ABORT("fatal error");
  13640. }
  13641. }
  13642. }
  13643. // ggml_compute_forward_map_binary
  13644. static void ggml_compute_forward_map_binary_f32(
  13645. const struct ggml_compute_params * params,
  13646. struct ggml_tensor * dst,
  13647. const ggml_binary_op_f32_t fun) {
  13648. const struct ggml_tensor * src0 = dst->src[0];
  13649. const struct ggml_tensor * src1 = dst->src[1];
  13650. if (params->ith != 0) {
  13651. return;
  13652. }
  13653. assert(ggml_is_contiguous_1(src0));
  13654. assert(ggml_is_contiguous_1(src1));
  13655. assert(ggml_is_contiguous_1(dst));
  13656. assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  13657. const int n = ggml_nrows(src0);
  13658. const int nc = src0->ne[0];
  13659. for (int i = 0; i < n; i++) {
  13660. fun(nc,
  13661. (float *) ((char *) dst->data + i*( dst->nb[1])),
  13662. (float *) ((char *) src0->data + i*(src0->nb[1])),
  13663. (float *) ((char *) src1->data + i*(src1->nb[1])));
  13664. }
  13665. }
  13666. static void ggml_compute_forward_map_binary(
  13667. const struct ggml_compute_params * params,
  13668. struct ggml_tensor * dst,
  13669. const ggml_binary_op_f32_t fun) {
  13670. const struct ggml_tensor * src0 = dst->src[0];
  13671. switch (src0->type) {
  13672. case GGML_TYPE_F32:
  13673. {
  13674. ggml_compute_forward_map_binary_f32(params, dst, fun);
  13675. } break;
  13676. default:
  13677. {
  13678. GGML_ABORT("fatal error");
  13679. }
  13680. }
  13681. }
  13682. // ggml_compute_forward_map_custom1
  13683. static void ggml_compute_forward_map_custom1_f32(
  13684. const struct ggml_compute_params * params,
  13685. struct ggml_tensor * dst,
  13686. const ggml_custom1_op_f32_t fun) {
  13687. const struct ggml_tensor * a = dst->src[0];
  13688. if (params->ith != 0) {
  13689. return;
  13690. }
  13691. fun(dst, a);
  13692. }
  13693. // ggml_compute_forward_map_custom2
  13694. static void ggml_compute_forward_map_custom2_f32(
  13695. const struct ggml_compute_params * params,
  13696. struct ggml_tensor * dst,
  13697. const ggml_custom2_op_f32_t fun) {
  13698. const struct ggml_tensor * a = dst->src[0];
  13699. const struct ggml_tensor * b = dst->src[1];
  13700. if (params->ith != 0) {
  13701. return;
  13702. }
  13703. fun(dst, a, b);
  13704. }
  13705. // ggml_compute_forward_map_custom3
  13706. static void ggml_compute_forward_map_custom3_f32(
  13707. const struct ggml_compute_params * params,
  13708. struct ggml_tensor * dst,
  13709. const ggml_custom3_op_f32_t fun) {
  13710. const struct ggml_tensor * a = dst->src[0];
  13711. const struct ggml_tensor * b = dst->src[1];
  13712. const struct ggml_tensor * c = dst->src[1];
  13713. if (params->ith != 0) {
  13714. return;
  13715. }
  13716. fun(dst, a, b, c);
  13717. }
  13718. // ggml_compute_forward_map_custom1
  13719. static void ggml_compute_forward_map_custom1(
  13720. const struct ggml_compute_params * params,
  13721. struct ggml_tensor * dst) {
  13722. const struct ggml_tensor * a = dst->src[0];
  13723. struct ggml_map_custom1_op_params p;
  13724. memcpy(&p, dst->op_params, sizeof(p));
  13725. p.fun(dst, a, params->ith, params->nth, p.userdata);
  13726. }
  13727. // ggml_compute_forward_map_custom2
  13728. static void ggml_compute_forward_map_custom2(
  13729. const struct ggml_compute_params * params,
  13730. struct ggml_tensor * dst) {
  13731. const struct ggml_tensor * a = dst->src[0];
  13732. const struct ggml_tensor * b = dst->src[1];
  13733. struct ggml_map_custom2_op_params p;
  13734. memcpy(&p, dst->op_params, sizeof(p));
  13735. p.fun(dst, a, b, params->ith, params->nth, p.userdata);
  13736. }
  13737. // ggml_compute_forward_map_custom3
  13738. static void ggml_compute_forward_map_custom3(
  13739. const struct ggml_compute_params * params,
  13740. struct ggml_tensor * dst) {
  13741. const struct ggml_tensor * a = dst->src[0];
  13742. const struct ggml_tensor * b = dst->src[1];
  13743. const struct ggml_tensor * c = dst->src[2];
  13744. struct ggml_map_custom3_op_params p;
  13745. memcpy(&p, dst->op_params, sizeof(p));
  13746. p.fun(dst, a, b, c, params->ith, params->nth, p.userdata);
  13747. }
  13748. // ggml_compute_forward_cross_entropy_loss
  13749. static void ggml_compute_forward_cross_entropy_loss_f32(
  13750. const struct ggml_compute_params * params,
  13751. struct ggml_tensor * dst) {
  13752. const struct ggml_tensor * src0 = dst->src[0];
  13753. const struct ggml_tensor * src1 = dst->src[1];
  13754. GGML_ASSERT(ggml_is_contiguous(src0));
  13755. GGML_ASSERT(ggml_is_contiguous(src1));
  13756. GGML_ASSERT(ggml_is_scalar(dst));
  13757. GGML_ASSERT(ggml_are_same_shape(src0, src1));
  13758. const int ith = params->ith;
  13759. const int nth = params->nth;
  13760. float * sums = (float *) params->wdata;
  13761. // TODO: handle transposed/permuted matrices
  13762. const int nc = src0->ne[0];
  13763. const int nr = ggml_nrows(src0);
  13764. GGML_ASSERT(params->wsize >= sizeof(float) * (nth + nth * nc));
  13765. if (ith == 0) {
  13766. memset(sums, 0, sizeof(float) * (nth + nth * nc));
  13767. }
  13768. ggml_barrier(params->threadpool);
  13769. // rows per thread
  13770. const int dr = (nr + nth - 1)/nth;
  13771. // row range for this thread
  13772. const int ir0 = dr*ith;
  13773. const int ir1 = MIN(ir0 + dr, nr);
  13774. for (int i1 = ir0; i1 < ir1; i1++) {
  13775. float * s0 = (float *)((char *) src0->data + i1*src0->nb[1]);
  13776. float * s1 = (float *)((char *) src1->data + i1*src1->nb[1]);
  13777. float * st = ((float *) params->wdata) + nth + ith*nc;
  13778. #ifndef NDEBUG
  13779. for (int i = 0; i < nc; ++i) {
  13780. //printf("p[%d] = %f\n", i, p[i]);
  13781. assert(!isnan(s0[i]));
  13782. assert(!isnan(s1[i]));
  13783. }
  13784. #endif
  13785. float max = -INFINITY;
  13786. ggml_vec_max_f32(nc, &max, s0);
  13787. ggml_float sum = ggml_vec_log_soft_max_f32(nc, st, s0, max);
  13788. assert(sum >= 0.0);
  13789. ggml_vec_add1_f32(nc, st, st, -sum);
  13790. ggml_vec_mul_f32(nc, st, st, s1);
  13791. float st_sum = 0.0f;
  13792. ggml_vec_sum_f32(nc, &st_sum, st);
  13793. sums[ith] += st_sum;
  13794. #ifndef NDEBUG
  13795. for (int i = 0; i < nc; ++i) {
  13796. assert(!isnan(st[i]));
  13797. assert(!isinf(st[i]));
  13798. }
  13799. #endif
  13800. }
  13801. ggml_barrier(params->threadpool);
  13802. if (ith == 0) {
  13803. float * dp = (float *) dst->data;
  13804. ggml_vec_sum_f32(nth, dp, sums);
  13805. dp[0] *= -1.0f / (float) nr;
  13806. }
  13807. }
  13808. static void ggml_compute_forward_cross_entropy_loss(
  13809. const struct ggml_compute_params * params,
  13810. struct ggml_tensor * dst) {
  13811. const struct ggml_tensor * src0 = dst->src[0];
  13812. switch (src0->type) {
  13813. case GGML_TYPE_F32:
  13814. {
  13815. ggml_compute_forward_cross_entropy_loss_f32(params, dst);
  13816. } break;
  13817. default:
  13818. {
  13819. GGML_ABORT("fatal error");
  13820. }
  13821. }
  13822. }
  13823. // ggml_compute_forward_cross_entropy_loss_back
  13824. static void ggml_compute_forward_cross_entropy_loss_back_f32(
  13825. const struct ggml_compute_params * params,
  13826. struct ggml_tensor * dst) {
  13827. const struct ggml_tensor * src0 = dst->src[0];
  13828. const struct ggml_tensor * src1 = dst->src[1];
  13829. const struct ggml_tensor * opt0 = dst->src[2];
  13830. GGML_ASSERT(ggml_is_contiguous(dst));
  13831. GGML_ASSERT(ggml_is_contiguous(src0));
  13832. GGML_ASSERT(ggml_is_contiguous(src1));
  13833. GGML_ASSERT(ggml_is_contiguous(opt0));
  13834. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  13835. const int64_t ith = params->ith;
  13836. const int64_t nth = params->nth;
  13837. // TODO: handle transposed/permuted matrices
  13838. const int64_t nc = src0->ne[0];
  13839. const int64_t nr = ggml_nrows(src0);
  13840. // rows per thread
  13841. const int64_t dr = (nr + nth - 1)/nth;
  13842. // row range for this thread
  13843. const int64_t ir0 = dr*ith;
  13844. const int64_t ir1 = MIN(ir0 + dr, nr);
  13845. const float d_by_nr = ((const float *) opt0->data)[0] / (float) nr;
  13846. for (int64_t i1 = ir0; i1 < ir1; i1++) {
  13847. float * ds0 = (float *)((char *) dst->data + i1*dst->nb[1]);
  13848. float * s0 = (float *)((char *) src0->data + i1*src0->nb[1]);
  13849. float * s1 = (float *)((char *) src1->data + i1*src1->nb[1]);
  13850. #ifndef NDEBUG
  13851. for (int i = 0; i < nc; ++i) {
  13852. //printf("p[%d] = %f\n", i, p[i]);
  13853. assert(!isnan(s0[i]));
  13854. assert(!isnan(s1[i]));
  13855. }
  13856. #endif
  13857. // soft_max
  13858. float max = -INFINITY;
  13859. ggml_vec_max_f32(nc, &max, s0);
  13860. ggml_float sum = ggml_vec_soft_max_f32(nc, ds0, s0, max);
  13861. assert(sum > 0.0);
  13862. ggml_vec_scale_f32(nc, ds0, 1.0/sum);
  13863. // grad(src0) = (softmax(src0) - src1) * grad(cross_entropy_loss(src0, src1)) / nr
  13864. ggml_vec_sub_f32(nc, ds0, ds0, s1);
  13865. ggml_vec_scale_f32(nc, ds0, d_by_nr);
  13866. #ifndef NDEBUG
  13867. for (int i = 0; i < nc; ++i) {
  13868. assert(!isnan(ds0[i]));
  13869. assert(!isinf(ds0[i]));
  13870. }
  13871. #endif
  13872. }
  13873. }
  13874. static void ggml_compute_forward_cross_entropy_loss_back(
  13875. const struct ggml_compute_params * params,
  13876. struct ggml_tensor * dst) {
  13877. const struct ggml_tensor * src0 = dst->src[0];
  13878. switch (src0->type) {
  13879. case GGML_TYPE_F32:
  13880. {
  13881. ggml_compute_forward_cross_entropy_loss_back_f32(params, dst);
  13882. } break;
  13883. default:
  13884. {
  13885. GGML_ABORT("fatal error");
  13886. }
  13887. }
  13888. }
  13889. static void ggml_compute_forward_opt_step_adamw_f32(
  13890. const struct ggml_compute_params * params,
  13891. struct ggml_tensor * dst) {
  13892. const struct ggml_tensor * src0 = dst->src[0];
  13893. const struct ggml_tensor * src0_grad = dst->src[1];
  13894. const struct ggml_tensor * src0_grad_m = dst->src[2];
  13895. const struct ggml_tensor * src0_grad_v = dst->src[3];
  13896. GGML_ASSERT(ggml_are_same_shape(src0, src0_grad));
  13897. const int ith = params->ith;
  13898. const int nth = params->nth;
  13899. const int nr = ggml_nrows(src0);
  13900. GGML_TENSOR_UNARY_OP_LOCALS
  13901. GGML_ASSERT(nb00 == sizeof(float));
  13902. // rows per thread
  13903. const int dr = (nr + nth - 1)/nth;
  13904. // row range for this thread
  13905. const int ir0 = dr*ith;
  13906. const int ir1 = MIN(ir0 + dr, nr);
  13907. /* const float gnorm = 1.0f; */
  13908. int64_t iter; memcpy(&iter, &dst->op_params[0], sizeof(int64_t));
  13909. const float alpha = ggml_get_op_params_f32(dst, 2);
  13910. const float beta1 = ggml_get_op_params_f32(dst, 3);
  13911. const float beta2 = ggml_get_op_params_f32(dst, 4);
  13912. const float eps = ggml_get_op_params_f32(dst, 5);
  13913. const float wd = ggml_get_op_params_f32(dst, 6);
  13914. const float beta1h = alpha/(1.0f - powf(beta1, iter));
  13915. const float beta2h = 1.0f/(1.0f - powf(beta2, iter));
  13916. for (int ir = ir0; ir < ir1; ++ir) {
  13917. const int64_t i03 = ir/(ne02*ne01);
  13918. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  13919. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  13920. const size_t offset = i03*nb03 + i02*nb02 + i01*nb01;
  13921. float * w = (float *) ((char *) src0->data + offset); // weight
  13922. const float * g = (const float *) ((const char *) src0_grad->data + offset); // grad
  13923. float * m = (float *) ((char *) src0_grad_m->data + offset);
  13924. float * v = (float *) ((char *) src0_grad_v->data + offset);
  13925. for (int i00 = 0; i00 < ne00; ++i00) {
  13926. m[i00] = m[i00]*beta1 + g[i00]*(1.0f - beta1);
  13927. v[i00] = v[i00]*beta2 + g[i00]*g[i00]*(1.0f - beta2);
  13928. const float mh = m[i00]*beta1h;
  13929. const float vh = sqrtf(v[i00]*beta2h) + eps;
  13930. // The weight decay is applied independently of the Adam momenta m and v.
  13931. // This is NOT equivalent to l2 regularization that adds w[i00]*w[i00] to the loss.
  13932. // See: https://arxiv.org/pdf/1711.05101v3.pdf
  13933. w[i00] = w[i00]*(1.0f - alpha*wd) - mh/vh;
  13934. }
  13935. }
  13936. ggml_barrier(params->threadpool);
  13937. if (ith != 0) {
  13938. return;
  13939. }
  13940. iter++;
  13941. memcpy(&dst->op_params[0], &iter, sizeof(int64_t));
  13942. }
  13943. static void ggml_compute_forward_opt_step_adamw(
  13944. const struct ggml_compute_params * params,
  13945. struct ggml_tensor * dst) {
  13946. const struct ggml_tensor * src0 = dst->src[0];
  13947. switch (src0->type) {
  13948. case GGML_TYPE_F32:
  13949. {
  13950. ggml_compute_forward_opt_step_adamw_f32(params, dst);
  13951. } break;
  13952. default:
  13953. {
  13954. GGML_ABORT("fatal error");
  13955. }
  13956. }
  13957. }
  13958. /////////////////////////////////
  13959. static void ggml_compute_forward(struct ggml_compute_params * params, struct ggml_tensor * tensor) {
  13960. GGML_ASSERT(params);
  13961. if (tensor->op == GGML_OP_NONE || ggml_is_empty(tensor)) {
  13962. return;
  13963. }
  13964. switch (tensor->op) {
  13965. case GGML_OP_DUP:
  13966. {
  13967. ggml_compute_forward_dup(params, tensor);
  13968. } break;
  13969. case GGML_OP_ADD:
  13970. {
  13971. ggml_compute_forward_add(params, tensor);
  13972. } break;
  13973. case GGML_OP_ADD1:
  13974. {
  13975. ggml_compute_forward_add1(params, tensor);
  13976. } break;
  13977. case GGML_OP_ACC:
  13978. {
  13979. ggml_compute_forward_acc(params, tensor);
  13980. } break;
  13981. case GGML_OP_SUB:
  13982. {
  13983. ggml_compute_forward_sub(params, tensor);
  13984. } break;
  13985. case GGML_OP_MUL:
  13986. {
  13987. ggml_compute_forward_mul(params, tensor);
  13988. } break;
  13989. case GGML_OP_DIV:
  13990. {
  13991. ggml_compute_forward_div(params, tensor);
  13992. } break;
  13993. case GGML_OP_SQR:
  13994. {
  13995. ggml_compute_forward_sqr(params, tensor);
  13996. } break;
  13997. case GGML_OP_SQRT:
  13998. {
  13999. ggml_compute_forward_sqrt(params, tensor);
  14000. } break;
  14001. case GGML_OP_LOG:
  14002. {
  14003. ggml_compute_forward_log(params, tensor);
  14004. } break;
  14005. case GGML_OP_SIN:
  14006. {
  14007. ggml_compute_forward_sin(params, tensor);
  14008. } break;
  14009. case GGML_OP_COS:
  14010. {
  14011. ggml_compute_forward_cos(params, tensor);
  14012. } break;
  14013. case GGML_OP_SUM:
  14014. {
  14015. ggml_compute_forward_sum(params, tensor);
  14016. } break;
  14017. case GGML_OP_SUM_ROWS:
  14018. {
  14019. ggml_compute_forward_sum_rows(params, tensor);
  14020. } break;
  14021. case GGML_OP_MEAN:
  14022. {
  14023. ggml_compute_forward_mean(params, tensor);
  14024. } break;
  14025. case GGML_OP_ARGMAX:
  14026. {
  14027. ggml_compute_forward_argmax(params, tensor);
  14028. } break;
  14029. case GGML_OP_REPEAT:
  14030. {
  14031. ggml_compute_forward_repeat(params, tensor);
  14032. } break;
  14033. case GGML_OP_REPEAT_BACK:
  14034. {
  14035. ggml_compute_forward_repeat_back(params, tensor);
  14036. } break;
  14037. case GGML_OP_CONCAT:
  14038. {
  14039. ggml_compute_forward_concat(params, tensor);
  14040. } break;
  14041. case GGML_OP_SILU_BACK:
  14042. {
  14043. ggml_compute_forward_silu_back(params, tensor);
  14044. } break;
  14045. case GGML_OP_NORM:
  14046. {
  14047. ggml_compute_forward_norm(params, tensor);
  14048. } break;
  14049. case GGML_OP_RMS_NORM:
  14050. {
  14051. ggml_compute_forward_rms_norm(params, tensor);
  14052. } break;
  14053. case GGML_OP_RMS_NORM_BACK:
  14054. {
  14055. ggml_compute_forward_rms_norm_back(params, tensor);
  14056. } break;
  14057. case GGML_OP_GROUP_NORM:
  14058. {
  14059. ggml_compute_forward_group_norm(params, tensor);
  14060. } break;
  14061. case GGML_OP_MUL_MAT:
  14062. {
  14063. ggml_compute_forward_mul_mat(params, tensor);
  14064. } break;
  14065. case GGML_OP_MUL_MAT_ID:
  14066. {
  14067. ggml_compute_forward_mul_mat_id(params, tensor);
  14068. } break;
  14069. case GGML_OP_OUT_PROD:
  14070. {
  14071. ggml_compute_forward_out_prod(params, tensor);
  14072. } break;
  14073. case GGML_OP_SCALE:
  14074. {
  14075. ggml_compute_forward_scale(params, tensor);
  14076. } break;
  14077. case GGML_OP_SET:
  14078. {
  14079. ggml_compute_forward_set(params, tensor);
  14080. } break;
  14081. case GGML_OP_CPY:
  14082. {
  14083. ggml_compute_forward_cpy(params, tensor);
  14084. } break;
  14085. case GGML_OP_CONT:
  14086. {
  14087. ggml_compute_forward_cont(params, tensor);
  14088. } break;
  14089. case GGML_OP_RESHAPE:
  14090. {
  14091. ggml_compute_forward_reshape(params, tensor);
  14092. } break;
  14093. case GGML_OP_VIEW:
  14094. {
  14095. ggml_compute_forward_view(params, tensor);
  14096. } break;
  14097. case GGML_OP_PERMUTE:
  14098. {
  14099. ggml_compute_forward_permute(params, tensor);
  14100. } break;
  14101. case GGML_OP_TRANSPOSE:
  14102. {
  14103. ggml_compute_forward_transpose(params, tensor);
  14104. } break;
  14105. case GGML_OP_GET_ROWS:
  14106. {
  14107. ggml_compute_forward_get_rows(params, tensor);
  14108. } break;
  14109. case GGML_OP_GET_ROWS_BACK:
  14110. {
  14111. ggml_compute_forward_get_rows_back(params, tensor);
  14112. } break;
  14113. case GGML_OP_DIAG:
  14114. {
  14115. ggml_compute_forward_diag(params, tensor);
  14116. } break;
  14117. case GGML_OP_DIAG_MASK_INF:
  14118. {
  14119. ggml_compute_forward_diag_mask_inf(params, tensor);
  14120. } break;
  14121. case GGML_OP_DIAG_MASK_ZERO:
  14122. {
  14123. ggml_compute_forward_diag_mask_zero(params, tensor);
  14124. } break;
  14125. case GGML_OP_SOFT_MAX:
  14126. {
  14127. ggml_compute_forward_soft_max(params, tensor);
  14128. } break;
  14129. case GGML_OP_SOFT_MAX_BACK:
  14130. {
  14131. ggml_compute_forward_soft_max_back(params, tensor);
  14132. } break;
  14133. case GGML_OP_ROPE:
  14134. {
  14135. ggml_compute_forward_rope(params, tensor);
  14136. } break;
  14137. case GGML_OP_ROPE_BACK:
  14138. {
  14139. ggml_compute_forward_rope_back(params, tensor);
  14140. } break;
  14141. case GGML_OP_CLAMP:
  14142. {
  14143. ggml_compute_forward_clamp(params, tensor);
  14144. } break;
  14145. case GGML_OP_CONV_TRANSPOSE_1D:
  14146. {
  14147. ggml_compute_forward_conv_transpose_1d(params, tensor);
  14148. } break;
  14149. case GGML_OP_IM2COL:
  14150. {
  14151. ggml_compute_forward_im2col(params, tensor);
  14152. } break;
  14153. case GGML_OP_IM2COL_BACK:
  14154. {
  14155. ggml_compute_forward_im2col_back_f32(params, tensor);
  14156. } break;
  14157. case GGML_OP_CONV_TRANSPOSE_2D:
  14158. {
  14159. ggml_compute_forward_conv_transpose_2d(params, tensor);
  14160. } break;
  14161. case GGML_OP_POOL_1D:
  14162. {
  14163. ggml_compute_forward_pool_1d(params, tensor);
  14164. } break;
  14165. case GGML_OP_POOL_2D:
  14166. {
  14167. ggml_compute_forward_pool_2d(params, tensor);
  14168. } break;
  14169. case GGML_OP_POOL_2D_BACK:
  14170. {
  14171. ggml_compute_forward_pool_2d_back(params, tensor);
  14172. } break;
  14173. case GGML_OP_UPSCALE:
  14174. {
  14175. ggml_compute_forward_upscale(params, tensor);
  14176. } break;
  14177. case GGML_OP_PAD:
  14178. {
  14179. ggml_compute_forward_pad(params, tensor);
  14180. } break;
  14181. case GGML_OP_ARANGE:
  14182. {
  14183. ggml_compute_forward_arange(params, tensor);
  14184. } break;
  14185. case GGML_OP_TIMESTEP_EMBEDDING:
  14186. {
  14187. ggml_compute_forward_timestep_embedding(params, tensor);
  14188. } break;
  14189. case GGML_OP_ARGSORT:
  14190. {
  14191. ggml_compute_forward_argsort(params, tensor);
  14192. } break;
  14193. case GGML_OP_LEAKY_RELU:
  14194. {
  14195. ggml_compute_forward_leaky_relu(params, tensor);
  14196. } break;
  14197. case GGML_OP_FLASH_ATTN_EXT:
  14198. {
  14199. ggml_compute_forward_flash_attn_ext(params, tensor->src[0], tensor->src[1], tensor->src[2], tensor->src[3], tensor);
  14200. } break;
  14201. case GGML_OP_FLASH_ATTN_BACK:
  14202. {
  14203. int32_t t = ggml_get_op_params_i32(tensor, 0);
  14204. GGML_ASSERT(t == 0 || t == 1);
  14205. bool masked = t != 0;
  14206. ggml_compute_forward_flash_attn_back(params, masked, tensor);
  14207. } break;
  14208. case GGML_OP_SSM_CONV:
  14209. {
  14210. ggml_compute_forward_ssm_conv(params, tensor);
  14211. } break;
  14212. case GGML_OP_SSM_SCAN:
  14213. {
  14214. ggml_compute_forward_ssm_scan(params, tensor);
  14215. } break;
  14216. case GGML_OP_WIN_PART:
  14217. {
  14218. ggml_compute_forward_win_part(params, tensor);
  14219. } break;
  14220. case GGML_OP_WIN_UNPART:
  14221. {
  14222. ggml_compute_forward_win_unpart(params, tensor);
  14223. } break;
  14224. case GGML_OP_UNARY:
  14225. {
  14226. ggml_compute_forward_unary(params, tensor);
  14227. } break;
  14228. case GGML_OP_GET_REL_POS:
  14229. {
  14230. ggml_compute_forward_get_rel_pos(params, tensor);
  14231. } break;
  14232. case GGML_OP_ADD_REL_POS:
  14233. {
  14234. ggml_compute_forward_add_rel_pos(params, tensor);
  14235. } break;
  14236. case GGML_OP_RWKV_WKV:
  14237. {
  14238. ggml_compute_forward_rwkv_wkv(params, tensor);
  14239. } break;
  14240. case GGML_OP_MAP_UNARY:
  14241. {
  14242. ggml_unary_op_f32_t fun;
  14243. memcpy(&fun, tensor->op_params, sizeof(fun));
  14244. ggml_compute_forward_map_unary(params, tensor, fun);
  14245. }
  14246. break;
  14247. case GGML_OP_MAP_BINARY:
  14248. {
  14249. ggml_binary_op_f32_t fun;
  14250. memcpy(&fun, tensor->op_params, sizeof(fun));
  14251. ggml_compute_forward_map_binary(params, tensor, fun);
  14252. }
  14253. break;
  14254. case GGML_OP_MAP_CUSTOM1_F32:
  14255. {
  14256. ggml_custom1_op_f32_t fun;
  14257. memcpy(&fun, tensor->op_params, sizeof(fun));
  14258. ggml_compute_forward_map_custom1_f32(params, tensor, fun);
  14259. }
  14260. break;
  14261. case GGML_OP_MAP_CUSTOM2_F32:
  14262. {
  14263. ggml_custom2_op_f32_t fun;
  14264. memcpy(&fun, tensor->op_params, sizeof(fun));
  14265. ggml_compute_forward_map_custom2_f32(params, tensor, fun);
  14266. }
  14267. break;
  14268. case GGML_OP_MAP_CUSTOM3_F32:
  14269. {
  14270. ggml_custom3_op_f32_t fun;
  14271. memcpy(&fun, tensor->op_params, sizeof(fun));
  14272. ggml_compute_forward_map_custom3_f32(params, tensor, fun);
  14273. }
  14274. break;
  14275. case GGML_OP_MAP_CUSTOM1:
  14276. {
  14277. ggml_compute_forward_map_custom1(params, tensor);
  14278. }
  14279. break;
  14280. case GGML_OP_MAP_CUSTOM2:
  14281. {
  14282. ggml_compute_forward_map_custom2(params, tensor);
  14283. }
  14284. break;
  14285. case GGML_OP_MAP_CUSTOM3:
  14286. {
  14287. ggml_compute_forward_map_custom3(params, tensor);
  14288. }
  14289. break;
  14290. case GGML_OP_CROSS_ENTROPY_LOSS:
  14291. {
  14292. ggml_compute_forward_cross_entropy_loss(params, tensor);
  14293. }
  14294. break;
  14295. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  14296. {
  14297. ggml_compute_forward_cross_entropy_loss_back(params, tensor);
  14298. }
  14299. break;
  14300. case GGML_OP_OPT_STEP_ADAMW:
  14301. {
  14302. ggml_compute_forward_opt_step_adamw(params, tensor);
  14303. }
  14304. break;
  14305. case GGML_OP_NONE:
  14306. {
  14307. // nop
  14308. } break;
  14309. case GGML_OP_COUNT:
  14310. {
  14311. GGML_ABORT("fatal error");
  14312. }
  14313. }
  14314. }
  14315. ////////////////////////////////////////////////////////////////////////////////
  14316. struct ggml_hash_set ggml_hash_set_new(size_t size) {
  14317. size = ggml_hash_size(size);
  14318. struct ggml_hash_set result;
  14319. result.size = size;
  14320. result.keys = GGML_MALLOC(sizeof(struct ggml_tensor *) * size);
  14321. result.used = GGML_CALLOC(ggml_bitset_size(size), sizeof(ggml_bitset_t));
  14322. return result;
  14323. }
  14324. void ggml_hash_set_reset(struct ggml_hash_set * hash_set) {
  14325. memset(hash_set->used, 0, sizeof(ggml_bitset_t) * ggml_bitset_size(hash_set->size));
  14326. }
  14327. void ggml_hash_set_free(struct ggml_hash_set * hash_set) {
  14328. GGML_FREE(hash_set->used);
  14329. GGML_FREE(hash_set->keys);
  14330. }
  14331. size_t ggml_hash_size(size_t min_sz) {
  14332. // next primes after powers of two
  14333. static const size_t primes[] = {
  14334. 2, 3, 5, 11, 17, 37, 67, 131, 257, 521, 1031,
  14335. 2053, 4099, 8209, 16411, 32771, 65537, 131101,
  14336. 262147, 524309, 1048583, 2097169, 4194319, 8388617,
  14337. 16777259, 33554467, 67108879, 134217757, 268435459,
  14338. 536870923, 1073741827, 2147483659
  14339. };
  14340. static const size_t n_primes = sizeof(primes)/sizeof(primes[0]);
  14341. // find the smallest prime that is larger or equal than min_sz
  14342. size_t l = 0;
  14343. size_t r = n_primes;
  14344. while (l < r) {
  14345. size_t m = (l + r)/2;
  14346. if (primes[m] < min_sz) {
  14347. l = m + 1;
  14348. } else {
  14349. r = m;
  14350. }
  14351. }
  14352. size_t sz = l < n_primes ? primes[l] : min_sz | 1;
  14353. return sz;
  14354. }
  14355. struct hash_map {
  14356. struct ggml_hash_set set;
  14357. struct ggml_tensor ** vals;
  14358. };
  14359. static struct hash_map * ggml_new_hash_map(size_t size) {
  14360. struct hash_map * result = GGML_MALLOC(sizeof(struct hash_map));
  14361. result->set = ggml_hash_set_new(size);
  14362. result->vals = GGML_CALLOC(result->set.size, sizeof(struct ggml_tensor *));
  14363. return result;
  14364. }
  14365. static void ggml_hash_map_free(struct hash_map * map) {
  14366. ggml_hash_set_free(&map->set);
  14367. GGML_FREE(map->vals);
  14368. GGML_FREE(map);
  14369. }
  14370. // gradient checkpointing
  14371. static struct ggml_tensor * ggml_recompute_graph_node(
  14372. struct ggml_context * ctx,
  14373. struct ggml_cgraph * graph,
  14374. struct hash_map * replacements,
  14375. struct ggml_tensor * node) {
  14376. if (node == NULL) {
  14377. return NULL;
  14378. }
  14379. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  14380. return node;
  14381. }
  14382. if (!ggml_hash_contains(&graph->visited_hash_set, node)) {
  14383. return node;
  14384. }
  14385. int count_children = 0;
  14386. for (int k = 0; k < GGML_MAX_SRC; ++k) {
  14387. if (node->src[k]) {
  14388. ++count_children;
  14389. }
  14390. }
  14391. if (count_children == 0) {
  14392. return node;
  14393. }
  14394. size_t i = ggml_hash_find(&replacements->set, node);
  14395. GGML_ASSERT(i != GGML_HASHSET_FULL); // assert that not full
  14396. if (replacements->set.keys[i] == node) {
  14397. return replacements->vals[i];
  14398. }
  14399. struct ggml_tensor * clone = ggml_new_tensor(ctx, node->type, GGML_MAX_DIMS, node->ne);
  14400. // insert clone into replacements
  14401. GGML_ASSERT(replacements->set.keys[i] == NULL); // assert that we don't overwrite
  14402. replacements->set.keys[i] = node;
  14403. replacements->vals[i] = clone;
  14404. clone->op = node->op;
  14405. clone->grad = node->grad;
  14406. clone->flags = node->flags;
  14407. clone->extra = node->extra;
  14408. for (int k = 0; k < GGML_MAX_DIMS; ++k) {
  14409. clone->nb[k] = node->nb[k];
  14410. }
  14411. for (int k = 0; k < GGML_MAX_SRC; ++k) {
  14412. clone->src[k] = ggml_recompute_graph_node(ctx, graph, replacements, node->src[k]);
  14413. }
  14414. if (node->view_src != NULL) {
  14415. clone->data = (node->view_src->data == NULL)
  14416. ? NULL // view_src not yet allocated
  14417. : (char *) node->view_src->data // view_src already allocated
  14418. + node->view_offs;
  14419. clone->view_src = node->view_src;
  14420. clone->view_offs = node->view_offs;
  14421. }
  14422. GGML_ASSERT(sizeof(node->op_params) == sizeof(int32_t) * (GGML_MAX_OP_PARAMS / sizeof(int32_t)));
  14423. GGML_ASSERT(sizeof(node->name) == GGML_MAX_NAME);
  14424. memcpy(clone->op_params, node->op_params, sizeof(node->op_params));
  14425. ggml_format_name(clone, "%s (clone)", ggml_get_name(node));
  14426. return clone;
  14427. }
  14428. void ggml_build_backward_gradient_checkpointing(
  14429. struct ggml_context * ctx,
  14430. struct ggml_cgraph * gf,
  14431. struct ggml_cgraph * gb,
  14432. struct ggml_cgraph * gb_tmp,
  14433. struct ggml_tensor * * checkpoints,
  14434. int n_checkpoints) {
  14435. ggml_graph_cpy(gf, gb_tmp);
  14436. ggml_build_backward_expand(ctx, gf, gb_tmp, false);
  14437. if (n_checkpoints <= 0) {
  14438. ggml_graph_cpy(gb_tmp, gb);
  14439. return;
  14440. }
  14441. struct hash_map * replacements = ggml_new_hash_map(gf->n_nodes + gf->n_leafs + n_checkpoints);
  14442. // insert checkpoints in replacements
  14443. for (int i = 0; i < n_checkpoints; ++i) {
  14444. size_t k = ggml_hash_find(&replacements->set, checkpoints[i]);
  14445. GGML_ASSERT(k != GGML_HASHSET_FULL); // assert that not full
  14446. GGML_ASSERT(replacements->set.keys[k] == NULL); // assert that we don't overwrite
  14447. replacements->set.keys[k] = checkpoints[i];
  14448. replacements->vals[k] = checkpoints[i];
  14449. }
  14450. ggml_graph_cpy(gf, gb);
  14451. // rewrite gb_tmp->nodes[gf->n_nodes:gb_tmp->n_nodes],
  14452. // replacing references to gb_tmp->nodes[0:gf->n_nodes] ( == gf->nodes[0:gf->n_nodes]),
  14453. // by recomputing them from checkpoints
  14454. for (int i = gf->n_nodes; i<gb_tmp->n_nodes; ++i) {
  14455. struct ggml_tensor * node = gb_tmp->nodes[i];
  14456. for (int k = 0; k < GGML_MAX_SRC; ++k) {
  14457. // insert new tensors recomputing src, reusing already made replacements,
  14458. // remember replacements: remember new tensors with mapping from corresponding gf nodes
  14459. // recurse for input tensors,
  14460. // unless (i.e. terminating when) input tensors are replacements (like checkpoints)
  14461. node->src[k] = ggml_recompute_graph_node(ctx, gf, replacements, node->src[k]);
  14462. }
  14463. // insert rewritten backward node with replacements made into resulting backward graph gb
  14464. ggml_build_forward_expand(gb, node);
  14465. }
  14466. ggml_hash_map_free(replacements);
  14467. }
  14468. // utility functions to change gradients
  14469. // if a is in acc_table, modify gradients in-place and mark result as gradient accumulator
  14470. // else if a is in zero_table, replace a
  14471. // else, just add/subtract/etc. the gradients
  14472. static struct ggml_tensor * ggml_add_or_set(
  14473. struct ggml_context * ctx,
  14474. struct ggml_tensor * a,
  14475. struct ggml_tensor * b,
  14476. struct ggml_hash_set * zero_table,
  14477. struct ggml_hash_set * acc_table) {
  14478. if (ggml_hash_contains(acc_table, a)) {
  14479. struct ggml_tensor * ret = ggml_add_impl(ctx, a, b, true);
  14480. const size_t insert_result = ggml_hash_insert(acc_table, ret);
  14481. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  14482. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  14483. return ret;
  14484. }
  14485. if (ggml_hash_contains(zero_table, a)) {
  14486. return b;
  14487. }
  14488. return ggml_add_impl(ctx, a, b, false);
  14489. }
  14490. static struct ggml_tensor * ggml_acc_or_set(
  14491. struct ggml_context * ctx,
  14492. struct ggml_tensor * a,
  14493. struct ggml_tensor * b,
  14494. const size_t nb1,
  14495. const size_t nb2,
  14496. const size_t nb3,
  14497. const size_t offset,
  14498. struct ggml_hash_set * zero_table,
  14499. struct ggml_hash_set * acc_table) {
  14500. if (ggml_hash_contains(acc_table, a)) {
  14501. struct ggml_tensor * ret = ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  14502. const size_t insert_result = ggml_hash_insert(acc_table, ret);
  14503. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  14504. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  14505. return ret;
  14506. }
  14507. if (ggml_hash_contains(zero_table, a)) {
  14508. struct ggml_tensor * a_zero = ggml_scale(ctx, a, 0.0f); // FIXME this is going to produce NaN if a contains inf/NaN
  14509. return ggml_acc_impl(ctx, a_zero, b, nb1, nb2, nb3, offset, false);
  14510. }
  14511. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  14512. }
  14513. static struct ggml_tensor * ggml_add1_or_set(
  14514. struct ggml_context * ctx,
  14515. struct ggml_tensor * a,
  14516. struct ggml_tensor * b,
  14517. struct ggml_hash_set * zero_table,
  14518. struct ggml_hash_set * acc_table) {
  14519. if (ggml_hash_contains(acc_table, a)) {
  14520. struct ggml_tensor * ret = ggml_add1_impl(ctx, a, b, true);
  14521. const size_t insert_result = ggml_hash_insert(acc_table, ret);
  14522. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  14523. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  14524. return ret;
  14525. }
  14526. if (ggml_hash_contains(zero_table, a)) {
  14527. return ggml_repeat(ctx, b, a);
  14528. }
  14529. return ggml_add1_impl(ctx, a, b, false);
  14530. }
  14531. static struct ggml_tensor * ggml_sub_or_set(
  14532. struct ggml_context * ctx,
  14533. struct ggml_tensor * a,
  14534. struct ggml_tensor * b,
  14535. struct ggml_hash_set * zero_table,
  14536. struct ggml_hash_set * acc_table) {
  14537. if (ggml_hash_contains(acc_table, a)) {
  14538. struct ggml_tensor * ret = ggml_sub_impl(ctx, a, b, true);
  14539. const size_t insert_result = ggml_hash_insert(acc_table, ret);
  14540. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  14541. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  14542. return ret;
  14543. }
  14544. if (ggml_hash_contains(zero_table, a)) {
  14545. return ggml_neg(ctx, b);
  14546. }
  14547. return ggml_sub_impl(ctx, a, b, false);
  14548. }
  14549. static void ggml_compute_backward(struct ggml_context * ctx, struct ggml_tensor * tensor, struct ggml_hash_set * zero_table, struct ggml_hash_set * acc_table) {
  14550. struct ggml_tensor * src0 = tensor->src[0];
  14551. struct ggml_tensor * src1 = tensor->src[1];
  14552. struct ggml_tensor * src2 = tensor->src[2];
  14553. switch (tensor->op) {
  14554. case GGML_OP_DUP:
  14555. {
  14556. if (src0->grad) {
  14557. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14558. }
  14559. } break;
  14560. case GGML_OP_ADD:
  14561. {
  14562. if (src0->grad) {
  14563. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14564. }
  14565. if (src1->grad) {
  14566. if (ggml_are_same_shape(src0, src1)) {
  14567. src1->grad = ggml_add_or_set(ctx, src1->grad, tensor->grad, zero_table, acc_table);
  14568. } else {
  14569. src1->grad = ggml_add_or_set(ctx, src1->grad, ggml_repeat_back(ctx, tensor->grad, src1), zero_table, acc_table);
  14570. }
  14571. }
  14572. } break;
  14573. case GGML_OP_ADD1:
  14574. {
  14575. if (src0->grad) {
  14576. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14577. }
  14578. if (src1->grad) {
  14579. src1->grad = ggml_add_or_set(ctx,
  14580. src1->grad,
  14581. ggml_mean(ctx, tensor->grad), // TODO: should probably be sum instead of mean
  14582. zero_table, acc_table);
  14583. }
  14584. } break;
  14585. case GGML_OP_ACC:
  14586. {
  14587. if (src0->grad) {
  14588. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14589. }
  14590. if (src1->grad) {
  14591. const size_t nb1 = ((int32_t *) tensor->op_params)[0];
  14592. const size_t nb2 = ((int32_t *) tensor->op_params)[1];
  14593. const size_t nb3 = ((int32_t *) tensor->op_params)[2];
  14594. const size_t offset = ((int32_t *) tensor->op_params)[3];
  14595. struct ggml_tensor * tensor_grad_view = ggml_view_4d(ctx,
  14596. tensor->grad,
  14597. src1->grad->ne[0],
  14598. src1->grad->ne[1],
  14599. src1->grad->ne[2],
  14600. src1->grad->ne[3],
  14601. nb1, nb2, nb3, offset);
  14602. src1->grad =
  14603. ggml_add_or_set(ctx,
  14604. src1->grad,
  14605. ggml_reshape(ctx,
  14606. ggml_cont(ctx, tensor_grad_view),
  14607. src1->grad),
  14608. zero_table, acc_table);
  14609. }
  14610. } break;
  14611. case GGML_OP_SUB:
  14612. {
  14613. if (src0->grad) {
  14614. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14615. }
  14616. if (src1->grad) {
  14617. src1->grad = ggml_sub_or_set(ctx, src1->grad, tensor->grad, zero_table, acc_table);
  14618. }
  14619. } break;
  14620. case GGML_OP_MUL:
  14621. {
  14622. if (src0->grad) {
  14623. src0->grad =
  14624. ggml_add_or_set(ctx,
  14625. src0->grad,
  14626. ggml_mul(ctx, src1, tensor->grad),
  14627. zero_table, acc_table);
  14628. }
  14629. if (src1->grad) {
  14630. src1->grad =
  14631. ggml_add_or_set(ctx,
  14632. src1->grad,
  14633. ggml_mul(ctx, src0, tensor->grad),
  14634. zero_table, acc_table);
  14635. }
  14636. } break;
  14637. case GGML_OP_DIV:
  14638. {
  14639. if (src0->grad) {
  14640. src0->grad =
  14641. ggml_add_or_set(ctx,
  14642. src0->grad,
  14643. ggml_div(ctx, tensor->grad, src1),
  14644. zero_table, acc_table);
  14645. }
  14646. if (src1->grad) {
  14647. src1->grad =
  14648. ggml_sub_or_set(ctx,
  14649. src1->grad,
  14650. ggml_mul(ctx,
  14651. tensor->grad,
  14652. ggml_div(ctx, tensor, src1)),
  14653. zero_table, acc_table);
  14654. }
  14655. } break;
  14656. case GGML_OP_SQR:
  14657. {
  14658. if (src0->grad) {
  14659. src0->grad =
  14660. ggml_add_or_set(ctx,
  14661. src0->grad,
  14662. ggml_scale(ctx,
  14663. ggml_mul(ctx, src0, tensor->grad),
  14664. 2.0f),
  14665. zero_table, acc_table);
  14666. }
  14667. } break;
  14668. case GGML_OP_SQRT:
  14669. {
  14670. if (src0->grad) {
  14671. src0->grad =
  14672. ggml_add_or_set(ctx,
  14673. src0->grad,
  14674. ggml_scale(ctx,
  14675. ggml_div(ctx,
  14676. tensor->grad,
  14677. tensor),
  14678. 0.5f),
  14679. zero_table, acc_table);
  14680. }
  14681. } break;
  14682. case GGML_OP_LOG:
  14683. {
  14684. if (src0->grad) {
  14685. src0->grad =
  14686. ggml_add_or_set(ctx,
  14687. src0->grad,
  14688. ggml_div(ctx,
  14689. tensor->grad,
  14690. src0),
  14691. zero_table, acc_table);
  14692. }
  14693. } break;
  14694. case GGML_OP_SIN:
  14695. {
  14696. if (src0->grad) {
  14697. src0->grad =
  14698. ggml_add_or_set(ctx,
  14699. src0->grad,
  14700. ggml_mul(ctx,
  14701. tensor->grad,
  14702. ggml_cos(ctx, src0)),
  14703. zero_table, acc_table);
  14704. }
  14705. } break;
  14706. case GGML_OP_COS:
  14707. {
  14708. if (src0->grad) {
  14709. src0->grad =
  14710. ggml_sub_or_set(ctx,
  14711. src0->grad,
  14712. ggml_mul(ctx,
  14713. tensor->grad,
  14714. ggml_sin(ctx, src0)),
  14715. zero_table, acc_table);
  14716. }
  14717. } break;
  14718. case GGML_OP_SUM:
  14719. {
  14720. if (src0->grad) {
  14721. src0->grad =
  14722. ggml_add1_or_set(ctx,
  14723. src0->grad,
  14724. tensor->grad,
  14725. zero_table, acc_table);
  14726. }
  14727. } break;
  14728. case GGML_OP_SUM_ROWS:
  14729. {
  14730. if (src0->grad) {
  14731. src0->grad =
  14732. ggml_add_or_set(ctx,
  14733. src0->grad,
  14734. ggml_repeat(ctx,
  14735. tensor->grad,
  14736. src0->grad),
  14737. zero_table, acc_table);
  14738. }
  14739. } break;
  14740. case GGML_OP_MEAN:
  14741. case GGML_OP_ARGMAX:
  14742. {
  14743. GGML_ABORT("fatal error"); // TODO: implement
  14744. }
  14745. case GGML_OP_REPEAT:
  14746. {
  14747. // necessary for llama
  14748. if (src0->grad) {
  14749. src0->grad = ggml_add_or_set(ctx,
  14750. src0->grad,
  14751. ggml_repeat_back(ctx, tensor->grad, src0->grad),
  14752. zero_table, acc_table);
  14753. }
  14754. } break;
  14755. case GGML_OP_REPEAT_BACK:
  14756. {
  14757. if (src0->grad) {
  14758. // TODO: test this
  14759. src0->grad = ggml_add_or_set(ctx,
  14760. src0->grad,
  14761. ggml_repeat(ctx, tensor->grad, src0->grad),
  14762. zero_table, acc_table);
  14763. }
  14764. } break;
  14765. case GGML_OP_CONCAT:
  14766. {
  14767. GGML_ABORT("fatal error"); // TODO: implement
  14768. }
  14769. case GGML_OP_SILU_BACK:
  14770. {
  14771. GGML_ABORT("fatal error"); // TODO: not implemented
  14772. }
  14773. case GGML_OP_NORM:
  14774. {
  14775. GGML_ABORT("fatal error"); // TODO: not implemented
  14776. }
  14777. case GGML_OP_RMS_NORM:
  14778. {
  14779. // necessary for llama
  14780. if (src0->grad) {
  14781. float eps;
  14782. memcpy(&eps, tensor->op_params, sizeof(float));
  14783. src0->grad = ggml_add_or_set(ctx,
  14784. src0->grad,
  14785. ggml_rms_norm_back(ctx, src0, tensor->grad, eps),
  14786. zero_table, acc_table);
  14787. }
  14788. } break;
  14789. case GGML_OP_RMS_NORM_BACK:
  14790. {
  14791. GGML_ABORT("fatal error"); // TODO: not implemented
  14792. }
  14793. case GGML_OP_GROUP_NORM:
  14794. {
  14795. GGML_ABORT("fatal error"); // TODO: not implemented
  14796. }
  14797. case GGML_OP_MUL_MAT:
  14798. {
  14799. // https://cs231n.github.io/optimization-2/#staged
  14800. // # forward pass
  14801. // s0 = np.random.randn(5, 10)
  14802. // s1 = np.random.randn(10, 3)
  14803. // t = s0.dot(s1)
  14804. // # now suppose we had the gradient on t from above in the circuit
  14805. // dt = np.random.randn(*t.shape) # same shape as t
  14806. // ds0 = dt.dot(s1.T) #.T gives the transpose of the matrix
  14807. // ds1 = t.T.dot(dt)
  14808. // tensor.shape [m,p,qq,rr]
  14809. // src0.shape [n,m,q1,r1]
  14810. // src1.shape [n,p,qq,rr]
  14811. // necessary for llama
  14812. if (src0->grad) {
  14813. struct ggml_tensor * s1_tg =
  14814. ggml_out_prod(ctx, // [n,m,qq,rr]
  14815. src1, // [n,p,qq,rr]
  14816. tensor->grad); // [m,p,qq,rr]
  14817. const int64_t qq = s1_tg->ne[2];
  14818. const int64_t rr = s1_tg->ne[3];
  14819. const int64_t q1 = src0->ne[2];
  14820. const int64_t r1 = src0->ne[3];
  14821. const bool ne2_broadcasted = qq > q1;
  14822. const bool ne3_broadcasted = rr > r1;
  14823. if (ne2_broadcasted || ne3_broadcasted) {
  14824. // sum broadcast repetitions of s1_tg into shape of src0
  14825. s1_tg = ggml_repeat_back(ctx, s1_tg, src0);
  14826. }
  14827. src0->grad =
  14828. ggml_add_or_set(ctx,
  14829. src0->grad, // [n,m,q1,r1]
  14830. s1_tg, // [n,m,q1,r1]
  14831. zero_table, acc_table);
  14832. }
  14833. if (src1->grad) {
  14834. src1->grad =
  14835. ggml_add_or_set(ctx,
  14836. src1->grad, // [n,p,qq,rr]
  14837. // ggml_mul_mat(ctx, // [n,p,qq,rr]
  14838. // ggml_cont(ctx, // [m,n,q1,r1]
  14839. // ggml_transpose(ctx, src0)), // [m,n,q1,r1]
  14840. // tensor->grad), // [m,p,qq,rr]
  14841. // // when src0 is bigger than tensor->grad (this is mostly the case in llama),
  14842. // // avoid transpose of src0, rather transpose smaller tensor->grad
  14843. // // and then use ggml_out_prod
  14844. ggml_out_prod(ctx, // [n,p,qq,rr]
  14845. src0, // [n,m,q1,r1]
  14846. ggml_transpose(ctx, // [p,m,qq,rr]
  14847. tensor->grad)), // [m,p,qq,rr]
  14848. zero_table, acc_table);
  14849. }
  14850. } break;
  14851. case GGML_OP_MUL_MAT_ID:
  14852. {
  14853. GGML_ABORT("fatal error"); // TODO: not implemented
  14854. }
  14855. case GGML_OP_OUT_PROD:
  14856. {
  14857. GGML_ABORT("fatal error"); // TODO: not implemented
  14858. }
  14859. case GGML_OP_SCALE:
  14860. {
  14861. // necessary for llama
  14862. if (src0->grad) {
  14863. float s;
  14864. memcpy(&s, tensor->op_params, sizeof(float));
  14865. src0->grad =
  14866. ggml_add_or_set(ctx,
  14867. src0->grad,
  14868. ggml_scale_impl(ctx, tensor->grad, s, false),
  14869. zero_table, acc_table);
  14870. }
  14871. } break;
  14872. case GGML_OP_SET:
  14873. {
  14874. const size_t nb1 = ((int32_t *) tensor->op_params)[0];
  14875. const size_t nb2 = ((int32_t *) tensor->op_params)[1];
  14876. const size_t nb3 = ((int32_t *) tensor->op_params)[2];
  14877. const size_t offset = ((int32_t *) tensor->op_params)[3];
  14878. struct ggml_tensor * tensor_grad_view = NULL;
  14879. if (src0->grad || src1->grad) {
  14880. GGML_ASSERT(src0->type == tensor->type);
  14881. GGML_ASSERT(tensor->grad->type == tensor->type);
  14882. GGML_ASSERT(!src1->grad || src1->grad->type == tensor->grad->type);
  14883. tensor_grad_view = ggml_view_4d(ctx,
  14884. tensor->grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
  14885. nb1, nb2, nb3, offset);
  14886. }
  14887. if (src0->grad) {
  14888. src0->grad = ggml_add_or_set(ctx,
  14889. src0->grad,
  14890. ggml_acc_impl(ctx,
  14891. tensor->grad,
  14892. ggml_neg(ctx, tensor_grad_view),
  14893. nb1, nb2, nb3, offset, false),
  14894. zero_table, acc_table);
  14895. }
  14896. if (src1->grad) {
  14897. src1->grad =
  14898. ggml_add_or_set(ctx,
  14899. src1->grad,
  14900. ggml_reshape(ctx,
  14901. ggml_cont(ctx, tensor_grad_view),
  14902. src1->grad),
  14903. zero_table, acc_table);
  14904. }
  14905. } break;
  14906. case GGML_OP_CPY:
  14907. {
  14908. // necessary for llama
  14909. // cpy overwrites value of src1 by src0 and returns view(src1)
  14910. // the overwriting is mathematically equivalent to:
  14911. // tensor = src0 * 1 + src1 * 0
  14912. if (src0->grad) {
  14913. // dsrc0 = dtensor * 1
  14914. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14915. }
  14916. if (src1->grad) {
  14917. // dsrc1 = dtensor * 0 -> noop
  14918. }
  14919. } break;
  14920. case GGML_OP_CONT:
  14921. {
  14922. // same as cpy
  14923. if (src0->grad) {
  14924. GGML_ASSERT(ggml_is_contiguous(src0->grad));
  14925. GGML_ASSERT(ggml_is_contiguous(tensor->grad));
  14926. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14927. }
  14928. } break;
  14929. case GGML_OP_RESHAPE:
  14930. {
  14931. // necessary for llama
  14932. if (src0->grad) {
  14933. src0->grad =
  14934. ggml_add_or_set(ctx, src0->grad,
  14935. ggml_reshape(ctx,
  14936. ggml_is_contiguous(tensor->grad)
  14937. ? tensor->grad
  14938. : ggml_cont(ctx, tensor->grad),
  14939. src0->grad),
  14940. zero_table, acc_table);
  14941. }
  14942. } break;
  14943. case GGML_OP_VIEW:
  14944. {
  14945. // necessary for llama
  14946. if (src0->grad) {
  14947. size_t offset;
  14948. memcpy(&offset, tensor->op_params, sizeof(offset));
  14949. size_t nb1 = tensor->nb[1];
  14950. size_t nb2 = tensor->nb[2];
  14951. size_t nb3 = tensor->nb[3];
  14952. if (src0->type != src0->grad->type) {
  14953. // gradient is typically F32, but src0 could be other type
  14954. size_t ng = ggml_element_size(src0->grad);
  14955. size_t n0 = ggml_element_size(src0);
  14956. GGML_ASSERT(offset % n0 == 0);
  14957. GGML_ASSERT(nb1 % n0 == 0);
  14958. GGML_ASSERT(nb2 % n0 == 0);
  14959. GGML_ASSERT(nb3 % n0 == 0);
  14960. offset = (offset / n0) * ng;
  14961. nb1 = (nb1 / n0) * ng;
  14962. nb2 = (nb2 / n0) * ng;
  14963. nb3 = (nb3 / n0) * ng;
  14964. }
  14965. src0->grad = ggml_acc_or_set(ctx, src0->grad, tensor->grad, nb1, nb2, nb3, offset, zero_table, acc_table);
  14966. }
  14967. } break;
  14968. case GGML_OP_PERMUTE:
  14969. {
  14970. // necessary for llama
  14971. if (src0->grad) {
  14972. int32_t * axes = (int32_t *) tensor->op_params;
  14973. int axis0 = axes[0] & 0x3;
  14974. int axis1 = axes[1] & 0x3;
  14975. int axis2 = axes[2] & 0x3;
  14976. int axis3 = axes[3] & 0x3;
  14977. int axes_backward[4] = {0,0,0,0};
  14978. axes_backward[axis0] = 0;
  14979. axes_backward[axis1] = 1;
  14980. axes_backward[axis2] = 2;
  14981. axes_backward[axis3] = 3;
  14982. src0->grad =
  14983. ggml_add_or_set(ctx, src0->grad,
  14984. ggml_permute(ctx,
  14985. tensor->grad,
  14986. axes_backward[0],
  14987. axes_backward[1],
  14988. axes_backward[2],
  14989. axes_backward[3]),
  14990. zero_table, acc_table);
  14991. }
  14992. } break;
  14993. case GGML_OP_TRANSPOSE:
  14994. {
  14995. // necessary for llama
  14996. if (src0->grad) {
  14997. src0->grad =
  14998. ggml_add_or_set(ctx, src0->grad,
  14999. ggml_transpose(ctx, tensor->grad),
  15000. zero_table, acc_table);
  15001. }
  15002. } break;
  15003. case GGML_OP_GET_ROWS:
  15004. {
  15005. // necessary for llama (only for tokenizer)
  15006. if (src0->grad) {
  15007. src0->grad =
  15008. ggml_add_or_set(ctx, src0->grad,
  15009. // last ggml_get_rows_back argument src0->grad is only
  15010. // necessary to setup correct output shape
  15011. ggml_get_rows_back(ctx, tensor->grad, src1, src0->grad),
  15012. zero_table, acc_table);
  15013. }
  15014. if (src1->grad) {
  15015. // noop
  15016. }
  15017. } break;
  15018. case GGML_OP_GET_ROWS_BACK:
  15019. {
  15020. GGML_ABORT("fatal error"); // TODO: not implemented
  15021. }
  15022. case GGML_OP_DIAG:
  15023. {
  15024. GGML_ABORT("fatal error"); // TODO: not implemented
  15025. }
  15026. case GGML_OP_DIAG_MASK_INF:
  15027. {
  15028. // necessary for llama
  15029. if (src0->grad) {
  15030. const int n_past = ((int32_t *) tensor->op_params)[0];
  15031. src0->grad =
  15032. ggml_add_or_set(ctx, src0->grad,
  15033. /* ggml_diag_mask_inf_impl() shouldn't be here */
  15034. /* ref: https://github.com/ggerganov/llama.cpp/pull/4203#discussion_r1412377992 */
  15035. ggml_diag_mask_zero_impl(ctx, tensor->grad, n_past, false),
  15036. zero_table, acc_table);
  15037. }
  15038. } break;
  15039. case GGML_OP_DIAG_MASK_ZERO:
  15040. {
  15041. // necessary for llama
  15042. if (src0->grad) {
  15043. const int n_past = ((int32_t *) tensor->op_params)[0];
  15044. src0->grad =
  15045. ggml_add_or_set(ctx, src0->grad,
  15046. ggml_diag_mask_zero_impl(ctx, tensor->grad, n_past, false),
  15047. zero_table, acc_table);
  15048. }
  15049. } break;
  15050. case GGML_OP_SOFT_MAX:
  15051. {
  15052. // necessary for llama
  15053. if (src0->grad) {
  15054. src0->grad =
  15055. ggml_add_or_set(ctx, src0->grad,
  15056. ggml_soft_max_back(ctx, tensor->grad, tensor),
  15057. zero_table, acc_table);
  15058. }
  15059. GGML_ASSERT((!src1 || !src1->grad) && "backward pass for softmax mask not implemented");
  15060. } break;
  15061. case GGML_OP_SOFT_MAX_BACK:
  15062. {
  15063. GGML_ABORT("fatal error"); // TODO: not implemented
  15064. }
  15065. case GGML_OP_ROPE:
  15066. {
  15067. // necessary for llama
  15068. if (src0->grad) {
  15069. //const int n_past = ((int32_t *) tensor->op_params)[0];
  15070. const int n_dims = ((int32_t *) tensor->op_params)[1];
  15071. const int mode = ((int32_t *) tensor->op_params)[2];
  15072. //const int n_ctx = ((int32_t *) tensor->op_params)[3];
  15073. const int n_ctx_orig = ((int32_t *) tensor->op_params)[4];
  15074. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  15075. memcpy(&freq_base, (int32_t *) tensor->op_params + 5, sizeof(float));
  15076. memcpy(&freq_scale, (int32_t *) tensor->op_params + 6, sizeof(float));
  15077. memcpy(&ext_factor, (int32_t *) tensor->op_params + 7, sizeof(float));
  15078. memcpy(&attn_factor, (int32_t *) tensor->op_params + 8, sizeof(float));
  15079. memcpy(&beta_fast, (int32_t *) tensor->op_params + 9, sizeof(float));
  15080. memcpy(&beta_slow, (int32_t *) tensor->op_params + 10, sizeof(float));
  15081. src0->grad = ggml_add_or_set(ctx,
  15082. src0->grad,
  15083. ggml_rope_back(ctx,
  15084. tensor->grad,
  15085. src1,
  15086. src2,
  15087. n_dims,
  15088. mode,
  15089. n_ctx_orig,
  15090. freq_base,
  15091. freq_scale,
  15092. ext_factor,
  15093. attn_factor,
  15094. beta_fast,
  15095. beta_slow),
  15096. zero_table, acc_table);
  15097. }
  15098. GGML_ASSERT((!src2 || !src2->grad) && "gradients for freq factors not implemented");
  15099. } break;
  15100. case GGML_OP_ROPE_BACK:
  15101. {
  15102. if (src0->grad) {
  15103. //const int n_past = ((int32_t *) tensor->op_params)[0];
  15104. const int n_dims = ((int32_t *) tensor->op_params)[1];
  15105. const int mode = ((int32_t *) tensor->op_params)[2];
  15106. //const int n_ctx = ((int32_t *) tensor->op_params)[3];
  15107. const int n_ctx_orig = ((int32_t *) tensor->op_params)[4];
  15108. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  15109. memcpy(&freq_base, (int32_t *) tensor->op_params + 5, sizeof(float));
  15110. memcpy(&freq_scale, (int32_t *) tensor->op_params + 6, sizeof(float));
  15111. memcpy(&ext_factor, (int32_t *) tensor->op_params + 7, sizeof(float));
  15112. memcpy(&attn_factor, (int32_t *) tensor->op_params + 8, sizeof(float));
  15113. memcpy(&beta_fast, (int32_t *) tensor->op_params + 9, sizeof(float));
  15114. memcpy(&beta_slow, (int32_t *) tensor->op_params + 10, sizeof(float));
  15115. src0->grad = ggml_add_or_set(ctx,
  15116. src0->grad,
  15117. ggml_rope_impl(ctx,
  15118. tensor->grad,
  15119. src1,
  15120. src2,
  15121. n_dims,
  15122. mode,
  15123. n_ctx_orig,
  15124. freq_base,
  15125. freq_scale,
  15126. ext_factor,
  15127. attn_factor,
  15128. beta_fast,
  15129. beta_slow,
  15130. false),
  15131. zero_table, acc_table);
  15132. }
  15133. } break;
  15134. case GGML_OP_CLAMP:
  15135. {
  15136. GGML_ABORT("fatal error"); // TODO: not implemented
  15137. }
  15138. case GGML_OP_CONV_TRANSPOSE_1D:
  15139. {
  15140. GGML_ABORT("fatal error"); // TODO: not implemented
  15141. }
  15142. case GGML_OP_IM2COL:
  15143. {
  15144. if (src1->grad) {
  15145. const int32_t s0 = ggml_get_op_params_i32(tensor, 0);
  15146. const int32_t s1 = ggml_get_op_params_i32(tensor, 1);
  15147. const int32_t p0 = ggml_get_op_params_i32(tensor, 2);
  15148. const int32_t p1 = ggml_get_op_params_i32(tensor, 3);
  15149. const int32_t d0 = ggml_get_op_params_i32(tensor, 4);
  15150. const int32_t d1 = ggml_get_op_params_i32(tensor, 5);
  15151. const bool is_2D = ggml_get_op_params_i32(tensor, 6) == 1;
  15152. src1->grad = ggml_add_or_set(ctx,
  15153. src1->grad,
  15154. ggml_im2col_back(ctx, src0, tensor->grad, src1->ne, s0, s1, p0, p1, d0, d1, is_2D),
  15155. zero_table, acc_table);
  15156. }
  15157. } break;
  15158. case GGML_OP_IM2COL_BACK:
  15159. {
  15160. GGML_ABORT("fatal error"); // TODO: not implemented
  15161. }
  15162. case GGML_OP_CONV_TRANSPOSE_2D:
  15163. {
  15164. GGML_ABORT("fatal error"); // TODO: not implemented
  15165. }
  15166. case GGML_OP_POOL_1D:
  15167. {
  15168. GGML_ABORT("fatal error"); // TODO: not implemented
  15169. }
  15170. case GGML_OP_POOL_2D:
  15171. {
  15172. if (src0->grad) {
  15173. const enum ggml_op_pool op = ggml_get_op_params_i32(tensor, 0);
  15174. const int32_t k0 = ggml_get_op_params_i32(tensor, 1);
  15175. const int32_t k1 = ggml_get_op_params_i32(tensor, 2);
  15176. const int32_t s0 = ggml_get_op_params_i32(tensor, 3);
  15177. const int32_t s1 = ggml_get_op_params_i32(tensor, 4);
  15178. const int32_t p0 = ggml_get_op_params_i32(tensor, 5);
  15179. const int32_t p1 = ggml_get_op_params_i32(tensor, 6);
  15180. src0->grad = ggml_add_or_set(ctx,
  15181. src0->grad,
  15182. ggml_pool_2d_back(ctx, tensor->grad, src0, op, k0, k1, s0, s1, p0, p1),
  15183. zero_table, acc_table);
  15184. }
  15185. } break;
  15186. case GGML_OP_POOL_2D_BACK:
  15187. {
  15188. GGML_ABORT("fatal error"); // TODO: not implemented
  15189. }
  15190. case GGML_OP_UPSCALE:
  15191. {
  15192. GGML_ABORT("fatal error"); // TODO: not implemented
  15193. }
  15194. case GGML_OP_PAD:
  15195. {
  15196. GGML_ABORT("fatal error"); // TODO: not implemented
  15197. }
  15198. case GGML_OP_ARANGE:
  15199. {
  15200. GGML_ABORT("fatal error"); // TODO: not implemented
  15201. }
  15202. case GGML_OP_TIMESTEP_EMBEDDING:
  15203. {
  15204. GGML_ABORT("fatal error"); // TODO: not implemented
  15205. }
  15206. case GGML_OP_ARGSORT:
  15207. {
  15208. GGML_ABORT("fatal error"); // TODO: not implemented
  15209. }
  15210. case GGML_OP_LEAKY_RELU:
  15211. {
  15212. GGML_ABORT("fatal error"); // TODO: not implemented
  15213. }
  15214. case GGML_OP_FLASH_ATTN_EXT:
  15215. {
  15216. GGML_ABORT("FA backward pass not adapted after rework");
  15217. struct ggml_tensor * flash_grad = NULL;
  15218. if (src0->grad || src1->grad || tensor->src[2]->grad) {
  15219. int32_t t = ggml_get_op_params_i32(tensor, 0);
  15220. GGML_ASSERT(t == 0 || t == 1);
  15221. bool masked = t != 0;
  15222. flash_grad =
  15223. ggml_flash_attn_back(ctx,
  15224. src0,
  15225. src1,
  15226. tensor->src[2],
  15227. tensor->grad,
  15228. masked);
  15229. }
  15230. const int64_t elem_q = ggml_nelements(src0);
  15231. const int64_t elem_k = ggml_nelements(src1);
  15232. const int64_t elem_v = ggml_nelements(src2);
  15233. enum ggml_type result_type = flash_grad->type;
  15234. GGML_ASSERT(ggml_blck_size(result_type) == 1);
  15235. const size_t tsize = ggml_type_size(result_type);
  15236. const size_t offs_q = 0;
  15237. const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
  15238. const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
  15239. if (src0->grad) {
  15240. struct ggml_tensor * view_q = ggml_view_1d(ctx, flash_grad, elem_q, offs_q);
  15241. struct ggml_tensor * grad_q = ggml_reshape(ctx, view_q, src0);
  15242. src0->grad = ggml_add_or_set(ctx,
  15243. src0->grad,
  15244. grad_q,
  15245. zero_table, acc_table);
  15246. }
  15247. if (src1->grad) {
  15248. struct ggml_tensor * view_k = ggml_view_1d(ctx, flash_grad, elem_k, offs_k);
  15249. struct ggml_tensor * grad_k = ggml_reshape(ctx, view_k, src1);
  15250. src1->grad = ggml_add_or_set(ctx,
  15251. src1->grad,
  15252. grad_k,
  15253. zero_table, acc_table);
  15254. }
  15255. if (src2->grad) {
  15256. struct ggml_tensor * view_v = ggml_view_1d(ctx, flash_grad, elem_v, offs_v);
  15257. struct ggml_tensor * grad_v = ggml_reshape(ctx, view_v, src2);
  15258. src2->grad = ggml_add_or_set(ctx,
  15259. src2->grad,
  15260. grad_v,
  15261. zero_table, acc_table);
  15262. }
  15263. } break;
  15264. case GGML_OP_FLASH_ATTN_BACK:
  15265. {
  15266. GGML_ABORT("fatal error"); // not supported
  15267. }
  15268. case GGML_OP_SSM_CONV:
  15269. case GGML_OP_SSM_SCAN:
  15270. {
  15271. GGML_ABORT("fatal error"); // TODO: not implemented
  15272. }
  15273. case GGML_OP_WIN_PART:
  15274. case GGML_OP_WIN_UNPART:
  15275. case GGML_OP_UNARY:
  15276. {
  15277. switch (ggml_get_unary_op(tensor)) {
  15278. case GGML_UNARY_OP_ABS:
  15279. {
  15280. if (src0->grad) {
  15281. src0->grad =
  15282. ggml_add_or_set(ctx,
  15283. src0->grad,
  15284. ggml_mul(ctx,
  15285. ggml_sgn(ctx, src0),
  15286. tensor->grad),
  15287. zero_table, acc_table);
  15288. }
  15289. } break;
  15290. case GGML_UNARY_OP_SGN:
  15291. {
  15292. if (src0->grad) {
  15293. // noop
  15294. }
  15295. } break;
  15296. case GGML_UNARY_OP_NEG:
  15297. {
  15298. if (src0->grad) {
  15299. src0->grad = ggml_sub_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  15300. }
  15301. } break;
  15302. case GGML_UNARY_OP_STEP:
  15303. {
  15304. if (src0->grad) {
  15305. // noop
  15306. }
  15307. } break;
  15308. case GGML_UNARY_OP_TANH:
  15309. {
  15310. GGML_ABORT("fatal error"); // TODO: not implemented
  15311. }
  15312. case GGML_UNARY_OP_ELU:
  15313. {
  15314. GGML_ABORT("fatal error"); // TODO: not implemented
  15315. }
  15316. case GGML_UNARY_OP_RELU:
  15317. {
  15318. if (src0->grad) {
  15319. src0->grad = ggml_add_or_set(ctx,
  15320. src0->grad,
  15321. ggml_mul(ctx,
  15322. ggml_step(ctx, src0),
  15323. tensor->grad),
  15324. zero_table, acc_table);
  15325. }
  15326. } break;
  15327. case GGML_UNARY_OP_SIGMOID:
  15328. {
  15329. GGML_ABORT("fatal error"); // TODO: not implemented
  15330. }
  15331. case GGML_UNARY_OP_GELU:
  15332. {
  15333. GGML_ABORT("fatal error"); // TODO: not implemented
  15334. }
  15335. case GGML_UNARY_OP_GELU_QUICK:
  15336. {
  15337. GGML_ABORT("fatal error"); // TODO: not implemented
  15338. }
  15339. case GGML_UNARY_OP_SILU:
  15340. {
  15341. // necessary for llama
  15342. if (src0->grad) {
  15343. src0->grad = ggml_add_or_set(ctx,
  15344. src0->grad,
  15345. ggml_silu_back(ctx, src0, tensor->grad),
  15346. zero_table, acc_table);
  15347. }
  15348. } break;
  15349. case GGML_UNARY_OP_EXP:
  15350. {
  15351. if (src0->grad) {
  15352. src0->grad = ggml_add_or_set(ctx,
  15353. src0->grad,
  15354. ggml_mul(ctx, tensor, tensor->grad),
  15355. zero_table, acc_table);
  15356. }
  15357. } break;
  15358. default:
  15359. GGML_ABORT("fatal error");
  15360. }
  15361. } break;
  15362. case GGML_OP_GET_REL_POS:
  15363. case GGML_OP_ADD_REL_POS:
  15364. case GGML_OP_RWKV_WKV:
  15365. case GGML_OP_MAP_UNARY:
  15366. case GGML_OP_MAP_BINARY:
  15367. case GGML_OP_MAP_CUSTOM1_F32:
  15368. case GGML_OP_MAP_CUSTOM2_F32:
  15369. case GGML_OP_MAP_CUSTOM3_F32:
  15370. case GGML_OP_MAP_CUSTOM1:
  15371. case GGML_OP_MAP_CUSTOM2:
  15372. case GGML_OP_MAP_CUSTOM3:
  15373. {
  15374. GGML_ABORT("fatal error"); // not supported
  15375. }
  15376. case GGML_OP_CROSS_ENTROPY_LOSS:
  15377. {
  15378. if (src0->grad) {
  15379. src0->grad = ggml_add_or_set(ctx,
  15380. src0->grad,
  15381. ggml_cross_entropy_loss_back(ctx,
  15382. src0,
  15383. src1,
  15384. tensor->grad),
  15385. zero_table, acc_table);
  15386. }
  15387. GGML_ASSERT(!src1->grad && "backward pass for labels not implemented");
  15388. } break;
  15389. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  15390. {
  15391. GGML_ABORT("fatal error"); // not supported
  15392. }
  15393. case GGML_OP_OPT_STEP_ADAMW:
  15394. {
  15395. GGML_ABORT("fatal error"); // not supported
  15396. }
  15397. case GGML_OP_NONE:
  15398. {
  15399. // nop
  15400. } break;
  15401. case GGML_OP_COUNT:
  15402. {
  15403. GGML_ABORT("fatal error");
  15404. }
  15405. }
  15406. for (int i = 0; i < GGML_MAX_SRC; ++i) {
  15407. if (tensor->src[i] && tensor->src[i]->grad) {
  15408. GGML_ASSERT(ggml_are_same_shape(tensor->src[i], tensor->src[i]->grad));
  15409. }
  15410. }
  15411. }
  15412. static void ggml_visit_parents(struct ggml_cgraph * cgraph, struct ggml_tensor * node) {
  15413. if (node->grad == NULL) {
  15414. // this usually happens when we generate intermediate nodes from constants in the backward pass
  15415. // it can also happen during forward pass, if the user performs computations with constants
  15416. if (node->op != GGML_OP_NONE) {
  15417. //GGML_PRINT_DEBUG("%s: warning: node %p has no grad, but op %d\n", __func__, (void *) node, node->op);
  15418. }
  15419. }
  15420. // check if already visited
  15421. if (ggml_hash_insert(&cgraph->visited_hash_set, node) == GGML_HASHSET_ALREADY_EXISTS) {
  15422. return;
  15423. }
  15424. for (int i = 0; i < GGML_MAX_SRC; ++i) {
  15425. const int k =
  15426. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT) ? i :
  15427. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT) ? (GGML_MAX_SRC-1-i) :
  15428. /* unknown order, just fall back to using i*/ i;
  15429. if (node->src[k]) {
  15430. ggml_visit_parents(cgraph, node->src[k]);
  15431. }
  15432. }
  15433. if (node->op == GGML_OP_NONE && !(node->flags & GGML_TENSOR_FLAG_PARAM)) {
  15434. // reached a leaf node, not part of the gradient graph (e.g. a constant)
  15435. GGML_ASSERT(cgraph->n_leafs < cgraph->size);
  15436. if (strlen(node->name) == 0) {
  15437. ggml_format_name(node, "leaf_%d", cgraph->n_leafs);
  15438. }
  15439. cgraph->leafs[cgraph->n_leafs] = node;
  15440. cgraph->n_leafs++;
  15441. } else {
  15442. GGML_ASSERT(cgraph->n_nodes < cgraph->size);
  15443. if (strlen(node->name) == 0) {
  15444. ggml_format_name(node, "node_%d", cgraph->n_nodes);
  15445. }
  15446. cgraph->nodes[cgraph->n_nodes] = node;
  15447. cgraph->n_nodes++;
  15448. }
  15449. }
  15450. static void ggml_build_forward_impl(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor, bool expand) {
  15451. if (!expand) {
  15452. // TODO: this branch isn't accessible anymore, maybe move this to ggml_build_forward_expand
  15453. ggml_graph_clear(cgraph);
  15454. }
  15455. const int n0 = cgraph->n_nodes;
  15456. ggml_visit_parents(cgraph, tensor);
  15457. const int n_new = cgraph->n_nodes - n0;
  15458. GGML_PRINT_DEBUG("%s: visited %d new nodes\n", __func__, n_new);
  15459. if (n_new > 0) {
  15460. // the last added node should always be starting point
  15461. GGML_ASSERT(cgraph->nodes[cgraph->n_nodes - 1] == tensor);
  15462. }
  15463. }
  15464. void ggml_build_forward_expand(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  15465. ggml_build_forward_impl(cgraph, tensor, true);
  15466. }
  15467. void ggml_build_backward_expand(struct ggml_context * ctx, struct ggml_cgraph * gf, struct ggml_cgraph * gb, bool accumulate) {
  15468. GGML_ASSERT(gf->n_nodes > 0);
  15469. GGML_ASSERT(gf->grads);
  15470. for (int i = 0; i < gf->n_nodes; ++i) {
  15471. struct ggml_tensor * node = gf->nodes[i];
  15472. bool needs_grad = node->flags & GGML_TENSOR_FLAG_PARAM;
  15473. bool ignore_src[GGML_MAX_SRC] = {false};
  15474. switch (node->op) {
  15475. // gradients in node->src[0] for one reason or another have no effect on output gradients
  15476. case GGML_OP_IM2COL: // only used for its shape
  15477. case GGML_OP_IM2COL_BACK: // same as IM2COL
  15478. ignore_src[0] = true;
  15479. break;
  15480. case GGML_OP_UNARY: {
  15481. const enum ggml_unary_op uop = ggml_get_unary_op(node);
  15482. // SGN and STEP unary ops are piecewise constant
  15483. if (uop == GGML_UNARY_OP_SGN || uop == GGML_UNARY_OP_STEP) {
  15484. ignore_src[0] = true;
  15485. }
  15486. } break;
  15487. // gradients in node->src[1] for one reason or another have no effect on output gradients
  15488. case GGML_OP_CPY: // gradients in CPY target are irrelevant
  15489. case GGML_OP_GET_ROWS: // row indices not differentiable
  15490. case GGML_OP_GET_ROWS_BACK: // same as for GET_ROWS
  15491. case GGML_OP_ROPE: // positions not differentiable
  15492. ignore_src[1] = true;
  15493. break;
  15494. default:
  15495. break;
  15496. }
  15497. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  15498. if (!node->src[j] || !node->src[j]->grad || ignore_src[j]) {
  15499. continue;
  15500. }
  15501. GGML_ASSERT(node->src[j]->type == GGML_TYPE_F32 || node->src[j]->type == GGML_TYPE_F16);
  15502. needs_grad = true;
  15503. break;
  15504. }
  15505. if (!needs_grad) {
  15506. continue;
  15507. }
  15508. // inplace operations are currently not supported
  15509. GGML_ASSERT(!node->view_src || node->op == GGML_OP_CPY || node->op == GGML_OP_VIEW ||
  15510. node->op == GGML_OP_RESHAPE || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_TRANSPOSE);
  15511. // create a new tensor with the same type and shape as the node and set it as grad
  15512. node->grad = ggml_dup_tensor(ctx, node);
  15513. }
  15514. // keep tables of original gradients for replacement/accumulation logic
  15515. struct ggml_hash_set zero_table = ggml_hash_set_new(gf->size);
  15516. struct ggml_hash_set acc_table = ggml_hash_set_new(gf->size);
  15517. for (int i = 0; i < gf->n_nodes; i++) {
  15518. struct ggml_tensor * node = gf->nodes[i];
  15519. if (node->grad) {
  15520. {
  15521. const size_t insert_result = ggml_hash_insert(&zero_table, node->grad);
  15522. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  15523. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  15524. }
  15525. // only gradients of trainable parameters should be accumulated
  15526. if (accumulate && (node->flags & GGML_TENSOR_FLAG_PARAM)) {
  15527. const size_t insert_result = ggml_hash_insert(&acc_table, node->grad);
  15528. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  15529. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  15530. }
  15531. }
  15532. }
  15533. for (int i = gf->n_nodes - 1; i >= 0; i--) {
  15534. struct ggml_tensor * node = gf->nodes[i];
  15535. // inplace operations to add gradients are not created by ggml_compute_backward except for gradient accumulation
  15536. // use allocator to automatically make inplace operations
  15537. if (node->grad) {
  15538. ggml_compute_backward(ctx, node, &zero_table, &acc_table);
  15539. }
  15540. }
  15541. for (int i = 0; i < gf->n_nodes; i++) {
  15542. struct ggml_tensor * node = gf->nodes[i];
  15543. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  15544. GGML_PRINT_DEBUG("%s: found root node %p\n", __func__, (void *) node);
  15545. ggml_build_forward_expand(gb, node->grad);
  15546. }
  15547. }
  15548. ggml_hash_set_free(&zero_table);
  15549. ggml_hash_set_free(&acc_table);
  15550. }
  15551. void ggml_build_opt_adamw(
  15552. struct ggml_context * ctx,
  15553. struct ggml_cgraph * gf,
  15554. struct ggml_cgraph * gb,
  15555. float alpha,
  15556. float beta1,
  15557. float beta2,
  15558. float eps,
  15559. float wd) {
  15560. for (int i = 0; i < gf->n_nodes; i++) {
  15561. struct ggml_tensor * node = gf->nodes[i];
  15562. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  15563. GGML_PRINT_DEBUG("%s: found root node %p\n", __func__, (void *) node);
  15564. struct ggml_tensor * opt_step = ggml_opt_step_adamw(ctx, node, alpha, beta1, beta2, eps, wd);
  15565. ggml_build_forward_expand(gb, opt_step);
  15566. }
  15567. }
  15568. }
  15569. static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
  15570. void * ptr = *p;
  15571. ptr = (void *) GGML_PAD((uintptr_t) ptr, align);
  15572. *p = (void *) ((char *) ptr + size);
  15573. return ptr;
  15574. }
  15575. static size_t ggml_graph_nbytes(size_t size, bool grads) {
  15576. size_t hash_size = ggml_hash_size(size * 2);
  15577. void * p = 0;
  15578. incr_ptr_aligned(&p, sizeof(struct ggml_cgraph), 1);
  15579. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // nodes
  15580. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // leafs
  15581. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // hash keys
  15582. if (grads) {
  15583. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grads
  15584. }
  15585. incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  15586. size_t nbytes = (size_t) p;
  15587. return nbytes;
  15588. }
  15589. size_t ggml_graph_overhead_custom(size_t size, bool grads) {
  15590. return GGML_OBJECT_SIZE + GGML_PAD(ggml_graph_nbytes(size, grads), GGML_MEM_ALIGN);
  15591. }
  15592. size_t ggml_graph_overhead(void) {
  15593. return ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, false);
  15594. }
  15595. struct ggml_cgraph * ggml_new_graph_custom(struct ggml_context * ctx, size_t size, bool grads) {
  15596. const size_t obj_size = ggml_graph_nbytes(size, grads);
  15597. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_GRAPH, obj_size);
  15598. struct ggml_cgraph * cgraph = (struct ggml_cgraph *) ((char *) ctx->mem_buffer + obj->offs);
  15599. // the size of the hash table is doubled since it needs to hold both nodes and leafs
  15600. size_t hash_size = ggml_hash_size(size * 2);
  15601. void * p = cgraph + 1;
  15602. struct ggml_tensor ** nodes_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  15603. struct ggml_tensor ** leafs_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  15604. struct ggml_tensor ** hash_keys_ptr = incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  15605. struct ggml_tensor ** grads_ptr = grads ? incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
  15606. ggml_bitset_t * hash_used = incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  15607. // check that we allocated the correct amount of memory
  15608. assert(obj_size == (size_t)((char *)p - (char *)cgraph));
  15609. *cgraph = (struct ggml_cgraph) {
  15610. /*.size =*/ size,
  15611. /*.n_nodes =*/ 0,
  15612. /*.n_leafs =*/ 0,
  15613. /*.nodes =*/ nodes_ptr,
  15614. /*.grads =*/ grads_ptr,
  15615. /*.leafs =*/ leafs_ptr,
  15616. /*.hash_table =*/ { hash_size, hash_used, hash_keys_ptr },
  15617. /*.order =*/ GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT,
  15618. };
  15619. ggml_hash_set_reset(&cgraph->visited_hash_set);
  15620. return cgraph;
  15621. }
  15622. struct ggml_cgraph * ggml_new_graph(struct ggml_context * ctx) {
  15623. return ggml_new_graph_custom(ctx, GGML_DEFAULT_GRAPH_SIZE, false);
  15624. }
  15625. struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph0, int i0, int i1) {
  15626. struct ggml_cgraph cgraph = {
  15627. /*.size =*/ 0,
  15628. /*.n_nodes =*/ i1 - i0,
  15629. /*.n_leafs =*/ 0,
  15630. /*.nodes =*/ cgraph0->nodes + i0,
  15631. /*.grads =*/ cgraph0->grads ? cgraph0->grads + i0 : NULL,
  15632. /*.leafs =*/ NULL,
  15633. /*.hash_table =*/ { 0, NULL, NULL },
  15634. /*.order =*/ cgraph0->order,
  15635. };
  15636. return cgraph;
  15637. }
  15638. void ggml_graph_cpy(struct ggml_cgraph * src, struct ggml_cgraph * dst) {
  15639. GGML_ASSERT(dst->size >= src->n_leafs);
  15640. GGML_ASSERT(dst->size >= src->n_nodes);
  15641. GGML_ASSERT(dst->visited_hash_set.size >= src->visited_hash_set.size);
  15642. dst->n_leafs = src->n_leafs;
  15643. dst->n_nodes = src->n_nodes;
  15644. dst->order = src->order;
  15645. for (int i = 0; i < src->n_leafs; ++i) {
  15646. dst->leafs[i] = src->leafs[i];
  15647. }
  15648. for (int i = 0; i < src->n_nodes; ++i) {
  15649. dst->nodes[i] = src->nodes[i];
  15650. }
  15651. if (src->grads) {
  15652. GGML_ASSERT(dst->grads != NULL);
  15653. for (int i = 0; i < src->n_nodes; ++i) {
  15654. dst->grads[i] = src->grads[i];
  15655. }
  15656. }
  15657. for (size_t i = 0; i < src->visited_hash_set.size; ++i) {
  15658. // copy all hashset keys (tensors) that are in use
  15659. if (ggml_bitset_get(src->visited_hash_set.used, i)) {
  15660. ggml_hash_insert(&dst->visited_hash_set, src->visited_hash_set.keys[i]);
  15661. }
  15662. }
  15663. }
  15664. struct ggml_cgraph * ggml_graph_dup(struct ggml_context * ctx, struct ggml_cgraph * cgraph) {
  15665. struct ggml_cgraph * result = ggml_new_graph_custom(ctx, cgraph->size, cgraph->grads != NULL);
  15666. ggml_graph_cpy(cgraph, result);
  15667. return result;
  15668. }
  15669. void ggml_graph_reset(struct ggml_cgraph * cgraph) {
  15670. GGML_ASSERT(cgraph->grads != NULL);
  15671. for (int i = 0; i < cgraph->n_nodes; i++) {
  15672. struct ggml_tensor * node = cgraph->nodes[i];
  15673. // initial gradients of loss should be 1, 0 otherwise
  15674. if (node->grad) {
  15675. if (node->flags & GGML_TENSOR_FLAG_LOSS) {
  15676. GGML_ASSERT(node->grad->buffer);
  15677. GGML_ASSERT(node->type == GGML_TYPE_F32);
  15678. GGML_ASSERT(ggml_is_scalar(node));
  15679. const float onef = 1.0f;
  15680. ggml_backend_tensor_set(node->grad, &onef, 0, ggml_nbytes(node->grad));
  15681. } else {
  15682. ggml_set_zero(node->grad);
  15683. }
  15684. }
  15685. GGML_ASSERT(node);
  15686. if (node->op == GGML_OP_OPT_STEP_ADAMW) {
  15687. // set iteration to 1 and clear momenta
  15688. ggml_set_op_params_i32(node, 0, 1);
  15689. ggml_set_zero(node->src[2]);
  15690. ggml_set_zero(node->src[3]);
  15691. }
  15692. }
  15693. }
  15694. void ggml_graph_clear(struct ggml_cgraph * cgraph) {
  15695. cgraph->n_leafs = 0;
  15696. cgraph->n_nodes = 0;
  15697. ggml_hash_set_reset(&cgraph->visited_hash_set);
  15698. }
  15699. int ggml_graph_size(struct ggml_cgraph * cgraph) {
  15700. return cgraph->size;
  15701. }
  15702. struct ggml_tensor * ggml_graph_node(struct ggml_cgraph * cgraph, int i) {
  15703. if (i < 0) {
  15704. GGML_ASSERT(cgraph->n_nodes + i >= 0);
  15705. return cgraph->nodes[cgraph->n_nodes + i];
  15706. }
  15707. GGML_ASSERT(i < cgraph->n_nodes);
  15708. return cgraph->nodes[i];
  15709. }
  15710. struct ggml_tensor ** ggml_graph_nodes(struct ggml_cgraph * cgraph) {
  15711. return cgraph->nodes;
  15712. }
  15713. int ggml_graph_n_nodes(struct ggml_cgraph * cgraph) {
  15714. return cgraph->n_nodes;
  15715. }
  15716. void ggml_graph_add_node(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  15717. GGML_ASSERT(cgraph->size > cgraph->n_nodes);
  15718. cgraph->nodes[cgraph->n_nodes] = tensor;
  15719. cgraph->n_nodes++;
  15720. }
  15721. // Android's libc implementation "bionic" does not support setting affinity
  15722. #if defined(__gnu_linux__)
  15723. static void set_numa_thread_affinity(int thread_n) {
  15724. if (!ggml_is_numa()) {
  15725. return;
  15726. }
  15727. int node_num;
  15728. int rv;
  15729. size_t setsize = CPU_ALLOC_SIZE(g_state.numa.total_cpus);
  15730. switch(g_state.numa.numa_strategy) {
  15731. case GGML_NUMA_STRATEGY_DISTRIBUTE:
  15732. // run thread on node_num thread_n / (threads per node)
  15733. node_num = thread_n % g_state.numa.n_nodes;
  15734. break;
  15735. case GGML_NUMA_STRATEGY_ISOLATE:
  15736. // run thread on current_node
  15737. node_num = g_state.numa.current_node;
  15738. break;
  15739. case GGML_NUMA_STRATEGY_NUMACTL:
  15740. // use the cpuset that numactl gave us
  15741. rv = pthread_setaffinity_np(pthread_self(), setsize, &g_state.numa.cpuset);
  15742. if (rv) {
  15743. fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n",strerror(rv));
  15744. }
  15745. return;
  15746. default:
  15747. return;
  15748. }
  15749. struct ggml_numa_node * node = &g_state.numa.nodes[node_num];
  15750. cpu_set_t * cpus = CPU_ALLOC(g_state.numa.total_cpus);
  15751. CPU_ZERO_S(setsize, cpus);
  15752. for (size_t i = 0; i < node->n_cpus; ++i) {
  15753. CPU_SET_S(node->cpus[i], setsize, cpus);
  15754. }
  15755. rv = pthread_setaffinity_np(pthread_self(), setsize, cpus);
  15756. if (rv) {
  15757. fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n", strerror(rv));
  15758. }
  15759. CPU_FREE(cpus);
  15760. }
  15761. static void clear_numa_thread_affinity(void) {
  15762. if (!ggml_is_numa()) {
  15763. return;
  15764. }
  15765. size_t setsize = CPU_ALLOC_SIZE(g_state.numa.total_cpus);
  15766. cpu_set_t * cpus = CPU_ALLOC(g_state.numa.total_cpus);
  15767. CPU_ZERO_S(setsize, cpus);
  15768. for (unsigned i = 0; i < g_state.numa.total_cpus; ++i) {
  15769. CPU_SET_S(i, setsize, cpus);
  15770. }
  15771. int rv = pthread_setaffinity_np(pthread_self(), setsize, cpus);
  15772. if (rv) {
  15773. fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n", strerror(rv));
  15774. }
  15775. CPU_FREE(cpus);
  15776. }
  15777. #else
  15778. // TODO: Windows etc.
  15779. // (the linux implementation may also work on BSD, someone should test)
  15780. static void set_numa_thread_affinity(int thread_n) { UNUSED(thread_n); }
  15781. static void clear_numa_thread_affinity(void) {}
  15782. #endif
  15783. static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) {
  15784. int n_tasks = 0;
  15785. if (ggml_is_empty(node)) {
  15786. // no need to multi-thread a no-op
  15787. n_tasks = 1;
  15788. return n_tasks;
  15789. }
  15790. switch (node->op) {
  15791. case GGML_OP_CPY:
  15792. case GGML_OP_DUP:
  15793. case GGML_OP_CONT:
  15794. case GGML_OP_ADD:
  15795. case GGML_OP_ADD1:
  15796. case GGML_OP_ACC:
  15797. {
  15798. n_tasks = n_threads;
  15799. } break;
  15800. case GGML_OP_SUB:
  15801. case GGML_OP_SQR:
  15802. case GGML_OP_SQRT:
  15803. case GGML_OP_LOG:
  15804. case GGML_OP_SIN:
  15805. case GGML_OP_COS:
  15806. case GGML_OP_SUM:
  15807. case GGML_OP_SUM_ROWS:
  15808. case GGML_OP_MEAN:
  15809. case GGML_OP_ARGMAX:
  15810. case GGML_OP_REPEAT:
  15811. case GGML_OP_REPEAT_BACK:
  15812. case GGML_OP_LEAKY_RELU:
  15813. {
  15814. n_tasks = 1;
  15815. } break;
  15816. case GGML_OP_UNARY:
  15817. switch (ggml_get_unary_op(node)) {
  15818. case GGML_UNARY_OP_ABS:
  15819. case GGML_UNARY_OP_SGN:
  15820. case GGML_UNARY_OP_NEG:
  15821. case GGML_UNARY_OP_STEP:
  15822. case GGML_UNARY_OP_TANH:
  15823. case GGML_UNARY_OP_ELU:
  15824. case GGML_UNARY_OP_RELU:
  15825. case GGML_UNARY_OP_SIGMOID:
  15826. case GGML_UNARY_OP_HARDSWISH:
  15827. case GGML_UNARY_OP_HARDSIGMOID:
  15828. case GGML_UNARY_OP_EXP:
  15829. {
  15830. n_tasks = 1;
  15831. } break;
  15832. case GGML_UNARY_OP_GELU:
  15833. case GGML_UNARY_OP_GELU_QUICK:
  15834. case GGML_UNARY_OP_SILU:
  15835. {
  15836. n_tasks = n_threads;
  15837. } break;
  15838. default:
  15839. GGML_ABORT("fatal error");
  15840. }
  15841. break;
  15842. case GGML_OP_SILU_BACK:
  15843. case GGML_OP_MUL:
  15844. case GGML_OP_DIV:
  15845. case GGML_OP_NORM:
  15846. case GGML_OP_RMS_NORM:
  15847. case GGML_OP_RMS_NORM_BACK:
  15848. case GGML_OP_GROUP_NORM:
  15849. case GGML_OP_CONCAT:
  15850. case GGML_OP_MUL_MAT:
  15851. case GGML_OP_MUL_MAT_ID:
  15852. case GGML_OP_OUT_PROD:
  15853. {
  15854. n_tasks = n_threads;
  15855. } break;
  15856. case GGML_OP_GET_ROWS:
  15857. {
  15858. // FIXME: get_rows can use additional threads, but the cost of launching additional threads
  15859. // decreases performance with GPU offloading
  15860. //n_tasks = n_threads;
  15861. n_tasks = 1;
  15862. } break;
  15863. case GGML_OP_SCALE:
  15864. case GGML_OP_SET:
  15865. case GGML_OP_RESHAPE:
  15866. case GGML_OP_VIEW:
  15867. case GGML_OP_PERMUTE:
  15868. case GGML_OP_TRANSPOSE:
  15869. case GGML_OP_GET_ROWS_BACK:
  15870. case GGML_OP_DIAG:
  15871. {
  15872. n_tasks = 1;
  15873. } break;
  15874. case GGML_OP_DIAG_MASK_ZERO:
  15875. case GGML_OP_DIAG_MASK_INF:
  15876. case GGML_OP_SOFT_MAX_BACK:
  15877. case GGML_OP_ROPE:
  15878. case GGML_OP_ROPE_BACK:
  15879. case GGML_OP_ADD_REL_POS:
  15880. {
  15881. n_tasks = n_threads;
  15882. } break;
  15883. case GGML_OP_CLAMP:
  15884. {
  15885. n_tasks = 1; //TODO
  15886. } break;
  15887. case GGML_OP_SOFT_MAX:
  15888. {
  15889. n_tasks = MIN(n_threads, ggml_nrows(node->src[0]));
  15890. } break;
  15891. case GGML_OP_IM2COL:
  15892. case GGML_OP_IM2COL_BACK:
  15893. case GGML_OP_CONV_TRANSPOSE_1D:
  15894. case GGML_OP_CONV_TRANSPOSE_2D:
  15895. {
  15896. n_tasks = n_threads;
  15897. } break;
  15898. case GGML_OP_POOL_1D:
  15899. case GGML_OP_POOL_2D:
  15900. case GGML_OP_POOL_2D_BACK:
  15901. {
  15902. n_tasks = 1;
  15903. } break;
  15904. case GGML_OP_UPSCALE:
  15905. case GGML_OP_PAD:
  15906. case GGML_OP_ARANGE:
  15907. case GGML_OP_TIMESTEP_EMBEDDING:
  15908. case GGML_OP_ARGSORT:
  15909. case GGML_OP_FLASH_ATTN_EXT:
  15910. case GGML_OP_FLASH_ATTN_BACK:
  15911. case GGML_OP_SSM_CONV:
  15912. case GGML_OP_SSM_SCAN:
  15913. {
  15914. n_tasks = n_threads;
  15915. } break;
  15916. case GGML_OP_WIN_PART:
  15917. case GGML_OP_WIN_UNPART:
  15918. case GGML_OP_GET_REL_POS:
  15919. case GGML_OP_RWKV_WKV:
  15920. case GGML_OP_MAP_UNARY:
  15921. case GGML_OP_MAP_BINARY:
  15922. case GGML_OP_MAP_CUSTOM1_F32:
  15923. case GGML_OP_MAP_CUSTOM2_F32:
  15924. case GGML_OP_MAP_CUSTOM3_F32:
  15925. {
  15926. n_tasks = 1;
  15927. } break;
  15928. case GGML_OP_MAP_CUSTOM1:
  15929. {
  15930. struct ggml_map_custom1_op_params p;
  15931. memcpy(&p, node->op_params, sizeof(p));
  15932. if (p.n_tasks == GGML_N_TASKS_MAX) {
  15933. n_tasks = n_threads;
  15934. } else {
  15935. n_tasks = MIN(p.n_tasks, n_threads);
  15936. }
  15937. } break;
  15938. case GGML_OP_MAP_CUSTOM2:
  15939. {
  15940. struct ggml_map_custom2_op_params p;
  15941. memcpy(&p, node->op_params, sizeof(p));
  15942. if (p.n_tasks == GGML_N_TASKS_MAX) {
  15943. n_tasks = n_threads;
  15944. } else {
  15945. n_tasks = MIN(p.n_tasks, n_threads);
  15946. }
  15947. } break;
  15948. case GGML_OP_MAP_CUSTOM3:
  15949. {
  15950. struct ggml_map_custom3_op_params p;
  15951. memcpy(&p, node->op_params, sizeof(p));
  15952. if (p.n_tasks == GGML_N_TASKS_MAX) {
  15953. n_tasks = n_threads;
  15954. } else {
  15955. n_tasks = MIN(p.n_tasks, n_threads);
  15956. }
  15957. } break;
  15958. case GGML_OP_CROSS_ENTROPY_LOSS:
  15959. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  15960. case GGML_OP_OPT_STEP_ADAMW:
  15961. {
  15962. n_tasks = n_threads;
  15963. } break;
  15964. case GGML_OP_NONE:
  15965. {
  15966. n_tasks = 1;
  15967. } break;
  15968. case GGML_OP_COUNT:
  15969. {
  15970. GGML_ABORT("fatal error");
  15971. }
  15972. default:
  15973. {
  15974. fprintf(stderr, "%s: op not implemented: ", __func__);
  15975. if (node->op < GGML_OP_COUNT) {
  15976. fprintf(stderr, "%s\n", ggml_op_name(node->op));
  15977. } else {
  15978. fprintf(stderr, "%d\n", node->op);
  15979. }
  15980. GGML_ABORT("fatal error");
  15981. }
  15982. }
  15983. assert(n_tasks > 0);
  15984. return n_tasks;
  15985. }
  15986. static thread_ret_t ggml_graph_compute_secondary_thread(void* data);
  15987. #if defined(_WIN32)
  15988. #include "windows.h"
  15989. // TODO: support > 64 CPUs
  15990. bool ggml_thread_apply_affinity(bool * mask) {
  15991. HANDLE h = GetCurrentThread();
  15992. uint64_t bitmask = 0ULL;
  15993. assert(GGML_MAX_N_THREADS >= 64);
  15994. for (int32_t i = 0; i < 8; i++) {
  15995. int32_t idx = i * 8;
  15996. uint8_t val = 0;
  15997. val |= mask[idx + 0] << 0;
  15998. val |= mask[idx + 1] << 1;
  15999. val |= mask[idx + 2] << 2;
  16000. val |= mask[idx + 3] << 3;
  16001. val |= mask[idx + 4] << 4;
  16002. val |= mask[idx + 5] << 5;
  16003. val |= mask[idx + 6] << 6;
  16004. val |= mask[idx + 7] << 7;
  16005. bitmask |= (uint64_t)val << idx;
  16006. }
  16007. for (int32_t i = 64; i < GGML_MAX_N_THREADS; i++) {
  16008. if (mask[i]) {
  16009. fprintf(stderr, "warn: setting thread-affinity for > 64 CPUs isn't supported on windows!\n");
  16010. break;
  16011. }
  16012. }
  16013. DWORD_PTR m = (DWORD_PTR)bitmask;
  16014. m = SetThreadAffinityMask(h, m);
  16015. return m != 0;
  16016. }
  16017. static bool ggml_thread_apply_priority(int32_t prio) {
  16018. // Note that on Windows the Process Priority Class must be updated in order to set Thread priority.
  16019. // This is up to the applications.
  16020. DWORD p = THREAD_PRIORITY_NORMAL;
  16021. switch (prio) {
  16022. case GGML_SCHED_PRIO_NORMAL: p = THREAD_PRIORITY_NORMAL; break;
  16023. case GGML_SCHED_PRIO_MEDIUM: p = THREAD_PRIORITY_ABOVE_NORMAL; break;
  16024. case GGML_SCHED_PRIO_HIGH: p = THREAD_PRIORITY_HIGHEST; break;
  16025. case GGML_SCHED_PRIO_REALTIME: p = THREAD_PRIORITY_TIME_CRITICAL; break;
  16026. }
  16027. if (prio == GGML_SCHED_PRIO_NORMAL) {
  16028. // Keep inherited policy/priority
  16029. return true;
  16030. }
  16031. if (!SetThreadPriority(GetCurrentThread(), p)) {
  16032. fprintf(stderr, "warn: failed to set thread priority %d : (%d)\n", prio, (int) GetLastError());
  16033. return false;
  16034. }
  16035. return true;
  16036. }
  16037. #elif defined(__APPLE__)
  16038. #include <sys/types.h>
  16039. #include <sys/resource.h>
  16040. static bool ggml_thread_apply_affinity(const bool * mask) {
  16041. // Not supported on Apple platforms
  16042. UNUSED(mask);
  16043. return true;
  16044. }
  16045. static bool ggml_thread_apply_priority(int32_t prio) {
  16046. struct sched_param p;
  16047. int32_t policy = SCHED_OTHER;
  16048. switch (prio) {
  16049. case GGML_SCHED_PRIO_NORMAL: policy = SCHED_OTHER; p.sched_priority = 0; break;
  16050. case GGML_SCHED_PRIO_MEDIUM: policy = SCHED_FIFO; p.sched_priority = 40; break;
  16051. case GGML_SCHED_PRIO_HIGH: policy = SCHED_FIFO; p.sched_priority = 80; break;
  16052. case GGML_SCHED_PRIO_REALTIME: policy = SCHED_FIFO; p.sched_priority = 90; break;
  16053. }
  16054. if (prio == GGML_SCHED_PRIO_NORMAL) {
  16055. // Keep inherited policy/priority
  16056. return true;
  16057. }
  16058. int32_t err = pthread_setschedparam(pthread_self(), policy, &p);
  16059. if (err != 0) {
  16060. fprintf(stderr, "warn: failed to set thread priority %d : %s (%d)\n", prio, strerror(err), err);
  16061. return false;
  16062. }
  16063. return true;
  16064. }
  16065. #elif defined(__gnu_linux__)
  16066. // TODO: this may not work on BSD, to be verified
  16067. static bool ggml_thread_apply_affinity(const bool * mask) {
  16068. cpu_set_t cpuset;
  16069. int err;
  16070. CPU_ZERO(&cpuset);
  16071. for (uint32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
  16072. if (mask[i]) {
  16073. GGML_PRINT_DEBUG("Thread %lx: adding %d to cpuset\n", pthread_self(), i);
  16074. CPU_SET(i, &cpuset);
  16075. }
  16076. }
  16077. #ifdef __ANDROID__
  16078. err = sched_setaffinity(0, sizeof(cpuset), &cpuset);
  16079. if (err < 0) {
  16080. err = errno;
  16081. }
  16082. #else
  16083. err = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
  16084. #endif
  16085. if (err != 0) {
  16086. fprintf(stderr, "warn: failed to set affinity mask 0x%llx : %s (%d)\n", (unsigned long long)mask, strerror(err), err);
  16087. return false;
  16088. }
  16089. return true;
  16090. }
  16091. static bool ggml_thread_apply_priority(int32_t prio) {
  16092. struct sched_param p;
  16093. int32_t policy = SCHED_OTHER;
  16094. switch (prio) {
  16095. case GGML_SCHED_PRIO_NORMAL: policy = SCHED_OTHER; p.sched_priority = 0; break;
  16096. case GGML_SCHED_PRIO_MEDIUM: policy = SCHED_FIFO; p.sched_priority = 40; break;
  16097. case GGML_SCHED_PRIO_HIGH: policy = SCHED_FIFO; p.sched_priority = 80; break;
  16098. case GGML_SCHED_PRIO_REALTIME: policy = SCHED_FIFO; p.sched_priority = 90; break;
  16099. }
  16100. if (prio == GGML_SCHED_PRIO_NORMAL) {
  16101. // Keep inherited policy/priority
  16102. return true;
  16103. }
  16104. int32_t err = pthread_setschedparam(pthread_self(), policy, &p);
  16105. if (err != 0) {
  16106. fprintf(stderr, "warn: failed to set thread priority %d : %s (%d)\n", prio, strerror(err), err);
  16107. return false;
  16108. }
  16109. return true;
  16110. }
  16111. #else // unsupported platforms
  16112. static bool ggml_thread_apply_affinity(const bool * mask) {
  16113. UNUSED(mask);
  16114. return true;
  16115. }
  16116. static bool ggml_thread_apply_priority(int32_t prio) {
  16117. UNUSED(prio);
  16118. return true;
  16119. }
  16120. #endif
  16121. static bool ggml_thread_cpumask_is_valid(const bool * mask) {
  16122. for (int i = 0; i < GGML_MAX_N_THREADS; i++) {
  16123. if (mask[i]) { return true; }
  16124. }
  16125. return false;
  16126. }
  16127. static void ggml_thread_cpumask_next(const bool * global_mask, bool * local_mask, bool strict, int32_t* iter) {
  16128. if (!strict) {
  16129. memcpy(local_mask, global_mask, GGML_MAX_N_THREADS);
  16130. return;
  16131. } else {
  16132. memset(local_mask, 0, GGML_MAX_N_THREADS);
  16133. int32_t base_idx = *iter;
  16134. for (int32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
  16135. int32_t idx = base_idx + i;
  16136. if (idx >= GGML_MAX_N_THREADS) {
  16137. // Just a cheaper modulo
  16138. idx -= GGML_MAX_N_THREADS;
  16139. }
  16140. if (global_mask[idx]) {
  16141. local_mask[idx] = 1;
  16142. *iter = idx + 1;
  16143. return;
  16144. }
  16145. }
  16146. }
  16147. }
  16148. void ggml_threadpool_free(struct ggml_threadpool* threadpool) {
  16149. if (!threadpool) return;
  16150. #ifndef GGML_USE_OPENMP
  16151. struct ggml_compute_state* workers = threadpool->workers;
  16152. const int n_threads = threadpool->n_threads_max;
  16153. ggml_mutex_lock(&threadpool->mutex);
  16154. threadpool->stop = true;
  16155. threadpool->pause = false;
  16156. ggml_cond_broadcast(&threadpool->cond);
  16157. ggml_mutex_unlock(&threadpool->mutex);
  16158. for (int j = 1; j < n_threads; j++) {
  16159. int32_t rc = ggml_thread_join(workers[j].thrd, NULL);
  16160. GGML_ASSERT(rc == GGML_EXIT_SUCCESS || rc == GGML_EXIT_ABORTED);
  16161. UNUSED(rc);
  16162. }
  16163. ggml_mutex_destroy(&threadpool->mutex);
  16164. ggml_cond_destroy(&threadpool->cond);
  16165. #endif // GGML_USE_OPENMP
  16166. GGML_ALIGNED_FREE(threadpool->workers);
  16167. GGML_ALIGNED_FREE(threadpool);
  16168. }
  16169. #ifndef GGML_USE_OPENMP
  16170. // pause/resume must be called under mutex
  16171. static void ggml_threadpool_pause_locked(struct ggml_threadpool * threadpool) {
  16172. GGML_PRINT_DEBUG("Pausing threadpool\n");
  16173. threadpool->pause = true;
  16174. ggml_cond_broadcast(&threadpool->cond);
  16175. }
  16176. static void ggml_threadpool_resume_locked(struct ggml_threadpool * threadpool) {
  16177. GGML_PRINT_DEBUG("Resuming threadpool\n");
  16178. threadpool->pause = false;
  16179. ggml_cond_broadcast(&threadpool->cond);
  16180. }
  16181. #endif
  16182. void ggml_threadpool_pause(struct ggml_threadpool * threadpool) {
  16183. #ifndef GGML_USE_OPENMP
  16184. ggml_mutex_lock(&threadpool->mutex);
  16185. if (!threadpool->pause) {
  16186. ggml_threadpool_pause_locked(threadpool);
  16187. }
  16188. ggml_mutex_unlock(&threadpool->mutex);
  16189. #else
  16190. UNUSED(threadpool);
  16191. #endif
  16192. }
  16193. void ggml_threadpool_resume(struct ggml_threadpool * threadpool) {
  16194. #ifndef GGML_USE_OPENMP
  16195. ggml_mutex_lock(&threadpool->mutex);
  16196. if (threadpool->pause) {
  16197. ggml_threadpool_resume_locked(threadpool);
  16198. }
  16199. ggml_mutex_unlock(&threadpool->mutex);
  16200. #else
  16201. UNUSED(threadpool);
  16202. #endif
  16203. }
  16204. struct ggml_cplan ggml_graph_plan(
  16205. const struct ggml_cgraph * cgraph,
  16206. int n_threads,
  16207. struct ggml_threadpool * threadpool) {
  16208. if (threadpool == NULL) {
  16209. GGML_PRINT_DEBUG("Threadpool is not specified. Will create a disposable threadpool : n_threads %d\n", n_threads);
  16210. }
  16211. if (n_threads <= 0) {
  16212. n_threads = threadpool ? threadpool->n_threads_max : GGML_DEFAULT_N_THREADS;
  16213. }
  16214. size_t work_size = 0;
  16215. struct ggml_cplan cplan;
  16216. memset(&cplan, 0, sizeof(struct ggml_cplan));
  16217. int max_tasks = 1;
  16218. // thread scheduling for the different operations + work buffer size estimation
  16219. for (int i = 0; i < cgraph->n_nodes; i++) {
  16220. struct ggml_tensor * node = cgraph->nodes[i];
  16221. const int n_tasks = ggml_get_n_tasks(node, n_threads);
  16222. max_tasks = MAX(max_tasks, n_tasks);
  16223. size_t cur = 0;
  16224. switch (node->op) {
  16225. case GGML_OP_CPY:
  16226. case GGML_OP_DUP:
  16227. {
  16228. if (ggml_is_quantized(node->type) ||
  16229. // F16 -> BF16 and BF16 -> F16 copies go through intermediate F32
  16230. (node->src[0]->type == GGML_TYPE_F16 && node->src[1] && node->src[1]->type == GGML_TYPE_BF16) ||
  16231. (node->src[0]->type == GGML_TYPE_BF16 && node->src[1] && node->src[1]->type == GGML_TYPE_F16)) {
  16232. cur = ggml_type_size(GGML_TYPE_F32) * node->ne[0] * n_tasks;
  16233. }
  16234. } break;
  16235. case GGML_OP_ADD:
  16236. case GGML_OP_ADD1:
  16237. {
  16238. if (ggml_is_quantized(node->src[0]->type)) {
  16239. cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
  16240. }
  16241. } break;
  16242. case GGML_OP_ACC:
  16243. {
  16244. if (ggml_is_quantized(node->src[0]->type)) {
  16245. cur = ggml_type_size(GGML_TYPE_F32) * node->src[1]->ne[0] * n_tasks;
  16246. }
  16247. } break;
  16248. case GGML_OP_MUL_MAT:
  16249. {
  16250. const enum ggml_type vec_dot_type = type_traits[node->src[0]->type].vec_dot_type;
  16251. if (node->src[1]->type != vec_dot_type) {
  16252. cur = ggml_row_size(vec_dot_type, ggml_nelements(node->src[1]));
  16253. }
  16254. } break;
  16255. case GGML_OP_MUL_MAT_ID:
  16256. {
  16257. cur = 0;
  16258. const struct ggml_tensor * src0 = node->src[0];
  16259. const struct ggml_tensor * src1 = node->src[1];
  16260. const enum ggml_type vec_dot_type = type_traits[src0->type].vec_dot_type;
  16261. if (src1->type != vec_dot_type) {
  16262. cur += ggml_row_size(vec_dot_type, ggml_nelements(src1));
  16263. }
  16264. const int n_as = src0->ne[2];
  16265. cur += GGML_PAD(cur, sizeof(int64_t)); // align
  16266. cur += n_as * sizeof(int64_t); // matrix_row_counts
  16267. cur += n_as * src1->ne[2] * sizeof(int64_t); // matrix_rows
  16268. } break;
  16269. case GGML_OP_OUT_PROD:
  16270. {
  16271. if (ggml_is_quantized(node->src[0]->type)) {
  16272. cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
  16273. }
  16274. } break;
  16275. case GGML_OP_SOFT_MAX:
  16276. case GGML_OP_ROPE:
  16277. {
  16278. cur = ggml_type_size(GGML_TYPE_F32) * node->ne[0] * n_tasks;
  16279. } break;
  16280. case GGML_OP_CONV_TRANSPOSE_1D:
  16281. {
  16282. GGML_ASSERT(node->src[0]->ne[3] == 1);
  16283. GGML_ASSERT(node->src[1]->ne[2] == 1);
  16284. GGML_ASSERT(node->src[1]->ne[3] == 1);
  16285. const int64_t ne00 = node->src[0]->ne[0]; // K
  16286. const int64_t ne01 = node->src[0]->ne[1]; // Cout
  16287. const int64_t ne02 = node->src[0]->ne[2]; // Cin
  16288. const int64_t ne10 = node->src[1]->ne[0]; // L
  16289. const int64_t ne11 = node->src[1]->ne[1]; // Cin
  16290. if ((node->src[0]->type == GGML_TYPE_F16 ||
  16291. node->src[0]->type == GGML_TYPE_BF16) &&
  16292. node->src[1]->type == GGML_TYPE_F32) {
  16293. cur += sizeof(ggml_fp16_t)*ne00*ne01*ne02;
  16294. cur += sizeof(ggml_fp16_t)*ne10*ne11;
  16295. } else if (node->src[0]->type == GGML_TYPE_F32 &&
  16296. node->src[1]->type == GGML_TYPE_F32) {
  16297. cur += sizeof(float)*ne00*ne01*ne02;
  16298. cur += sizeof(float)*ne10*ne11;
  16299. } else {
  16300. GGML_ABORT("fatal error");
  16301. }
  16302. } break;
  16303. case GGML_OP_CONV_TRANSPOSE_2D:
  16304. {
  16305. const int64_t ne00 = node->src[0]->ne[0]; // W
  16306. const int64_t ne01 = node->src[0]->ne[1]; // H
  16307. const int64_t ne02 = node->src[0]->ne[2]; // Channels Out
  16308. const int64_t ne03 = node->src[0]->ne[3]; // Channels In
  16309. const int64_t ne10 = node->src[1]->ne[0]; // W
  16310. const int64_t ne11 = node->src[1]->ne[1]; // H
  16311. const int64_t ne12 = node->src[1]->ne[2]; // Channels In
  16312. cur += sizeof(ggml_fp16_t)*ne00*ne01*ne02*ne03;
  16313. cur += sizeof(ggml_fp16_t)*ne10*ne11*ne12;
  16314. } break;
  16315. case GGML_OP_FLASH_ATTN_EXT:
  16316. {
  16317. const int64_t ne00 = node->src[0]->ne[0]; // D
  16318. cur = 3*sizeof(float)*ne00*n_tasks; // 3x head size/thread
  16319. } break;
  16320. case GGML_OP_FLASH_ATTN_BACK:
  16321. {
  16322. const int64_t D = node->src[0]->ne[0];
  16323. const int64_t ne11 = ggml_up(node->src[1]->ne[1], GGML_SOFT_MAX_UNROLL);
  16324. const int64_t mxDn = MAX(D, ne11) * 2; // *2 because of S and SM in ggml_compute_forward_flash_attn_back
  16325. if (node->src[1]->type == GGML_TYPE_F32) {
  16326. cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1)
  16327. cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2
  16328. } else if (node->src[1]->type == GGML_TYPE_F16) {
  16329. cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1)
  16330. cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2
  16331. } else if (node->src[1]->type == GGML_TYPE_BF16) {
  16332. cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1)
  16333. cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2
  16334. }
  16335. } break;
  16336. case GGML_OP_CROSS_ENTROPY_LOSS:
  16337. {
  16338. cur = ggml_type_size(node->type)*(n_tasks + node->src[0]->ne[0]*n_tasks);
  16339. } break;
  16340. case GGML_OP_COUNT:
  16341. {
  16342. GGML_ABORT("fatal error");
  16343. }
  16344. default:
  16345. break;
  16346. }
  16347. work_size = MAX(work_size, cur);
  16348. }
  16349. if (work_size > 0) {
  16350. work_size += CACHE_LINE_SIZE*(n_threads);
  16351. }
  16352. cplan.threadpool = threadpool;
  16353. cplan.n_threads = MIN(max_tasks, n_threads);
  16354. cplan.work_size = work_size;
  16355. cplan.work_data = NULL;
  16356. return cplan;
  16357. }
  16358. static thread_ret_t ggml_graph_compute_thread(void * data) {
  16359. struct ggml_compute_state * state = (struct ggml_compute_state *) data;
  16360. struct ggml_threadpool * tp = state->threadpool;
  16361. const struct ggml_cgraph * cgraph = tp->cgraph;
  16362. const struct ggml_cplan * cplan = tp->cplan;
  16363. set_numa_thread_affinity(state->ith);
  16364. struct ggml_compute_params params = {
  16365. /*.ith =*/ state->ith,
  16366. /*.nth =*/ atomic_load_explicit(&tp->n_threads_cur, memory_order_relaxed),
  16367. /*.wsize =*/ cplan->work_size,
  16368. /*.wdata =*/ cplan->work_data,
  16369. /*.threadpool=*/ tp,
  16370. };
  16371. for (int node_n = 0; node_n < cgraph->n_nodes && !tp->abort; node_n++) {
  16372. struct ggml_tensor * node = cgraph->nodes[node_n];
  16373. ggml_compute_forward(&params, node);
  16374. if (state->ith == 0 && cplan->abort_callback &&
  16375. cplan->abort_callback(cplan->abort_callback_data)) {
  16376. tp->abort = true;
  16377. tp->ec = GGML_STATUS_ABORTED;
  16378. }
  16379. ggml_barrier(state->threadpool);
  16380. }
  16381. return 0;
  16382. }
  16383. #ifndef GGML_USE_OPENMP
  16384. // check if thread is active
  16385. static inline bool ggml_graph_compute_thread_active(struct ggml_compute_state * state) {
  16386. struct ggml_threadpool * threadpool = state->threadpool;
  16387. int n_threads = atomic_load_explicit(&threadpool->n_threads_cur, memory_order_relaxed);
  16388. return (state->ith < n_threads);
  16389. }
  16390. // check if thread is ready to proceed (exit from polling or sleeping)
  16391. static inline bool ggml_graph_compute_thread_ready(struct ggml_compute_state * state) {
  16392. struct ggml_threadpool * threadpool = state->threadpool;
  16393. if (state->pending || threadpool->stop || threadpool->pause) { return true; }
  16394. // check for new graph/work
  16395. int new_graph = atomic_load_explicit(&threadpool->n_graph, memory_order_relaxed);
  16396. if (new_graph != state->last_graph) {
  16397. state->pending = ggml_graph_compute_thread_active(state);
  16398. state->last_graph = new_graph;
  16399. }
  16400. return state->pending;
  16401. }
  16402. // sync thread state after polling
  16403. static inline void ggml_graph_compute_thread_sync(struct ggml_compute_state * state) {
  16404. // TSAN doesn't support standalone fence yet, we use a dummy read-modify-write instead
  16405. #ifdef GGML_TSAN_ENABLED
  16406. atomic_fetch_add_explicit(&state->threadpool->n_graph, 0, memory_order_seq_cst);
  16407. #else
  16408. atomic_thread_fence(memory_order_seq_cst);
  16409. #endif
  16410. UNUSED(state);
  16411. }
  16412. static inline bool ggml_graph_compute_poll_for_work(struct ggml_compute_state * state) {
  16413. struct ggml_threadpool * threadpool = state->threadpool;
  16414. // Skip polling for unused threads
  16415. if (!ggml_graph_compute_thread_active(state)) {
  16416. return state->pending;
  16417. }
  16418. // This seems to make 0 ... 100 a decent range for polling level across modern processors.
  16419. // Perhaps, we can adjust it dynamically based on load and things.
  16420. const uint64_t n_rounds = 1024UL * 128 * threadpool->poll;
  16421. for (uint64_t i=0; !ggml_graph_compute_thread_ready(state) && i < n_rounds; i++) {
  16422. // No new work. Keep polling.
  16423. ggml_thread_cpu_relax();
  16424. }
  16425. return state->pending;
  16426. }
  16427. static inline bool ggml_graph_compute_check_for_work(struct ggml_compute_state * state) {
  16428. struct ggml_threadpool * threadpool = state->threadpool;
  16429. if (ggml_graph_compute_poll_for_work(state)) {
  16430. ggml_graph_compute_thread_sync(state);
  16431. return state->pending;
  16432. }
  16433. ggml_mutex_lock_shared(&threadpool->mutex);
  16434. while (!ggml_graph_compute_thread_ready(state)) {
  16435. // No new work. Wait for the signal.
  16436. GGML_PRINT_DEBUG("thread #%d waiting for work (sleeping)\n", state->ith);
  16437. ggml_cond_wait(&threadpool->cond, &threadpool->mutex);
  16438. }
  16439. ggml_mutex_unlock_shared(&threadpool->mutex);
  16440. return state->pending;
  16441. }
  16442. static thread_ret_t ggml_graph_compute_secondary_thread(void* data) {
  16443. struct ggml_compute_state * state = (struct ggml_compute_state *) data;
  16444. struct ggml_threadpool * threadpool = state->threadpool;
  16445. ggml_thread_apply_priority(threadpool->prio);
  16446. if (ggml_thread_cpumask_is_valid(state->cpumask)) {
  16447. ggml_thread_apply_affinity(state->cpumask);
  16448. }
  16449. while (true) {
  16450. // Check if we need to sleep
  16451. while (threadpool->pause) {
  16452. GGML_PRINT_DEBUG("thread #%d inside pause loop\n", state->ith);
  16453. ggml_mutex_lock_shared(&threadpool->mutex);
  16454. if (threadpool->pause) {
  16455. ggml_cond_wait(&threadpool->cond, &threadpool->mutex);
  16456. }
  16457. GGML_PRINT_DEBUG("thread #%d resuming after wait\n", state->ith);
  16458. ggml_mutex_unlock_shared(&threadpool->mutex);
  16459. }
  16460. // This needs to be checked for after the cond_wait
  16461. if (threadpool->stop) break;
  16462. // Check if there is new work
  16463. // The main thread is the only one that can dispatch new work
  16464. ggml_graph_compute_check_for_work(state);
  16465. if (state->pending) {
  16466. state->pending = false;
  16467. ggml_graph_compute_thread(state);
  16468. }
  16469. }
  16470. return (thread_ret_t) 0;
  16471. }
  16472. // Start processing new graph
  16473. static void ggml_graph_compute_kickoff(struct ggml_threadpool * threadpool, int n_threads)
  16474. {
  16475. // Always take the mutex here because the worker threads are doing hybrid poll/wait
  16476. ggml_mutex_lock(&threadpool->mutex);
  16477. GGML_PRINT_DEBUG("threadpool: n_threads_cur %d n_threads %d\n", threadpool->n_threads_cur, n_threads);
  16478. // Update the number of active threads
  16479. atomic_store_explicit(&threadpool->n_threads_cur, n_threads, memory_order_relaxed);
  16480. // Indicate the graph is ready to be processed
  16481. // We need the full seq-cst fence here because of the polling threads (used in thread_sync)
  16482. atomic_fetch_add_explicit(&threadpool->n_graph, 1, memory_order_seq_cst);
  16483. if (threadpool->pause) {
  16484. // Update main thread prio and affinity to match the threadpool settings
  16485. ggml_thread_apply_priority(threadpool->prio);
  16486. if (ggml_thread_cpumask_is_valid(threadpool->workers[0].cpumask)) {
  16487. ggml_thread_apply_affinity(threadpool->workers[0].cpumask);
  16488. }
  16489. // resume does cond broadcast
  16490. ggml_threadpool_resume_locked(threadpool);
  16491. } else {
  16492. ggml_cond_broadcast(&threadpool->cond);
  16493. }
  16494. ggml_mutex_unlock(&threadpool->mutex);
  16495. }
  16496. #endif // GGML_USE_OPENMP
  16497. void ggml_threadpool_params_init(struct ggml_threadpool_params * p, int n_threads) {
  16498. p->n_threads = n_threads;
  16499. p->prio = 0; // default priority (usually means normal or inherited)
  16500. p->poll = 50; // hybrid-polling enabled
  16501. p->strict_cpu = false; // no strict placement (all threads share same cpumask)
  16502. p->paused = false; // threads are ready to go
  16503. memset(p->cpumask, 0, GGML_MAX_N_THREADS); // all-zero means use the default affinity (usually inherited)
  16504. }
  16505. struct ggml_threadpool_params ggml_threadpool_params_default(int n_threads) {
  16506. struct ggml_threadpool_params p;
  16507. ggml_threadpool_params_init(&p, n_threads);
  16508. return p;
  16509. }
  16510. bool ggml_threadpool_params_match(const struct ggml_threadpool_params * p0, const struct ggml_threadpool_params * p1) {
  16511. if (p0->n_threads != p1->n_threads ) return false;
  16512. if (p0->prio != p1->prio ) return false;
  16513. if (p0->poll != p1->poll ) return false;
  16514. if (p0->strict_cpu != p1->strict_cpu ) return false;
  16515. return memcmp(p0->cpumask, p1->cpumask, GGML_MAX_N_THREADS) == 0;
  16516. }
  16517. static struct ggml_threadpool * ggml_threadpool_new_impl(
  16518. struct ggml_threadpool_params * tpp,
  16519. struct ggml_cgraph * cgraph,
  16520. struct ggml_cplan * cplan) {
  16521. struct ggml_threadpool * threadpool =
  16522. GGML_ALIGNED_MALLOC(sizeof(struct ggml_threadpool));
  16523. {
  16524. threadpool->cgraph = cgraph;
  16525. threadpool->cplan = cplan;
  16526. threadpool->n_graph = 0;
  16527. threadpool->n_barrier = 0;
  16528. threadpool->n_barrier_passed = 0;
  16529. threadpool->current_chunk = 0;
  16530. threadpool->stop = false;
  16531. threadpool->pause = tpp->paused;
  16532. threadpool->abort = false;
  16533. threadpool->workers = NULL;
  16534. threadpool->n_threads_max = tpp->n_threads;
  16535. threadpool->n_threads_cur = tpp->n_threads;
  16536. threadpool->poll = tpp->poll;
  16537. threadpool->prio = tpp->prio;
  16538. threadpool->ec = GGML_STATUS_SUCCESS;
  16539. }
  16540. // Allocate and init workers state
  16541. const size_t workers_size = sizeof(struct ggml_compute_state) * tpp->n_threads;
  16542. struct ggml_compute_state * workers = GGML_ALIGNED_MALLOC(workers_size);
  16543. memset(workers, 0, workers_size);
  16544. for (int j = 0; j < tpp->n_threads; j++) {
  16545. workers[j].threadpool = threadpool;
  16546. workers[j].ith = j;
  16547. }
  16548. threadpool->workers = workers;
  16549. #ifndef GGML_USE_OPENMP
  16550. ggml_mutex_init(&threadpool->mutex);
  16551. ggml_cond_init(&threadpool->cond);
  16552. // Spin the threads for all workers, and update CPU placements.
  16553. // Place the main thread last (towards the higher numbered CPU cores).
  16554. int32_t cpumask_iter = 0;
  16555. for (int j = 1; j < tpp->n_threads; j++) {
  16556. ggml_thread_cpumask_next(tpp->cpumask, workers[j].cpumask, tpp->strict_cpu, &cpumask_iter);
  16557. int32_t rc = ggml_thread_create(&workers[j].thrd, NULL, ggml_graph_compute_secondary_thread, &workers[j]);
  16558. GGML_ASSERT(rc == 0);
  16559. }
  16560. ggml_thread_cpumask_next(tpp->cpumask, workers[0].cpumask, tpp->strict_cpu, &cpumask_iter);
  16561. if (!threadpool->pause) {
  16562. // Update main thread prio and affinity at the start, otherwise we'll do it in resume
  16563. ggml_thread_apply_priority(threadpool->prio);
  16564. if (ggml_thread_cpumask_is_valid(threadpool->workers[0].cpumask)) {
  16565. ggml_thread_apply_affinity(threadpool->workers[0].cpumask);
  16566. }
  16567. }
  16568. #endif // GGML_USE_OPENMP
  16569. return threadpool;
  16570. }
  16571. struct ggml_threadpool * ggml_threadpool_new(struct ggml_threadpool_params * tpp) {
  16572. return ggml_threadpool_new_impl(tpp, NULL, NULL);
  16573. }
  16574. enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cplan * cplan) {
  16575. GGML_ASSERT(cplan);
  16576. GGML_ASSERT(cplan->n_threads > 0);
  16577. GGML_ASSERT(cplan->work_size == 0 || cplan->work_data != NULL);
  16578. int n_threads = cplan->n_threads;
  16579. struct ggml_threadpool * threadpool = cplan->threadpool;
  16580. bool disposable_threadpool = false;
  16581. if (threadpool == NULL) {
  16582. GGML_PRINT_DEBUG("Threadpool is not specified. Will create a disposable threadpool : n_threads %d\n", n_threads);
  16583. disposable_threadpool = true;
  16584. struct ggml_threadpool_params ttp = ggml_threadpool_params_default(n_threads);
  16585. threadpool = ggml_threadpool_new_impl(&ttp, cgraph, cplan);
  16586. } else {
  16587. // Reset some of the parameters that need resetting
  16588. // No worker threads should be accessing the parameters below at this stage
  16589. threadpool->cgraph = cgraph;
  16590. threadpool->cplan = cplan;
  16591. threadpool->current_chunk = 0;
  16592. threadpool->abort = false;
  16593. threadpool->ec = GGML_STATUS_SUCCESS;
  16594. }
  16595. #ifdef GGML_USE_OPENMP
  16596. if (n_threads > 1) {
  16597. #pragma omp parallel num_threads(n_threads)
  16598. {
  16599. #pragma omp single
  16600. {
  16601. // update the number of threads from the actual number of threads that we got from OpenMP
  16602. n_threads = omp_get_num_threads();
  16603. atomic_store_explicit(&threadpool->n_threads_cur, n_threads, memory_order_relaxed);
  16604. }
  16605. ggml_graph_compute_thread(&threadpool->workers[omp_get_thread_num()]);
  16606. }
  16607. } else {
  16608. atomic_store_explicit(&threadpool->n_threads_cur, 1, memory_order_relaxed);
  16609. ggml_graph_compute_thread(&threadpool->workers[0]);
  16610. }
  16611. #else
  16612. if (n_threads > threadpool->n_threads_max) {
  16613. GGML_PRINT("WARNING: cplan requested more threads (%d) than available (%d)\n", n_threads, threadpool->n_threads_max);
  16614. n_threads = threadpool->n_threads_max;
  16615. }
  16616. // Kick all threads to start the new graph
  16617. ggml_graph_compute_kickoff(threadpool, n_threads);
  16618. // This is a work thread too
  16619. ggml_graph_compute_thread(&threadpool->workers[0]);
  16620. #endif
  16621. // don't leave affinity set on the main thread
  16622. clear_numa_thread_affinity();
  16623. enum ggml_status ret = threadpool->ec;
  16624. if (disposable_threadpool) {
  16625. ggml_threadpool_free(threadpool);
  16626. }
  16627. return ret;
  16628. }
  16629. enum ggml_status ggml_graph_compute_with_ctx(struct ggml_context * ctx, struct ggml_cgraph * cgraph, int n_threads) {
  16630. struct ggml_cplan cplan = ggml_graph_plan(cgraph, n_threads, NULL);
  16631. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, cplan.work_size);
  16632. cplan.work_data = (uint8_t *)ctx->mem_buffer + obj->offs;
  16633. return ggml_graph_compute(cgraph, &cplan);
  16634. }
  16635. struct ggml_tensor * ggml_graph_get_tensor(struct ggml_cgraph * cgraph, const char * name) {
  16636. for (int i = 0; i < cgraph->n_leafs; i++) {
  16637. struct ggml_tensor * leaf = cgraph->leafs[i];
  16638. if (strcmp(leaf->name, name) == 0) {
  16639. return leaf;
  16640. }
  16641. }
  16642. for (int i = 0; i < cgraph->n_nodes; i++) {
  16643. struct ggml_tensor * node = cgraph->nodes[i];
  16644. if (strcmp(node->name, name) == 0) {
  16645. return node;
  16646. }
  16647. }
  16648. return NULL;
  16649. }
  16650. static void ggml_graph_export_leaf(const struct ggml_tensor * tensor, FILE * fout) {
  16651. const int64_t * ne = tensor->ne;
  16652. const size_t * nb = tensor->nb;
  16653. fprintf(fout, "%-6s %-12s %8d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %16zu %16zu %16zu %16zu %16p %32s\n",
  16654. ggml_type_name(tensor->type),
  16655. ggml_op_name (tensor->op),
  16656. ggml_n_dims(tensor),
  16657. ne[0], ne[1], ne[2], ne[3],
  16658. nb[0], nb[1], nb[2], nb[3],
  16659. tensor->data,
  16660. tensor->name);
  16661. }
  16662. static void ggml_graph_export_node(const struct ggml_tensor * tensor, const char * arg, FILE * fout) {
  16663. const int64_t * ne = tensor->ne;
  16664. const size_t * nb = tensor->nb;
  16665. fprintf(fout, "%-6s %-6s %-12s %8d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %16zu %16zu %16zu %16zu %16p %32s\n",
  16666. arg,
  16667. ggml_type_name(tensor->type),
  16668. ggml_op_name (tensor->op),
  16669. ggml_n_dims(tensor),
  16670. ne[0], ne[1], ne[2], ne[3],
  16671. nb[0], nb[1], nb[2], nb[3],
  16672. tensor->data,
  16673. tensor->name);
  16674. }
  16675. void ggml_graph_export(const struct ggml_cgraph * cgraph, const char * fname) {
  16676. uint64_t size_eval = 0;
  16677. // compute size of intermediate results
  16678. // TODO: does not take into account scratch buffers !!!!
  16679. for (int i = 0; i < cgraph->n_nodes; ++i) {
  16680. size_eval += ggml_nbytes_pad(cgraph->nodes[i]);
  16681. }
  16682. // print
  16683. {
  16684. FILE * fout = stdout;
  16685. fprintf(fout, "\n");
  16686. fprintf(fout, "%-16s %8x\n", "magic", GGML_FILE_MAGIC);
  16687. fprintf(fout, "%-16s %8d\n", "version", GGML_FILE_VERSION);
  16688. fprintf(fout, "%-16s %8d\n", "leafs", cgraph->n_leafs);
  16689. fprintf(fout, "%-16s %8d\n", "nodes", cgraph->n_nodes);
  16690. fprintf(fout, "%-16s %" PRIu64 "\n", "eval", size_eval);
  16691. // header
  16692. fprintf(fout, "\n");
  16693. fprintf(fout, "%-6s %-12s %8s %8s %8s %8s %8s %16s %16s %16s %16s %16s %16s\n",
  16694. "TYPE", "OP", "NDIMS", "NE0", "NE1", "NE2", "NE3", "NB0", "NB1", "NB2", "NB3", "DATA", "NAME");
  16695. for (int i = 0; i < cgraph->n_leafs; ++i) {
  16696. ggml_graph_export_leaf(cgraph->leafs[i], fout);
  16697. GGML_ASSERT(cgraph->leafs[i]->op == GGML_OP_NONE);
  16698. GGML_ASSERT(cgraph->leafs[i]->src[0] == NULL);
  16699. GGML_ASSERT(cgraph->leafs[i]->src[1] == NULL);
  16700. }
  16701. // header
  16702. fprintf(fout, "\n");
  16703. fprintf(fout, "%-6s %-6s %-12s %8s %8s %8s %8s %8s %16s %16s %16s %16s %8s %16s %16s\n",
  16704. "ARG", "TYPE", "OP", "NDIMS", "NE0", "NE1", "NE2", "NE3", "NB0", "NB1", "NB2", "NB3", "NTASKS", "DATA", "NAME");
  16705. for (int i = 0; i < cgraph->n_nodes; ++i) {
  16706. ggml_graph_export_node(cgraph->nodes[i], "DST", fout);
  16707. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  16708. if (cgraph->nodes[i]->src[j]) {
  16709. ggml_graph_export_node(cgraph->nodes[i]->src[j], "SRC", fout);
  16710. }
  16711. }
  16712. fprintf(fout, "\n");
  16713. }
  16714. fprintf(fout, "\n");
  16715. }
  16716. // write binary data
  16717. {
  16718. FILE * fout = ggml_fopen(fname, "wb");
  16719. if (!fout) {
  16720. fprintf(stderr, "%s: failed to open %s: %s\n", __func__, fname, strerror(errno));
  16721. return;
  16722. }
  16723. // header
  16724. {
  16725. const uint32_t magic = GGML_FILE_MAGIC;
  16726. const uint32_t version = GGML_FILE_VERSION;
  16727. const uint32_t n_leafs = cgraph->n_leafs;
  16728. const uint32_t n_nodes = cgraph->n_nodes;
  16729. fwrite(&magic, sizeof(uint32_t), 1, fout);
  16730. fwrite(&version, sizeof(uint32_t), 1, fout);
  16731. fwrite(&n_leafs, sizeof(uint32_t), 1, fout);
  16732. fwrite(&n_nodes, sizeof(uint32_t), 1, fout);
  16733. fwrite(&size_eval, sizeof(uint64_t), 1, fout);
  16734. }
  16735. // leafs
  16736. {
  16737. for (int i = 0; i < cgraph->n_leafs; ++i) {
  16738. const struct ggml_tensor * tensor = cgraph->leafs[i];
  16739. const uint32_t type = tensor->type;
  16740. const uint32_t op = tensor->op;
  16741. const int32_t flags = tensor->flags;
  16742. fwrite(&type, sizeof(uint32_t), 1, fout);
  16743. fwrite(&op, sizeof(uint32_t), 1, fout);
  16744. fwrite(&flags, sizeof(int32_t), 1, fout);
  16745. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  16746. const uint64_t ne = tensor->ne[j];
  16747. const uint64_t nb = tensor->nb[j];
  16748. fwrite(&ne, sizeof(uint64_t), 1, fout);
  16749. fwrite(&nb, sizeof(uint64_t), 1, fout);
  16750. }
  16751. fwrite(tensor->name, sizeof(char), GGML_MAX_NAME, fout);
  16752. fwrite(tensor->op_params, sizeof(char), GGML_MAX_OP_PARAMS, fout);
  16753. // dump the data
  16754. // TODO: pad this to 32 byte boundary
  16755. {
  16756. const size_t size = ggml_nbytes(tensor);
  16757. fwrite(tensor->data, sizeof(char), size, fout);
  16758. }
  16759. }
  16760. }
  16761. // nodes
  16762. {
  16763. for (int i = 0; i < cgraph->n_nodes; ++i) {
  16764. const struct ggml_tensor * tensor = cgraph->nodes[i];
  16765. const uint32_t type = tensor->type;
  16766. const uint32_t op = tensor->op;
  16767. const int32_t flags = tensor->flags;
  16768. fwrite(&type, sizeof(uint32_t), 1, fout);
  16769. fwrite(&op, sizeof(uint32_t), 1, fout);
  16770. fwrite(&flags, sizeof(int32_t), 1, fout);
  16771. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  16772. const uint64_t ne = tensor->ne[j];
  16773. const uint64_t nb = tensor->nb[j];
  16774. fwrite(&ne, sizeof(uint64_t), 1, fout);
  16775. fwrite(&nb, sizeof(uint64_t), 1, fout);
  16776. }
  16777. fwrite(tensor->name, sizeof(char), GGML_MAX_NAME, fout);
  16778. fwrite(tensor->op_params, sizeof(char), GGML_MAX_OP_PARAMS, fout);
  16779. // output the op arguments
  16780. {
  16781. struct ggml_tensor * args[GGML_MAX_SRC] = { NULL };
  16782. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  16783. args[j] = tensor->src[j];
  16784. }
  16785. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  16786. if (args[j]) {
  16787. int32_t idx = -1;
  16788. // check if leaf
  16789. {
  16790. for (int k = 0; k < cgraph->n_leafs; ++k) {
  16791. if (args[j] == cgraph->leafs[k]) {
  16792. idx = k;
  16793. break;
  16794. }
  16795. }
  16796. }
  16797. // check if node
  16798. if (idx == -1) {
  16799. for (int k = 0; k < cgraph->n_nodes; ++k) {
  16800. if (args[j] == cgraph->nodes[k]) {
  16801. idx = cgraph->n_leafs + k;
  16802. break;
  16803. }
  16804. }
  16805. }
  16806. if (idx == -1) {
  16807. fprintf(stderr, "%s: failed to find tensor, arg = %d, node = %d\n", __func__, j, i);
  16808. fclose(fout);
  16809. return;
  16810. }
  16811. fwrite(&idx, sizeof(int32_t), 1, fout);
  16812. } else {
  16813. const int32_t nul = -1;
  16814. fwrite(&nul, sizeof(int32_t), 1, fout);
  16815. }
  16816. }
  16817. }
  16818. // dump the data
  16819. // TODO: pad this to 32 byte boundary
  16820. if ((flags & GGML_TENSOR_FLAG_PARAM)) {
  16821. const size_t size = ggml_nbytes(tensor);
  16822. fwrite(tensor->data, sizeof(char), size, fout);
  16823. }
  16824. }
  16825. }
  16826. fclose(fout);
  16827. }
  16828. }
  16829. struct ggml_cgraph * ggml_graph_import(const char * fname, struct ggml_context ** ctx_data, struct ggml_context ** ctx_eval) {
  16830. assert(*ctx_data == NULL);
  16831. assert(*ctx_eval == NULL);
  16832. struct ggml_cgraph * result = NULL;
  16833. struct ggml_tensor * data = NULL;
  16834. // read file into data
  16835. {
  16836. FILE * fin = ggml_fopen(fname, "rb");
  16837. if (!fin) {
  16838. fprintf(stderr, "%s: failed to open %s: %s\n", __func__, fname, strerror(errno));
  16839. return result;
  16840. }
  16841. size_t fsize = 0;
  16842. fseek(fin, 0, SEEK_END);
  16843. fsize = ftell(fin);
  16844. fseek(fin, 0, SEEK_SET);
  16845. // create the data context
  16846. {
  16847. const size_t overhead = 1*ggml_tensor_overhead();
  16848. struct ggml_init_params params = {
  16849. .mem_size = fsize + overhead,
  16850. .mem_buffer = NULL,
  16851. .no_alloc = false,
  16852. };
  16853. *ctx_data = ggml_init(params);
  16854. if (!*ctx_data) {
  16855. fprintf(stderr, "%s: failed to create ggml context\n", __func__);
  16856. fclose(fin);
  16857. return result;
  16858. }
  16859. }
  16860. data = ggml_new_tensor_1d(*ctx_data, GGML_TYPE_I8, fsize);
  16861. {
  16862. const size_t ret = fread(data->data, sizeof(char), fsize, fin);
  16863. if (ret != fsize) {
  16864. fprintf(stderr, "%s: failed to read %s\n", __func__, fname);
  16865. fclose(fin);
  16866. return result;
  16867. }
  16868. }
  16869. fclose(fin);
  16870. }
  16871. // populate result
  16872. {
  16873. char * ptr = (char *) data->data;
  16874. const uint32_t magic = *(const uint32_t *) ptr; ptr += sizeof(magic);
  16875. if (magic != GGML_FILE_MAGIC) {
  16876. fprintf(stderr, "%s: invalid magic number, got %08x\n", __func__, magic);
  16877. return result;
  16878. }
  16879. const uint32_t version = *(const uint32_t *) ptr; ptr += sizeof(version);
  16880. if (version != GGML_FILE_VERSION) {
  16881. fprintf(stderr, "%s: invalid version number\n", __func__);
  16882. return result;
  16883. }
  16884. const uint32_t n_leafs = *(const uint32_t *) ptr; ptr += sizeof(n_leafs);
  16885. const uint32_t n_nodes = *(const uint32_t *) ptr; ptr += sizeof(n_nodes);
  16886. const uint64_t size_eval = *(const uint64_t *) ptr; ptr += sizeof(size_eval);
  16887. const int graph_size = MAX(n_leafs, n_nodes);
  16888. // create the data context
  16889. {
  16890. const size_t overhead = (n_leafs + n_nodes)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false);
  16891. struct ggml_init_params params = {
  16892. .mem_size = size_eval + overhead,
  16893. .mem_buffer = NULL,
  16894. .no_alloc = true,
  16895. };
  16896. *ctx_eval = ggml_init(params);
  16897. if (!*ctx_eval) {
  16898. fprintf(stderr, "%s: failed to create ggml context\n", __func__);
  16899. return result;
  16900. }
  16901. }
  16902. result = ggml_new_graph_custom(*ctx_eval, graph_size, false);
  16903. result->n_leafs = n_leafs;
  16904. result->n_nodes = n_nodes;
  16905. // leafs
  16906. {
  16907. uint32_t type;
  16908. uint32_t op;
  16909. int32_t flags;
  16910. for (uint32_t i = 0; i < n_leafs; ++i) {
  16911. type = *(const uint32_t *) ptr; ptr += sizeof(type);
  16912. op = *(const uint32_t *) ptr; ptr += sizeof(op);
  16913. flags = *(const int32_t *) ptr; ptr += sizeof(flags);
  16914. int64_t ne[GGML_MAX_DIMS];
  16915. size_t nb[GGML_MAX_DIMS];
  16916. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  16917. uint64_t ne_cur;
  16918. uint64_t nb_cur;
  16919. ne_cur = *(const uint64_t *) ptr; ptr += sizeof(ne_cur);
  16920. nb_cur = *(const uint64_t *) ptr; ptr += sizeof(nb_cur);
  16921. ne[j] = ne_cur;
  16922. nb[j] = nb_cur;
  16923. }
  16924. struct ggml_tensor * tensor = ggml_new_tensor(*ctx_eval, (enum ggml_type) type, GGML_MAX_DIMS, ne);
  16925. tensor->op = (enum ggml_op) op;
  16926. tensor->flags = flags;
  16927. memcpy(tensor->name, ptr, GGML_MAX_NAME); ptr += GGML_MAX_NAME;
  16928. memcpy(tensor->op_params, ptr, GGML_MAX_OP_PARAMS); ptr += GGML_MAX_OP_PARAMS;
  16929. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  16930. tensor->nb[j] = nb[j];
  16931. }
  16932. tensor->data = (void *) ptr; ptr += ggml_nbytes(tensor);
  16933. result->leafs[i] = tensor;
  16934. fprintf(stderr, "%s: loaded leaf %u: '%16s', %9zu bytes\n", __func__, i, tensor->name, ggml_nbytes(tensor));
  16935. }
  16936. }
  16937. ggml_set_no_alloc(*ctx_eval, false);
  16938. // nodes
  16939. {
  16940. uint32_t type;
  16941. uint32_t op;
  16942. int32_t flags;
  16943. for (uint32_t i = 0; i < n_nodes; ++i) {
  16944. type = *(const uint32_t *) ptr; ptr += sizeof(type);
  16945. op = *(const uint32_t *) ptr; ptr += sizeof(op);
  16946. flags = *(const int32_t *) ptr; ptr += sizeof(flags);
  16947. enum ggml_op eop = (enum ggml_op) op;
  16948. int64_t ne[GGML_MAX_DIMS];
  16949. size_t nb[GGML_MAX_DIMS];
  16950. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  16951. uint64_t ne_cur;
  16952. uint64_t nb_cur;
  16953. ne_cur = *(const uint64_t *) ptr; ptr += sizeof(ne_cur);
  16954. nb_cur = *(const uint64_t *) ptr; ptr += sizeof(nb_cur);
  16955. ne[j] = ne_cur;
  16956. nb[j] = nb_cur;
  16957. }
  16958. const char * ptr_name = ptr; ptr += GGML_MAX_NAME;
  16959. const char * ptr_op_params = ptr; ptr += GGML_MAX_OP_PARAMS;
  16960. const int32_t * ptr_arg_idx = (const int32_t *) ptr; ptr += GGML_MAX_SRC*sizeof(int32_t);
  16961. struct ggml_tensor * args[GGML_MAX_SRC] = { NULL };
  16962. // parse args
  16963. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  16964. const int32_t arg_idx = ptr_arg_idx[j];
  16965. if (arg_idx == -1) {
  16966. continue;
  16967. }
  16968. if (arg_idx < result->n_leafs) {
  16969. args[j] = result->leafs[arg_idx];
  16970. } else {
  16971. args[j] = result->nodes[arg_idx - result->n_leafs];
  16972. }
  16973. }
  16974. // create the tensor
  16975. // "view" operations are handled differently
  16976. // TODO: handle inplace ops - currently a copy is always made
  16977. struct ggml_tensor * tensor = NULL;
  16978. switch (eop) {
  16979. // TODO: implement other view ops
  16980. case GGML_OP_RESHAPE:
  16981. {
  16982. tensor = ggml_reshape_4d(*ctx_eval, args[0], ne[0], ne[1], ne[2], ne[3]);
  16983. } break;
  16984. case GGML_OP_VIEW:
  16985. {
  16986. tensor = ggml_view_4d(*ctx_eval, args[0], ne[0], ne[1], ne[2], ne[3], 0, 0, 0, 0);
  16987. size_t offs;
  16988. memcpy(&offs, ptr_op_params, sizeof(offs));
  16989. tensor->data = ((char *) tensor->data) + offs;
  16990. } break;
  16991. case GGML_OP_TRANSPOSE:
  16992. {
  16993. tensor = ggml_transpose(*ctx_eval, args[0]);
  16994. } break;
  16995. case GGML_OP_PERMUTE:
  16996. {
  16997. tensor = ggml_view_4d(*ctx_eval, args[0], ne[0], ne[1], ne[2], ne[3], 0, 0, 0, 0);
  16998. } break;
  16999. default:
  17000. {
  17001. tensor = ggml_new_tensor(*ctx_eval, (enum ggml_type) type, GGML_MAX_DIMS, ne);
  17002. tensor->op = eop;
  17003. } break;
  17004. }
  17005. memcpy(tensor->name, ptr_name, GGML_MAX_NAME);
  17006. memcpy(tensor->op_params, ptr_op_params, GGML_MAX_OP_PARAMS);
  17007. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  17008. tensor->nb[j] = nb[j];
  17009. }
  17010. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  17011. tensor->src[j] = args[j];
  17012. }
  17013. result->nodes[i] = tensor;
  17014. // TODO tensor data is be duplicated due to ggml_new_tensor call above
  17015. if (flags & GGML_TENSOR_FLAG_PARAM) {
  17016. tensor->data = (void *) ptr; ptr += ggml_nbytes(tensor);
  17017. }
  17018. fprintf(stderr, "%s: loaded node %u: '%16s', %9zu bytes\n", __func__, i, tensor->name, ggml_nbytes(tensor));
  17019. }
  17020. }
  17021. }
  17022. return result;
  17023. }
  17024. void ggml_graph_print(const struct ggml_cgraph * cgraph) {
  17025. GGML_PRINT("=== GRAPH ===\n");
  17026. GGML_PRINT("n_nodes = %d\n", cgraph->n_nodes);
  17027. for (int i = 0; i < cgraph->n_nodes; i++) {
  17028. struct ggml_tensor * node = cgraph->nodes[i];
  17029. GGML_PRINT(" - %3d: [ %5" PRId64 ", %5" PRId64 ", %5" PRId64 "] %16s %s\n",
  17030. i,
  17031. node->ne[0], node->ne[1], node->ne[2],
  17032. ggml_op_name(node->op), (node->flags & GGML_TENSOR_FLAG_PARAM) ? "x" : node->grad ? "g" : " ");
  17033. }
  17034. GGML_PRINT("n_leafs = %d\n", cgraph->n_leafs);
  17035. for (int i = 0; i < cgraph->n_leafs; i++) {
  17036. struct ggml_tensor * node = cgraph->leafs[i];
  17037. GGML_PRINT(" - %3d: [ %5" PRId64 ", %5" PRId64 "] %8s %16s\n",
  17038. i,
  17039. node->ne[0], node->ne[1],
  17040. ggml_op_name(node->op),
  17041. ggml_get_name(node));
  17042. }
  17043. GGML_PRINT("========================================\n");
  17044. }
  17045. // check if node is part of the graph
  17046. static bool ggml_graph_find(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  17047. if (cgraph == NULL) {
  17048. return true;
  17049. }
  17050. for (int i = 0; i < cgraph->n_nodes; i++) {
  17051. if (cgraph->nodes[i] == node) {
  17052. return true;
  17053. }
  17054. }
  17055. return false;
  17056. }
  17057. static struct ggml_tensor * ggml_graph_get_parent(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  17058. for (int i = 0; i < cgraph->n_nodes; i++) {
  17059. struct ggml_tensor * parent = cgraph->nodes[i];
  17060. if (parent->grad == node) {
  17061. return parent;
  17062. }
  17063. }
  17064. return NULL;
  17065. }
  17066. static void ggml_graph_dump_dot_node_edge(FILE * fp, const struct ggml_cgraph * gb, struct ggml_tensor * node, struct ggml_tensor * parent, const char * label) {
  17067. struct ggml_tensor * gparent = ggml_graph_get_parent(gb, node);
  17068. struct ggml_tensor * gparent0 = ggml_graph_get_parent(gb, parent);
  17069. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ arrowhead = %s; style = %s; label = \"%s\"; ]\n",
  17070. gparent0 ? (void *) gparent0 : (void *) parent,
  17071. gparent0 ? "g" : "x",
  17072. gparent ? (void *) gparent : (void *) node,
  17073. gparent ? "g" : "x",
  17074. gparent ? "empty" : "vee",
  17075. gparent ? "dashed" : "solid",
  17076. label);
  17077. }
  17078. static void ggml_graph_dump_dot_leaf_edge(FILE * fp, struct ggml_tensor * node, struct ggml_tensor * parent, const char * label) {
  17079. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ label = \"%s\"; ]\n",
  17080. (void *) parent, "x",
  17081. (void *) node, "x",
  17082. label);
  17083. }
  17084. void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * gf, const char * filename) {
  17085. char color[16];
  17086. FILE * fp = ggml_fopen(filename, "w");
  17087. GGML_ASSERT(fp);
  17088. fprintf(fp, "digraph G {\n");
  17089. fprintf(fp, " newrank = true;\n");
  17090. fprintf(fp, " rankdir = TB;\n");
  17091. for (int i = 0; i < gb->n_nodes; i++) {
  17092. struct ggml_tensor * node = gb->nodes[i];
  17093. if (ggml_graph_get_parent(gb, node) != NULL) {
  17094. continue;
  17095. }
  17096. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  17097. snprintf(color, sizeof(color), "yellow");
  17098. } else if (node->grad) {
  17099. if (ggml_graph_find(gf, node)) {
  17100. snprintf(color, sizeof(color), "green");
  17101. } else {
  17102. snprintf(color, sizeof(color), "lightblue");
  17103. }
  17104. } else {
  17105. snprintf(color, sizeof(color), "white");
  17106. }
  17107. fprintf(fp, " \"%p\" [ "
  17108. "style = filled; fillcolor = %s; shape = record; "
  17109. "label=\"",
  17110. (void *) node, color);
  17111. if (strlen(node->name) > 0) {
  17112. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  17113. } else {
  17114. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  17115. }
  17116. if (ggml_is_matrix(node)) {
  17117. fprintf(fp, "%d [%" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], ggml_op_symbol(node->op));
  17118. } else {
  17119. fprintf(fp, "%d [%" PRId64 ", %" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], node->ne[2], ggml_op_symbol(node->op));
  17120. }
  17121. if (node->grad) {
  17122. fprintf(fp, " | <g>%s\"; ]\n", ggml_op_symbol(node->grad->op));
  17123. } else {
  17124. fprintf(fp, "\"; ]\n");
  17125. }
  17126. }
  17127. for (int i = 0; i < gb->n_leafs; i++) {
  17128. struct ggml_tensor * node = gb->leafs[i];
  17129. snprintf(color, sizeof(color), "pink");
  17130. fprintf(fp, " \"%p\" [ "
  17131. "style = filled; fillcolor = %s; shape = record; "
  17132. "label=\"<x>",
  17133. (void *) node, color);
  17134. if (strlen(node->name) > 0) {
  17135. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  17136. } else {
  17137. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  17138. }
  17139. fprintf(fp, "CONST %d [%" PRId64 ", %" PRId64 "]", i, node->ne[0], node->ne[1]);
  17140. if (ggml_nelements(node) < 5 && node->data != NULL) {
  17141. fprintf(fp, " | (");
  17142. for (int j = 0; j < ggml_nelements(node); j++) {
  17143. if (node->type == GGML_TYPE_I8 || node->type == GGML_TYPE_I16 || node->type == GGML_TYPE_I32) {
  17144. fprintf(fp, "%d", ggml_get_i32_1d(node, j));
  17145. }
  17146. else if (node->type == GGML_TYPE_F32 ||
  17147. node->type == GGML_TYPE_F16 ||
  17148. node->type == GGML_TYPE_BF16) {
  17149. fprintf(fp, "%.1e", (double)ggml_get_f32_1d(node, j));
  17150. }
  17151. else {
  17152. fprintf(fp, "#");
  17153. }
  17154. if (j < ggml_nelements(node) - 1) {
  17155. fprintf(fp, ", ");
  17156. }
  17157. }
  17158. fprintf(fp, ")");
  17159. }
  17160. fprintf(fp, "\"; ]\n");
  17161. }
  17162. for (int i = 0; i < gb->n_nodes; i++) {
  17163. struct ggml_tensor * node = gb->nodes[i];
  17164. for (int j = 0; j < GGML_MAX_SRC; j++) {
  17165. if (node->src[j]) {
  17166. char label[16];
  17167. snprintf(label, sizeof(label), "src %d", j);
  17168. ggml_graph_dump_dot_node_edge(fp, gb, node, node->src[j], label);
  17169. }
  17170. }
  17171. }
  17172. for (int i = 0; i < gb->n_leafs; i++) {
  17173. struct ggml_tensor * node = gb->leafs[i];
  17174. for (int j = 0; j < GGML_MAX_SRC; j++) {
  17175. if (node->src[j]) {
  17176. char label[16];
  17177. snprintf(label, sizeof(label), "src %d", j);
  17178. ggml_graph_dump_dot_leaf_edge(fp, node, node->src[j], label);
  17179. }
  17180. }
  17181. }
  17182. fprintf(fp, "}\n");
  17183. fclose(fp);
  17184. GGML_PRINT("%s: dot -Tpng %s -o %s.png && open %s.png\n", __func__, filename, filename, filename);
  17185. }
  17186. ////////////////////////////////////////////////////////////////////////////////
  17187. static void ggml_opt_set_params(int np, struct ggml_tensor * const ps[], const float * x) {
  17188. int i = 0;
  17189. for (int p = 0; p < np; ++p) {
  17190. const int64_t ne = ggml_nelements(ps[p]) ;
  17191. // TODO: add function to set tensor from array
  17192. for (int64_t j = 0; j < ne; ++j) {
  17193. ggml_set_f32_1d(ps[p], j, x[i++]);
  17194. }
  17195. }
  17196. }
  17197. static void ggml_opt_get_params(int np, struct ggml_tensor * const ps[], float * x) {
  17198. int i = 0;
  17199. for (int p = 0; p < np; ++p) {
  17200. const int64_t ne = ggml_nelements(ps[p]) ;
  17201. // TODO: add function to get all elements at once
  17202. for (int64_t j = 0; j < ne; ++j) {
  17203. x[i++] = ggml_get_f32_1d(ps[p], j);
  17204. }
  17205. }
  17206. }
  17207. static void ggml_opt_get_grad(int np, struct ggml_tensor * const ps[], float * g) {
  17208. int64_t i = 0;
  17209. for (int p = 0; p < np; ++p) {
  17210. const int64_t ne = ggml_nelements(ps[p]) ;
  17211. // TODO: add function to get all elements at once
  17212. for (int64_t j = 0; j < ne; ++j) {
  17213. g[i++] = ggml_get_f32_1d(ps[p]->grad, j);
  17214. }
  17215. }
  17216. }
  17217. static void ggml_opt_acc_grad(int np, struct ggml_tensor * const ps[], float * g, float scale) {
  17218. int64_t i = 0;
  17219. for (int p = 0; p < np; ++p) {
  17220. const int64_t ne = ggml_nelements(ps[p]) ;
  17221. // TODO: add function to get all elements at once
  17222. for (int64_t j = 0; j < ne; ++j) {
  17223. g[i++] += ggml_get_f32_1d(ps[p]->grad, j) * scale;
  17224. }
  17225. }
  17226. }
  17227. //
  17228. // Using AdamW - ref: https://arxiv.org/pdf/1711.05101v3.pdf
  17229. //
  17230. // (Original Adam - ref: https://arxiv.org/pdf/1412.6980.pdf)
  17231. //
  17232. static enum ggml_opt_result ggml_opt_adam(
  17233. struct ggml_context * ctx,
  17234. struct ggml_opt_context * opt,
  17235. struct ggml_opt_params params,
  17236. struct ggml_tensor * f,
  17237. struct ggml_cgraph * gf,
  17238. struct ggml_cgraph * gb,
  17239. ggml_opt_callback callback,
  17240. void * callback_data) {
  17241. GGML_ASSERT(ggml_is_scalar(f));
  17242. GGML_ASSERT(f->type == GGML_TYPE_F32);
  17243. // these will store the parameters we want to optimize
  17244. struct ggml_tensor * ps[GGML_MAX_PARAMS];
  17245. int np = 0;
  17246. int64_t nx = 0;
  17247. for (int i = 0; i < gf->n_nodes; ++i) {
  17248. if (gf->nodes[i]->flags & GGML_TENSOR_FLAG_PARAM) {
  17249. GGML_PRINT_DEBUG("found param %d: grad->op = %d\n", np, gf->nodes[i]->grad->op);
  17250. GGML_ASSERT(np < GGML_MAX_PARAMS);
  17251. ps[np++] = gf->nodes[i];
  17252. nx += ggml_nelements(gf->nodes[i]);
  17253. }
  17254. }
  17255. if ((opt->params.type != params.type) || (opt->nx != nx) || (opt->params.past != params.past)) {
  17256. int iter = opt->iter;
  17257. ggml_opt_init(opt->ctx, opt, params, nx);
  17258. opt->iter = iter;
  17259. }
  17260. // constants
  17261. float sched = params.adam.sched;
  17262. const float alpha = params.adam.alpha;
  17263. const float decay = params.adam.decay * alpha;
  17264. const float beta1 = params.adam.beta1;
  17265. const float beta2 = params.adam.beta2;
  17266. const float eps = params.adam.eps;
  17267. const float gclip = params.adam.gclip;
  17268. const int decay_min_ndim = params.adam.decay_min_ndim;
  17269. const int n_accum = MAX(1, params.n_gradient_accumulation);
  17270. const float accum_norm = 1.0f / (float) n_accum;
  17271. float * g = opt->adam.g->data; // gradients
  17272. float * m = opt->adam.m->data; // first moment
  17273. float * v = opt->adam.v->data; // second moment
  17274. float * pf = params.past > 0 ? opt->adam.pf->data : NULL; // past function values
  17275. struct ggml_cplan cplan = ggml_graph_plan(gb, params.n_threads, NULL);
  17276. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, cplan.work_size);
  17277. cplan.work_data = (uint8_t *)ctx->mem_buffer + obj->offs;
  17278. bool cancel = false;
  17279. // compute the function value
  17280. float fx = 0;
  17281. ggml_set_zero(opt->adam.g);
  17282. for (int accum_step = 0; accum_step < n_accum; ++accum_step) {
  17283. if (callback) {
  17284. callback(callback_data, accum_step, &sched, &cancel);
  17285. if (cancel) {
  17286. return GGML_OPT_RESULT_CANCEL;
  17287. }
  17288. }
  17289. // ggml_graph_reset (gf);
  17290. ggml_set_f32 (f->grad, 1.0f);
  17291. ggml_graph_compute(gb, &cplan);
  17292. ggml_opt_acc_grad(np, ps, g, accum_norm);
  17293. fx += ggml_get_f32_1d(f, 0);
  17294. }
  17295. fx *= accum_norm;
  17296. opt->adam.fx_prev = fx;
  17297. opt->adam.fx_best = opt->adam.fx_prev;
  17298. if (pf) {
  17299. pf[opt->iter % params.past] = opt->adam.fx_prev;
  17300. }
  17301. opt->loss_before = opt->adam.fx_prev;
  17302. opt->loss_after = opt->adam.fx_prev;
  17303. // initialize
  17304. if (opt->just_initialized) {
  17305. opt->adam.n_no_improvement = 0;
  17306. opt->just_initialized = false;
  17307. }
  17308. float * fx_best = &opt->adam.fx_best;
  17309. float * fx_prev = &opt->adam.fx_prev;
  17310. int * n_no_improvement = &opt->adam.n_no_improvement;
  17311. int iter0 = opt->iter;
  17312. // run the optimizer
  17313. for (int t = 0; t < params.adam.n_iter; ++t) {
  17314. opt->iter = iter0 + t + 1;
  17315. GGML_PRINT_DEBUG ("=== iter %d ===\n", t);
  17316. GGML_PRINT_DEBUG ("f = %10.6f\n", ggml_get_f32_1d(f, 0));
  17317. GGML_PRINT_DEBUG_5("df/dx0 = %10.6f\n", ggml_get_f32_1d(ps[0]->grad, 0));
  17318. GGML_PRINT_DEBUG_5("df/dx1 = %10.6f\n", ggml_get_f32_1d(ps[1]->grad, 0));
  17319. for (int i = 0; i < np; ++i) {
  17320. GGML_PRINT_DEBUG("param %d: %10.6f, g = %10.6f\n", i,
  17321. ggml_get_f32_1d(ps[i], 0), ggml_get_f32_1d(ps[i]->grad, 0));
  17322. }
  17323. const int64_t t_start_wall = ggml_time_us();
  17324. const int64_t t_start_cpu = ggml_cycles();
  17325. UNUSED(t_start_wall);
  17326. UNUSED(t_start_cpu);
  17327. {
  17328. float gnorm = 1.0f;
  17329. if (gclip > 0.0f) {
  17330. // gradient clipping
  17331. ggml_float sum = 0.0;
  17332. for (int64_t i = 0; i < nx; ++i) {
  17333. sum += (ggml_float)(g[i]*g[i]);
  17334. }
  17335. ggml_float norm = sqrt(sum);
  17336. if (norm > (ggml_float) gclip) {
  17337. gnorm = (float) ((ggml_float) gclip / norm);
  17338. }
  17339. }
  17340. const float beta1h = alpha*sched/(1.0f - powf(beta1, opt->iter));
  17341. const float beta2h = 1.0f/(1.0f - powf(beta2, opt->iter));
  17342. int64_t i = 0;
  17343. for (int p = 0; p < np; ++p) {
  17344. const int64_t ne = ggml_nelements(ps[p]);
  17345. const float p_decay = ((ggml_n_dims(ps[p]) >= decay_min_ndim) ? decay : 0.0f) * sched;
  17346. for (int64_t j = 0; j < ne; ++j) {
  17347. float x = ggml_get_f32_1d(ps[p], j);
  17348. float g_ = g[i]*gnorm;
  17349. m[i] = m[i]*beta1 + g_*(1.0f - beta1);
  17350. v[i] = v[i]*beta2 + g_*g_*(1.0f - beta2);
  17351. float mh = m[i]*beta1h;
  17352. float vh = v[i]*beta2h;
  17353. vh = sqrtf(vh) + eps;
  17354. x = x*(1.0f - p_decay) - mh/vh;
  17355. ggml_set_f32_1d(ps[p], j, x);
  17356. ++i;
  17357. }
  17358. }
  17359. }
  17360. fx = 0;
  17361. ggml_set_zero(opt->adam.g);
  17362. for (int accum_step = 0; accum_step < n_accum; ++accum_step) {
  17363. if (callback) {
  17364. callback(callback_data, accum_step, &sched, &cancel);
  17365. if (cancel) {
  17366. return GGML_OPT_RESULT_CANCEL;;
  17367. }
  17368. }
  17369. // ggml_graph_reset (gf);
  17370. ggml_set_f32 (f->grad, 1.0f);
  17371. ggml_graph_compute(gb, &cplan);
  17372. ggml_opt_acc_grad(np, ps, g, accum_norm);
  17373. fx += ggml_get_f32_1d(f, 0);
  17374. }
  17375. fx *= accum_norm;
  17376. opt->loss_after = fx;
  17377. // check convergence
  17378. if (fabsf(fx - fx_prev[0])/fx < params.adam.eps_f) {
  17379. GGML_PRINT_DEBUG("converged\n");
  17380. return GGML_OPT_RESULT_OK;
  17381. }
  17382. // delta-based convergence test
  17383. if (pf != NULL) {
  17384. // need at least params.past iterations to start checking for convergence
  17385. if (params.past <= iter0 + t) {
  17386. const float rate = (pf[(iter0 + t)%params.past] - fx)/fx;
  17387. if (fabsf(rate) < params.delta) {
  17388. return GGML_OPT_RESULT_OK;
  17389. }
  17390. }
  17391. pf[(iter0 + t)%params.past] = fx;
  17392. }
  17393. // check for improvement
  17394. if (params.max_no_improvement > 0) {
  17395. if (fx_best[0] > fx) {
  17396. fx_best[0] = fx;
  17397. n_no_improvement[0] = 0;
  17398. } else {
  17399. ++n_no_improvement[0];
  17400. if (n_no_improvement[0] >= params.max_no_improvement) {
  17401. return GGML_OPT_RESULT_OK;
  17402. }
  17403. }
  17404. }
  17405. fx_prev[0] = fx;
  17406. {
  17407. const int64_t t_end_cpu = ggml_cycles();
  17408. GGML_PRINT_DEBUG("time iter: %5.3f s\n", ((float)(t_end_cpu - t_start_cpu))/CLOCKS_PER_SEC);
  17409. UNUSED(t_end_cpu);
  17410. const int64_t t_end_wall = ggml_time_us();
  17411. GGML_PRINT_DEBUG("wall time iter: %5.3f s\n", (t_end_wall - t_start_wall)/1e6);
  17412. UNUSED(t_end_wall);
  17413. }
  17414. }
  17415. return GGML_OPT_RESULT_DID_NOT_CONVERGE;
  17416. }
  17417. //
  17418. // L-BFGS
  17419. //
  17420. // the L-BFGS implementation below is based on the following implementation:
  17421. //
  17422. // https://github.com/chokkan/liblbfgs
  17423. //
  17424. struct ggml_lbfgs_iteration_data {
  17425. float alpha;
  17426. float ys;
  17427. float * s;
  17428. float * y;
  17429. };
  17430. static enum ggml_opt_result linesearch_backtracking(
  17431. const struct ggml_opt_params * params,
  17432. int nx,
  17433. float * x,
  17434. float * fx,
  17435. float * g,
  17436. float * d,
  17437. float * step,
  17438. const float * xp,
  17439. struct ggml_tensor * f,
  17440. struct ggml_cgraph * gb,
  17441. struct ggml_cplan * cplan,
  17442. const int np,
  17443. struct ggml_tensor * ps[],
  17444. bool * cancel,
  17445. ggml_opt_callback callback,
  17446. void * callback_data) {
  17447. int count = 0;
  17448. float width = 0.0f;
  17449. float dg = 0.0f;
  17450. float finit = 0.0f;
  17451. float dginit = 0.0f;
  17452. float dgtest = 0.0f;
  17453. const float dec = 0.5f;
  17454. const float inc = 2.1f;
  17455. const int n_accum = MAX(1, params->n_gradient_accumulation);
  17456. const float accum_norm = 1.0f / (float) n_accum;
  17457. if (*step <= 0.f) {
  17458. return GGML_LINESEARCH_INVALID_PARAMETERS;
  17459. }
  17460. // compute the initial gradient in the search direction
  17461. ggml_vec_dot_f32(nx, &dginit, 0, g, 0, d, 0, 1);
  17462. // make sure that d points to a descent direction
  17463. if (0 < dginit) {
  17464. return GGML_LINESEARCH_FAIL;
  17465. }
  17466. // initialize local variables
  17467. finit = *fx;
  17468. dgtest = params->lbfgs.ftol*dginit;
  17469. while (true) {
  17470. ggml_vec_cpy_f32(nx, x, xp);
  17471. ggml_vec_mad_f32(nx, x, d, *step);
  17472. // evaluate the function and gradient values
  17473. {
  17474. ggml_opt_set_params(np, ps, x);
  17475. *fx = 0;
  17476. memset(g, 0, sizeof(float)*nx);
  17477. for (int accum_step = 0; accum_step < n_accum; ++accum_step) {
  17478. if (callback) {
  17479. // LBFG-S does not support learning rate -> ignore learning schedule
  17480. float sched = 0;
  17481. callback(callback_data, accum_step, &sched, cancel);
  17482. if (*cancel) {
  17483. return GGML_OPT_RESULT_CANCEL;
  17484. }
  17485. }
  17486. // ggml_graph_reset (gf);
  17487. ggml_set_f32 (f->grad, 1.0f);
  17488. ggml_graph_compute(gb, cplan);
  17489. ggml_opt_acc_grad(np, ps, g, accum_norm);
  17490. *fx += ggml_get_f32_1d(f, 0);
  17491. }
  17492. *fx *= accum_norm;
  17493. }
  17494. ++count;
  17495. if (*fx > finit + (*step)*dgtest) {
  17496. width = dec;
  17497. } else {
  17498. // Armijo condition is satisfied
  17499. if (params->lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_ARMIJO) {
  17500. return count;
  17501. }
  17502. ggml_vec_dot_f32(nx, &dg, 0, g, 0, d, 0, 1);
  17503. // check the Wolfe condition
  17504. if (dg < params->lbfgs.wolfe * dginit) {
  17505. width = inc;
  17506. } else {
  17507. if(params->lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_WOLFE) {
  17508. // regular Wolfe conditions
  17509. return count;
  17510. }
  17511. if(dg > -params->lbfgs.wolfe*dginit) {
  17512. width = dec;
  17513. } else {
  17514. // strong Wolfe condition (GGML_LINESEARCH_BACKTRACKING_STRONG_WOLFE)
  17515. return count;
  17516. }
  17517. }
  17518. }
  17519. if (*step < params->lbfgs.min_step) {
  17520. return GGML_LINESEARCH_MINIMUM_STEP;
  17521. }
  17522. if (*step > params->lbfgs.max_step) {
  17523. return GGML_LINESEARCH_MAXIMUM_STEP;
  17524. }
  17525. if (params->lbfgs.max_linesearch <= count) {
  17526. return GGML_LINESEARCH_MAXIMUM_ITERATIONS;
  17527. }
  17528. (*step) *= width;
  17529. }
  17530. GGML_ABORT("line search failed");
  17531. //return GGML_LINESEARCH_FAIL;
  17532. }
  17533. static enum ggml_opt_result ggml_opt_lbfgs(
  17534. struct ggml_context * ctx,
  17535. struct ggml_opt_context * opt,
  17536. struct ggml_opt_params params,
  17537. struct ggml_tensor * f,
  17538. struct ggml_cgraph * gf,
  17539. struct ggml_cgraph * gb,
  17540. ggml_opt_callback callback,
  17541. void * callback_data) {
  17542. if (params.lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_WOLFE ||
  17543. params.lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_STRONG_WOLFE) {
  17544. if (params.lbfgs.wolfe <= params.lbfgs.ftol || 1.f <= params.lbfgs.wolfe) {
  17545. return GGML_OPT_RESULT_INVALID_WOLFE;
  17546. }
  17547. }
  17548. const int m = params.lbfgs.m;
  17549. // these will store the parameters we want to optimize
  17550. struct ggml_tensor * ps[GGML_MAX_PARAMS];
  17551. int np = 0;
  17552. int nx = 0;
  17553. for (int i = 0; i < gf->n_nodes; ++i) {
  17554. if (gf->nodes[i]->flags & GGML_TENSOR_FLAG_PARAM) {
  17555. GGML_PRINT_DEBUG("found param %d: grad->op = %d\n", np, gf->nodes[i]->grad->op);
  17556. GGML_ASSERT(np < GGML_MAX_PARAMS);
  17557. ps[np++] = gf->nodes[i];
  17558. nx += ggml_nelements(gf->nodes[i]);
  17559. }
  17560. }
  17561. if ((opt->params.type != params.type) || (opt->nx != nx) || (opt->params.past != params.past) || (opt->params.lbfgs.m != params.lbfgs.m)) {
  17562. int iter = opt->iter;
  17563. ggml_opt_init(ctx, opt, params, nx);
  17564. opt->iter = iter;
  17565. }
  17566. struct ggml_cplan cplan = ggml_graph_plan(gb, params.n_threads, NULL);
  17567. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, cplan.work_size);
  17568. cplan.work_data = (uint8_t *)ctx->mem_buffer + obj->offs;
  17569. float * x = opt->lbfgs.x->data; // current parameters
  17570. float * xp = opt->lbfgs.xp->data; // previous parameters
  17571. float * g = opt->lbfgs.g->data; // current gradient
  17572. float * gp = opt->lbfgs.gp->data; // previous gradient
  17573. float * d = opt->lbfgs.d->data; // search direction
  17574. float * pf = params.past > 0 ? opt->lbfgs.pf->data : NULL; // past function values
  17575. const int n_accum = MAX(1, params.n_gradient_accumulation);
  17576. const float accum_norm = 1.0f / (float) n_accum;
  17577. float fx = 0.0f; // cost function value
  17578. float xnorm = 0.0f; // ||x||
  17579. float gnorm = 0.0f; // ||g||
  17580. // initialize x from the graph nodes
  17581. ggml_opt_get_params(np, ps, x);
  17582. // the L-BFGS memory
  17583. float * lm_alpha = opt->lbfgs.lmal->data;
  17584. float * lm_ys = opt->lbfgs.lmys->data;
  17585. float * lm_s = opt->lbfgs.lms->data;
  17586. float * lm_y = opt->lbfgs.lmy->data;
  17587. bool cancel = false;
  17588. // evaluate the function value and its gradient
  17589. {
  17590. ggml_opt_set_params(np, ps, x);
  17591. fx = 0;
  17592. memset(g, 0, sizeof(float)*nx);
  17593. for (int accum_step = 0; accum_step < n_accum; ++accum_step) {
  17594. if (callback) {
  17595. // LBFG-S does not support learning rate -> ignore learning schedule
  17596. float sched = 0;
  17597. callback(callback_data, accum_step, &sched, &cancel);
  17598. if (cancel) {
  17599. return GGML_OPT_RESULT_CANCEL;
  17600. }
  17601. }
  17602. // ggml_graph_reset (gf);
  17603. ggml_set_f32 (f->grad, 1.0f);
  17604. ggml_graph_compute(gb, &cplan);
  17605. ggml_opt_acc_grad(np, ps, g, accum_norm);
  17606. fx += ggml_get_f32_1d(f, 0);
  17607. }
  17608. fx *= accum_norm;
  17609. opt->loss_before = fx;
  17610. opt->loss_after = fx;
  17611. }
  17612. // search direction = -gradient
  17613. ggml_vec_neg_f32(nx, d, g);
  17614. // ||x||, ||g||
  17615. ggml_vec_norm_f32(nx, &xnorm, x);
  17616. ggml_vec_norm_f32(nx, &gnorm, g);
  17617. if (xnorm < 1.0f) {
  17618. xnorm = 1.0f;
  17619. }
  17620. // already optimized
  17621. if (gnorm/xnorm <= params.lbfgs.eps) {
  17622. return GGML_OPT_RESULT_OK;
  17623. }
  17624. if (opt->just_initialized) {
  17625. if (pf) {
  17626. pf[0] = fx;
  17627. }
  17628. opt->lbfgs.fx_best = fx;
  17629. // initial step
  17630. ggml_vec_norm_inv_f32(nx, &opt->lbfgs.step, d);
  17631. opt->lbfgs.j = 0;
  17632. opt->lbfgs.k = 1;
  17633. opt->lbfgs.end = 0;
  17634. opt->lbfgs.n_no_improvement = 0;
  17635. opt->just_initialized = false;
  17636. }
  17637. float * fx_best = &opt->lbfgs.fx_best;
  17638. float * step = &opt->lbfgs.step;
  17639. int * j = &opt->lbfgs.j;
  17640. int * k = &opt->lbfgs.k;
  17641. int * end = &opt->lbfgs.end;
  17642. int * n_no_improvement = &opt->lbfgs.n_no_improvement;
  17643. int ls = 0;
  17644. int bound = 0;
  17645. float ys = 0.0f;
  17646. float yy = 0.0f;
  17647. float beta = 0.0f;
  17648. int it = 0;
  17649. while (true) {
  17650. // store the current position and gradient vectors
  17651. ggml_vec_cpy_f32(nx, xp, x);
  17652. ggml_vec_cpy_f32(nx, gp, g);
  17653. // TODO: instead of passing &cancel here, use the return code of the linesearch
  17654. // to determine if the optimization should be cancelled
  17655. // this is a simple change, but not doing this atm, since I don't have a nice
  17656. // way to test and don't want to break something with so many changes lined up
  17657. ls = linesearch_backtracking(&params, nx, x, &fx, g, d, step, xp, f, gb, &cplan, np, ps, &cancel, callback, callback_data);
  17658. if (cancel) {
  17659. return GGML_OPT_RESULT_CANCEL;
  17660. }
  17661. if (ls < 0) {
  17662. // linesearch failed - go back to the previous point and return
  17663. ggml_vec_cpy_f32(nx, x, xp);
  17664. ggml_vec_cpy_f32(nx, g, gp);
  17665. return ls;
  17666. }
  17667. opt->loss_after = fx;
  17668. ggml_vec_norm_f32(nx, &xnorm, x);
  17669. ggml_vec_norm_f32(nx, &gnorm, g);
  17670. GGML_PRINT_DEBUG("f = %10.6f\n", ggml_get_f32_1d(f, 0));
  17671. if (xnorm < 1.0f) {
  17672. xnorm = 1.0f;
  17673. }
  17674. if (gnorm/xnorm <= params.lbfgs.eps) {
  17675. // converged
  17676. return GGML_OPT_RESULT_OK;
  17677. }
  17678. // delta-based convergence test
  17679. if (pf != NULL) {
  17680. // need at least params.past iterations to start checking for convergence
  17681. if (params.past <= k[0]) {
  17682. const float rate = (pf[k[0]%params.past] - fx)/fx;
  17683. if (fabsf(rate) < params.delta) {
  17684. return GGML_OPT_RESULT_OK;
  17685. }
  17686. }
  17687. pf[k[0]%params.past] = fx;
  17688. }
  17689. // check for improvement
  17690. if (params.max_no_improvement > 0) {
  17691. if (fx < fx_best[0]) {
  17692. fx_best[0] = fx;
  17693. n_no_improvement[0] = 0;
  17694. } else {
  17695. n_no_improvement[0]++;
  17696. if (n_no_improvement[0] >= params.max_no_improvement) {
  17697. return GGML_OPT_RESULT_OK;
  17698. }
  17699. }
  17700. }
  17701. if (params.lbfgs.n_iter != 0 && params.lbfgs.n_iter < it + 1) {
  17702. // reached the maximum number of iterations
  17703. return GGML_OPT_RESULT_DID_NOT_CONVERGE;
  17704. }
  17705. // update vectors s and y:
  17706. // s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}.
  17707. // y_{k+1} = g_{k+1} - g_{k}.
  17708. //
  17709. ggml_vec_sub_f32(nx, &lm_s[end[0]*nx], x, xp);
  17710. ggml_vec_sub_f32(nx, &lm_y[end[0]*nx], g, gp);
  17711. // compute scalars ys and yy:
  17712. // ys = y^t \cdot s -> 1 / \rho.
  17713. // yy = y^t \cdot y.
  17714. //
  17715. ggml_vec_dot_f32(nx, &ys, 0, &lm_y[end[0]*nx], 0, &lm_s[end[0]*nx], 0, 1);
  17716. ggml_vec_dot_f32(nx, &yy, 0, &lm_y[end[0]*nx], 0, &lm_y[end[0]*nx], 0, 1);
  17717. lm_ys[end[0]] = ys;
  17718. // find new search direction
  17719. // ref: https://en.wikipedia.org/wiki/Limited-memory_BFGS
  17720. bound = (m <= k[0]) ? m : k[0];
  17721. k[0]++;
  17722. it++;
  17723. end[0] = (end[0] + 1)%m;
  17724. // initialize search direction with -g
  17725. ggml_vec_neg_f32(nx, d, g);
  17726. j[0] = end[0];
  17727. for (int i = 0; i < bound; ++i) {
  17728. j[0] = (j[0] + m - 1) % m;
  17729. // \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}
  17730. ggml_vec_dot_f32(nx, &lm_alpha[j[0]], 0, &lm_s[j[0]*nx], 0, d, 0, 1);
  17731. lm_alpha[j[0]] /= lm_ys[j[0]];
  17732. // q_{i} = q_{i+1} - \alpha_{i} y_{i}
  17733. ggml_vec_mad_f32(nx, d, &lm_y[j[0]*nx], -lm_alpha[j[0]]);
  17734. }
  17735. ggml_vec_scale_f32(nx, d, ys/yy);
  17736. for (int i = 0; i < bound; ++i) {
  17737. // \beta_{j} = \rho_{j} y^t_{j} \cdot \gamma_{i}
  17738. ggml_vec_dot_f32(nx, &beta, 0, &lm_y[j[0]*nx], 0, d, 0, 1);
  17739. beta /= lm_ys[j[0]];
  17740. // \gamma_{i+1} = \gamma_{i} + (\alpha_{j} - \beta_{j}) s_{j}
  17741. ggml_vec_mad_f32(nx, d, &lm_s[j[0]*nx], lm_alpha[j[0]] - beta);
  17742. j[0] = (j[0] + 1)%m;
  17743. }
  17744. step[0] = 1.0;
  17745. }
  17746. GGML_ABORT("lbfgs failed");
  17747. //return GGML_OPT_RESULT_DID_NOT_CONVERGE;
  17748. }
  17749. struct ggml_opt_params ggml_opt_default_params(enum ggml_opt_type type) {
  17750. struct ggml_opt_params result;
  17751. switch (type) {
  17752. case GGML_OPT_TYPE_ADAM:
  17753. {
  17754. result = (struct ggml_opt_params) {
  17755. .type = GGML_OPT_TYPE_ADAM,
  17756. .graph_size = GGML_DEFAULT_GRAPH_SIZE,
  17757. .n_threads = 1, // FIXME: GGML_DEFAULT_N_THREADS ?
  17758. .past = 0,
  17759. .delta = 1e-5f,
  17760. .max_no_improvement = 100,
  17761. .print_forward_graph = true,
  17762. .print_backward_graph = true,
  17763. .n_gradient_accumulation = 1,
  17764. .adam = {
  17765. .n_iter = 10000,
  17766. .sched = 1.000f,
  17767. .decay = 0.0f,
  17768. .decay_min_ndim = 2,
  17769. .alpha = 0.001f,
  17770. .beta1 = 0.9f,
  17771. .beta2 = 0.999f,
  17772. .eps = 1e-8f,
  17773. .eps_f = 1e-5f,
  17774. .eps_g = 1e-3f,
  17775. .gclip = 0.0f,
  17776. },
  17777. };
  17778. } break;
  17779. case GGML_OPT_TYPE_LBFGS:
  17780. {
  17781. result = (struct ggml_opt_params) {
  17782. .type = GGML_OPT_TYPE_LBFGS,
  17783. .graph_size = GGML_DEFAULT_GRAPH_SIZE,
  17784. .n_threads = 1,
  17785. .past = 0,
  17786. .delta = 1e-5f,
  17787. .max_no_improvement = 0,
  17788. .print_forward_graph = true,
  17789. .print_backward_graph = true,
  17790. .n_gradient_accumulation = 1,
  17791. .lbfgs = {
  17792. .m = 6,
  17793. .n_iter = 100,
  17794. .max_linesearch = 20,
  17795. .eps = 1e-5f,
  17796. .ftol = 1e-4f,
  17797. .wolfe = 0.9f,
  17798. .min_step = 1e-20f,
  17799. .max_step = 1e+20f,
  17800. .linesearch = GGML_LINESEARCH_DEFAULT,
  17801. },
  17802. };
  17803. } break;
  17804. }
  17805. return result;
  17806. }
  17807. GGML_API void ggml_opt_init(
  17808. struct ggml_context * ctx,
  17809. struct ggml_opt_context * opt,
  17810. struct ggml_opt_params params,
  17811. int64_t nx) {
  17812. opt->ctx = ctx;
  17813. opt->params = params;
  17814. opt->iter = 0;
  17815. opt->nx = nx;
  17816. opt->just_initialized = true;
  17817. if (opt->ctx == NULL) {
  17818. struct ggml_init_params ctx_opt_params;
  17819. if (opt->params.type == GGML_OPT_TYPE_ADAM) {
  17820. ctx_opt_params.mem_size = GGML_MEM_ALIGN*3 + ggml_tensor_overhead()*3 + ggml_type_size(GGML_TYPE_F32)*nx*3;
  17821. if (opt->params.past > 0) {
  17822. ctx_opt_params.mem_size += GGML_MEM_ALIGN + ggml_tensor_overhead() + ggml_type_size(GGML_TYPE_F32)*opt->params.past;
  17823. }
  17824. } else if (opt->params.type == GGML_OPT_TYPE_LBFGS) {
  17825. ctx_opt_params.mem_size = GGML_MEM_ALIGN*9 + ggml_tensor_overhead()*9 + ggml_type_size(GGML_TYPE_F32)*(nx*5 + opt->params.lbfgs.m*2 + nx*opt->params.lbfgs.m*2);
  17826. if (opt->params.past > 0) {
  17827. ctx_opt_params.mem_size += GGML_MEM_ALIGN + ggml_tensor_overhead() + ggml_type_size(GGML_TYPE_F32)*opt->params.past;
  17828. }
  17829. }
  17830. ctx_opt_params.mem_buffer = NULL;
  17831. ctx_opt_params.no_alloc = false;
  17832. opt->ctx = ggml_init(ctx_opt_params);
  17833. }
  17834. switch (opt->params.type) {
  17835. case GGML_OPT_TYPE_ADAM:
  17836. {
  17837. opt->adam.g = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17838. opt->adam.m = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17839. opt->adam.v = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17840. opt->adam.pf = params.past > 0
  17841. ? ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, params.past)
  17842. : NULL;
  17843. ggml_set_zero(opt->adam.m);
  17844. ggml_set_zero(opt->adam.v);
  17845. if (opt->adam.pf) {
  17846. ggml_set_zero(opt->adam.pf);
  17847. }
  17848. } break;
  17849. case GGML_OPT_TYPE_LBFGS:
  17850. {
  17851. opt->lbfgs.x = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17852. opt->lbfgs.xp = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17853. opt->lbfgs.g = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17854. opt->lbfgs.gp = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17855. opt->lbfgs.d = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17856. opt->lbfgs.pf = params.past > 0
  17857. ? ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, params.past)
  17858. : NULL;
  17859. opt->lbfgs.lmal = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, params.lbfgs.m);
  17860. opt->lbfgs.lmys = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, params.lbfgs.m);
  17861. opt->lbfgs.lms = ggml_new_tensor_2d(opt->ctx, GGML_TYPE_F32, nx, params.lbfgs.m);
  17862. opt->lbfgs.lmy = ggml_new_tensor_2d(opt->ctx, GGML_TYPE_F32, nx, params.lbfgs.m);
  17863. ggml_set_zero(opt->lbfgs.x);
  17864. ggml_set_zero(opt->lbfgs.xp);
  17865. ggml_set_zero(opt->lbfgs.g);
  17866. ggml_set_zero(opt->lbfgs.gp);
  17867. ggml_set_zero(opt->lbfgs.d);
  17868. if (opt->lbfgs.pf) {
  17869. ggml_set_zero(opt->lbfgs.pf);
  17870. }
  17871. ggml_set_zero(opt->lbfgs.lmal);
  17872. ggml_set_zero(opt->lbfgs.lmys);
  17873. ggml_set_zero(opt->lbfgs.lms);
  17874. ggml_set_zero(opt->lbfgs.lmy);
  17875. } break;
  17876. }
  17877. }
  17878. enum ggml_opt_result ggml_opt(
  17879. struct ggml_context * ctx,
  17880. struct ggml_opt_params params,
  17881. struct ggml_tensor * f) {
  17882. bool free_ctx = false;
  17883. if (ctx == NULL) {
  17884. struct ggml_init_params params_ctx = {
  17885. .mem_size = 16*1024*1024,
  17886. .mem_buffer = NULL,
  17887. .no_alloc = false,
  17888. };
  17889. ctx = ggml_init(params_ctx);
  17890. if (ctx == NULL) {
  17891. return GGML_OPT_RESULT_NO_CONTEXT;
  17892. }
  17893. free_ctx = true;
  17894. }
  17895. enum ggml_opt_result result = GGML_OPT_RESULT_OK;
  17896. struct ggml_opt_context * opt = (struct ggml_opt_context *) alloca(sizeof(struct ggml_opt_context));
  17897. ggml_opt_init(ctx, opt, params, 0);
  17898. result = ggml_opt_resume(ctx, opt, f);
  17899. if (free_ctx) {
  17900. ggml_free(ctx);
  17901. }
  17902. return result;
  17903. }
  17904. enum ggml_opt_result ggml_opt_resume(
  17905. struct ggml_context * ctx,
  17906. struct ggml_opt_context * opt,
  17907. struct ggml_tensor * f) {
  17908. // build forward + backward compute graphs
  17909. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx, opt->params.graph_size, true);
  17910. ggml_build_forward_expand(gf, f);
  17911. struct ggml_cgraph * gb = ggml_graph_dup(ctx, gf);
  17912. ggml_build_backward_expand(ctx, gf, gb, false);
  17913. return ggml_opt_resume_g(ctx, opt, f, gf, gb, NULL, NULL);
  17914. }
  17915. enum ggml_opt_result ggml_opt_resume_g(
  17916. struct ggml_context * ctx,
  17917. struct ggml_opt_context * opt,
  17918. struct ggml_tensor * f,
  17919. struct ggml_cgraph * gf,
  17920. struct ggml_cgraph * gb,
  17921. ggml_opt_callback callback,
  17922. void * callback_data) {
  17923. GGML_ASSERT(f->grad && "ggml_set_param must be called for at least one ancestor");
  17924. // build forward + backward compute graphs
  17925. enum ggml_opt_result result = GGML_OPT_RESULT_OK;
  17926. switch (opt->params.type) {
  17927. case GGML_OPT_TYPE_ADAM:
  17928. {
  17929. result = ggml_opt_adam(ctx, opt, opt->params, f, gf, gb, callback, callback_data);
  17930. } break;
  17931. case GGML_OPT_TYPE_LBFGS:
  17932. {
  17933. result = ggml_opt_lbfgs(ctx, opt, opt->params, f, gf, gb, callback, callback_data);
  17934. } break;
  17935. }
  17936. if (opt->params.print_forward_graph) {
  17937. ggml_graph_print (gf);
  17938. ggml_graph_dump_dot(gf, NULL, "opt-forward.dot");
  17939. }
  17940. if (opt->params.print_backward_graph) {
  17941. ggml_graph_print (gb);
  17942. ggml_graph_dump_dot(gb, gf, "opt-backward.dot");
  17943. }
  17944. return result;
  17945. }
  17946. ////////////////////////////////////////////////////////////////////////////////
  17947. void ggml_set_input(struct ggml_tensor * tensor) {
  17948. tensor->flags |= GGML_TENSOR_FLAG_INPUT;
  17949. }
  17950. void ggml_set_output(struct ggml_tensor * tensor) {
  17951. tensor->flags |= GGML_TENSOR_FLAG_OUTPUT;
  17952. }
  17953. void ggml_set_param(struct ggml_context * ctx, struct ggml_tensor * tensor) {
  17954. GGML_UNUSED(ctx); // TODO: remove this parameter
  17955. tensor->flags |= GGML_TENSOR_FLAG_PARAM;
  17956. }
  17957. void ggml_set_loss(struct ggml_tensor * tensor) {
  17958. GGML_ASSERT(ggml_is_scalar(tensor));
  17959. GGML_ASSERT(tensor->type == GGML_TYPE_F32);
  17960. tensor->flags |= GGML_TENSOR_FLAG_LOSS;
  17961. }
  17962. ////////////////////////////////////////////////////////////////////////////////
  17963. void ggml_quantize_init(enum ggml_type type) {
  17964. ggml_critical_section_start();
  17965. switch (type) {
  17966. case GGML_TYPE_IQ2_XXS:
  17967. case GGML_TYPE_IQ2_XS:
  17968. case GGML_TYPE_IQ2_S:
  17969. case GGML_TYPE_IQ1_S:
  17970. case GGML_TYPE_IQ1_M: iq2xs_init_impl(type); break;
  17971. case GGML_TYPE_IQ3_XXS: iq3xs_init_impl(256); break;
  17972. case GGML_TYPE_IQ3_S: iq3xs_init_impl(512); break;
  17973. default: // nothing
  17974. break;
  17975. }
  17976. ggml_critical_section_end();
  17977. }
  17978. void ggml_quantize_free(void) {
  17979. ggml_critical_section_start();
  17980. iq2xs_free_impl(GGML_TYPE_IQ2_XXS);
  17981. iq2xs_free_impl(GGML_TYPE_IQ2_XS);
  17982. iq2xs_free_impl(GGML_TYPE_IQ1_S);
  17983. iq3xs_free_impl(256);
  17984. ggml_critical_section_end();
  17985. }
  17986. bool ggml_quantize_requires_imatrix(enum ggml_type type) {
  17987. return
  17988. type == GGML_TYPE_IQ2_XXS ||
  17989. type == GGML_TYPE_IQ2_XS ||
  17990. type == GGML_TYPE_IQ1_S;// ||
  17991. //type == GGML_TYPE_IQ1_M;
  17992. }
  17993. size_t ggml_quantize_chunk(
  17994. enum ggml_type type,
  17995. const float * src,
  17996. void * dst,
  17997. int64_t start,
  17998. int64_t nrows,
  17999. int64_t n_per_row,
  18000. const float * imatrix) {
  18001. const int64_t n = (int64_t) nrows * n_per_row;
  18002. if (ggml_quantize_requires_imatrix(type)) {
  18003. GGML_ASSERT(imatrix != NULL);
  18004. }
  18005. GGML_ASSERT(start % type_traits[type].blck_size == 0);
  18006. GGML_ASSERT(start % n_per_row == 0);
  18007. ggml_quantize_init(type); // this is noop if already initialized
  18008. const size_t start_row = start / n_per_row;
  18009. const size_t row_size = ggml_row_size(type, n_per_row);
  18010. size_t result = 0;
  18011. switch (type) {
  18012. case GGML_TYPE_Q4_0: result = quantize_q4_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18013. case GGML_TYPE_Q4_1: result = quantize_q4_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18014. case GGML_TYPE_Q5_0: result = quantize_q5_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18015. case GGML_TYPE_Q5_1: result = quantize_q5_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18016. case GGML_TYPE_Q8_0: result = quantize_q8_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18017. case GGML_TYPE_Q2_K: result = quantize_q2_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18018. case GGML_TYPE_Q3_K: result = quantize_q3_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18019. case GGML_TYPE_Q4_K: result = quantize_q4_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18020. case GGML_TYPE_Q5_K: result = quantize_q5_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18021. case GGML_TYPE_Q6_K: result = quantize_q6_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18022. case GGML_TYPE_TQ1_0: result = quantize_tq1_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18023. case GGML_TYPE_TQ2_0: result = quantize_tq2_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18024. case GGML_TYPE_IQ2_XXS: result = quantize_iq2_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18025. case GGML_TYPE_IQ2_XS: result = quantize_iq2_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18026. case GGML_TYPE_IQ3_XXS: result = quantize_iq3_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18027. case GGML_TYPE_IQ3_S: result = quantize_iq3_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18028. case GGML_TYPE_IQ2_S: result = quantize_iq2_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18029. case GGML_TYPE_IQ1_S: result = quantize_iq1_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18030. case GGML_TYPE_IQ1_M: result = quantize_iq1_m (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18031. case GGML_TYPE_IQ4_NL: result = quantize_iq4_nl (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18032. case GGML_TYPE_IQ4_XS: result = quantize_iq4_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18033. case GGML_TYPE_Q4_0_4_4: result = quantize_q4_0_4x4(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18034. case GGML_TYPE_Q4_0_4_8: result = quantize_q4_0_4x8(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18035. case GGML_TYPE_Q4_0_8_8: result = quantize_q4_0_8x8(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18036. case GGML_TYPE_F16:
  18037. {
  18038. size_t elemsize = sizeof(ggml_fp16_t);
  18039. ggml_fp32_to_fp16_row(src + start, (ggml_fp16_t *)dst + start, n);
  18040. result = n * elemsize;
  18041. } break;
  18042. case GGML_TYPE_BF16:
  18043. {
  18044. size_t elemsize = sizeof(ggml_bf16_t);
  18045. ggml_fp32_to_bf16_row_ref(src + start, (ggml_bf16_t *)dst + start, n);
  18046. result = n * elemsize;
  18047. } break;
  18048. case GGML_TYPE_F32:
  18049. {
  18050. size_t elemsize = sizeof(float);
  18051. result = n * elemsize;
  18052. memcpy((uint8_t *)dst + start * elemsize, src + start, result);
  18053. } break;
  18054. default:
  18055. assert(false);
  18056. }
  18057. GGML_ASSERT(result == nrows * row_size);
  18058. return result;
  18059. }
  18060. ////////////////////////////////////////////////////////////////////////////////
  18061. struct gguf_str {
  18062. uint64_t n; // GGUFv2
  18063. char * data;
  18064. };
  18065. static const size_t GGUF_TYPE_SIZE[GGUF_TYPE_COUNT] = {
  18066. [GGUF_TYPE_UINT8] = sizeof(uint8_t),
  18067. [GGUF_TYPE_INT8] = sizeof(int8_t),
  18068. [GGUF_TYPE_UINT16] = sizeof(uint16_t),
  18069. [GGUF_TYPE_INT16] = sizeof(int16_t),
  18070. [GGUF_TYPE_UINT32] = sizeof(uint32_t),
  18071. [GGUF_TYPE_INT32] = sizeof(int32_t),
  18072. [GGUF_TYPE_FLOAT32] = sizeof(float),
  18073. [GGUF_TYPE_BOOL] = sizeof(bool),
  18074. [GGUF_TYPE_STRING] = sizeof(struct gguf_str),
  18075. [GGUF_TYPE_UINT64] = sizeof(uint64_t),
  18076. [GGUF_TYPE_INT64] = sizeof(int64_t),
  18077. [GGUF_TYPE_FLOAT64] = sizeof(double),
  18078. [GGUF_TYPE_ARRAY] = 0, // undefined
  18079. };
  18080. static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
  18081. static const char * GGUF_TYPE_NAME[GGUF_TYPE_COUNT] = {
  18082. [GGUF_TYPE_UINT8] = "u8",
  18083. [GGUF_TYPE_INT8] = "i8",
  18084. [GGUF_TYPE_UINT16] = "u16",
  18085. [GGUF_TYPE_INT16] = "i16",
  18086. [GGUF_TYPE_UINT32] = "u32",
  18087. [GGUF_TYPE_INT32] = "i32",
  18088. [GGUF_TYPE_FLOAT32] = "f32",
  18089. [GGUF_TYPE_BOOL] = "bool",
  18090. [GGUF_TYPE_STRING] = "str",
  18091. [GGUF_TYPE_ARRAY] = "arr",
  18092. [GGUF_TYPE_UINT64] = "u64",
  18093. [GGUF_TYPE_INT64] = "i64",
  18094. [GGUF_TYPE_FLOAT64] = "f64",
  18095. };
  18096. static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
  18097. union gguf_value {
  18098. uint8_t uint8;
  18099. int8_t int8;
  18100. uint16_t uint16;
  18101. int16_t int16;
  18102. uint32_t uint32;
  18103. int32_t int32;
  18104. float float32;
  18105. uint64_t uint64;
  18106. int64_t int64;
  18107. double float64;
  18108. bool bool_;
  18109. struct gguf_str str;
  18110. struct {
  18111. enum gguf_type type;
  18112. uint64_t n; // GGUFv2
  18113. void * data;
  18114. } arr;
  18115. };
  18116. struct gguf_kv {
  18117. struct gguf_str key;
  18118. enum gguf_type type;
  18119. union gguf_value value;
  18120. };
  18121. struct gguf_header {
  18122. char magic[4];
  18123. uint32_t version;
  18124. uint64_t n_tensors; // GGUFv2
  18125. uint64_t n_kv; // GGUFv2
  18126. };
  18127. struct gguf_tensor_info {
  18128. struct gguf_str name;
  18129. uint32_t n_dims;
  18130. uint64_t ne[GGML_MAX_DIMS];
  18131. enum ggml_type type;
  18132. uint64_t offset; // offset from start of `data`, must be a multiple of `ALIGNMENT`
  18133. // for writing API
  18134. const void * data;
  18135. size_t size;
  18136. };
  18137. struct gguf_context {
  18138. struct gguf_header header;
  18139. struct gguf_kv * kv;
  18140. struct gguf_tensor_info * infos;
  18141. size_t alignment;
  18142. size_t offset; // offset of `data` from beginning of file
  18143. size_t size; // size of `data` in bytes
  18144. //uint8_t * padding;
  18145. void * data;
  18146. };
  18147. static size_t gguf_type_size(enum gguf_type type) {
  18148. GGML_ASSERT(0 <= type && type < GGUF_TYPE_COUNT);
  18149. return GGUF_TYPE_SIZE[type];
  18150. }
  18151. static void gguf_tensor_info_sanitize(struct gguf_tensor_info * info) {
  18152. GGML_ASSERT(info->n_dims <= GGML_MAX_DIMS);
  18153. GGML_ASSERT(0 <= info->type && info->type < GGML_TYPE_COUNT);
  18154. for (uint32_t i = 0; i < info->n_dims; ++i) {
  18155. GGML_ASSERT(info->ne[i] > 0);
  18156. }
  18157. // prevent overflow for total number of elements
  18158. GGML_ASSERT(INT64_MAX/info->ne[1] > info->ne[0]);
  18159. GGML_ASSERT(INT64_MAX/info->ne[2] > info->ne[0]*info->ne[1]);
  18160. GGML_ASSERT(INT64_MAX/info->ne[3] > info->ne[0]*info->ne[1]*info->ne[2]);
  18161. }
  18162. static bool gguf_fread_el(FILE * file, void * dst, size_t size, size_t * offset) {
  18163. const size_t n = fread(dst, 1, size, file);
  18164. *offset += n;
  18165. return n == size;
  18166. }
  18167. static bool gguf_fread_str(FILE * file, struct gguf_str * p, size_t * offset) {
  18168. p->n = 0;
  18169. p->data = NULL;
  18170. bool ok = true;
  18171. ok = ok && gguf_fread_el(file, &p->n, sizeof(p->n), offset);
  18172. // early exit if string length is invalid, prevents from integer overflow
  18173. if (p->n == SIZE_MAX) {
  18174. fprintf(stderr, "%s: invalid string length (%" PRIu64 ")\n", __func__, p->n);
  18175. return false;
  18176. }
  18177. p->data = GGML_CALLOC(p->n + 1, 1);
  18178. ok = ok && gguf_fread_el(file, p->data, p->n, offset);
  18179. return ok;
  18180. }
  18181. static void gguf_free_kv(struct gguf_kv * kv) {
  18182. if (kv->key.data) {
  18183. GGML_FREE(kv->key.data);
  18184. }
  18185. if (kv->type == GGUF_TYPE_STRING) {
  18186. if (kv->value.str.data) {
  18187. GGML_FREE(kv->value.str.data);
  18188. }
  18189. }
  18190. if (kv->type == GGUF_TYPE_ARRAY) {
  18191. if (kv->value.arr.data) {
  18192. if (kv->value.arr.type == GGUF_TYPE_STRING) {
  18193. for (uint64_t j = 0; j < kv->value.arr.n; ++j) {
  18194. struct gguf_str * str = &((struct gguf_str *) kv->value.arr.data)[j];
  18195. if (str->data) {
  18196. GGML_FREE(str->data);
  18197. }
  18198. }
  18199. }
  18200. GGML_FREE(kv->value.arr.data);
  18201. }
  18202. }
  18203. }
  18204. struct gguf_context * gguf_init_empty(void) {
  18205. struct gguf_context * ctx = GGML_CALLOC(1, sizeof(struct gguf_context));
  18206. memcpy(ctx->header.magic, GGUF_MAGIC, sizeof(ctx->header.magic));
  18207. ctx->header.version = GGUF_VERSION;
  18208. ctx->header.n_tensors = 0;
  18209. ctx->header.n_kv = 0;
  18210. ctx->kv = NULL;
  18211. ctx->infos = NULL;
  18212. ctx->alignment = GGUF_DEFAULT_ALIGNMENT;
  18213. ctx->offset = 0;
  18214. ctx->size = 0;
  18215. ctx->data = NULL;
  18216. return ctx;
  18217. }
  18218. struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params) {
  18219. FILE * file = ggml_fopen(fname, "rb");
  18220. if (!file) {
  18221. fprintf(stderr, "%s: failed to open '%s': '%s'\n", __func__, fname, strerror(errno));
  18222. return NULL;
  18223. }
  18224. // offset from start of file
  18225. size_t offset = 0;
  18226. char magic[4];
  18227. // check the magic before making allocations
  18228. {
  18229. gguf_fread_el(file, &magic, sizeof(magic), &offset);
  18230. for (uint32_t i = 0; i < sizeof(magic); i++) {
  18231. if (magic[i] != GGUF_MAGIC[i]) {
  18232. fprintf(stderr, "%s: invalid magic characters '%c%c%c%c'\n", __func__, magic[0], magic[1], magic[2], magic[3]);
  18233. fclose(file);
  18234. return NULL;
  18235. }
  18236. }
  18237. }
  18238. bool ok = true;
  18239. struct gguf_context * ctx = GGML_CALLOC(1, sizeof(struct gguf_context));
  18240. // read the header
  18241. {
  18242. strncpy(ctx->header.magic, magic, 4);
  18243. ctx->kv = NULL;
  18244. ctx->infos = NULL;
  18245. ctx->data = NULL;
  18246. ok = ok && gguf_fread_el(file, &ctx->header.version, sizeof(ctx->header.version), &offset);
  18247. ok = ok && gguf_fread_el(file, &ctx->header.n_tensors, sizeof(ctx->header.n_tensors), &offset);
  18248. ok = ok && gguf_fread_el(file, &ctx->header.n_kv, sizeof(ctx->header.n_kv), &offset);
  18249. if (ctx->header.version == 1) {
  18250. fprintf(stderr, "%s: GGUFv1 is no longer supported. please use a more up-to-date version\n", __func__);
  18251. fclose(file);
  18252. gguf_free(ctx);
  18253. return NULL;
  18254. }
  18255. // sanity-checks to prevent from integer/buffer overflows
  18256. ok = ok && (ctx->header.n_tensors < (SIZE_MAX/2)/sizeof(struct gguf_tensor_info));
  18257. ok = ok && (ctx->header.n_tensors < (SIZE_MAX/2)/ggml_tensor_overhead());
  18258. ok = ok && (ctx->header.n_kv < (SIZE_MAX/2)/sizeof(struct gguf_kv));
  18259. if (!ok) {
  18260. fprintf(stderr, "%s: failed to read header\n", __func__);
  18261. fclose(file);
  18262. gguf_free(ctx);
  18263. return NULL;
  18264. }
  18265. }
  18266. // read the kv pairs
  18267. {
  18268. const uint64_t n_kv = ctx->header.n_kv;
  18269. // header.n_kv will hold the actual value of pairs that were successfully read in the loop below
  18270. ctx->header.n_kv = 0;
  18271. ctx->kv = GGML_CALLOC(n_kv, sizeof(struct gguf_kv));
  18272. for (uint64_t i = 0; i < n_kv; ++i) {
  18273. struct gguf_kv * kv = &ctx->kv[i];
  18274. //fprintf(stderr, "%s: reading kv %d\n", __func__, i);
  18275. ok = ok && gguf_fread_str(file, &kv->key, &offset);
  18276. ok = ok && gguf_fread_el (file, &kv->type, sizeof(kv->type), &offset);
  18277. //fprintf(stderr, "%s: reading kv with key %s\n", __func__, kv->key.data);
  18278. switch (kv->type) {
  18279. case GGUF_TYPE_UINT8: ok = ok && gguf_fread_el (file, &kv->value.uint8, sizeof(kv->value.uint8), &offset); break;
  18280. case GGUF_TYPE_INT8: ok = ok && gguf_fread_el (file, &kv->value.int8, sizeof(kv->value.int8), &offset); break;
  18281. case GGUF_TYPE_UINT16: ok = ok && gguf_fread_el (file, &kv->value.uint16, sizeof(kv->value.uint16), &offset); break;
  18282. case GGUF_TYPE_INT16: ok = ok && gguf_fread_el (file, &kv->value.int16, sizeof(kv->value.int16), &offset); break;
  18283. case GGUF_TYPE_UINT32: ok = ok && gguf_fread_el (file, &kv->value.uint32, sizeof(kv->value.uint32), &offset); break;
  18284. case GGUF_TYPE_INT32: ok = ok && gguf_fread_el (file, &kv->value.int32, sizeof(kv->value.int32), &offset); break;
  18285. case GGUF_TYPE_FLOAT32: ok = ok && gguf_fread_el (file, &kv->value.float32, sizeof(kv->value.float32), &offset); break;
  18286. case GGUF_TYPE_UINT64: ok = ok && gguf_fread_el (file, &kv->value.uint64, sizeof(kv->value.uint64), &offset); break;
  18287. case GGUF_TYPE_INT64: ok = ok && gguf_fread_el (file, &kv->value.int64, sizeof(kv->value.int64), &offset); break;
  18288. case GGUF_TYPE_FLOAT64: ok = ok && gguf_fread_el (file, &kv->value.float64, sizeof(kv->value.float64), &offset); break;
  18289. case GGUF_TYPE_BOOL: ok = ok && gguf_fread_el (file, &kv->value.bool_, sizeof(kv->value.bool_), &offset); break;
  18290. case GGUF_TYPE_STRING: ok = ok && gguf_fread_str(file, &kv->value.str, &offset); break;
  18291. case GGUF_TYPE_ARRAY:
  18292. {
  18293. ok = ok && gguf_fread_el(file, &kv->value.arr.type, sizeof(kv->value.arr.type), &offset);
  18294. ok = ok && gguf_fread_el(file, &kv->value.arr.n, sizeof(kv->value.arr.n), &offset);
  18295. switch (kv->value.arr.type) {
  18296. case GGUF_TYPE_UINT8:
  18297. case GGUF_TYPE_INT8:
  18298. case GGUF_TYPE_UINT16:
  18299. case GGUF_TYPE_INT16:
  18300. case GGUF_TYPE_UINT32:
  18301. case GGUF_TYPE_INT32:
  18302. case GGUF_TYPE_FLOAT32:
  18303. case GGUF_TYPE_UINT64:
  18304. case GGUF_TYPE_INT64:
  18305. case GGUF_TYPE_FLOAT64:
  18306. case GGUF_TYPE_BOOL:
  18307. {
  18308. // prevent from integer overflow in the malloc below
  18309. if (kv->value.arr.n >= SIZE_MAX/gguf_type_size(kv->value.arr.type)) {
  18310. fprintf(stderr, "%s: array size is too large (%" PRIu64 ")\n", __func__, kv->value.arr.n);
  18311. fclose(file);
  18312. gguf_free(ctx);
  18313. return NULL;
  18314. }
  18315. kv->value.arr.data = GGML_CALLOC(kv->value.arr.n, gguf_type_size(kv->value.arr.type));
  18316. ok = ok && gguf_fread_el(file, kv->value.arr.data, kv->value.arr.n * gguf_type_size(kv->value.arr.type), &offset);
  18317. } break;
  18318. case GGUF_TYPE_STRING:
  18319. {
  18320. // prevent from integer overflow in the malloc below
  18321. if (kv->value.arr.n >= SIZE_MAX/sizeof(struct gguf_str)) {
  18322. fprintf(stderr, "%s: array size is too large (%" PRIu64 ")\n", __func__, kv->value.arr.n);
  18323. fclose(file);
  18324. gguf_free(ctx);
  18325. return NULL;
  18326. }
  18327. kv->value.arr.data = GGML_CALLOC(kv->value.arr.n, sizeof(struct gguf_str));
  18328. for (uint64_t j = 0; j < kv->value.arr.n; ++j) {
  18329. ok = ok && gguf_fread_str(file, &((struct gguf_str *) kv->value.arr.data)[j], &offset);
  18330. }
  18331. } break;
  18332. case GGUF_TYPE_ARRAY:
  18333. default: GGML_ABORT("invalid type");
  18334. }
  18335. } break;
  18336. default: GGML_ABORT("invalid type");
  18337. }
  18338. if (!ok) {
  18339. break;
  18340. }
  18341. ctx->header.n_kv++;
  18342. }
  18343. if (!ok) {
  18344. fprintf(stderr, "%s: failed to read key-value pairs\n", __func__);
  18345. fclose(file);
  18346. gguf_free(ctx);
  18347. return NULL;
  18348. }
  18349. }
  18350. // read the tensor infos
  18351. if (ctx->header.n_tensors > 0) {
  18352. ctx->infos = GGML_CALLOC(ctx->header.n_tensors, sizeof(struct gguf_tensor_info));
  18353. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  18354. struct gguf_tensor_info * info = &ctx->infos[i];
  18355. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  18356. info->ne[j] = 1;
  18357. }
  18358. ok = ok && gguf_fread_str(file, &info->name, &offset);
  18359. ok = ok && gguf_fread_el (file, &info->n_dims, sizeof(info->n_dims), &offset);
  18360. ok = ok && (info->n_dims <= GGML_MAX_DIMS);
  18361. for (uint32_t j = 0; j < info->n_dims; ++j) {
  18362. ok = ok && gguf_fread_el(file, &info->ne[j], sizeof(info->ne[j]), &offset);
  18363. }
  18364. ok = ok && gguf_fread_el (file, &info->type, sizeof(info->type), &offset);
  18365. ok = ok && gguf_fread_el (file, &info->offset, sizeof(info->offset), &offset);
  18366. // TODO: return an error instead of crashing with GGML_ASSERT
  18367. gguf_tensor_info_sanitize(info);
  18368. // make sure there is no duplicated tensor names
  18369. for (uint64_t j = 0; j < i && ok; ++j) {
  18370. if (strcmp(info->name.data, ctx->infos[j].name.data) == 0) {
  18371. fprintf(stderr, "%s: duplicated tensor name %s\n", __func__, info->name.data);
  18372. ok = false;
  18373. }
  18374. }
  18375. if (!ok) {
  18376. fprintf(stderr, "%s: failed to read tensor info\n", __func__);
  18377. fclose(file);
  18378. gguf_free(ctx);
  18379. return NULL;
  18380. }
  18381. }
  18382. }
  18383. ctx->alignment = GGUF_DEFAULT_ALIGNMENT;
  18384. int alignment_idx = gguf_find_key(ctx, "general.alignment");
  18385. if (alignment_idx != -1) {
  18386. ctx->alignment = gguf_get_val_u32(ctx, alignment_idx);
  18387. }
  18388. // we require the data section to be aligned, so take into account any padding
  18389. {
  18390. const size_t offset_pad = offset % ctx->alignment;
  18391. if (offset_pad != 0) {
  18392. offset += ctx->alignment - offset_pad;
  18393. fseek(file, offset, SEEK_SET);
  18394. }
  18395. }
  18396. // store the current file offset - this is where the data section starts
  18397. ctx->offset = offset;
  18398. // compute the total size of the data section, taking into account the alignment
  18399. {
  18400. ctx->size = 0;
  18401. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  18402. struct gguf_tensor_info * info = &ctx->infos[i];
  18403. const int64_t ne =
  18404. (int64_t) info->ne[0] *
  18405. (int64_t) info->ne[1] *
  18406. (int64_t) info->ne[2] *
  18407. (int64_t) info->ne[3];
  18408. if (ggml_blck_size(info->type) == 0 || ne % ggml_blck_size(info->type) != 0) {
  18409. fprintf(stderr, "%s: tensor '%s' of type %d (%s) number of elements (%" PRId64 ") is not a multiple of block size (%" PRId64 ")\n",
  18410. __func__, info->name.data, (int) info->type, ggml_type_name(info->type), ne, ggml_blck_size(info->type));
  18411. fclose(file);
  18412. gguf_free(ctx);
  18413. return NULL;
  18414. }
  18415. const size_t size_cur = ggml_row_size(info->type, ne);
  18416. ctx->size += GGML_PAD(size_cur, ctx->alignment);
  18417. }
  18418. }
  18419. // load the tensor data only if requested
  18420. if (params.ctx != NULL) {
  18421. // if the provided gguf_context is no_alloc, then we create "empty" tensors and do not read the binary blob
  18422. // otherwise, we load the binary blob into the created ggml_context as well, and point the "data" members of
  18423. // the ggml_tensor structs to the appropriate locations in the binary blob
  18424. // compute the exact size needed for the new ggml_context
  18425. const size_t mem_size =
  18426. params.no_alloc ?
  18427. (ctx->header.n_tensors )*ggml_tensor_overhead() :
  18428. (ctx->header.n_tensors + 1)*ggml_tensor_overhead() + ctx->size;
  18429. struct ggml_init_params pdata = {
  18430. .mem_size = mem_size,
  18431. .mem_buffer = NULL,
  18432. .no_alloc = params.no_alloc,
  18433. };
  18434. *params.ctx = ggml_init(pdata);
  18435. if (*params.ctx == NULL) {
  18436. fprintf(stderr, "%s: failed to initialize context\n", __func__);
  18437. fclose(file);
  18438. gguf_free(ctx);
  18439. return NULL;
  18440. }
  18441. struct ggml_context * ctx_data = *params.ctx;
  18442. struct ggml_tensor * data = NULL;
  18443. if (!params.no_alloc) {
  18444. data = ggml_new_tensor_1d(ctx_data, GGML_TYPE_I8, ctx->size);
  18445. ok = ok && data != NULL;
  18446. // read the binary blob with the tensor data
  18447. ok = ok && gguf_fread_el(file, data->data, ctx->size, &offset);
  18448. if (!ok) {
  18449. fprintf(stderr, "%s: failed to read tensor data\n", __func__);
  18450. fclose(file);
  18451. ggml_free(ctx_data);
  18452. gguf_free(ctx);
  18453. return NULL;
  18454. }
  18455. ctx->data = data->data;
  18456. }
  18457. ggml_set_no_alloc(ctx_data, true);
  18458. // create the tensors
  18459. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  18460. const int64_t ne[GGML_MAX_DIMS] = {
  18461. ctx->infos[i].ne[0],
  18462. ctx->infos[i].ne[1],
  18463. ctx->infos[i].ne[2],
  18464. ctx->infos[i].ne[3],
  18465. };
  18466. struct ggml_tensor * cur = ggml_new_tensor(ctx_data, ctx->infos[i].type, ctx->infos[i].n_dims, ne);
  18467. ok = ok && cur != NULL;
  18468. if (!ok) {
  18469. break;
  18470. }
  18471. ggml_set_name(cur, ctx->infos[i].name.data);
  18472. // point the data member to the appropriate location in the binary blob using the tensor infos
  18473. if (!params.no_alloc) {
  18474. //cur->data = (char *) data->data + ctx->infos[i].offset - ctx->offset; // offset from start of file
  18475. cur->data = (char *) data->data + ctx->infos[i].offset; // offset from data
  18476. }
  18477. }
  18478. if (!ok) {
  18479. fprintf(stderr, "%s: failed to read the tensor data\n", __func__);
  18480. fclose(file);
  18481. ggml_free(ctx_data);
  18482. gguf_free(ctx);
  18483. return NULL;
  18484. }
  18485. ggml_set_no_alloc(ctx_data, params.no_alloc);
  18486. }
  18487. fclose(file);
  18488. return ctx;
  18489. }
  18490. void gguf_free(struct gguf_context * ctx) {
  18491. if (ctx == NULL) {
  18492. return;
  18493. }
  18494. if (ctx->kv) {
  18495. // free string memory - not great..
  18496. for (uint64_t i = 0; i < ctx->header.n_kv; ++i) {
  18497. gguf_free_kv(&ctx->kv[i]);
  18498. }
  18499. GGML_FREE(ctx->kv);
  18500. }
  18501. if (ctx->infos) {
  18502. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  18503. struct gguf_tensor_info * info = &ctx->infos[i];
  18504. if (info->name.data) {
  18505. GGML_FREE(info->name.data);
  18506. }
  18507. }
  18508. GGML_FREE(ctx->infos);
  18509. }
  18510. GGML_FREE(ctx);
  18511. }
  18512. const char * gguf_type_name(enum gguf_type type) {
  18513. return GGUF_TYPE_NAME[type];
  18514. }
  18515. int gguf_get_version(const struct gguf_context * ctx) {
  18516. return ctx->header.version;
  18517. }
  18518. size_t gguf_get_alignment(const struct gguf_context * ctx) {
  18519. return ctx->alignment;
  18520. }
  18521. size_t gguf_get_data_offset(const struct gguf_context * ctx) {
  18522. return ctx->offset;
  18523. }
  18524. void * gguf_get_data(const struct gguf_context * ctx) {
  18525. return ctx->data;
  18526. }
  18527. int gguf_get_n_kv(const struct gguf_context * ctx) {
  18528. return ctx->header.n_kv;
  18529. }
  18530. int gguf_find_key(const struct gguf_context * ctx, const char * key) {
  18531. // return -1 if key not found
  18532. int keyfound = -1;
  18533. const int n_kv = gguf_get_n_kv(ctx);
  18534. for (int i = 0; i < n_kv; ++i) {
  18535. if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
  18536. keyfound = i;
  18537. break;
  18538. }
  18539. }
  18540. return keyfound;
  18541. }
  18542. const char * gguf_get_key(const struct gguf_context * ctx, int key_id) {
  18543. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18544. return ctx->kv[key_id].key.data;
  18545. }
  18546. enum gguf_type gguf_get_kv_type(const struct gguf_context * ctx, int key_id) {
  18547. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18548. return ctx->kv[key_id].type;
  18549. }
  18550. enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int key_id) {
  18551. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18552. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  18553. return ctx->kv[key_id].value.arr.type;
  18554. }
  18555. const void * gguf_get_arr_data(const struct gguf_context * ctx, int key_id) {
  18556. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18557. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  18558. return ctx->kv[key_id].value.arr.data;
  18559. }
  18560. const char * gguf_get_arr_str(const struct gguf_context * ctx, int key_id, int i) {
  18561. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18562. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  18563. struct gguf_kv * kv = &ctx->kv[key_id];
  18564. struct gguf_str * str = &((struct gguf_str *) kv->value.arr.data)[i];
  18565. return str->data;
  18566. }
  18567. int gguf_get_arr_n(const struct gguf_context * ctx, int key_id) {
  18568. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18569. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  18570. return ctx->kv[key_id].value.arr.n;
  18571. }
  18572. uint8_t gguf_get_val_u8(const struct gguf_context * ctx, int key_id) {
  18573. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18574. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT8);
  18575. return ctx->kv[key_id].value.uint8;
  18576. }
  18577. int8_t gguf_get_val_i8(const struct gguf_context * ctx, int key_id) {
  18578. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18579. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT8);
  18580. return ctx->kv[key_id].value.int8;
  18581. }
  18582. uint16_t gguf_get_val_u16(const struct gguf_context * ctx, int key_id) {
  18583. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18584. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT16);
  18585. return ctx->kv[key_id].value.uint16;
  18586. }
  18587. int16_t gguf_get_val_i16(const struct gguf_context * ctx, int key_id) {
  18588. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18589. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT16);
  18590. return ctx->kv[key_id].value.int16;
  18591. }
  18592. uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int key_id) {
  18593. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18594. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT32);
  18595. return ctx->kv[key_id].value.uint32;
  18596. }
  18597. int32_t gguf_get_val_i32(const struct gguf_context * ctx, int key_id) {
  18598. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18599. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT32);
  18600. return ctx->kv[key_id].value.int32;
  18601. }
  18602. float gguf_get_val_f32(const struct gguf_context * ctx, int key_id) {
  18603. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18604. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_FLOAT32);
  18605. return ctx->kv[key_id].value.float32;
  18606. }
  18607. uint64_t gguf_get_val_u64(const struct gguf_context * ctx, int key_id) {
  18608. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18609. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT64);
  18610. return ctx->kv[key_id].value.uint64;
  18611. }
  18612. int64_t gguf_get_val_i64(const struct gguf_context * ctx, int key_id) {
  18613. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18614. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT64);
  18615. return ctx->kv[key_id].value.int64;
  18616. }
  18617. double gguf_get_val_f64(const struct gguf_context * ctx, int key_id) {
  18618. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18619. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_FLOAT64);
  18620. return ctx->kv[key_id].value.float64;
  18621. }
  18622. bool gguf_get_val_bool(const struct gguf_context * ctx, int key_id) {
  18623. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18624. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_BOOL);
  18625. return ctx->kv[key_id].value.bool_;
  18626. }
  18627. const char * gguf_get_val_str(const struct gguf_context * ctx, int key_id) {
  18628. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18629. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_STRING);
  18630. return ctx->kv[key_id].value.str.data;
  18631. }
  18632. const void * gguf_get_val_data(const struct gguf_context * ctx, int key_id) {
  18633. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18634. GGML_ASSERT(ctx->kv[key_id].type != GGUF_TYPE_ARRAY);
  18635. GGML_ASSERT(ctx->kv[key_id].type != GGUF_TYPE_STRING);
  18636. return &ctx->kv[key_id].value;
  18637. }
  18638. int gguf_get_n_tensors(const struct gguf_context * ctx) {
  18639. return ctx->header.n_tensors;
  18640. }
  18641. int gguf_find_tensor(const struct gguf_context * ctx, const char * name) {
  18642. // return -1 if tensor not found
  18643. int tensorfound = -1;
  18644. const int n_tensors = gguf_get_n_tensors(ctx);
  18645. for (int i = 0; i < n_tensors; ++i) {
  18646. if (strcmp(name, gguf_get_tensor_name(ctx, i)) == 0) {
  18647. tensorfound = i;
  18648. break;
  18649. }
  18650. }
  18651. return tensorfound;
  18652. }
  18653. size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int i) {
  18654. return ctx->infos[i].offset;
  18655. }
  18656. char * gguf_get_tensor_name(const struct gguf_context * ctx, int i) {
  18657. return ctx->infos[i].name.data;
  18658. }
  18659. enum ggml_type gguf_get_tensor_type(const struct gguf_context * ctx, int i) {
  18660. return ctx->infos[i].type;
  18661. }
  18662. // returns the index
  18663. static int gguf_get_or_add_key(struct gguf_context * ctx, const char * key) {
  18664. const int idx = gguf_find_key(ctx, key);
  18665. if (idx >= 0) {
  18666. return idx;
  18667. }
  18668. const int n_kv = gguf_get_n_kv(ctx);
  18669. ctx->kv = realloc(ctx->kv, (n_kv + 1) * sizeof(struct gguf_kv));
  18670. ctx->kv[n_kv].key.n = strlen(key);
  18671. ctx->kv[n_kv].key.data = strdup(key);
  18672. ctx->header.n_kv++;
  18673. return n_kv;
  18674. }
  18675. void gguf_remove_key(struct gguf_context * ctx, const char * key) {
  18676. const int idx = gguf_find_key(ctx, key);
  18677. if (idx >= 0) {
  18678. const int n_kv = gguf_get_n_kv(ctx);
  18679. gguf_free_kv(&ctx->kv[idx]);
  18680. for (int i = idx; i < n_kv-1; ++i) {
  18681. ctx->kv[i] = ctx->kv[i+1];
  18682. }
  18683. ctx->kv = realloc(ctx->kv, (n_kv - 1) * sizeof(struct gguf_kv));
  18684. ctx->header.n_kv--;
  18685. }
  18686. }
  18687. void gguf_set_val_u8(struct gguf_context * ctx, const char * key, uint8_t val) {
  18688. const int idx = gguf_get_or_add_key(ctx, key);
  18689. ctx->kv[idx].type = GGUF_TYPE_UINT8;
  18690. ctx->kv[idx].value.uint8 = val;
  18691. }
  18692. void gguf_set_val_i8(struct gguf_context * ctx, const char * key, int8_t val) {
  18693. const int idx = gguf_get_or_add_key(ctx, key);
  18694. ctx->kv[idx].type = GGUF_TYPE_INT8;
  18695. ctx->kv[idx].value.int8 = val;
  18696. }
  18697. void gguf_set_val_u16(struct gguf_context * ctx, const char * key, uint16_t val) {
  18698. const int idx = gguf_get_or_add_key(ctx, key);
  18699. ctx->kv[idx].type = GGUF_TYPE_UINT16;
  18700. ctx->kv[idx].value.uint16 = val;
  18701. }
  18702. void gguf_set_val_i16(struct gguf_context * ctx, const char * key, int16_t val) {
  18703. const int idx = gguf_get_or_add_key(ctx, key);
  18704. ctx->kv[idx].type = GGUF_TYPE_INT16;
  18705. ctx->kv[idx].value.int16 = val;
  18706. }
  18707. void gguf_set_val_u32(struct gguf_context * ctx, const char * key, uint32_t val) {
  18708. const int idx = gguf_get_or_add_key(ctx, key);
  18709. ctx->kv[idx].type = GGUF_TYPE_UINT32;
  18710. ctx->kv[idx].value.uint32 = val;
  18711. }
  18712. void gguf_set_val_i32(struct gguf_context * ctx, const char * key, int32_t val) {
  18713. const int idx = gguf_get_or_add_key(ctx, key);
  18714. ctx->kv[idx].type = GGUF_TYPE_INT32;
  18715. ctx->kv[idx].value.int32 = val;
  18716. }
  18717. void gguf_set_val_f32(struct gguf_context * ctx, const char * key, float val) {
  18718. const int idx = gguf_get_or_add_key(ctx, key);
  18719. ctx->kv[idx].type = GGUF_TYPE_FLOAT32;
  18720. ctx->kv[idx].value.float32 = val;
  18721. }
  18722. void gguf_set_val_u64(struct gguf_context * ctx, const char * key, uint64_t val) {
  18723. const int idx = gguf_get_or_add_key(ctx, key);
  18724. ctx->kv[idx].type = GGUF_TYPE_UINT64;
  18725. ctx->kv[idx].value.uint64 = val;
  18726. }
  18727. void gguf_set_val_i64(struct gguf_context * ctx, const char * key, int64_t val) {
  18728. const int idx = gguf_get_or_add_key(ctx, key);
  18729. ctx->kv[idx].type = GGUF_TYPE_INT64;
  18730. ctx->kv[idx].value.int64 = val;
  18731. }
  18732. void gguf_set_val_f64(struct gguf_context * ctx, const char * key, double val) {
  18733. const int idx = gguf_get_or_add_key(ctx, key);
  18734. ctx->kv[idx].type = GGUF_TYPE_FLOAT64;
  18735. ctx->kv[idx].value.float64 = val;
  18736. }
  18737. void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val) {
  18738. const int idx = gguf_get_or_add_key(ctx, key);
  18739. ctx->kv[idx].type = GGUF_TYPE_BOOL;
  18740. ctx->kv[idx].value.bool_ = val;
  18741. }
  18742. void gguf_set_val_str(struct gguf_context * ctx, const char * key, const char * val) {
  18743. const int idx = gguf_get_or_add_key(ctx, key);
  18744. ctx->kv[idx].type = GGUF_TYPE_STRING;
  18745. ctx->kv[idx].value.str.n = strlen(val);
  18746. ctx->kv[idx].value.str.data = strdup(val);
  18747. }
  18748. void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, int n) {
  18749. const int idx = gguf_get_or_add_key(ctx, key);
  18750. ctx->kv[idx].type = GGUF_TYPE_ARRAY;
  18751. ctx->kv[idx].value.arr.type = type;
  18752. ctx->kv[idx].value.arr.n = n;
  18753. ctx->kv[idx].value.arr.data = GGML_CALLOC(n, gguf_type_size(type));
  18754. memcpy(ctx->kv[idx].value.arr.data, data, n*gguf_type_size(type));
  18755. }
  18756. void gguf_set_arr_str(struct gguf_context * ctx, const char * key, const char ** data, int n) {
  18757. const int idx = gguf_get_or_add_key(ctx, key);
  18758. ctx->kv[idx].type = GGUF_TYPE_ARRAY;
  18759. ctx->kv[idx].value.arr.type = GGUF_TYPE_STRING;
  18760. ctx->kv[idx].value.arr.n = n;
  18761. ctx->kv[idx].value.arr.data = GGML_CALLOC(n, sizeof(struct gguf_str));
  18762. for (int i = 0; i < n; i++) {
  18763. struct gguf_str * str = &((struct gguf_str *)ctx->kv[idx].value.arr.data)[i];
  18764. str->n = strlen(data[i]);
  18765. str->data = strdup(data[i]);
  18766. }
  18767. }
  18768. // set or add KV pairs from another context
  18769. void gguf_set_kv(struct gguf_context * ctx, struct gguf_context * src) {
  18770. for (uint32_t i = 0; i < src->header.n_kv; i++) {
  18771. switch (src->kv[i].type) {
  18772. case GGUF_TYPE_UINT8: gguf_set_val_u8 (ctx, src->kv[i].key.data, src->kv[i].value.uint8); break;
  18773. case GGUF_TYPE_INT8: gguf_set_val_i8 (ctx, src->kv[i].key.data, src->kv[i].value.int8); break;
  18774. case GGUF_TYPE_UINT16: gguf_set_val_u16 (ctx, src->kv[i].key.data, src->kv[i].value.uint16); break;
  18775. case GGUF_TYPE_INT16: gguf_set_val_i16 (ctx, src->kv[i].key.data, src->kv[i].value.int16); break;
  18776. case GGUF_TYPE_UINT32: gguf_set_val_u32 (ctx, src->kv[i].key.data, src->kv[i].value.uint32); break;
  18777. case GGUF_TYPE_INT32: gguf_set_val_i32 (ctx, src->kv[i].key.data, src->kv[i].value.int32); break;
  18778. case GGUF_TYPE_FLOAT32: gguf_set_val_f32 (ctx, src->kv[i].key.data, src->kv[i].value.float32); break;
  18779. case GGUF_TYPE_UINT64: gguf_set_val_u64 (ctx, src->kv[i].key.data, src->kv[i].value.uint64); break;
  18780. case GGUF_TYPE_INT64: gguf_set_val_i64 (ctx, src->kv[i].key.data, src->kv[i].value.int64); break;
  18781. case GGUF_TYPE_FLOAT64: gguf_set_val_f64 (ctx, src->kv[i].key.data, src->kv[i].value.float64); break;
  18782. case GGUF_TYPE_BOOL: gguf_set_val_bool(ctx, src->kv[i].key.data, src->kv[i].value.bool_); break;
  18783. case GGUF_TYPE_STRING: gguf_set_val_str (ctx, src->kv[i].key.data, src->kv[i].value.str.data); break;
  18784. case GGUF_TYPE_ARRAY:
  18785. {
  18786. if (src->kv[i].value.arr.type == GGUF_TYPE_STRING) {
  18787. const char ** data = GGML_CALLOC(src->kv[i].value.arr.n, sizeof(char *));
  18788. for (uint32_t j = 0; j < src->kv[i].value.arr.n; j++) {
  18789. data[j] = ((struct gguf_str *)src->kv[i].value.arr.data)[j].data;
  18790. }
  18791. gguf_set_arr_str(ctx, src->kv[i].key.data, data, src->kv[i].value.arr.n);
  18792. GGML_FREE((void *)data);
  18793. } else if (src->kv[i].value.arr.type == GGUF_TYPE_ARRAY) {
  18794. GGML_ABORT("nested arrays not supported");
  18795. } else {
  18796. gguf_set_arr_data(ctx, src->kv[i].key.data, src->kv[i].value.arr.type, src->kv[i].value.arr.data, src->kv[i].value.arr.n);
  18797. }
  18798. } break;
  18799. default: GGML_ABORT("invalid type");
  18800. }
  18801. }
  18802. }
  18803. void gguf_add_tensor(
  18804. struct gguf_context * ctx,
  18805. const struct ggml_tensor * tensor) {
  18806. GGML_ASSERT(tensor);
  18807. if (gguf_find_tensor(ctx, tensor->name) != -1) {
  18808. GGML_ABORT("duplicated tensor name");
  18809. }
  18810. const int idx = ctx->header.n_tensors;
  18811. ctx->infos = realloc(ctx->infos, (idx + 1)*sizeof(struct gguf_tensor_info));
  18812. ctx->infos[idx].name.n = strlen(tensor->name);
  18813. ctx->infos[idx].name.data = strdup(tensor->name);
  18814. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  18815. ctx->infos[idx].ne[i] = 1;
  18816. }
  18817. ctx->infos[idx].n_dims = ggml_n_dims(tensor);
  18818. for (uint32_t i = 0; i < ctx->infos[idx].n_dims; i++) {
  18819. ctx->infos[idx].ne[i] = tensor->ne[i];
  18820. }
  18821. ctx->infos[idx].type = tensor->type;
  18822. ctx->infos[idx].offset = 0;
  18823. ctx->infos[idx].data = tensor->data;
  18824. ctx->infos[idx].size = ggml_nbytes(tensor);
  18825. if (ctx->header.n_tensors > 0) {
  18826. ctx->infos[idx].offset = ctx->infos[idx - 1].offset + GGML_PAD(ctx->infos[idx - 1].size, ctx->alignment);
  18827. }
  18828. ctx->header.n_tensors++;
  18829. }
  18830. void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
  18831. const int idx = gguf_find_tensor(ctx, name);
  18832. if (idx < 0) {
  18833. GGML_ABORT("tensor not found");
  18834. }
  18835. ctx->infos[idx].type = type;
  18836. }
  18837. void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data, size_t size) {
  18838. const int idx = gguf_find_tensor(ctx, name);
  18839. if (idx < 0) {
  18840. GGML_ABORT("tensor not found");
  18841. }
  18842. ctx->infos[idx].data = data;
  18843. ctx->infos[idx].size = size;
  18844. // update offsets
  18845. for (uint32_t i = idx + 1; i < ctx->header.n_tensors; ++i) {
  18846. ctx->infos[i].offset = ctx->infos[i - 1].offset + GGML_PAD(ctx->infos[i - 1].size, ctx->alignment);
  18847. }
  18848. }
  18849. //static void gguf_fwrite_str(FILE * file, const struct gguf_str * val) {
  18850. // fwrite(&val->n, sizeof(val->n), 1, file);
  18851. // fwrite(val->data, sizeof(char), val->n, file);
  18852. //}
  18853. //
  18854. //static void gguf_fwrite_el(FILE * file, const void * val, size_t size) {
  18855. // fwrite(val, sizeof(char), size, file);
  18856. //}
  18857. struct gguf_buf {
  18858. void * data;
  18859. size_t size;
  18860. size_t offset;
  18861. };
  18862. static struct gguf_buf gguf_buf_init(size_t size) {
  18863. struct gguf_buf buf = {
  18864. /*buf.data =*/ size == 0 ? NULL : GGML_CALLOC(1, size),
  18865. /*buf.size =*/ size,
  18866. /*buf.offset =*/ 0,
  18867. };
  18868. return buf;
  18869. }
  18870. static void gguf_buf_free(struct gguf_buf buf) {
  18871. if (buf.data) {
  18872. GGML_FREE(buf.data);
  18873. }
  18874. }
  18875. static void gguf_buf_grow(struct gguf_buf * buf, size_t size) {
  18876. if (buf->offset + size > buf->size) {
  18877. buf->size = 1.5*(buf->offset + size);
  18878. if (buf->data) {
  18879. buf->data = realloc(buf->data, buf->size);
  18880. }
  18881. }
  18882. }
  18883. static void gguf_bwrite_str(struct gguf_buf * buf, const struct gguf_str * val) {
  18884. gguf_buf_grow(buf, sizeof(val->n) + val->n);
  18885. if (buf->data) {
  18886. memcpy((char *) buf->data + buf->offset, &val->n, sizeof(val->n));
  18887. }
  18888. buf->offset += sizeof(val->n);
  18889. if (buf->data) {
  18890. memcpy((char *) buf->data + buf->offset, val->data, val->n);
  18891. }
  18892. buf->offset += val->n;
  18893. }
  18894. static void gguf_bwrite_el(struct gguf_buf * buf, const void * val, size_t el_size) {
  18895. gguf_buf_grow(buf, el_size);
  18896. if (buf->data) {
  18897. memcpy((char *) buf->data + buf->offset, val, el_size);
  18898. }
  18899. buf->offset += el_size;
  18900. }
  18901. static void gguf_write_to_buf(const struct gguf_context * ctx, struct gguf_buf * buf, bool only_meta) {
  18902. // write header
  18903. gguf_bwrite_el(buf, &ctx->header.magic, sizeof(ctx->header.magic));
  18904. gguf_bwrite_el(buf, &ctx->header.version, sizeof(ctx->header.version));
  18905. gguf_bwrite_el(buf, &ctx->header.n_tensors, sizeof(ctx->header.n_tensors));
  18906. gguf_bwrite_el(buf, &ctx->header.n_kv, sizeof(ctx->header.n_kv));
  18907. // write key-value pairs
  18908. for (uint32_t i = 0; i < ctx->header.n_kv; ++i) {
  18909. struct gguf_kv * kv = &ctx->kv[i];
  18910. gguf_bwrite_str(buf, &kv->key);
  18911. gguf_bwrite_el (buf, &kv->type, sizeof(kv->type));
  18912. switch (kv->type) {
  18913. case GGUF_TYPE_UINT8: gguf_bwrite_el( buf, &kv->value.uint8, sizeof(kv->value.uint8) ); break;
  18914. case GGUF_TYPE_INT8: gguf_bwrite_el (buf, &kv->value.int8, sizeof(kv->value.int8) ); break;
  18915. case GGUF_TYPE_UINT16: gguf_bwrite_el (buf, &kv->value.uint16, sizeof(kv->value.uint16) ); break;
  18916. case GGUF_TYPE_INT16: gguf_bwrite_el (buf, &kv->value.int16, sizeof(kv->value.int16) ); break;
  18917. case GGUF_TYPE_UINT32: gguf_bwrite_el (buf, &kv->value.uint32, sizeof(kv->value.uint32) ); break;
  18918. case GGUF_TYPE_INT32: gguf_bwrite_el (buf, &kv->value.int32, sizeof(kv->value.int32) ); break;
  18919. case GGUF_TYPE_FLOAT32: gguf_bwrite_el (buf, &kv->value.float32, sizeof(kv->value.float32)); break;
  18920. case GGUF_TYPE_UINT64: gguf_bwrite_el (buf, &kv->value.uint64, sizeof(kv->value.uint64) ); break;
  18921. case GGUF_TYPE_INT64: gguf_bwrite_el (buf, &kv->value.int64, sizeof(kv->value.int64) ); break;
  18922. case GGUF_TYPE_FLOAT64: gguf_bwrite_el (buf, &kv->value.float64, sizeof(kv->value.float64)); break;
  18923. case GGUF_TYPE_BOOL: gguf_bwrite_el (buf, &kv->value.bool_, sizeof(kv->value.bool_) ); break;
  18924. case GGUF_TYPE_STRING: gguf_bwrite_str(buf, &kv->value.str ); break;
  18925. case GGUF_TYPE_ARRAY:
  18926. {
  18927. gguf_bwrite_el(buf, &kv->value.arr.type, sizeof(kv->value.arr.type));
  18928. gguf_bwrite_el(buf, &kv->value.arr.n, sizeof(kv->value.arr.n) );
  18929. switch (kv->value.arr.type) {
  18930. case GGUF_TYPE_UINT8:
  18931. case GGUF_TYPE_INT8:
  18932. case GGUF_TYPE_UINT16:
  18933. case GGUF_TYPE_INT16:
  18934. case GGUF_TYPE_UINT32:
  18935. case GGUF_TYPE_INT32:
  18936. case GGUF_TYPE_FLOAT32:
  18937. case GGUF_TYPE_UINT64:
  18938. case GGUF_TYPE_INT64:
  18939. case GGUF_TYPE_FLOAT64:
  18940. case GGUF_TYPE_BOOL:
  18941. {
  18942. gguf_bwrite_el(buf, kv->value.arr.data, kv->value.arr.n * gguf_type_size(kv->value.arr.type));
  18943. } break;
  18944. case GGUF_TYPE_STRING:
  18945. {
  18946. for (uint32_t j = 0; j < kv->value.arr.n; ++j) {
  18947. gguf_bwrite_str(buf, &((struct gguf_str *) kv->value.arr.data)[j]);
  18948. }
  18949. } break;
  18950. case GGUF_TYPE_ARRAY:
  18951. default: GGML_ABORT("invalid type");
  18952. }
  18953. } break;
  18954. default: GGML_ABORT("invalid type");
  18955. }
  18956. }
  18957. // write tensor infos
  18958. for (uint32_t i = 0; i < ctx->header.n_tensors; ++i) {
  18959. struct gguf_tensor_info * info = &ctx->infos[i];
  18960. gguf_bwrite_str(buf, &info->name);
  18961. gguf_bwrite_el (buf, &info->n_dims, sizeof(info->n_dims));
  18962. for (uint32_t j = 0; j < info->n_dims; ++j) {
  18963. gguf_bwrite_el(buf, &info->ne[j], sizeof(info->ne[j]));
  18964. }
  18965. gguf_bwrite_el(buf, &info->type, sizeof(info->type));
  18966. gguf_bwrite_el(buf, &info->offset, sizeof(info->offset));
  18967. }
  18968. // we require the data section to be aligned, so take into account any padding
  18969. {
  18970. const size_t offset = buf->offset;
  18971. const size_t offset_pad = GGML_PAD(offset, ctx->alignment);
  18972. if (offset_pad != offset) {
  18973. uint8_t pad = 0;
  18974. for (size_t i = 0; i < offset_pad - offset; ++i) {
  18975. gguf_bwrite_el(buf, &pad, sizeof(pad));
  18976. }
  18977. }
  18978. }
  18979. if (only_meta) {
  18980. return;
  18981. }
  18982. size_t offset = 0;
  18983. // write tensor data
  18984. for (uint32_t i = 0; i < ctx->header.n_tensors; ++i) {
  18985. struct gguf_tensor_info * info = &ctx->infos[i];
  18986. const size_t size = info->size;
  18987. const size_t size_pad = GGML_PAD(size, ctx->alignment);
  18988. gguf_bwrite_el(buf, info->data, size);
  18989. if (size_pad != size) {
  18990. uint8_t pad = 0;
  18991. for (size_t j = 0; j < size_pad - size; ++j) {
  18992. gguf_bwrite_el(buf, &pad, sizeof(pad));
  18993. }
  18994. }
  18995. GGML_ASSERT(offset == info->offset);
  18996. offset += size_pad;
  18997. }
  18998. }
  18999. void gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta) {
  19000. FILE * file = ggml_fopen(fname, "wb");
  19001. if (!file) {
  19002. GGML_ABORT("failed to open file for writing");
  19003. }
  19004. struct gguf_buf buf = gguf_buf_init(16*1024);
  19005. gguf_write_to_buf(ctx, &buf, only_meta);
  19006. fwrite(buf.data, 1, buf.offset, file);
  19007. gguf_buf_free(buf);
  19008. fclose(file);
  19009. }
  19010. size_t gguf_get_meta_size(const struct gguf_context * ctx) {
  19011. // no allocs - only compute size
  19012. struct gguf_buf buf = gguf_buf_init(0);
  19013. gguf_write_to_buf(ctx, &buf, true);
  19014. return buf.offset;
  19015. }
  19016. void gguf_get_meta_data(const struct gguf_context * ctx, void * data) {
  19017. struct gguf_buf buf = gguf_buf_init(16*1024);
  19018. gguf_write_to_buf(ctx, &buf, true);
  19019. memcpy(data, buf.data, buf.offset);
  19020. gguf_buf_free(buf);
  19021. }
  19022. ////////////////////////////////////////////////////////////////////////////////
  19023. int ggml_cpu_has_avx(void) {
  19024. #if defined(__AVX__)
  19025. return 1;
  19026. #else
  19027. return 0;
  19028. #endif
  19029. }
  19030. int ggml_cpu_has_avx_vnni(void) {
  19031. #if defined(__AVXVNNI__)
  19032. return 1;
  19033. #else
  19034. return 0;
  19035. #endif
  19036. }
  19037. int ggml_cpu_has_avx2(void) {
  19038. #if defined(__AVX2__)
  19039. return 1;
  19040. #else
  19041. return 0;
  19042. #endif
  19043. }
  19044. int ggml_cpu_has_avx512(void) {
  19045. #if defined(__AVX512F__)
  19046. return 1;
  19047. #else
  19048. return 0;
  19049. #endif
  19050. }
  19051. int ggml_cpu_has_avx512_vbmi(void) {
  19052. #if defined(__AVX512VBMI__)
  19053. return 1;
  19054. #else
  19055. return 0;
  19056. #endif
  19057. }
  19058. int ggml_cpu_has_avx512_vnni(void) {
  19059. #if defined(__AVX512VNNI__)
  19060. return 1;
  19061. #else
  19062. return 0;
  19063. #endif
  19064. }
  19065. int ggml_cpu_has_avx512_bf16(void) {
  19066. #if defined(__AVX512BF16__)
  19067. return 1;
  19068. #else
  19069. return 0;
  19070. #endif
  19071. }
  19072. int ggml_cpu_has_fma(void) {
  19073. #if defined(__FMA__)
  19074. return 1;
  19075. #else
  19076. return 0;
  19077. #endif
  19078. }
  19079. int ggml_cpu_has_neon(void) {
  19080. #if defined(__ARM_ARCH)
  19081. return ggml_arm_arch_features.has_neon;
  19082. #else
  19083. return 0;
  19084. #endif
  19085. }
  19086. int ggml_cpu_has_sve(void) {
  19087. #if defined(__ARM_ARCH)
  19088. return ggml_arm_arch_features.has_sve;
  19089. #else
  19090. return 0;
  19091. #endif
  19092. }
  19093. int ggml_cpu_has_arm_fma(void) {
  19094. #if defined(__ARM_FEATURE_FMA)
  19095. return 1;
  19096. #else
  19097. return 0;
  19098. #endif
  19099. }
  19100. int ggml_cpu_has_riscv_v(void) {
  19101. #if defined(__riscv_v_intrinsic)
  19102. return 1;
  19103. #else
  19104. return 0;
  19105. #endif
  19106. }
  19107. int ggml_cpu_has_metal(void) {
  19108. #if defined(GGML_USE_METAL)
  19109. return 1;
  19110. #else
  19111. return 0;
  19112. #endif
  19113. }
  19114. int ggml_cpu_has_f16c(void) {
  19115. #if defined(__F16C__)
  19116. return 1;
  19117. #else
  19118. return 0;
  19119. #endif
  19120. }
  19121. int ggml_cpu_has_fp16_va(void) {
  19122. #if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
  19123. return 1;
  19124. #else
  19125. return 0;
  19126. #endif
  19127. }
  19128. int ggml_cpu_has_wasm_simd(void) {
  19129. #if defined(__wasm_simd128__)
  19130. return 1;
  19131. #else
  19132. return 0;
  19133. #endif
  19134. }
  19135. int ggml_cpu_has_blas(void) {
  19136. #if defined(GGML_USE_BLAS) || defined(GGML_USE_CUDA) || defined(GGML_USE_VULKAN) || defined(GGML_USE_SYCL)
  19137. return 1;
  19138. #else
  19139. return 0;
  19140. #endif
  19141. }
  19142. int ggml_cpu_has_cuda(void) {
  19143. #if defined(GGML_USE_CUDA)
  19144. return 1;
  19145. #else
  19146. return 0;
  19147. #endif
  19148. }
  19149. int ggml_cpu_has_vulkan(void) {
  19150. #if defined(GGML_USE_VULKAN)
  19151. return 1;
  19152. #else
  19153. return 0;
  19154. #endif
  19155. }
  19156. int ggml_cpu_has_kompute(void) {
  19157. #if defined(GGML_USE_KOMPUTE)
  19158. return 1;
  19159. #else
  19160. return 0;
  19161. #endif
  19162. }
  19163. int ggml_cpu_has_sycl(void) {
  19164. #if defined(GGML_USE_SYCL)
  19165. return 1;
  19166. #else
  19167. return 0;
  19168. #endif
  19169. }
  19170. int ggml_cpu_has_rpc(void) {
  19171. #if defined(GGML_USE_RPC)
  19172. return 1;
  19173. #else
  19174. return 0;
  19175. #endif
  19176. }
  19177. int ggml_cpu_has_cann(void) {
  19178. #if defined(GGML_USE_CANN)
  19179. return 1;
  19180. #else
  19181. return 0;
  19182. #endif
  19183. }
  19184. int ggml_cpu_has_llamafile(void) {
  19185. #if defined(GGML_USE_LLAMAFILE)
  19186. return 1;
  19187. #else
  19188. return 0;
  19189. #endif
  19190. }
  19191. int ggml_cpu_has_gpublas(void) {
  19192. return ggml_cpu_has_cuda() || ggml_cpu_has_vulkan() || ggml_cpu_has_kompute() || ggml_cpu_has_sycl();
  19193. }
  19194. int ggml_cpu_has_sse3(void) {
  19195. #if defined(__SSE3__)
  19196. return 1;
  19197. #else
  19198. return 0;
  19199. #endif
  19200. }
  19201. int ggml_cpu_has_ssse3(void) {
  19202. #if defined(__SSSE3__)
  19203. return 1;
  19204. #else
  19205. return 0;
  19206. #endif
  19207. }
  19208. int ggml_cpu_has_vsx(void) {
  19209. #if defined(__POWER9_VECTOR__)
  19210. return 1;
  19211. #else
  19212. return 0;
  19213. #endif
  19214. }
  19215. int ggml_cpu_has_matmul_int8(void) {
  19216. #if defined(__ARM_ARCH)
  19217. return ggml_arm_arch_features.has_i8mm;
  19218. #else
  19219. return 0;
  19220. #endif
  19221. }
  19222. int ggml_cpu_get_sve_cnt(void) {
  19223. #if defined(__ARM_ARCH)
  19224. return ggml_arm_arch_features.sve_cnt;
  19225. #else
  19226. return 0;
  19227. #endif
  19228. }
  19229. ////////////////////////////////////////////////////////////////////////////////