ggml.c 763 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355
  1. /**
  2. * llama.cpp - commit 3f1ae2e32cde00c39b96be6d01c2997c29bae555 - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #define _CRT_SECURE_NO_DEPRECATE // Disables ridiculous "unsafe" warnings on Windows
  27. #define _USE_MATH_DEFINES // For M_PI on MSVC
  28. #include "ggml-backend.h"
  29. #include "ggml-impl.h"
  30. #include "ggml-cpu-impl.h"
  31. #include "ggml-quants.h"
  32. #include "ggml.h"
  33. #include "ggml-aarch64.h"
  34. #if defined(_MSC_VER) || defined(__MINGW32__)
  35. #include <malloc.h> // using malloc.h with MSC/MINGW
  36. #elif !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
  37. #include <alloca.h>
  38. #endif
  39. #include <assert.h>
  40. #include <errno.h>
  41. #include <time.h>
  42. #include <math.h>
  43. #include <stdlib.h>
  44. #include <string.h>
  45. #include <stdint.h>
  46. #include <inttypes.h>
  47. #include <stdio.h>
  48. #include <float.h>
  49. #include <limits.h>
  50. #include <stdarg.h>
  51. #include <signal.h>
  52. #if defined(__gnu_linux__)
  53. #include <syscall.h>
  54. #endif
  55. #ifdef GGML_USE_OPENMP
  56. #include <omp.h>
  57. #endif
  58. #ifdef GGML_USE_METAL
  59. #include <unistd.h>
  60. #endif
  61. #if defined(__ARM_FEATURE_SVE) || defined(__ARM_FEATURE_MATMUL_INT8)
  62. #undef GGML_USE_LLAMAFILE
  63. #endif
  64. #ifdef GGML_USE_LLAMAFILE
  65. #include <llamafile/sgemm.h>
  66. #endif
  67. #if defined(_MSC_VER)
  68. // disable "possible loss of data" to avoid hundreds of casts
  69. // we should just be careful :)
  70. #pragma warning(disable: 4244 4267)
  71. // disable POSIX deprecation warnings
  72. // these functions are never going away, anyway
  73. #pragma warning(disable: 4996)
  74. // unreachable code because of multiple instances of code after GGML_ABORT
  75. #pragma warning(disable: 4702)
  76. #endif
  77. // Note: once we move threading into a separate C++ file
  78. // will use std::hardware_destructive_interference_size instead of hardcoding it here
  79. // and we'll use C++ attribute syntax.
  80. #define GGML_CACHE_LINE 64
  81. #if defined(__clang__) || defined(__GNUC__)
  82. #define GGML_CACHE_ALIGN __attribute__((aligned(GGML_CACHE_LINE)))
  83. #endif
  84. #if defined(__has_feature)
  85. #if __has_feature(thread_sanitizer)
  86. #define GGML_TSAN_ENABLED 1
  87. #endif
  88. #else // __has_feature
  89. #if defined(__SANITIZE_THREAD__)
  90. #define GGML_TSAN_ENABLED 1
  91. #endif
  92. #endif // __has_feature
  93. #if defined(_WIN32)
  94. #define WIN32_LEAN_AND_MEAN
  95. #ifndef NOMINMAX
  96. #define NOMINMAX
  97. #endif
  98. #include <windows.h>
  99. #if !defined(__clang__)
  100. #define GGML_CACHE_ALIGN __declspec(align(GGML_CACHE_LINE))
  101. typedef volatile LONG atomic_int;
  102. typedef atomic_int atomic_bool;
  103. typedef atomic_int atomic_flag;
  104. #define ATOMIC_FLAG_INIT 0
  105. typedef enum {
  106. memory_order_relaxed,
  107. memory_order_consume,
  108. memory_order_acquire,
  109. memory_order_release,
  110. memory_order_acq_rel,
  111. memory_order_seq_cst
  112. } memory_order;
  113. static void atomic_store(atomic_int * ptr, LONG val) {
  114. InterlockedExchange(ptr, val);
  115. }
  116. static void atomic_store_explicit(atomic_int * ptr, LONG val, memory_order mo) {
  117. // TODO: add support for explicit memory order
  118. InterlockedExchange(ptr, val);
  119. }
  120. static LONG atomic_load(atomic_int * ptr) {
  121. return InterlockedCompareExchange(ptr, 0, 0);
  122. }
  123. static LONG atomic_load_explicit(atomic_int * ptr, memory_order mo) {
  124. // TODO: add support for explicit memory order
  125. return InterlockedCompareExchange(ptr, 0, 0);
  126. }
  127. static LONG atomic_fetch_add(atomic_int * ptr, LONG inc) {
  128. return InterlockedExchangeAdd(ptr, inc);
  129. }
  130. static LONG atomic_fetch_add_explicit(atomic_int * ptr, LONG inc, memory_order mo) {
  131. // TODO: add support for explicit memory order
  132. return InterlockedExchangeAdd(ptr, inc);
  133. }
  134. static atomic_bool atomic_flag_test_and_set(atomic_flag * ptr) {
  135. return InterlockedExchange(ptr, 1);
  136. }
  137. static void atomic_flag_clear(atomic_flag * ptr) {
  138. InterlockedExchange(ptr, 0);
  139. }
  140. static void atomic_thread_fence(memory_order mo) {
  141. MemoryBarrier();
  142. }
  143. #else // clang
  144. #include <stdatomic.h>
  145. #endif
  146. typedef HANDLE pthread_t;
  147. typedef DWORD thread_ret_t;
  148. static int pthread_create(pthread_t * out, void * unused, thread_ret_t(*func)(void *), void * arg) {
  149. (void) unused;
  150. HANDLE handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) func, arg, 0, NULL);
  151. if (handle == NULL)
  152. {
  153. return EAGAIN;
  154. }
  155. *out = handle;
  156. return 0;
  157. }
  158. static int pthread_join(pthread_t thread, void * unused) {
  159. (void) unused;
  160. int ret = (int) WaitForSingleObject(thread, INFINITE);
  161. CloseHandle(thread);
  162. return ret;
  163. }
  164. static int sched_yield (void) {
  165. Sleep (0);
  166. return 0;
  167. }
  168. #else
  169. #include <pthread.h>
  170. #include <stdatomic.h>
  171. #include <sched.h>
  172. #if defined(__FreeBSD__)
  173. #include <pthread_np.h>
  174. #endif
  175. typedef void * thread_ret_t;
  176. #include <sys/types.h>
  177. #include <sys/stat.h>
  178. #include <unistd.h>
  179. #endif
  180. typedef pthread_t ggml_thread_t;
  181. #ifdef GGML_USE_CPU_HBM
  182. #include <hbwmalloc.h>
  183. #endif
  184. #if defined(__APPLE__)
  185. #include <TargetConditionals.h>
  186. #endif
  187. #if (defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) && \
  188. (!defined(TARGET_OS_TV) && !defined(TARGET_OS_WATCH))
  189. #include <sys/wait.h>
  190. #if defined(__ANDROID__)
  191. #include <unwind.h>
  192. #include <dlfcn.h>
  193. #include <stdio.h>
  194. struct backtrace_state {
  195. void ** current;
  196. void ** end;
  197. };
  198. static _Unwind_Reason_Code unwind_callback(struct _Unwind_Context* context, void* arg) {
  199. struct backtrace_state * state = (struct backtrace_state *)arg;
  200. uintptr_t pc = _Unwind_GetIP(context);
  201. if (pc) {
  202. if (state->current == state->end) {
  203. return _URC_END_OF_STACK;
  204. } else {
  205. *state->current++ = (void*)pc;
  206. }
  207. }
  208. return _URC_NO_REASON;
  209. }
  210. static void ggml_print_backtrace_symbols(void) {
  211. const int max = 100;
  212. void* buffer[max];
  213. struct backtrace_state state = {buffer, buffer + max};
  214. _Unwind_Backtrace(unwind_callback, &state);
  215. int count = state.current - buffer;
  216. for (int idx = 0; idx < count; ++idx) {
  217. const void * addr = buffer[idx];
  218. const char * symbol = "";
  219. Dl_info info;
  220. if (dladdr(addr, &info) && info.dli_sname) {
  221. symbol = info.dli_sname;
  222. }
  223. fprintf(stderr, "%d: %p %s\n", idx, addr, symbol);
  224. }
  225. }
  226. #elif defined(__linux__) && defined(__GLIBC__)
  227. #include <execinfo.h>
  228. static void ggml_print_backtrace_symbols(void) {
  229. void * trace[100];
  230. int nptrs = backtrace(trace, sizeof(trace)/sizeof(trace[0]));
  231. backtrace_symbols_fd(trace, nptrs, STDERR_FILENO);
  232. }
  233. #else
  234. static void ggml_print_backtrace_symbols(void) {
  235. // platform not supported
  236. }
  237. #endif
  238. static void ggml_print_backtrace(void) {
  239. char attach[32];
  240. snprintf(attach, sizeof(attach), "attach %d", getpid());
  241. int pid = fork();
  242. if (pid == 0) {
  243. // try gdb
  244. execlp("gdb", "gdb", "--batch",
  245. "-ex", "set style enabled on",
  246. "-ex", attach,
  247. "-ex", "bt -frame-info source-and-location",
  248. "-ex", "detach",
  249. "-ex", "quit",
  250. (char *) NULL);
  251. // try lldb
  252. execlp("lldb", "lldb", "--batch",
  253. "-o", "bt",
  254. "-o", "quit",
  255. "-p", attach,
  256. (char *) NULL);
  257. exit(EXIT_FAILURE);
  258. } else {
  259. int wstatus;
  260. waitpid(pid, &wstatus, 0);
  261. if (WIFEXITED(wstatus)) {
  262. if (WEXITSTATUS(wstatus) == EXIT_FAILURE) {
  263. // gdb failed, fallback to backtrace_symbols
  264. ggml_print_backtrace_symbols();
  265. }
  266. }
  267. }
  268. }
  269. #else
  270. static void ggml_print_backtrace(void) {
  271. // platform not supported
  272. }
  273. #endif
  274. void ggml_abort(const char * file, int line, const char * fmt, ...) {
  275. fflush(stdout);
  276. fprintf(stderr, "%s:%d: ", file, line);
  277. va_list args;
  278. va_start(args, fmt);
  279. vfprintf(stderr, fmt, args);
  280. va_end(args);
  281. fprintf(stderr, "\n");
  282. ggml_print_backtrace();
  283. abort();
  284. }
  285. #define GGML_DEBUG 0
  286. #define GGML_GELU_FP16
  287. #define GGML_GELU_QUICK_FP16
  288. #define GGML_SOFT_MAX_UNROLL 4
  289. #define GGML_VEC_DOT_UNROLL 2
  290. #define GGML_VEC_MAD_UNROLL 32
  291. //
  292. // logging
  293. //
  294. #if (GGML_DEBUG >= 1)
  295. #define GGML_PRINT_DEBUG(...) printf(__VA_ARGS__)
  296. #else
  297. #define GGML_PRINT_DEBUG(...)
  298. #endif
  299. #if (GGML_DEBUG >= 5)
  300. #define GGML_PRINT_DEBUG_5(...) printf(__VA_ARGS__)
  301. #else
  302. #define GGML_PRINT_DEBUG_5(...)
  303. #endif
  304. #if (GGML_DEBUG >= 10)
  305. #define GGML_PRINT_DEBUG_10(...) printf(__VA_ARGS__)
  306. #else
  307. #define GGML_PRINT_DEBUG_10(...)
  308. #endif
  309. #define GGML_PRINT(...) printf(__VA_ARGS__)
  310. //
  311. // end of logging block
  312. //
  313. #ifdef GGML_USE_ACCELERATE
  314. // uncomment to use vDSP for soft max computation
  315. // note: not sure if it is actually faster
  316. //#define GGML_SOFT_MAX_ACCELERATE
  317. #endif
  318. #if defined(_MSC_VER) || defined(__MINGW32__)
  319. #define GGML_ALIGNED_MALLOC(size) _aligned_malloc(size, GGML_MEM_ALIGN)
  320. #define GGML_ALIGNED_FREE(ptr) _aligned_free(ptr)
  321. #else
  322. inline static void * ggml_aligned_malloc(size_t size) {
  323. if (size == 0) {
  324. GGML_PRINT("WARNING: Behavior may be unexpected when allocating 0 bytes for ggml_aligned_malloc!\n");
  325. return NULL;
  326. }
  327. void * aligned_memory = NULL;
  328. #ifdef GGML_USE_CPU_HBM
  329. int result = hbw_posix_memalign(&aligned_memory, 16, size);
  330. #elif GGML_USE_METAL
  331. int result = posix_memalign(&aligned_memory, sysconf(_SC_PAGESIZE), size);
  332. #else
  333. int result = posix_memalign(&aligned_memory, GGML_MEM_ALIGN, size);
  334. #endif
  335. if (result != 0) {
  336. // Handle allocation failure
  337. const char *error_desc = "unknown allocation error";
  338. switch (result) {
  339. case EINVAL:
  340. error_desc = "invalid alignment value";
  341. break;
  342. case ENOMEM:
  343. error_desc = "insufficient memory";
  344. break;
  345. }
  346. GGML_PRINT("%s: %s (attempted to allocate %6.2f MB)\n", __func__, error_desc, size/(1024.0*1024.0));
  347. GGML_ABORT("fatal error");
  348. return NULL;
  349. }
  350. return aligned_memory;
  351. }
  352. #define GGML_ALIGNED_MALLOC(size) ggml_aligned_malloc(size)
  353. #ifdef GGML_USE_CPU_HBM
  354. #define GGML_ALIGNED_FREE(ptr) if(NULL != ptr) hbw_free(ptr)
  355. #else
  356. #define GGML_ALIGNED_FREE(ptr) free(ptr)
  357. #endif
  358. #endif
  359. inline static void * ggml_malloc(size_t size) {
  360. if (size == 0) {
  361. GGML_PRINT("WARNING: Behavior may be unexpected when allocating 0 bytes for ggml_malloc!\n");
  362. return NULL;
  363. }
  364. void * result = malloc(size);
  365. if (result == NULL) {
  366. GGML_PRINT("%s: failed to allocate %6.2f MB\n", __func__, size/(1024.0*1024.0));
  367. GGML_ABORT("fatal error");
  368. }
  369. return result;
  370. }
  371. // calloc
  372. inline static void * ggml_calloc(size_t num, size_t size) {
  373. if (num == 0 || size == 0) {
  374. GGML_PRINT("WARNING: Behavior may be unexpected when allocating 0 bytes for ggml_calloc!\n");
  375. return NULL;
  376. }
  377. void * result = calloc(num, size);
  378. if (result == NULL) {
  379. GGML_PRINT("%s: failed to allocate %6.2f MB\n", __func__, size/(1024.0*1024.0));
  380. GGML_ABORT("fatal error");
  381. }
  382. return result;
  383. }
  384. #define GGML_MALLOC(size) ggml_malloc(size)
  385. #define GGML_CALLOC(num, size) ggml_calloc(num, size)
  386. #define GGML_FREE(ptr) free(ptr)
  387. #define UNUSED GGML_UNUSED
  388. #define SWAP(x, y, T) do { T SWAP = x; (x) = y; (y) = SWAP; } while (0)
  389. #if defined(GGML_USE_ACCELERATE)
  390. #include <Accelerate/Accelerate.h>
  391. #endif
  392. // floating point type used to accumulate sums
  393. typedef double ggml_float;
  394. #undef MIN
  395. #undef MAX
  396. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  397. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  398. //
  399. // global data
  400. //
  401. // precomputed gelu table for f16 (128 KB)
  402. static ggml_fp16_t ggml_table_gelu_f16[1 << 16];
  403. // precomputed quick gelu table for f16 (128 KB)
  404. static ggml_fp16_t ggml_table_gelu_quick_f16[1 << 16];
  405. // precomputed f32 table for f16 (256 KB) (ggml-impl.h)
  406. float ggml_table_f32_f16[1 << 16];
  407. #if defined(__ARM_ARCH)
  408. struct ggml_arm_arch_features_type {
  409. int has_neon;
  410. int has_i8mm;
  411. int has_sve;
  412. int sve_cnt;
  413. } ggml_arm_arch_features = {-1, -1, -1, 0};
  414. #endif
  415. GGML_CALL const char * ggml_status_to_string(enum ggml_status status) {
  416. switch (status) {
  417. case GGML_STATUS_ALLOC_FAILED: return "GGML status: error (failed to allocate memory)";
  418. case GGML_STATUS_FAILED: return "GGML status: error (operation failed)";
  419. case GGML_STATUS_SUCCESS: return "GGML status: success";
  420. case GGML_STATUS_ABORTED: return "GGML status: warning (operation aborted)";
  421. }
  422. return "GGML status: unknown";
  423. }
  424. float ggml_fp16_to_fp32(ggml_fp16_t x) {
  425. #define ggml_fp16_to_fp32 do_not_use__ggml_fp16_to_fp32__in_ggml
  426. return GGML_FP16_TO_FP32(x);
  427. }
  428. ggml_fp16_t ggml_fp32_to_fp16(float x) {
  429. #define ggml_fp32_to_fp16 do_not_use__ggml_fp32_to_fp16__in_ggml
  430. return GGML_FP32_TO_FP16(x);
  431. }
  432. float ggml_bf16_to_fp32(ggml_bf16_t x) {
  433. #define ggml_bf16_to_fp32 do_not_use__ggml_bf16_to_fp32__in_ggml
  434. return GGML_BF16_TO_FP32(x); // it just left shifts
  435. }
  436. ggml_bf16_t ggml_fp32_to_bf16(float x) {
  437. #define ggml_fp32_to_bf16 do_not_use__ggml_fp32_to_bf16__in_ggml
  438. return GGML_FP32_TO_BF16(x);
  439. }
  440. void ggml_fp16_to_fp32_row(const ggml_fp16_t * x, float * y, int64_t n) {
  441. for (int64_t i = 0; i < n; i++) {
  442. y[i] = GGML_FP16_TO_FP32(x[i]);
  443. }
  444. }
  445. void ggml_fp32_to_fp16_row(const float * x, ggml_fp16_t * y, int64_t n) {
  446. int64_t i = 0;
  447. #if defined(__F16C__)
  448. for (; i + 7 < n; i += 8) {
  449. __m256 x_vec = _mm256_loadu_ps(x + i);
  450. __m128i y_vec = _mm256_cvtps_ph(x_vec, _MM_FROUND_TO_NEAREST_INT);
  451. _mm_storeu_si128((__m128i *)(y + i), y_vec);
  452. }
  453. for(; i + 3 < n; i += 4) {
  454. __m128 x_vec = _mm_loadu_ps(x + i);
  455. __m128i y_vec = _mm_cvtps_ph(x_vec, _MM_FROUND_TO_NEAREST_INT);
  456. _mm_storel_epi64((__m128i *)(y + i), y_vec);
  457. }
  458. #endif
  459. for (; i < n; i++) {
  460. y[i] = GGML_FP32_TO_FP16(x[i]);
  461. }
  462. }
  463. void ggml_bf16_to_fp32_row(const ggml_bf16_t * x, float * y, int64_t n) {
  464. int64_t i = 0;
  465. #if defined(__AVX512F__)
  466. for (; i + 16 <= n; i += 16) {
  467. _mm512_storeu_ps(y + i,
  468. _mm512_castsi512_ps(
  469. _mm512_slli_epi32(
  470. _mm512_cvtepu16_epi32(
  471. _mm256_loadu_si256(
  472. (const __m256i *)(x + i))),
  473. 16)));
  474. }
  475. #elif defined(__AVX2__)
  476. for (; i + 8 <= n; i += 8) {
  477. _mm256_storeu_ps(y + i,
  478. _mm256_castsi256_ps(
  479. _mm256_slli_epi32(
  480. _mm256_cvtepu16_epi32(
  481. _mm_loadu_si128(
  482. (const __m128i *)(x + i))),
  483. 16)));
  484. }
  485. #endif
  486. for (; i < n; i++) {
  487. y[i] = GGML_BF16_TO_FP32(x[i]);
  488. }
  489. }
  490. void ggml_fp32_to_bf16_row_ref(const float * x, ggml_bf16_t * y, int64_t n) {
  491. for (int i = 0; i < n; i++) {
  492. y[i] = ggml_compute_fp32_to_bf16(x[i]);
  493. }
  494. }
  495. void ggml_fp32_to_bf16_row(const float * x, ggml_bf16_t * y, int64_t n) {
  496. int i = 0;
  497. #if defined(__AVX512BF16__)
  498. // subnormals are flushed to zero on this platform
  499. for (; i + 32 <= n; i += 32) {
  500. _mm512_storeu_si512(
  501. (__m512i *)(y + i),
  502. m512i(_mm512_cvtne2ps_pbh(_mm512_loadu_ps(x + i + 16),
  503. _mm512_loadu_ps(x + i))));
  504. }
  505. #endif
  506. for (; i < n; i++) {
  507. y[i] = GGML_FP32_TO_BF16(x[i]);
  508. }
  509. }
  510. bool ggml_guid_matches(ggml_guid_t guid_a, ggml_guid_t guid_b) {
  511. return memcmp(guid_a, guid_b, sizeof(ggml_guid)) == 0;
  512. }
  513. //
  514. // timing
  515. //
  516. #if defined(_MSC_VER) || defined(__MINGW32__)
  517. static int64_t timer_freq, timer_start;
  518. void ggml_time_init(void) {
  519. LARGE_INTEGER t;
  520. QueryPerformanceFrequency(&t);
  521. timer_freq = t.QuadPart;
  522. // The multiplication by 1000 or 1000000 below can cause an overflow if timer_freq
  523. // and the uptime is high enough.
  524. // We subtract the program start time to reduce the likelihood of that happening.
  525. QueryPerformanceCounter(&t);
  526. timer_start = t.QuadPart;
  527. }
  528. int64_t ggml_time_ms(void) {
  529. LARGE_INTEGER t;
  530. QueryPerformanceCounter(&t);
  531. return ((t.QuadPart-timer_start) * 1000) / timer_freq;
  532. }
  533. int64_t ggml_time_us(void) {
  534. LARGE_INTEGER t;
  535. QueryPerformanceCounter(&t);
  536. return ((t.QuadPart-timer_start) * 1000000) / timer_freq;
  537. }
  538. #else
  539. void ggml_time_init(void) {}
  540. int64_t ggml_time_ms(void) {
  541. struct timespec ts;
  542. clock_gettime(CLOCK_MONOTONIC, &ts);
  543. return (int64_t)ts.tv_sec*1000 + (int64_t)ts.tv_nsec/1000000;
  544. }
  545. int64_t ggml_time_us(void) {
  546. struct timespec ts;
  547. clock_gettime(CLOCK_MONOTONIC, &ts);
  548. return (int64_t)ts.tv_sec*1000000 + (int64_t)ts.tv_nsec/1000;
  549. }
  550. #endif
  551. int64_t ggml_cycles(void) {
  552. return clock();
  553. }
  554. int64_t ggml_cycles_per_ms(void) {
  555. return CLOCKS_PER_SEC/1000;
  556. }
  557. //
  558. // cross-platform UTF-8 file paths
  559. //
  560. #ifdef _WIN32
  561. static wchar_t * ggml_mbstowcs(const char * mbs) {
  562. int wlen = MultiByteToWideChar(CP_UTF8, 0, mbs, -1, NULL, 0);
  563. if (!wlen) {
  564. errno = EINVAL;
  565. return NULL;
  566. }
  567. wchar_t * wbuf = GGML_MALLOC(wlen * sizeof(wchar_t));
  568. wlen = MultiByteToWideChar(CP_UTF8, 0, mbs, -1, wbuf, wlen);
  569. if (!wlen) {
  570. GGML_FREE(wbuf);
  571. errno = EINVAL;
  572. return NULL;
  573. }
  574. return wbuf;
  575. }
  576. #endif
  577. FILE * ggml_fopen(const char * fname, const char * mode) {
  578. #ifdef _WIN32
  579. FILE * file = NULL;
  580. // convert fname (UTF-8)
  581. wchar_t * wfname = ggml_mbstowcs(fname);
  582. if (wfname) {
  583. // convert mode (ANSI)
  584. wchar_t * wmode = GGML_MALLOC((strlen(mode) + 1) * sizeof(wchar_t));
  585. wchar_t * wmode_p = wmode;
  586. do {
  587. *wmode_p++ = (wchar_t)*mode;
  588. } while (*mode++);
  589. // open file
  590. file = _wfopen(wfname, wmode);
  591. GGML_FREE(wfname);
  592. GGML_FREE(wmode);
  593. }
  594. return file;
  595. #else
  596. return fopen(fname, mode);
  597. #endif
  598. }
  599. //
  600. // cache line
  601. //
  602. #if defined(__cpp_lib_hardware_interference_size)
  603. #define CACHE_LINE_SIZE hardware_destructive_interference_size
  604. #else
  605. #if defined(__POWER9_VECTOR__)
  606. #define CACHE_LINE_SIZE 128
  607. #else
  608. #define CACHE_LINE_SIZE 64
  609. #endif
  610. #endif
  611. static const size_t CACHE_LINE_SIZE_F32 = CACHE_LINE_SIZE/sizeof(float);
  612. 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);
  613. 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);
  614. 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);
  615. static const ggml_type_traits_t type_traits[GGML_TYPE_COUNT] = {
  616. [GGML_TYPE_I8] = {
  617. .type_name = "i8",
  618. .blck_size = 1,
  619. .type_size = sizeof(int8_t),
  620. .is_quantized = false,
  621. },
  622. [GGML_TYPE_I16] = {
  623. .type_name = "i16",
  624. .blck_size = 1,
  625. .type_size = sizeof(int16_t),
  626. .is_quantized = false,
  627. },
  628. [GGML_TYPE_I32] = {
  629. .type_name = "i32",
  630. .blck_size = 1,
  631. .type_size = sizeof(int32_t),
  632. .is_quantized = false,
  633. },
  634. [GGML_TYPE_I64] = {
  635. .type_name = "i64",
  636. .blck_size = 1,
  637. .type_size = sizeof(int64_t),
  638. .is_quantized = false,
  639. },
  640. [GGML_TYPE_F64] = {
  641. .type_name = "f64",
  642. .blck_size = 1,
  643. .type_size = sizeof(double),
  644. .is_quantized = false,
  645. .nrows = 1,
  646. },
  647. [GGML_TYPE_F32] = {
  648. .type_name = "f32",
  649. .blck_size = 1,
  650. .type_size = sizeof(float),
  651. .is_quantized = false,
  652. .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_f32,
  653. .vec_dot_type = GGML_TYPE_F32,
  654. .nrows = 1,
  655. },
  656. [GGML_TYPE_F16] = {
  657. .type_name = "f16",
  658. .blck_size = 1,
  659. .type_size = sizeof(ggml_fp16_t),
  660. .is_quantized = false,
  661. .to_float = (ggml_to_float_t) ggml_fp16_to_fp32_row,
  662. .from_float = (ggml_from_float_t) ggml_fp32_to_fp16_row,
  663. .from_float_ref = (ggml_from_float_t) ggml_fp32_to_fp16_row,
  664. .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_f16,
  665. .vec_dot_type = GGML_TYPE_F16,
  666. .nrows = 1,
  667. },
  668. [GGML_TYPE_Q4_0] = {
  669. .type_name = "q4_0",
  670. .blck_size = QK4_0,
  671. .type_size = sizeof(block_q4_0),
  672. .is_quantized = true,
  673. .to_float = (ggml_to_float_t) dequantize_row_q4_0,
  674. .from_float = quantize_row_q4_0,
  675. .from_float_ref = (ggml_from_float_t) quantize_row_q4_0_ref,
  676. .vec_dot = ggml_vec_dot_q4_0_q8_0,
  677. .vec_dot_type = GGML_TYPE_Q8_0,
  678. #if defined (__ARM_FEATURE_MATMUL_INT8)
  679. .nrows = 2,
  680. #else
  681. .nrows = 1,
  682. #endif
  683. },
  684. [GGML_TYPE_Q4_1] = {
  685. .type_name = "q4_1",
  686. .blck_size = QK4_1,
  687. .type_size = sizeof(block_q4_1),
  688. .is_quantized = true,
  689. .to_float = (ggml_to_float_t) dequantize_row_q4_1,
  690. .from_float = quantize_row_q4_1,
  691. .from_float_ref = (ggml_from_float_t) quantize_row_q4_1_ref,
  692. .vec_dot = ggml_vec_dot_q4_1_q8_1,
  693. .vec_dot_type = GGML_TYPE_Q8_1,
  694. #if defined (__ARM_FEATURE_MATMUL_INT8)
  695. .nrows = 2,
  696. #else
  697. .nrows = 1,
  698. #endif
  699. },
  700. [4] = { // GGML_TYPE_Q4_2
  701. .type_name = "DEPRECATED",
  702. .blck_size = 0,
  703. .type_size = 0,
  704. .is_quantized = false,
  705. .to_float = NULL,
  706. .from_float = NULL,
  707. .from_float_ref = NULL,
  708. .vec_dot = NULL,
  709. .vec_dot_type = GGML_TYPE_COUNT,
  710. .nrows = 1,
  711. },
  712. [5] = { // GGML_TYPE_Q4_3
  713. .type_name = "DEPRECATED",
  714. .blck_size = 0,
  715. .type_size = 0,
  716. .is_quantized = false,
  717. .to_float = NULL,
  718. .from_float = NULL,
  719. .from_float_ref = NULL,
  720. .vec_dot = NULL,
  721. .vec_dot_type = GGML_TYPE_COUNT,
  722. .nrows = 1,
  723. },
  724. [GGML_TYPE_Q5_0] = {
  725. .type_name = "q5_0",
  726. .blck_size = QK5_0,
  727. .type_size = sizeof(block_q5_0),
  728. .is_quantized = true,
  729. .to_float = (ggml_to_float_t) dequantize_row_q5_0,
  730. .from_float = quantize_row_q5_0,
  731. .from_float_ref = (ggml_from_float_t) quantize_row_q5_0_ref,
  732. .vec_dot = ggml_vec_dot_q5_0_q8_0,
  733. .vec_dot_type = GGML_TYPE_Q8_0,
  734. .nrows = 1,
  735. },
  736. [GGML_TYPE_Q5_1] = {
  737. .type_name = "q5_1",
  738. .blck_size = QK5_1,
  739. .type_size = sizeof(block_q5_1),
  740. .is_quantized = true,
  741. .to_float = (ggml_to_float_t) dequantize_row_q5_1,
  742. .from_float = quantize_row_q5_1,
  743. .from_float_ref = (ggml_from_float_t) quantize_row_q5_1_ref,
  744. .vec_dot = ggml_vec_dot_q5_1_q8_1,
  745. .vec_dot_type = GGML_TYPE_Q8_1,
  746. .nrows = 1,
  747. },
  748. [GGML_TYPE_Q8_0] = {
  749. .type_name = "q8_0",
  750. .blck_size = QK8_0,
  751. .type_size = sizeof(block_q8_0),
  752. .is_quantized = true,
  753. .to_float = (ggml_to_float_t) dequantize_row_q8_0,
  754. .from_float = quantize_row_q8_0,
  755. .from_float_ref = (ggml_from_float_t) quantize_row_q8_0_ref,
  756. .from_float_to_mat = quantize_mat_q8_0,
  757. .vec_dot = ggml_vec_dot_q8_0_q8_0,
  758. .vec_dot_type = GGML_TYPE_Q8_0,
  759. #if defined (__ARM_FEATURE_MATMUL_INT8)
  760. .nrows = 2,
  761. #else
  762. .nrows = 1,
  763. #endif
  764. },
  765. [GGML_TYPE_Q8_1] = {
  766. .type_name = "q8_1",
  767. .blck_size = QK8_1,
  768. .type_size = sizeof(block_q8_1),
  769. .is_quantized = true,
  770. .from_float = quantize_row_q8_1,
  771. .from_float_ref = (ggml_from_float_t) quantize_row_q8_1_ref,
  772. .vec_dot_type = GGML_TYPE_Q8_1,
  773. .nrows = 1,
  774. },
  775. [GGML_TYPE_Q2_K] = {
  776. .type_name = "q2_K",
  777. .blck_size = QK_K,
  778. .type_size = sizeof(block_q2_K),
  779. .is_quantized = true,
  780. .to_float = (ggml_to_float_t) dequantize_row_q2_K,
  781. .from_float = quantize_row_q2_K,
  782. .from_float_ref = (ggml_from_float_t) quantize_row_q2_K_ref,
  783. .vec_dot = ggml_vec_dot_q2_K_q8_K,
  784. .vec_dot_type = GGML_TYPE_Q8_K,
  785. .nrows = 1,
  786. },
  787. [GGML_TYPE_Q3_K] = {
  788. .type_name = "q3_K",
  789. .blck_size = QK_K,
  790. .type_size = sizeof(block_q3_K),
  791. .is_quantized = true,
  792. .to_float = (ggml_to_float_t) dequantize_row_q3_K,
  793. .from_float = quantize_row_q3_K,
  794. .from_float_ref = (ggml_from_float_t) quantize_row_q3_K_ref,
  795. .vec_dot = ggml_vec_dot_q3_K_q8_K,
  796. .vec_dot_type = GGML_TYPE_Q8_K,
  797. .nrows = 1,
  798. },
  799. [GGML_TYPE_Q4_K] = {
  800. .type_name = "q4_K",
  801. .blck_size = QK_K,
  802. .type_size = sizeof(block_q4_K),
  803. .is_quantized = true,
  804. .to_float = (ggml_to_float_t) dequantize_row_q4_K,
  805. .from_float = quantize_row_q4_K,
  806. .from_float_ref = (ggml_from_float_t) quantize_row_q4_K_ref,
  807. .vec_dot = ggml_vec_dot_q4_K_q8_K,
  808. .vec_dot_type = GGML_TYPE_Q8_K,
  809. .nrows = 1,
  810. },
  811. [GGML_TYPE_Q5_K] = {
  812. .type_name = "q5_K",
  813. .blck_size = QK_K,
  814. .type_size = sizeof(block_q5_K),
  815. .is_quantized = true,
  816. .to_float = (ggml_to_float_t) dequantize_row_q5_K,
  817. .from_float = quantize_row_q5_K,
  818. .from_float_ref = (ggml_from_float_t) quantize_row_q5_K_ref,
  819. .vec_dot = ggml_vec_dot_q5_K_q8_K,
  820. .vec_dot_type = GGML_TYPE_Q8_K,
  821. .nrows = 1,
  822. },
  823. [GGML_TYPE_Q6_K] = {
  824. .type_name = "q6_K",
  825. .blck_size = QK_K,
  826. .type_size = sizeof(block_q6_K),
  827. .is_quantized = true,
  828. .to_float = (ggml_to_float_t) dequantize_row_q6_K,
  829. .from_float = quantize_row_q6_K,
  830. .from_float_ref = (ggml_from_float_t) quantize_row_q6_K_ref,
  831. .vec_dot = ggml_vec_dot_q6_K_q8_K,
  832. .vec_dot_type = GGML_TYPE_Q8_K,
  833. .nrows = 1,
  834. },
  835. [GGML_TYPE_IQ2_XXS] = {
  836. .type_name = "iq2_xxs",
  837. .blck_size = QK_K,
  838. .type_size = sizeof(block_iq2_xxs),
  839. .is_quantized = true,
  840. .to_float = (ggml_to_float_t) dequantize_row_iq2_xxs,
  841. .from_float = NULL,
  842. .from_float_ref = NULL,
  843. .vec_dot = ggml_vec_dot_iq2_xxs_q8_K,
  844. .vec_dot_type = GGML_TYPE_Q8_K,
  845. .nrows = 1,
  846. },
  847. [GGML_TYPE_IQ2_XS] = {
  848. .type_name = "iq2_xs",
  849. .blck_size = QK_K,
  850. .type_size = sizeof(block_iq2_xs),
  851. .is_quantized = true,
  852. .to_float = (ggml_to_float_t) dequantize_row_iq2_xs,
  853. .from_float = NULL,
  854. .from_float_ref = NULL,
  855. .vec_dot = ggml_vec_dot_iq2_xs_q8_K,
  856. .vec_dot_type = GGML_TYPE_Q8_K,
  857. .nrows = 1,
  858. },
  859. [GGML_TYPE_IQ3_XXS] = {
  860. .type_name = "iq3_xxs",
  861. .blck_size = QK_K,
  862. .type_size = sizeof(block_iq3_xxs),
  863. .is_quantized = true,
  864. .to_float = (ggml_to_float_t) dequantize_row_iq3_xxs,
  865. .from_float = quantize_row_iq3_xxs,
  866. .from_float_ref = (ggml_from_float_t)quantize_row_iq3_xxs_ref,
  867. .vec_dot = ggml_vec_dot_iq3_xxs_q8_K,
  868. .vec_dot_type = GGML_TYPE_Q8_K,
  869. .nrows = 1,
  870. },
  871. [GGML_TYPE_IQ3_S] = {
  872. .type_name = "iq3_s",
  873. .blck_size = QK_K,
  874. .type_size = sizeof(block_iq3_s),
  875. .is_quantized = true,
  876. .to_float = (ggml_to_float_t) dequantize_row_iq3_s,
  877. .from_float = quantize_row_iq3_s,
  878. .from_float_ref = (ggml_from_float_t)quantize_row_iq3_s_ref,
  879. .vec_dot = ggml_vec_dot_iq3_s_q8_K,
  880. .vec_dot_type = GGML_TYPE_Q8_K,
  881. .nrows = 1,
  882. },
  883. [GGML_TYPE_IQ2_S] = {
  884. .type_name = "iq2_s",
  885. .blck_size = QK_K,
  886. .type_size = sizeof(block_iq2_s),
  887. .is_quantized = true,
  888. .to_float = (ggml_to_float_t) dequantize_row_iq2_s,
  889. .from_float = quantize_row_iq2_s,
  890. .from_float_ref = (ggml_from_float_t)quantize_row_iq2_s_ref,
  891. .vec_dot = ggml_vec_dot_iq2_s_q8_K,
  892. .vec_dot_type = GGML_TYPE_Q8_K,
  893. .nrows = 1,
  894. },
  895. [GGML_TYPE_IQ1_S] = {
  896. .type_name = "iq1_s",
  897. .blck_size = QK_K,
  898. .type_size = sizeof(block_iq1_s),
  899. .is_quantized = true,
  900. .to_float = (ggml_to_float_t) dequantize_row_iq1_s,
  901. .from_float = NULL,
  902. .from_float_ref = NULL,
  903. .vec_dot = ggml_vec_dot_iq1_s_q8_K,
  904. .vec_dot_type = GGML_TYPE_Q8_K,
  905. .nrows = 1,
  906. },
  907. [GGML_TYPE_IQ1_M] = {
  908. .type_name = "iq1_m",
  909. .blck_size = QK_K,
  910. .type_size = sizeof(block_iq1_m),
  911. .is_quantized = true,
  912. .to_float = (ggml_to_float_t) dequantize_row_iq1_m,
  913. .from_float = NULL,
  914. .from_float_ref = NULL,
  915. .vec_dot = ggml_vec_dot_iq1_m_q8_K,
  916. .vec_dot_type = GGML_TYPE_Q8_K,
  917. .nrows = 1,
  918. },
  919. [GGML_TYPE_IQ4_NL] = {
  920. .type_name = "iq4_nl",
  921. .blck_size = QK4_NL,
  922. .type_size = sizeof(block_iq4_nl),
  923. .is_quantized = true,
  924. .to_float = (ggml_to_float_t) dequantize_row_iq4_nl,
  925. .from_float = quantize_row_iq4_nl,
  926. .from_float_ref = (ggml_from_float_t)quantize_row_iq4_nl_ref,
  927. .vec_dot = ggml_vec_dot_iq4_nl_q8_0,
  928. .vec_dot_type = GGML_TYPE_Q8_0,
  929. .nrows = 1,
  930. },
  931. [GGML_TYPE_IQ4_XS] = {
  932. .type_name = "iq4_xs",
  933. .blck_size = QK_K,
  934. .type_size = sizeof(block_iq4_xs),
  935. .is_quantized = true,
  936. .to_float = (ggml_to_float_t) dequantize_row_iq4_xs,
  937. .from_float = quantize_row_iq4_xs,
  938. .from_float_ref = (ggml_from_float_t)quantize_row_iq4_xs_ref,
  939. .vec_dot = ggml_vec_dot_iq4_xs_q8_K,
  940. .vec_dot_type = GGML_TYPE_Q8_K,
  941. .nrows = 1,
  942. },
  943. [GGML_TYPE_Q8_K] = {
  944. .type_name = "q8_K",
  945. .blck_size = QK_K,
  946. .type_size = sizeof(block_q8_K),
  947. .is_quantized = true,
  948. .from_float = quantize_row_q8_K,
  949. },
  950. [GGML_TYPE_BF16] = {
  951. .type_name = "bf16",
  952. .blck_size = 1,
  953. .type_size = sizeof(ggml_bf16_t),
  954. .is_quantized = false,
  955. .to_float = (ggml_to_float_t) ggml_bf16_to_fp32_row,
  956. .from_float = (ggml_from_float_t) ggml_fp32_to_bf16_row,
  957. .from_float_ref = (ggml_from_float_t) ggml_fp32_to_bf16_row_ref,
  958. .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_bf16,
  959. .vec_dot_type = GGML_TYPE_BF16,
  960. .nrows = 1,
  961. },
  962. [GGML_TYPE_Q4_0_4_4] = {
  963. .type_name = "q4_0_4x4",
  964. .blck_size = QK4_0,
  965. .blck_size_interleave = 4,
  966. .type_size = sizeof(block_q4_0),
  967. .is_quantized = true,
  968. .to_float = NULL,
  969. .from_float = NULL,
  970. .from_float_ref = NULL,
  971. .vec_dot = NULL,
  972. .vec_dot_type = GGML_TYPE_Q8_0,
  973. .nrows = 1,
  974. .ncols = 4,
  975. .gemv = ggml_gemv_q4_0_4x4_q8_0,
  976. .gemm = ggml_gemm_q4_0_4x4_q8_0,
  977. },
  978. [GGML_TYPE_Q4_0_4_8] = {
  979. .type_name = "q4_0_4x8",
  980. .blck_size = QK4_0,
  981. .blck_size_interleave = 8,
  982. .type_size = sizeof(block_q4_0),
  983. .is_quantized = true,
  984. .to_float = NULL,
  985. .from_float = NULL,
  986. .from_float_ref = NULL,
  987. .vec_dot = NULL,
  988. .vec_dot_type = GGML_TYPE_Q8_0,
  989. .nrows = 1,
  990. .ncols = 4,
  991. .gemv = ggml_gemv_q4_0_4x8_q8_0,
  992. .gemm = ggml_gemm_q4_0_4x8_q8_0,
  993. },
  994. [GGML_TYPE_Q4_0_8_8] = {
  995. .type_name = "q4_0_8x8",
  996. .blck_size = QK4_0,
  997. .blck_size_interleave = 8,
  998. .type_size = sizeof(block_q4_0),
  999. .is_quantized = true,
  1000. .to_float = NULL,
  1001. .from_float = NULL,
  1002. .from_float_ref = NULL,
  1003. .vec_dot = NULL,
  1004. .vec_dot_type = GGML_TYPE_Q8_0,
  1005. .nrows = 1,
  1006. .ncols = 8,
  1007. .gemv = ggml_gemv_q4_0_8x8_q8_0,
  1008. .gemm = ggml_gemm_q4_0_8x8_q8_0,
  1009. },
  1010. [GGML_TYPE_TQ1_0] = {
  1011. .type_name = "tq1_0",
  1012. .blck_size = QK_K,
  1013. .type_size = sizeof(block_tq1_0),
  1014. .is_quantized = true,
  1015. .to_float = (ggml_to_float_t) dequantize_row_tq1_0,
  1016. .from_float = quantize_row_tq1_0,
  1017. .from_float_ref = (ggml_from_float_t) quantize_row_tq1_0_ref,
  1018. .vec_dot = ggml_vec_dot_tq1_0_q8_K,
  1019. .vec_dot_type = GGML_TYPE_Q8_K,
  1020. .nrows = 1,
  1021. },
  1022. [GGML_TYPE_TQ2_0] = {
  1023. .type_name = "tq2_0",
  1024. .blck_size = QK_K,
  1025. .type_size = sizeof(block_tq2_0),
  1026. .is_quantized = true,
  1027. .to_float = (ggml_to_float_t) dequantize_row_tq2_0,
  1028. .from_float = quantize_row_tq2_0,
  1029. .from_float_ref = (ggml_from_float_t) quantize_row_tq2_0_ref,
  1030. .vec_dot = ggml_vec_dot_tq2_0_q8_K,
  1031. .vec_dot_type = GGML_TYPE_Q8_K,
  1032. .nrows = 1,
  1033. },
  1034. };
  1035. // For internal test use
  1036. ggml_type_traits_t ggml_internal_get_type_traits(enum ggml_type type) {
  1037. GGML_ASSERT(type < GGML_TYPE_COUNT);
  1038. return type_traits[type];
  1039. }
  1040. //
  1041. // simd mappings
  1042. //
  1043. // we define a common set of C macros which map to specific intrinsics based on the current architecture
  1044. // we then implement the fundamental computation operations below using only these macros
  1045. // adding support for new architectures requires to define the corresponding SIMD macros
  1046. //
  1047. // GGML_F32_STEP / GGML_F16_STEP
  1048. // number of elements to process in a single step
  1049. //
  1050. // GGML_F32_EPR / GGML_F16_EPR
  1051. // number of elements to fit in a single register
  1052. //
  1053. #if defined(__ARM_NEON) && defined(__ARM_FEATURE_FMA)
  1054. #define GGML_SIMD
  1055. // F32 NEON
  1056. #define GGML_F32_STEP 16
  1057. #define GGML_F32_EPR 4
  1058. #define GGML_F32x4 float32x4_t
  1059. #define GGML_F32x4_ZERO vdupq_n_f32(0.0f)
  1060. #define GGML_F32x4_SET1(x) vdupq_n_f32(x)
  1061. #define GGML_F32x4_LOAD vld1q_f32
  1062. #define GGML_F32x4_STORE vst1q_f32
  1063. #define GGML_F32x4_FMA(a, b, c) vfmaq_f32(a, b, c)
  1064. #define GGML_F32x4_ADD vaddq_f32
  1065. #define GGML_F32x4_MUL vmulq_f32
  1066. #define GGML_F32x4_REDUCE_ONE(x) vaddvq_f32(x)
  1067. #define GGML_F32x4_REDUCE(res, x) \
  1068. { \
  1069. int offset = GGML_F32_ARR >> 1; \
  1070. for (int i = 0; i < offset; ++i) { \
  1071. (x)[i] = vaddq_f32((x)[i], (x)[offset+i]); \
  1072. } \
  1073. offset >>= 1; \
  1074. for (int i = 0; i < offset; ++i) { \
  1075. (x)[i] = vaddq_f32((x)[i], (x)[offset+i]); \
  1076. } \
  1077. offset >>= 1; \
  1078. for (int i = 0; i < offset; ++i) { \
  1079. (x)[i] = vaddq_f32((x)[i], (x)[offset+i]); \
  1080. } \
  1081. (res) = GGML_F32x4_REDUCE_ONE((x)[0]); \
  1082. }
  1083. #define GGML_F32_VEC GGML_F32x4
  1084. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1085. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1086. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1087. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1088. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1089. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1090. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1091. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1092. // F16 NEON
  1093. #if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
  1094. #define GGML_F16_STEP 32
  1095. #define GGML_F16_EPR 8
  1096. #define GGML_F16x8 float16x8_t
  1097. #define GGML_F16x8_ZERO vdupq_n_f16(0.0f)
  1098. #define GGML_F16x8_SET1(x) vdupq_n_f16(x)
  1099. #define GGML_F16x8_LOAD(x) vld1q_f16((const ggml_fp16_internal_t *)(x))
  1100. #define GGML_F16x8_STORE vst1q_f16
  1101. #define GGML_F16x8_FMA(a, b, c) vfmaq_f16(a, b, c)
  1102. #define GGML_F16x8_ADD vaddq_f16
  1103. #define GGML_F16x8_MUL vmulq_f16
  1104. #define GGML_F16x8_REDUCE(res, x) \
  1105. do { \
  1106. int offset = GGML_F16_ARR >> 1; \
  1107. for (int i = 0; i < offset; ++i) { \
  1108. (x)[i] = vaddq_f16((x)[i], (x)[offset+i]); \
  1109. } \
  1110. offset >>= 1; \
  1111. for (int i = 0; i < offset; ++i) { \
  1112. (x)[i] = vaddq_f16((x)[i], (x)[offset+i]); \
  1113. } \
  1114. offset >>= 1; \
  1115. for (int i = 0; i < offset; ++i) { \
  1116. (x)[i] = vaddq_f16((x)[i], (x)[offset+i]); \
  1117. } \
  1118. const float32x4_t t0 = vcvt_f32_f16(vget_low_f16 ((x)[0])); \
  1119. const float32x4_t t1 = vcvt_f32_f16(vget_high_f16((x)[0])); \
  1120. (res) = (ggml_float) vaddvq_f32(vaddq_f32(t0, t1)); \
  1121. } while (0)
  1122. #define GGML_F16_VEC GGML_F16x8
  1123. #define GGML_F16_VEC_ZERO GGML_F16x8_ZERO
  1124. #define GGML_F16_VEC_SET1 GGML_F16x8_SET1
  1125. #define GGML_F16_VEC_LOAD(p, i) GGML_F16x8_LOAD(p)
  1126. #define GGML_F16_VEC_STORE(p, r, i) GGML_F16x8_STORE((ggml_fp16_internal_t *)(p), (r)[i])
  1127. #define GGML_F16_VEC_FMA GGML_F16x8_FMA
  1128. #define GGML_F16_VEC_ADD GGML_F16x8_ADD
  1129. #define GGML_F16_VEC_MUL GGML_F16x8_MUL
  1130. #define GGML_F16_VEC_REDUCE GGML_F16x8_REDUCE
  1131. #else
  1132. // if FP16 vector arithmetic is not supported, we use FP32 instead
  1133. // and take advantage of the vcvt_ functions to convert to/from FP16
  1134. #define GGML_F16_STEP 16
  1135. #define GGML_F16_EPR 4
  1136. #define GGML_F32Cx4 float32x4_t
  1137. #define GGML_F32Cx4_ZERO vdupq_n_f32(0.0f)
  1138. #define GGML_F32Cx4_SET1(x) vdupq_n_f32(x)
  1139. #define GGML_F32Cx4_LOAD(x) vcvt_f32_f16(vld1_f16((const ggml_fp16_internal_t *)(x)))
  1140. #define GGML_F32Cx4_STORE(x, y) vst1_f16(x, vcvt_f16_f32(y))
  1141. #define GGML_F32Cx4_FMA(a, b, c) vfmaq_f32(a, b, c)
  1142. #define GGML_F32Cx4_ADD vaddq_f32
  1143. #define GGML_F32Cx4_MUL vmulq_f32
  1144. #define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
  1145. #define GGML_F16_VEC GGML_F32Cx4
  1146. #define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
  1147. #define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
  1148. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
  1149. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE((ggml_fp16_internal_t *)(p), r[i])
  1150. #define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
  1151. #define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
  1152. #define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
  1153. #define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
  1154. #endif
  1155. #elif defined(__AVX512F__)
  1156. #define GGML_SIMD
  1157. // F32 AVX512
  1158. #define GGML_F32_STEP 64
  1159. #define GGML_F32_EPR 16
  1160. #define GGML_F32x16 __m512
  1161. #define GGML_F32x16_ZERO _mm512_setzero_ps()
  1162. #define GGML_F32x16_SET1(x) _mm512_set1_ps(x)
  1163. #define GGML_F32x16_LOAD _mm512_loadu_ps
  1164. #define GGML_F32x16_STORE _mm512_storeu_ps
  1165. // _mm512_fmadd_ps is defined in AVX512F so no guard is required
  1166. #define GGML_F32x16_FMA(a, b, c) _mm512_fmadd_ps(b, c, a)
  1167. #define GGML_F32x16_ADD _mm512_add_ps
  1168. #define GGML_F32x16_MUL _mm512_mul_ps
  1169. #define GGML_F32x16_REDUCE(res, x) \
  1170. do { \
  1171. int offset = GGML_F32_ARR >> 1; \
  1172. for (int i = 0; i < offset; ++i) { \
  1173. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1174. } \
  1175. offset >>= 1; \
  1176. for (int i = 0; i < offset; ++i) { \
  1177. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1178. } \
  1179. offset >>= 1; \
  1180. for (int i = 0; i < offset; ++i) { \
  1181. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1182. } \
  1183. res = _mm512_reduce_add_ps(x[0]); \
  1184. } while (0)
  1185. // TODO: is this optimal ?
  1186. #define GGML_F32_VEC GGML_F32x16
  1187. #define GGML_F32_VEC_ZERO GGML_F32x16_ZERO
  1188. #define GGML_F32_VEC_SET1 GGML_F32x16_SET1
  1189. #define GGML_F32_VEC_LOAD GGML_F32x16_LOAD
  1190. #define GGML_F32_VEC_STORE GGML_F32x16_STORE
  1191. #define GGML_F32_VEC_FMA GGML_F32x16_FMA
  1192. #define GGML_F32_VEC_ADD GGML_F32x16_ADD
  1193. #define GGML_F32_VEC_MUL GGML_F32x16_MUL
  1194. #define GGML_F32_VEC_REDUCE GGML_F32x16_REDUCE
  1195. // F16 AVX512
  1196. // F16 AVX
  1197. #define GGML_F16_STEP 64
  1198. #define GGML_F16_EPR 16
  1199. // AVX512 has FP16 extension (AVX512_FP16) but I don't have it on my machine so I use FP32 instead
  1200. #define GGML_F32Cx16 __m512
  1201. #define GGML_F32Cx16_ZERO _mm512_setzero_ps()
  1202. #define GGML_F32Cx16_SET1(x) _mm512_set1_ps(x)
  1203. // unlike _mm256_cvt intrinsics that require F16C, _mm512_cvt is defined in AVX512F
  1204. // so F16C guard isn't required
  1205. #define GGML_F32Cx16_LOAD(x) _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(x)))
  1206. #define GGML_F32Cx16_STORE(x, y) _mm256_storeu_si256((__m256i *)(x), _mm512_cvtps_ph(y, 0))
  1207. #define GGML_F32Cx16_FMA(a, b, c) _mm512_fmadd_ps(b, c, a)
  1208. #define GGML_F32Cx16_ADD _mm512_add_ps
  1209. #define GGML_F32Cx16_MUL _mm512_mul_ps
  1210. #define GGML_F32Cx16_REDUCE(res, x) \
  1211. do { \
  1212. int offset = GGML_F32_ARR >> 1; \
  1213. for (int i = 0; i < offset; ++i) { \
  1214. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1215. } \
  1216. offset >>= 1; \
  1217. for (int i = 0; i < offset; ++i) { \
  1218. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1219. } \
  1220. offset >>= 1; \
  1221. for (int i = 0; i < offset; ++i) { \
  1222. x[i] = _mm512_add_ps(x[i], x[offset+i]); \
  1223. } \
  1224. res = _mm512_reduce_add_ps(x[0]); \
  1225. } while (0)
  1226. #define GGML_F16_VEC GGML_F32Cx16
  1227. #define GGML_F16_VEC_ZERO GGML_F32Cx16_ZERO
  1228. #define GGML_F16_VEC_SET1 GGML_F32Cx16_SET1
  1229. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx16_LOAD(p)
  1230. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx16_STORE(p, r[i])
  1231. #define GGML_F16_VEC_FMA GGML_F32Cx16_FMA
  1232. #define GGML_F16_VEC_ADD GGML_F32Cx16_ADD
  1233. #define GGML_F16_VEC_MUL GGML_F32Cx16_MUL
  1234. #define GGML_F16_VEC_REDUCE GGML_F32Cx16_REDUCE
  1235. #elif defined(__AVX__)
  1236. #define GGML_SIMD
  1237. // F32 AVX
  1238. #define GGML_F32_STEP 32
  1239. #define GGML_F32_EPR 8
  1240. #define GGML_F32x8 __m256
  1241. #define GGML_F32x8_ZERO _mm256_setzero_ps()
  1242. #define GGML_F32x8_SET1(x) _mm256_set1_ps(x)
  1243. #define GGML_F32x8_LOAD _mm256_loadu_ps
  1244. #define GGML_F32x8_STORE _mm256_storeu_ps
  1245. #if defined(__FMA__)
  1246. #define GGML_F32x8_FMA(a, b, c) _mm256_fmadd_ps(b, c, a)
  1247. #else
  1248. #define GGML_F32x8_FMA(a, b, c) _mm256_add_ps(_mm256_mul_ps(b, c), a)
  1249. #endif
  1250. #define GGML_F32x8_ADD _mm256_add_ps
  1251. #define GGML_F32x8_MUL _mm256_mul_ps
  1252. #define GGML_F32x8_REDUCE(res, x) \
  1253. do { \
  1254. int offset = GGML_F32_ARR >> 1; \
  1255. for (int i = 0; i < offset; ++i) { \
  1256. x[i] = _mm256_add_ps(x[i], x[offset+i]); \
  1257. } \
  1258. offset >>= 1; \
  1259. for (int i = 0; i < offset; ++i) { \
  1260. x[i] = _mm256_add_ps(x[i], x[offset+i]); \
  1261. } \
  1262. offset >>= 1; \
  1263. for (int i = 0; i < offset; ++i) { \
  1264. x[i] = _mm256_add_ps(x[i], x[offset+i]); \
  1265. } \
  1266. const __m128 t0 = _mm_add_ps(_mm256_castps256_ps128(x[0]), \
  1267. _mm256_extractf128_ps(x[0], 1)); \
  1268. const __m128 t1 = _mm_hadd_ps(t0, t0); \
  1269. res = (ggml_float) _mm_cvtss_f32(_mm_hadd_ps(t1, t1)); \
  1270. } while (0)
  1271. // TODO: is this optimal ?
  1272. #define GGML_F32_VEC GGML_F32x8
  1273. #define GGML_F32_VEC_ZERO GGML_F32x8_ZERO
  1274. #define GGML_F32_VEC_SET1 GGML_F32x8_SET1
  1275. #define GGML_F32_VEC_LOAD GGML_F32x8_LOAD
  1276. #define GGML_F32_VEC_STORE GGML_F32x8_STORE
  1277. #define GGML_F32_VEC_FMA GGML_F32x8_FMA
  1278. #define GGML_F32_VEC_ADD GGML_F32x8_ADD
  1279. #define GGML_F32_VEC_MUL GGML_F32x8_MUL
  1280. #define GGML_F32_VEC_REDUCE GGML_F32x8_REDUCE
  1281. // F16 AVX
  1282. #define GGML_F16_STEP 32
  1283. #define GGML_F16_EPR 8
  1284. // F16 arithmetic is not supported by AVX, so we use F32 instead
  1285. #define GGML_F32Cx8 __m256
  1286. #define GGML_F32Cx8_ZERO _mm256_setzero_ps()
  1287. #define GGML_F32Cx8_SET1(x) _mm256_set1_ps(x)
  1288. #if defined(__F16C__)
  1289. // the _mm256_cvt intrinsics require F16C
  1290. #define GGML_F32Cx8_LOAD(x) _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *)(x)))
  1291. #define GGML_F32Cx8_STORE(x, y) _mm_storeu_si128((__m128i *)(x), _mm256_cvtps_ph(y, 0))
  1292. #else
  1293. static inline __m256 __avx_f32cx8_load(ggml_fp16_t *x) {
  1294. float tmp[8];
  1295. for (int i = 0; i < 8; i++) {
  1296. tmp[i] = GGML_FP16_TO_FP32(x[i]);
  1297. }
  1298. return _mm256_loadu_ps(tmp);
  1299. }
  1300. static inline void __avx_f32cx8_store(ggml_fp16_t *x, __m256 y) {
  1301. float arr[8];
  1302. _mm256_storeu_ps(arr, y);
  1303. for (int i = 0; i < 8; i++)
  1304. x[i] = GGML_FP32_TO_FP16(arr[i]);
  1305. }
  1306. #define GGML_F32Cx8_LOAD(x) __avx_f32cx8_load(x)
  1307. #define GGML_F32Cx8_STORE(x, y) __avx_f32cx8_store(x, y)
  1308. #endif
  1309. #define GGML_F32Cx8_FMA GGML_F32x8_FMA
  1310. #define GGML_F32Cx8_ADD _mm256_add_ps
  1311. #define GGML_F32Cx8_MUL _mm256_mul_ps
  1312. #define GGML_F32Cx8_REDUCE GGML_F32x8_REDUCE
  1313. #define GGML_F16_VEC GGML_F32Cx8
  1314. #define GGML_F16_VEC_ZERO GGML_F32Cx8_ZERO
  1315. #define GGML_F16_VEC_SET1 GGML_F32Cx8_SET1
  1316. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx8_LOAD(p)
  1317. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx8_STORE(p, r[i])
  1318. #define GGML_F16_VEC_FMA GGML_F32Cx8_FMA
  1319. #define GGML_F16_VEC_ADD GGML_F32Cx8_ADD
  1320. #define GGML_F16_VEC_MUL GGML_F32Cx8_MUL
  1321. #define GGML_F16_VEC_REDUCE GGML_F32Cx8_REDUCE
  1322. #elif defined(__POWER9_VECTOR__)
  1323. #define GGML_SIMD
  1324. // F32 POWER9
  1325. #define GGML_F32_STEP 32
  1326. #define GGML_F32_EPR 4
  1327. #define GGML_F32x4 vector float
  1328. #define GGML_F32x4_ZERO 0.0f
  1329. #define GGML_F32x4_SET1 vec_splats
  1330. #define GGML_F32x4_LOAD(p) vec_xl(0, p)
  1331. #define GGML_F32x4_STORE(p, r) vec_xst(r, 0, p)
  1332. #define GGML_F32x4_FMA(a, b, c) vec_madd(b, c, a)
  1333. #define GGML_F32x4_ADD vec_add
  1334. #define GGML_F32x4_MUL vec_mul
  1335. #define GGML_F32x4_REDUCE(res, x) \
  1336. { \
  1337. int offset = GGML_F32_ARR >> 1; \
  1338. for (int i = 0; i < offset; ++i) { \
  1339. x[i] = vec_add(x[i], x[offset+i]); \
  1340. } \
  1341. offset >>= 1; \
  1342. for (int i = 0; i < offset; ++i) { \
  1343. x[i] = vec_add(x[i], x[offset+i]); \
  1344. } \
  1345. offset >>= 1; \
  1346. for (int i = 0; i < offset; ++i) { \
  1347. x[i] = vec_add(x[i], x[offset+i]); \
  1348. } \
  1349. res = vec_extract(x[0], 0) + \
  1350. vec_extract(x[0], 1) + \
  1351. vec_extract(x[0], 2) + \
  1352. vec_extract(x[0], 3); \
  1353. }
  1354. #define GGML_F32_VEC GGML_F32x4
  1355. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1356. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1357. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1358. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1359. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1360. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1361. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1362. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1363. // F16 POWER9
  1364. #define GGML_F16_STEP GGML_F32_STEP
  1365. #define GGML_F16_EPR GGML_F32_EPR
  1366. #define GGML_F16_VEC GGML_F32x4
  1367. #define GGML_F16_VEC_ZERO GGML_F32x4_ZERO
  1368. #define GGML_F16_VEC_SET1 GGML_F32x4_SET1
  1369. #define GGML_F16_VEC_FMA GGML_F32x4_FMA
  1370. #define GGML_F16_VEC_ADD GGML_F32x4_ADD
  1371. #define GGML_F16_VEC_MUL GGML_F32x4_MUL
  1372. #define GGML_F16_VEC_REDUCE GGML_F32x4_REDUCE
  1373. // Use vec_xl, not vec_ld, in case the load address is not aligned.
  1374. #define GGML_F16_VEC_LOAD(p, i) (i & 0x1) ? \
  1375. vec_extract_fp32_from_shorth(vec_xl(0, p - GGML_F16_EPR)) : \
  1376. vec_extract_fp32_from_shortl(vec_xl(0, p))
  1377. #define GGML_ENDIAN_BYTE(i) ((unsigned char *)&(uint16_t){1})[i]
  1378. #define GGML_F16_VEC_STORE(p, r, i) \
  1379. if (i & 0x1) \
  1380. vec_xst(vec_pack_to_short_fp32(r[i - GGML_ENDIAN_BYTE(1)], \
  1381. r[i - GGML_ENDIAN_BYTE(0)]), \
  1382. 0, p - GGML_F16_EPR)
  1383. #elif defined(__wasm_simd128__)
  1384. #define GGML_SIMD
  1385. // F32 WASM
  1386. #define GGML_F32_STEP 16
  1387. #define GGML_F32_EPR 4
  1388. #define GGML_F32x4 v128_t
  1389. #define GGML_F32x4_ZERO wasm_f32x4_splat(0.0f)
  1390. #define GGML_F32x4_SET1(x) wasm_f32x4_splat(x)
  1391. #define GGML_F32x4_LOAD wasm_v128_load
  1392. #define GGML_F32x4_STORE wasm_v128_store
  1393. #define GGML_F32x4_FMA(a, b, c) wasm_f32x4_add(wasm_f32x4_mul(b, c), a)
  1394. #define GGML_F32x4_ADD wasm_f32x4_add
  1395. #define GGML_F32x4_MUL wasm_f32x4_mul
  1396. #define GGML_F32x4_REDUCE(res, x) \
  1397. { \
  1398. int offset = GGML_F32_ARR >> 1; \
  1399. for (int i = 0; i < offset; ++i) { \
  1400. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1401. } \
  1402. offset >>= 1; \
  1403. for (int i = 0; i < offset; ++i) { \
  1404. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1405. } \
  1406. offset >>= 1; \
  1407. for (int i = 0; i < offset; ++i) { \
  1408. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1409. } \
  1410. res = wasm_f32x4_extract_lane(x[0], 0) + \
  1411. wasm_f32x4_extract_lane(x[0], 1) + \
  1412. wasm_f32x4_extract_lane(x[0], 2) + \
  1413. wasm_f32x4_extract_lane(x[0], 3); \
  1414. }
  1415. #define GGML_F32_VEC GGML_F32x4
  1416. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1417. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1418. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1419. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1420. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1421. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1422. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1423. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1424. // F16 WASM
  1425. #define GGML_F16_STEP 16
  1426. #define GGML_F16_EPR 4
  1427. inline static v128_t __wasm_f16x4_load(const ggml_fp16_t * p) {
  1428. float tmp[4];
  1429. tmp[0] = GGML_FP16_TO_FP32(p[0]);
  1430. tmp[1] = GGML_FP16_TO_FP32(p[1]);
  1431. tmp[2] = GGML_FP16_TO_FP32(p[2]);
  1432. tmp[3] = GGML_FP16_TO_FP32(p[3]);
  1433. return wasm_v128_load(tmp);
  1434. }
  1435. inline static void __wasm_f16x4_store(ggml_fp16_t * p, v128_t x) {
  1436. float tmp[4];
  1437. wasm_v128_store(tmp, x);
  1438. p[0] = GGML_FP32_TO_FP16(tmp[0]);
  1439. p[1] = GGML_FP32_TO_FP16(tmp[1]);
  1440. p[2] = GGML_FP32_TO_FP16(tmp[2]);
  1441. p[3] = GGML_FP32_TO_FP16(tmp[3]);
  1442. }
  1443. #define GGML_F16x4 v128_t
  1444. #define GGML_F16x4_ZERO wasm_f32x4_splat(0.0f)
  1445. #define GGML_F16x4_SET1(x) wasm_f32x4_splat(x)
  1446. #define GGML_F16x4_LOAD(x) __wasm_f16x4_load(x)
  1447. #define GGML_F16x4_STORE(x, y) __wasm_f16x4_store(x, y)
  1448. #define GGML_F16x4_FMA GGML_F32x4_FMA
  1449. #define GGML_F16x4_ADD wasm_f32x4_add
  1450. #define GGML_F16x4_MUL wasm_f32x4_mul
  1451. #define GGML_F16x4_REDUCE(res, x) \
  1452. { \
  1453. int offset = GGML_F16_ARR >> 1; \
  1454. for (int i = 0; i < offset; ++i) { \
  1455. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1456. } \
  1457. offset >>= 1; \
  1458. for (int i = 0; i < offset; ++i) { \
  1459. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1460. } \
  1461. offset >>= 1; \
  1462. for (int i = 0; i < offset; ++i) { \
  1463. x[i] = wasm_f32x4_add(x[i], x[offset+i]); \
  1464. } \
  1465. res = wasm_f32x4_extract_lane(x[0], 0) + \
  1466. wasm_f32x4_extract_lane(x[0], 1) + \
  1467. wasm_f32x4_extract_lane(x[0], 2) + \
  1468. wasm_f32x4_extract_lane(x[0], 3); \
  1469. }
  1470. #define GGML_F16_VEC GGML_F16x4
  1471. #define GGML_F16_VEC_ZERO GGML_F16x4_ZERO
  1472. #define GGML_F16_VEC_SET1 GGML_F16x4_SET1
  1473. #define GGML_F16_VEC_LOAD(p, i) GGML_F16x4_LOAD(p)
  1474. #define GGML_F16_VEC_STORE(p, r, i) GGML_F16x4_STORE(p, r[i])
  1475. #define GGML_F16_VEC_FMA GGML_F16x4_FMA
  1476. #define GGML_F16_VEC_ADD GGML_F16x4_ADD
  1477. #define GGML_F16_VEC_MUL GGML_F16x4_MUL
  1478. #define GGML_F16_VEC_REDUCE GGML_F16x4_REDUCE
  1479. #elif defined(__SSE3__)
  1480. #define GGML_SIMD
  1481. // F32 SSE
  1482. #define GGML_F32_STEP 32
  1483. #define GGML_F32_EPR 4
  1484. #define GGML_F32x4 __m128
  1485. #define GGML_F32x4_ZERO _mm_setzero_ps()
  1486. #define GGML_F32x4_SET1(x) _mm_set1_ps(x)
  1487. #define GGML_F32x4_LOAD _mm_loadu_ps
  1488. #define GGML_F32x4_STORE _mm_storeu_ps
  1489. #if defined(__FMA__)
  1490. // TODO: Does this work?
  1491. #define GGML_F32x4_FMA(a, b, c) _mm_fmadd_ps(b, c, a)
  1492. #else
  1493. #define GGML_F32x4_FMA(a, b, c) _mm_add_ps(_mm_mul_ps(b, c), a)
  1494. #endif
  1495. #define GGML_F32x4_ADD _mm_add_ps
  1496. #define GGML_F32x4_MUL _mm_mul_ps
  1497. #define GGML_F32x4_REDUCE(res, x) \
  1498. { \
  1499. int offset = GGML_F32_ARR >> 1; \
  1500. for (int i = 0; i < offset; ++i) { \
  1501. x[i] = _mm_add_ps(x[i], x[offset+i]); \
  1502. } \
  1503. offset >>= 1; \
  1504. for (int i = 0; i < offset; ++i) { \
  1505. x[i] = _mm_add_ps(x[i], x[offset+i]); \
  1506. } \
  1507. offset >>= 1; \
  1508. for (int i = 0; i < offset; ++i) { \
  1509. x[i] = _mm_add_ps(x[i], x[offset+i]); \
  1510. } \
  1511. const __m128 t0 = _mm_hadd_ps(x[0], x[0]); \
  1512. res = (ggml_float) _mm_cvtss_f32(_mm_hadd_ps(t0, t0)); \
  1513. }
  1514. // TODO: is this optimal ?
  1515. #define GGML_F32_VEC GGML_F32x4
  1516. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1517. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1518. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1519. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1520. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1521. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1522. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1523. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1524. // F16 SSE
  1525. #define GGML_F16_STEP 32
  1526. #define GGML_F16_EPR 4
  1527. static inline __m128 __sse_f16x4_load(ggml_fp16_t *x) {
  1528. float tmp[4];
  1529. tmp[0] = GGML_FP16_TO_FP32(x[0]);
  1530. tmp[1] = GGML_FP16_TO_FP32(x[1]);
  1531. tmp[2] = GGML_FP16_TO_FP32(x[2]);
  1532. tmp[3] = GGML_FP16_TO_FP32(x[3]);
  1533. return _mm_loadu_ps(tmp);
  1534. }
  1535. static inline void __sse_f16x4_store(ggml_fp16_t *x, __m128 y) {
  1536. float arr[4];
  1537. _mm_storeu_ps(arr, y);
  1538. x[0] = GGML_FP32_TO_FP16(arr[0]);
  1539. x[1] = GGML_FP32_TO_FP16(arr[1]);
  1540. x[2] = GGML_FP32_TO_FP16(arr[2]);
  1541. x[3] = GGML_FP32_TO_FP16(arr[3]);
  1542. }
  1543. #define GGML_F32Cx4 __m128
  1544. #define GGML_F32Cx4_ZERO _mm_setzero_ps()
  1545. #define GGML_F32Cx4_SET1(x) _mm_set1_ps(x)
  1546. #define GGML_F32Cx4_LOAD(x) __sse_f16x4_load(x)
  1547. #define GGML_F32Cx4_STORE(x, y) __sse_f16x4_store(x, y)
  1548. #define GGML_F32Cx4_FMA GGML_F32x4_FMA
  1549. #define GGML_F32Cx4_ADD _mm_add_ps
  1550. #define GGML_F32Cx4_MUL _mm_mul_ps
  1551. #define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
  1552. #define GGML_F16_VEC GGML_F32Cx4
  1553. #define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
  1554. #define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
  1555. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
  1556. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE(p, r[i])
  1557. #define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
  1558. #define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
  1559. #define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
  1560. #define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
  1561. #elif defined(__loongarch_asx)
  1562. #define GGML_SIMD
  1563. // F32 LASX
  1564. #define GGML_F32_STEP 32
  1565. #define GGML_F32_EPR 8
  1566. #define GGML_F32x8 __m256
  1567. #define GGML_F32x8_ZERO (__m256)__lasx_xvldi(0)
  1568. #define GGML_F32x8_SET1(x) (__m256)__lasx_xvreplfr2vr_s((x))
  1569. #define GGML_F32x8_LOAD(x) (__m256)__lasx_xvld((x), 0)
  1570. #define GGML_F32x8_STORE(x,y) __lasx_xvst((y), (x), 0)
  1571. #define GGML_F32x8_FMA(a, b, c) __lasx_xvfmadd_s(b, c, a)
  1572. #define GGML_F32x8_ADD __lasx_xvfadd_s
  1573. #define GGML_F32x8_MUL __lasx_xvfmul_s
  1574. #define GGML_F32x8_REDUCE(res, x) \
  1575. do { \
  1576. int offset = GGML_F32_ARR >> 1; \
  1577. for (int i = 0; i < offset; ++i) { \
  1578. x[i] = __lasx_xvfadd_s(x[i], x[offset+i]); \
  1579. } \
  1580. offset >>= 1; \
  1581. for (int i = 0; i < offset; ++i) { \
  1582. x[i] = __lasx_xvfadd_s(x[i], x[offset+i]); \
  1583. } \
  1584. offset >>= 1; \
  1585. for (int i = 0; i < offset; ++i) { \
  1586. x[i] = __lasx_xvfadd_s(x[i], x[offset+i]); \
  1587. } \
  1588. float *tmp_p = (float *)&x[0]; \
  1589. 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]; \
  1590. } while (0)
  1591. // TODO: is this optimal ?
  1592. #define GGML_F32_VEC GGML_F32x8
  1593. #define GGML_F32_VEC_ZERO GGML_F32x8_ZERO
  1594. #define GGML_F32_VEC_SET1 GGML_F32x8_SET1
  1595. #define GGML_F32_VEC_LOAD GGML_F32x8_LOAD
  1596. #define GGML_F32_VEC_STORE GGML_F32x8_STORE
  1597. #define GGML_F32_VEC_FMA GGML_F32x8_FMA
  1598. #define GGML_F32_VEC_ADD GGML_F32x8_ADD
  1599. #define GGML_F32_VEC_MUL GGML_F32x8_MUL
  1600. #define GGML_F32_VEC_REDUCE GGML_F32x8_REDUCE
  1601. // F16 LASX
  1602. #define GGML_F16_STEP 32
  1603. #define GGML_F16_EPR 8
  1604. // F16 arithmetic is not supported by AVX, so we use F32 instead
  1605. #define GGML_F32Cx8 __m256
  1606. #define GGML_F32Cx8_ZERO (__m256)__lasx_xvldi(0)
  1607. #define GGML_F32Cx8_SET1(x) (__m256)__lasx_xvreplgr2vr_w((x))
  1608. static inline __m256 __lasx_f32cx8_load(const ggml_fp16_t * x) {
  1609. float tmp[8];
  1610. for (int i = 0; i < 8; i++) {
  1611. tmp[i] = GGML_FP16_TO_FP32(x[i]);
  1612. }
  1613. return (__m256)__lasx_xvld(tmp, 0);
  1614. }
  1615. static inline void __lasx_f32cx8_store(ggml_fp16_t * x, __m256 y) {
  1616. float arr[8];
  1617. __lasx_xvst(y, arr, 0);
  1618. for (int i = 0; i < 8; i++) {
  1619. x[i] = GGML_FP32_TO_FP16(arr[i]);
  1620. }
  1621. }
  1622. #define GGML_F32Cx8_LOAD(x) __lasx_f32cx8_load(x)
  1623. #define GGML_F32Cx8_STORE(x, y) __lasx_f32cx8_store(x, y)
  1624. #define GGML_F32Cx8_FMA GGML_F32x8_FMA
  1625. #define GGML_F32Cx8_ADD __lasx_xvfadd_s
  1626. #define GGML_F32Cx8_MUL __lasx_xvfmul_s
  1627. #define GGML_F32Cx8_REDUCE GGML_F32x8_REDUCE
  1628. #define GGML_F16_VEC GGML_F32Cx8
  1629. #define GGML_F16_VEC_ZERO GGML_F32Cx8_ZERO
  1630. #define GGML_F16_VEC_SET1 GGML_F32Cx8_SET1
  1631. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx8_LOAD(p)
  1632. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx8_STORE(p, r[i])
  1633. #define GGML_F16_VEC_FMA GGML_F32Cx8_FMA
  1634. #define GGML_F16_VEC_ADD GGML_F32Cx8_ADD
  1635. #define GGML_F16_VEC_MUL GGML_F32Cx8_MUL
  1636. #define GGML_F16_VEC_REDUCE GGML_F32Cx8_REDUCE
  1637. #elif defined(__loongarch_sx)
  1638. #define GGML_SIMD
  1639. // F32 LSX
  1640. #define GGML_F32_STEP 32
  1641. #define GGML_F32_EPR 4
  1642. #define GGML_F32x4 __m128
  1643. #define GGML_F32x4_ZERO __lsx_vldi(0)
  1644. #define GGML_F32x4_SET1(x) __lsx_vinsgr2vr_w(__lsx_vldi(0),(x), 0)
  1645. #define GGML_F32x4_LOAD(x) __lsx_vld((x), 0)
  1646. #define GGML_F32x4_STORE((x),(y)) __lsx_vst((y), (x), 0)
  1647. #define GGML_F32x4_FMA(a, b, c) __lsx_vfmadd_s(b, c, a)
  1648. #define GGML_F32x4_ADD __lsx_vfadd_s
  1649. #define GGML_F32x4_MUL __lsx_vfmul_s
  1650. #define GGML_F32x4_REDUCE(res, x) \
  1651. { \
  1652. int offset = GGML_F32_ARR >> 1; \
  1653. for (int i = 0; i < offset; ++i) { \
  1654. x[i] = __lsx_vfadd_s(x[i], x[offset+i]); \
  1655. } \
  1656. offset >>= 1; \
  1657. for (int i = 0; i < offset; ++i) { \
  1658. x[i] = __lsx_vfadd_s(x[i], x[offset+i]); \
  1659. } \
  1660. offset >>= 1; \
  1661. for (int i = 0; i < offset; ++i) { \
  1662. x[i] = __lsx_vfadd_s(x[i], x[offset+i]); \
  1663. } \
  1664. __m128i tmp = __lsx_vsrli_d((__m128i)x[0], 32); \
  1665. tmp = (__m128i)__lsx_vfadd_s((__m128)tmp, x[0]); \
  1666. tmp = __lsx_vpickev_w(__lsx_vldi(0), tmp); \
  1667. const __m128 t0 = __lsx_vshuf4i_w(tmp, 0x88); \
  1668. tmp = __lsx_vsrli_d((__m128i)t0, 32); \
  1669. tmp = (__m128i)__lsx_vfadd_s((__m128)tmp, t0); \
  1670. tmp = __lsx_vpickev_w(__lsx_vldi(0), tmp); \
  1671. res = (ggml_float) __lsx_vpickve2gr_w(__lsx_vshuf4i_w(tmp, 0x88), 0); \
  1672. }
  1673. #define GGML_F32_VEC GGML_F32x4
  1674. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  1675. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  1676. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  1677. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  1678. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  1679. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  1680. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  1681. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  1682. // F16 LSX
  1683. #define GGML_F16_STEP 32
  1684. #define GGML_F16_EPR 4
  1685. static inline __m128 __lsx_f16x4_load(const ggml_fp16_t * x) {
  1686. float tmp[4];
  1687. tmp[0] = GGML_FP16_TO_FP32(x[0]);
  1688. tmp[1] = GGML_FP16_TO_FP32(x[1]);
  1689. tmp[2] = GGML_FP16_TO_FP32(x[2]);
  1690. tmp[3] = GGML_FP16_TO_FP32(x[3]);
  1691. return __lsx_vld(tmp, 0);
  1692. }
  1693. static inline void __lsx_f16x4_store(ggml_fp16_t * x, __m128 y) {
  1694. float arr[4];
  1695. __lsx_vst(y, arr, 0);
  1696. x[0] = GGML_FP32_TO_FP16(arr[0]);
  1697. x[1] = GGML_FP32_TO_FP16(arr[1]);
  1698. x[2] = GGML_FP32_TO_FP16(arr[2]);
  1699. x[3] = GGML_FP32_TO_FP16(arr[3]);
  1700. }
  1701. #define GGML_F32Cx4 __m128
  1702. #define GGML_F32Cx4_ZERO __lsx_vldi(0)
  1703. #define GGML_F32Cx4_SET1(x) __lsx_vinsgr2vr_w(__lsx_vldi(0),(x), 0)
  1704. #define GGML_F32Cx4_LOAD(x) __lsx_f16x4_load(x)
  1705. #define GGML_F32Cx4_STORE(x, y) __lsx_f16x4_store(x, y)
  1706. #define GGML_F32Cx4_FMA GGML_F32x4_FMA
  1707. #define GGML_F32Cx4_ADD __lsx_vfadd_s
  1708. #define GGML_F32Cx4_MUL __lsx_vfmul_s
  1709. #define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
  1710. #define GGML_F16_VEC GGML_F32Cx4
  1711. #define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
  1712. #define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
  1713. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
  1714. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE(p, r[i])
  1715. #define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
  1716. #define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
  1717. #define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
  1718. #define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
  1719. #endif
  1720. // GGML_F32_ARR / GGML_F16_ARR
  1721. // number of registers to use per step
  1722. #ifdef GGML_SIMD
  1723. #define GGML_F32_ARR (GGML_F32_STEP/GGML_F32_EPR)
  1724. #define GGML_F16_ARR (GGML_F16_STEP/GGML_F16_EPR)
  1725. #endif
  1726. //
  1727. // ggml object
  1728. //
  1729. struct ggml_object {
  1730. size_t offs;
  1731. size_t size;
  1732. struct ggml_object * next;
  1733. enum ggml_object_type type;
  1734. char padding[4];
  1735. };
  1736. static const size_t GGML_OBJECT_SIZE = sizeof(struct ggml_object);
  1737. //
  1738. // ggml context
  1739. //
  1740. struct ggml_context {
  1741. size_t mem_size;
  1742. void* mem_buffer;
  1743. bool mem_buffer_owned;
  1744. bool no_alloc;
  1745. bool no_alloc_save; // this is used to save the no_alloc state when using scratch buffers
  1746. int n_objects;
  1747. struct ggml_object * objects_begin;
  1748. struct ggml_object * objects_end;
  1749. struct ggml_scratch scratch;
  1750. struct ggml_scratch scratch_save;
  1751. };
  1752. struct ggml_context_container {
  1753. bool used;
  1754. struct ggml_context context;
  1755. };
  1756. //
  1757. // Threading defs
  1758. //
  1759. typedef pthread_t ggml_thread_t;
  1760. #if defined(_WIN32)
  1761. typedef CONDITION_VARIABLE ggml_cond_t;
  1762. typedef SRWLOCK ggml_mutex_t;
  1763. #define ggml_mutex_init(m) InitializeSRWLock(m)
  1764. #define ggml_mutex_destroy(m)
  1765. #define ggml_mutex_lock(m) AcquireSRWLockExclusive(m)
  1766. #define ggml_mutex_unlock(m) ReleaseSRWLockExclusive(m)
  1767. #define ggml_mutex_lock_shared(m) AcquireSRWLockShared(m)
  1768. #define ggml_mutex_unlock_shared(m) ReleaseSRWLockShared(m)
  1769. #define ggml_cond_init(c) InitializeConditionVariable(c)
  1770. #define ggml_cond_destroy(c)
  1771. #define ggml_cond_wait(c, m) SleepConditionVariableSRW(c, m, INFINITE, CONDITION_VARIABLE_LOCKMODE_SHARED)
  1772. #define ggml_cond_broadcast(c) WakeAllConditionVariable(c)
  1773. #define ggml_thread_create pthread_create
  1774. #define ggml_thread_join pthread_join
  1775. #else
  1776. typedef pthread_cond_t ggml_cond_t;
  1777. typedef pthread_mutex_t ggml_mutex_t;
  1778. #define ggml_mutex_init(m) pthread_mutex_init(m, NULL)
  1779. #define ggml_mutex_destroy(m) pthread_mutex_destroy(m)
  1780. #define ggml_mutex_lock(m) pthread_mutex_lock(m)
  1781. #define ggml_mutex_unlock(m) pthread_mutex_unlock(m)
  1782. #define ggml_mutex_lock_shared(m) pthread_mutex_lock(m)
  1783. #define ggml_mutex_unlock_shared(m) pthread_mutex_unlock(m)
  1784. #define ggml_lock_init(x) UNUSED(x)
  1785. #define ggml_lock_destroy(x) UNUSED(x)
  1786. #if defined(__x86_64__) || (defined(_MSC_VER) && defined(_M_AMD64))
  1787. #define ggml_lock_lock(x) _mm_pause()
  1788. #else
  1789. #define ggml_lock_lock(x) UNUSED(x)
  1790. #endif
  1791. #define ggml_lock_unlock(x) UNUSED(x)
  1792. #define GGML_LOCK_INITIALIZER 0
  1793. #define ggml_cond_init(c) pthread_cond_init(c, NULL)
  1794. #define ggml_cond_destroy(c) pthread_cond_destroy(c)
  1795. #define ggml_cond_wait(c, m) pthread_cond_wait(c, m)
  1796. #define ggml_cond_broadcast(c) pthread_cond_broadcast(c)
  1797. #define ggml_thread_create pthread_create
  1798. #define ggml_thread_join pthread_join
  1799. #endif
  1800. // Threadpool def
  1801. struct ggml_threadpool {
  1802. ggml_mutex_t mutex; // mutex for cond.var
  1803. ggml_cond_t cond; // cond.var for waiting for new work
  1804. struct ggml_cgraph * cgraph;
  1805. struct ggml_cplan * cplan;
  1806. // synchronization primitives
  1807. atomic_int n_graph; // incremented when there is work to be done (i.e each graph)
  1808. atomic_int GGML_CACHE_ALIGN n_barrier;
  1809. atomic_int GGML_CACHE_ALIGN n_barrier_passed;
  1810. atomic_int current_chunk; // currently processing chunk during Mat_Mul, shared between all the threads.
  1811. // these are atomic as an annotation for thread-sanitizer
  1812. atomic_bool stop; // Used for stopping the threadpool altogether
  1813. atomic_bool pause; // Used for pausing the threadpool or individual threads
  1814. atomic_bool abort; // Used for aborting processing of a graph
  1815. struct ggml_compute_state * workers; // per thread state
  1816. int n_threads_max; // number of threads in the pool
  1817. atomic_int n_threads_cur; // number of threads used in the current graph
  1818. int32_t prio; // Scheduling priority
  1819. uint32_t poll; // Polling level (0 - no polling)
  1820. enum ggml_status ec;
  1821. };
  1822. // Per-thread state
  1823. struct ggml_compute_state {
  1824. #ifndef GGML_USE_OPENMP
  1825. ggml_thread_t thrd;
  1826. bool cpumask[GGML_MAX_N_THREADS];
  1827. int last_graph;
  1828. bool pending;
  1829. #endif
  1830. struct ggml_threadpool * threadpool;
  1831. int ith;
  1832. };
  1833. struct ggml_compute_params {
  1834. // ith = thread index, nth = number of threads
  1835. int ith, nth;
  1836. // work buffer for all threads
  1837. size_t wsize;
  1838. void * wdata;
  1839. struct ggml_threadpool * threadpool;
  1840. };
  1841. //
  1842. // fundamental operations
  1843. //
  1844. 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; }
  1845. 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; }
  1846. 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; }
  1847. 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; }
  1848. 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; }
  1849. 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]; }
  1850. 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; }
  1851. 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]; }
  1852. 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; }
  1853. 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]; }
  1854. 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; }
  1855. 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]; }
  1856. 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]; }
  1857. 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]; }
  1858. 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]; }
  1859. 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) {
  1860. assert(nrc == 1);
  1861. UNUSED(nrc);
  1862. UNUSED(bx);
  1863. UNUSED(by);
  1864. UNUSED(bs);
  1865. #if defined(GGML_SIMD)
  1866. float sumf = 0.0f;
  1867. const int np = (n & ~(GGML_F32_STEP - 1));
  1868. GGML_F32_VEC sum[GGML_F32_ARR] = { GGML_F32_VEC_ZERO };
  1869. GGML_F32_VEC ax[GGML_F32_ARR];
  1870. GGML_F32_VEC ay[GGML_F32_ARR];
  1871. for (int i = 0; i < np; i += GGML_F32_STEP) {
  1872. for (int j = 0; j < GGML_F32_ARR; j++) {
  1873. ax[j] = GGML_F32_VEC_LOAD(x + i + j*GGML_F32_EPR);
  1874. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  1875. sum[j] = GGML_F32_VEC_FMA(sum[j], ax[j], ay[j]);
  1876. }
  1877. }
  1878. // reduce sum0..sum3 to sum0
  1879. GGML_F32_VEC_REDUCE(sumf, sum);
  1880. // leftovers
  1881. for (int i = np; i < n; ++i) {
  1882. sumf += x[i]*y[i];
  1883. }
  1884. #else
  1885. // scalar
  1886. ggml_float sumf = 0.0;
  1887. for (int i = 0; i < n; ++i) {
  1888. sumf += (ggml_float)(x[i]*y[i]);
  1889. }
  1890. #endif
  1891. *s = sumf;
  1892. }
  1893. 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) {
  1894. assert(nrc == 1);
  1895. UNUSED(nrc);
  1896. UNUSED(bx);
  1897. UNUSED(by);
  1898. UNUSED(bs);
  1899. int i = 0;
  1900. ggml_float sumf = 0;
  1901. #if defined(__AVX512BF16__)
  1902. __m512 c1 = _mm512_setzero_ps();
  1903. __m512 c2 = _mm512_setzero_ps();
  1904. for (; i + 64 <= n; i += 64) {
  1905. c1 = _mm512_dpbf16_ps(c1, m512bh(_mm512_loadu_si512((x + i))),
  1906. m512bh(_mm512_loadu_si512((y + i))));
  1907. c2 = _mm512_dpbf16_ps(c2, m512bh(_mm512_loadu_si512((x + i + 32))),
  1908. m512bh(_mm512_loadu_si512((y + i + 32))));
  1909. }
  1910. sumf += (ggml_float)_mm512_reduce_add_ps(c1);
  1911. sumf += (ggml_float)_mm512_reduce_add_ps(c2);
  1912. #elif defined(__AVX512F__)
  1913. #define LOAD(p) _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(_mm256_loadu_si256((const __m256i *)(p))), 16))
  1914. __m512 c1 = _mm512_setzero_ps();
  1915. __m512 c2 = _mm512_setzero_ps();
  1916. for (; i + 32 <= n; i += 32) {
  1917. c1 = _mm512_add_ps(_mm512_mul_ps(LOAD(x + i), LOAD(y + i)), c1);
  1918. c2 = _mm512_add_ps(_mm512_mul_ps(LOAD(x + i + 16), LOAD(y + i + 16)), c2);
  1919. }
  1920. sumf += (ggml_float)_mm512_reduce_add_ps(c1);
  1921. sumf += (ggml_float)_mm512_reduce_add_ps(c2);
  1922. #undef LOAD
  1923. #elif defined(__AVX2__)
  1924. #define LOAD(p) _mm256_castsi256_ps(_mm256_slli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i *)(p))), 16))
  1925. __m256 c1 = _mm256_setzero_ps();
  1926. __m256 c2 = _mm256_setzero_ps();
  1927. __m256 c3 = _mm256_setzero_ps();
  1928. __m256 c4 = _mm256_setzero_ps();
  1929. for (; i + 32 <= n; i += 32) {
  1930. c1 = _mm256_add_ps(_mm256_mul_ps(LOAD(x + i), LOAD(y + i)), c1);
  1931. c2 = _mm256_add_ps(_mm256_mul_ps(LOAD(x + i + 8), LOAD(y + i + 8)), c2);
  1932. c3 = _mm256_add_ps(_mm256_mul_ps(LOAD(x + i + 16), LOAD(y + i + 16)), c3);
  1933. c4 = _mm256_add_ps(_mm256_mul_ps(LOAD(x + i + 24), LOAD(y + i + 24)), c4);
  1934. }
  1935. __m128 g;
  1936. c1 = _mm256_add_ps(_mm256_add_ps(c1, c3),
  1937. _mm256_add_ps(c2, c4));
  1938. g = _mm_add_ps(_mm256_extractf128_ps(c1, 1),
  1939. _mm256_castps256_ps128(c1));
  1940. g = _mm_add_ps(g, _mm_movehl_ps(g, g));
  1941. g = _mm_add_ss(g, _mm_movehdup_ps(g));
  1942. sumf += (ggml_float)_mm_cvtss_f32(g);
  1943. #undef LOAD
  1944. #endif
  1945. for (; i < n; ++i) {
  1946. sumf += (ggml_float)(GGML_BF16_TO_FP32(x[i]) *
  1947. GGML_BF16_TO_FP32(y[i]));
  1948. }
  1949. *s = sumf;
  1950. }
  1951. 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) {
  1952. assert(nrc == 1);
  1953. UNUSED(nrc);
  1954. UNUSED(bx);
  1955. UNUSED(by);
  1956. UNUSED(bs);
  1957. ggml_float sumf = 0.0;
  1958. #if defined(GGML_SIMD)
  1959. const int np = (n & ~(GGML_F16_STEP - 1));
  1960. GGML_F16_VEC sum[GGML_F16_ARR] = { GGML_F16_VEC_ZERO };
  1961. GGML_F16_VEC ax[GGML_F16_ARR];
  1962. GGML_F16_VEC ay[GGML_F16_ARR];
  1963. for (int i = 0; i < np; i += GGML_F16_STEP) {
  1964. for (int j = 0; j < GGML_F16_ARR; j++) {
  1965. ax[j] = GGML_F16_VEC_LOAD(x + i + j*GGML_F16_EPR, j);
  1966. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  1967. sum[j] = GGML_F16_VEC_FMA(sum[j], ax[j], ay[j]);
  1968. }
  1969. }
  1970. // reduce sum0..sum3 to sum0
  1971. GGML_F16_VEC_REDUCE(sumf, sum);
  1972. // leftovers
  1973. for (int i = np; i < n; ++i) {
  1974. sumf += (ggml_float)(GGML_FP16_TO_FP32(x[i])*GGML_FP16_TO_FP32(y[i]));
  1975. }
  1976. #else
  1977. for (int i = 0; i < n; ++i) {
  1978. sumf += (ggml_float)(GGML_FP16_TO_FP32(x[i])*GGML_FP16_TO_FP32(y[i]));
  1979. }
  1980. #endif
  1981. *s = sumf;
  1982. }
  1983. // compute GGML_VEC_DOT_UNROLL dot products at once
  1984. // xs - x row stride in bytes
  1985. 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) {
  1986. ggml_float sumf[GGML_VEC_DOT_UNROLL] = { 0.0 };
  1987. ggml_fp16_t * restrict x[GGML_VEC_DOT_UNROLL];
  1988. for (int i = 0; i < GGML_VEC_DOT_UNROLL; ++i) {
  1989. x[i] = (ggml_fp16_t *) ((char *) xv + i*xs);
  1990. }
  1991. #if defined(GGML_SIMD)
  1992. const int np = (n & ~(GGML_F16_STEP - 1));
  1993. GGML_F16_VEC sum[GGML_VEC_DOT_UNROLL][GGML_F16_ARR] = { { GGML_F16_VEC_ZERO } };
  1994. GGML_F16_VEC ax[GGML_F16_ARR];
  1995. GGML_F16_VEC ay[GGML_F16_ARR];
  1996. for (int i = 0; i < np; i += GGML_F16_STEP) {
  1997. for (int j = 0; j < GGML_F16_ARR; j++) {
  1998. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  1999. for (int k = 0; k < GGML_VEC_DOT_UNROLL; ++k) {
  2000. ax[j] = GGML_F16_VEC_LOAD(x[k] + i + j*GGML_F16_EPR, j);
  2001. sum[k][j] = GGML_F16_VEC_FMA(sum[k][j], ax[j], ay[j]);
  2002. }
  2003. }
  2004. }
  2005. // reduce sum0..sum3 to sum0
  2006. for (int k = 0; k < GGML_VEC_DOT_UNROLL; ++k) {
  2007. GGML_F16_VEC_REDUCE(sumf[k], sum[k]);
  2008. }
  2009. // leftovers
  2010. for (int i = np; i < n; ++i) {
  2011. for (int j = 0; j < GGML_VEC_DOT_UNROLL; ++j) {
  2012. sumf[j] += (ggml_float)(GGML_FP16_TO_FP32(x[j][i])*GGML_FP16_TO_FP32(y[i]));
  2013. }
  2014. }
  2015. #else
  2016. for (int i = 0; i < n; ++i) {
  2017. for (int j = 0; j < GGML_VEC_DOT_UNROLL; ++j) {
  2018. sumf[j] += (ggml_float)(GGML_FP16_TO_FP32(x[j][i])*GGML_FP16_TO_FP32(y[i]));
  2019. }
  2020. }
  2021. #endif
  2022. for (int i = 0; i < GGML_VEC_DOT_UNROLL; ++i) {
  2023. s[i] = sumf[i];
  2024. }
  2025. }
  2026. inline static void ggml_vec_mad_f32(const int n, float * restrict y, const float * restrict x, const float v) {
  2027. #if defined(GGML_SIMD)
  2028. const int np = (n & ~(GGML_F32_STEP - 1));
  2029. GGML_F32_VEC vx = GGML_F32_VEC_SET1(v);
  2030. GGML_F32_VEC ax[GGML_F32_ARR];
  2031. GGML_F32_VEC ay[GGML_F32_ARR];
  2032. for (int i = 0; i < np; i += GGML_F32_STEP) {
  2033. for (int j = 0; j < GGML_F32_ARR; j++) {
  2034. ax[j] = GGML_F32_VEC_LOAD(x + i + j*GGML_F32_EPR);
  2035. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  2036. ay[j] = GGML_F32_VEC_FMA(ay[j], ax[j], vx);
  2037. GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
  2038. }
  2039. }
  2040. // leftovers
  2041. for (int i = np; i < n; ++i) {
  2042. y[i] += x[i]*v;
  2043. }
  2044. #else
  2045. // scalar
  2046. for (int i = 0; i < n; ++i) {
  2047. y[i] += x[i]*v;
  2048. }
  2049. #endif
  2050. }
  2051. inline static void ggml_vec_mad_f16(const int n, ggml_fp16_t * restrict y, const ggml_fp16_t * restrict x, const float v) {
  2052. #if defined(GGML_SIMD)
  2053. const int np = (n & ~(GGML_F16_STEP - 1));
  2054. GGML_F16_VEC vx = GGML_F16_VEC_SET1(v);
  2055. GGML_F16_VEC ax[GGML_F16_ARR];
  2056. GGML_F16_VEC ay[GGML_F16_ARR];
  2057. for (int i = 0; i < np; i += GGML_F16_STEP) {
  2058. for (int j = 0; j < GGML_F16_ARR; j++) {
  2059. ax[j] = GGML_F16_VEC_LOAD(x + i + j*GGML_F16_EPR, j);
  2060. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  2061. ay[j] = GGML_F16_VEC_FMA(ay[j], ax[j], vx);
  2062. GGML_F16_VEC_STORE(y + i + j*GGML_F16_EPR, ay, j);
  2063. }
  2064. }
  2065. // leftovers
  2066. for (int i = np; i < n; ++i) {
  2067. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i]) + GGML_FP16_TO_FP32(x[i])*v);
  2068. }
  2069. #else
  2070. // scalar
  2071. for (int i = 0; i < n; ++i) {
  2072. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i]) + GGML_FP16_TO_FP32(x[i])*v);
  2073. }
  2074. #endif
  2075. }
  2076. // xs and vs are byte strides of x and v
  2077. 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) {
  2078. const float * restrict x[GGML_VEC_MAD_UNROLL];
  2079. const float * restrict v[GGML_VEC_MAD_UNROLL];
  2080. for (int i = 0; i < GGML_VEC_MAD_UNROLL; ++i) {
  2081. x[i] = (const float *) ((const char *) xv + i*xs);
  2082. v[i] = (const float *) ((const char *) vv + i*vs);
  2083. }
  2084. #if defined(GGML_SIMD)
  2085. const int np = (n & ~(GGML_F32_STEP - 1));
  2086. GGML_F32_VEC vx[GGML_VEC_MAD_UNROLL];
  2087. for (int k = 0; k < GGML_VEC_MAD_UNROLL; ++k) {
  2088. vx[k] = GGML_F32_VEC_SET1(v[k][0]);
  2089. }
  2090. GGML_F32_VEC ax[GGML_VEC_MAD_UNROLL][GGML_F32_ARR];
  2091. GGML_F32_VEC ay[GGML_F32_ARR];
  2092. for (int i = 0; i < np; i += GGML_F32_STEP) {
  2093. for (int j = 0; j < GGML_F32_ARR; j++) {
  2094. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  2095. for (int k = 0; k < GGML_VEC_MAD_UNROLL; ++k) {
  2096. ax[k][j] = GGML_F32_VEC_LOAD(x[k] + i + j*GGML_F32_EPR);
  2097. ay[j] = GGML_F32_VEC_FMA(ay[j], ax[k][j], vx[k]);
  2098. }
  2099. GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
  2100. }
  2101. }
  2102. // leftovers
  2103. for (int k = 0; k < GGML_VEC_MAD_UNROLL; ++k) {
  2104. for (int i = np; i < n; ++i) {
  2105. y[i] += x[k][i]*v[k][0];
  2106. }
  2107. }
  2108. #else
  2109. // scalar
  2110. for (int k = 0; k < GGML_VEC_MAD_UNROLL; ++k) {
  2111. for (int i = 0; i < n; ++i) {
  2112. y[i] += x[k][i]*v[k][0];
  2113. }
  2114. }
  2115. #endif
  2116. }
  2117. //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; }
  2118. inline static void ggml_vec_scale_f32(const int n, float * y, const float v) {
  2119. #if defined(GGML_USE_ACCELERATE)
  2120. vDSP_vsmul(y, 1, &v, y, 1, n);
  2121. #elif defined(GGML_SIMD)
  2122. const int np = (n & ~(GGML_F32_STEP - 1));
  2123. GGML_F32_VEC vx = GGML_F32_VEC_SET1(v);
  2124. GGML_F32_VEC ay[GGML_F32_ARR];
  2125. for (int i = 0; i < np; i += GGML_F32_STEP) {
  2126. for (int j = 0; j < GGML_F32_ARR; j++) {
  2127. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  2128. ay[j] = GGML_F32_VEC_MUL(ay[j], vx);
  2129. GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
  2130. }
  2131. }
  2132. // leftovers
  2133. for (int i = np; i < n; ++i) {
  2134. y[i] *= v;
  2135. }
  2136. #else
  2137. // scalar
  2138. for (int i = 0; i < n; ++i) {
  2139. y[i] *= v;
  2140. }
  2141. #endif
  2142. }
  2143. inline static void ggml_vec_scale_f16(const int n, ggml_fp16_t * y, const float v) {
  2144. #if defined(GGML_SIMD)
  2145. const int np = (n & ~(GGML_F16_STEP - 1));
  2146. GGML_F16_VEC vx = GGML_F16_VEC_SET1(v);
  2147. GGML_F16_VEC ay[GGML_F16_ARR];
  2148. for (int i = 0; i < np; i += GGML_F16_STEP) {
  2149. for (int j = 0; j < GGML_F16_ARR; j++) {
  2150. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  2151. ay[j] = GGML_F16_VEC_MUL(ay[j], vx);
  2152. GGML_F16_VEC_STORE(y + i + j*GGML_F16_EPR, ay, j);
  2153. }
  2154. }
  2155. // leftovers
  2156. for (int i = np; i < n; ++i) {
  2157. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i])*v);
  2158. }
  2159. #else
  2160. // scalar
  2161. for (int i = 0; i < n; ++i) {
  2162. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i])*v);
  2163. }
  2164. #endif
  2165. }
  2166. 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); }
  2167. 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]; }
  2168. 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]); }
  2169. 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]); }
  2170. 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]); }
  2171. 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]); }
  2172. 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]); }
  2173. 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); }
  2174. 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; }
  2175. 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]); }
  2176. 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]); }
  2177. 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; }
  2178. 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); }
  2179. 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])); }
  2180. // TODO: optimize performance
  2181. 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)); }
  2182. 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)); }
  2183. 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]); }
  2184. static const float GELU_COEF_A = 0.044715f;
  2185. static const float GELU_QUICK_COEF = -1.702f;
  2186. static const float SQRT_2_OVER_PI = 0.79788456080286535587989211986876f;
  2187. inline static float ggml_gelu_f32(float x) {
  2188. return 0.5f*x*(1.0f + tanhf(SQRT_2_OVER_PI*x*(1.0f + GELU_COEF_A*x*x)));
  2189. }
  2190. inline static void ggml_vec_gelu_f16(const int n, ggml_fp16_t * y, const ggml_fp16_t * x) {
  2191. const uint16_t * i16 = (const uint16_t *) x;
  2192. for (int i = 0; i < n; ++i) {
  2193. y[i] = ggml_table_gelu_f16[i16[i]];
  2194. }
  2195. }
  2196. #ifdef GGML_GELU_FP16
  2197. inline static void ggml_vec_gelu_f32(const int n, float * y, const float * x) {
  2198. uint16_t t;
  2199. for (int i = 0; i < n; ++i) {
  2200. if (x[i] <= -10.0f) {
  2201. y[i] = 0.0f;
  2202. } else if (x[i] >= 10.0f) {
  2203. y[i] = x[i];
  2204. } else {
  2205. ggml_fp16_t fp16 = GGML_FP32_TO_FP16(x[i]);
  2206. memcpy(&t, &fp16, sizeof(uint16_t));
  2207. y[i] = GGML_FP16_TO_FP32(ggml_table_gelu_f16[t]);
  2208. }
  2209. }
  2210. }
  2211. #else
  2212. inline static void ggml_vec_gelu_f32(const int n, float * y, const float * x) {
  2213. for (int i = 0; i < n; ++i) {
  2214. y[i] = ggml_gelu_f32(x[i]);
  2215. }
  2216. }
  2217. #endif
  2218. inline static float ggml_gelu_quick_f32(float x) {
  2219. return x*(1.0f/(1.0f+expf(GELU_QUICK_COEF*x)));
  2220. }
  2221. //inline static void ggml_vec_gelu_quick_f16(const int n, ggml_fp16_t * y, const ggml_fp16_t * x) {
  2222. // const uint16_t * i16 = (const uint16_t *) x;
  2223. // for (int i = 0; i < n; ++i) {
  2224. // y[i] = ggml_table_gelu_quick_f16[i16[i]];
  2225. // }
  2226. //}
  2227. #ifdef GGML_GELU_QUICK_FP16
  2228. inline static void ggml_vec_gelu_quick_f32(const int n, float * y, const float * x) {
  2229. uint16_t t;
  2230. for (int i = 0; i < n; ++i) {
  2231. ggml_fp16_t fp16 = GGML_FP32_TO_FP16(x[i]);
  2232. memcpy(&t, &fp16, sizeof(uint16_t));
  2233. y[i] = GGML_FP16_TO_FP32(ggml_table_gelu_quick_f16[t]);
  2234. }
  2235. }
  2236. #else
  2237. inline static void ggml_vec_gelu_quick_f32(const int n, float * y, const float * x) {
  2238. for (int i = 0; i < n; ++i) {
  2239. y[i] = ggml_gelu_quick_f32(x[i]);
  2240. }
  2241. }
  2242. #endif
  2243. // Sigmoid Linear Unit (SiLU) function
  2244. inline static float ggml_silu_f32(float x) {
  2245. return x/(1.0f + expf(-x));
  2246. }
  2247. #if __FINITE_MATH_ONLY__
  2248. #error "some routines in ggml.c require non-finite math arithmetics -- pass -fno-finite-math-only to the compiler to fix"
  2249. #error "ref: https://github.com/ggerganov/llama.cpp/pull/7154#issuecomment-2143844461"
  2250. #endif
  2251. #if defined(__ARM_NEON) && defined(__aarch64__)
  2252. // adapted from arm limited optimized routine
  2253. // the maximum error is 1.45358 plus 0.5 ulps
  2254. // numbers above 88.38 will flush to infinity
  2255. // numbers beneath -103.97 will flush to zero
  2256. inline static float32x4_t ggml_v_expf(float32x4_t x) {
  2257. const float32x4_t r = vdupq_n_f32(0x1.8p23f);
  2258. const float32x4_t z = vfmaq_f32(r, x, vdupq_n_f32(0x1.715476p+0f));
  2259. const float32x4_t n = vsubq_f32(z, r);
  2260. const float32x4_t b = vfmsq_f32(vfmsq_f32(x, n, vdupq_n_f32(0x1.62e4p-1f)), n,
  2261. vdupq_n_f32(0x1.7f7d1cp-20f));
  2262. const uint32x4_t e = vshlq_n_u32(vreinterpretq_u32_f32(z), 23);
  2263. const float32x4_t k = vreinterpretq_f32_u32(vaddq_u32(e, vreinterpretq_u32_f32(vdupq_n_f32(1))));
  2264. const uint32x4_t c = vcagtq_f32(n, vdupq_n_f32(126));
  2265. const float32x4_t u = vmulq_f32(b, b);
  2266. const float32x4_t j = vfmaq_f32(
  2267. vmulq_f32(vdupq_n_f32(0x1.ffffecp-1f), b),
  2268. vfmaq_f32(vfmaq_f32(vdupq_n_f32(0x1.fffdb6p-2f), vdupq_n_f32(0x1.555e66p-3f), b),
  2269. vfmaq_f32(vdupq_n_f32(0x1.573e2ep-5f), vdupq_n_f32(0x1.0e4020p-7f), b), u), u);
  2270. if (!vpaddd_u64(vreinterpretq_u64_u32(c)))
  2271. return vfmaq_f32(k, j, k);
  2272. const uint32x4_t d = vandq_u32(vclezq_f32(n), vdupq_n_u32(0x82000000));
  2273. const float32x4_t s1 = vreinterpretq_f32_u32(vaddq_u32(d, vdupq_n_u32(0x7f000000)));
  2274. const float32x4_t s2 = vreinterpretq_f32_u32(vsubq_u32(e, d));
  2275. return vbslq_f32(vcagtq_f32(n, vdupq_n_f32(192)), vmulq_f32(s1, s1),
  2276. vbslq_f32(c, vmulq_f32(vfmaq_f32(s2, s2, j), s1), vfmaq_f32(k, k, j)));
  2277. }
  2278. // computes silu x/(1+exp(-x)) in single precision vector
  2279. inline static float32x4_t ggml_v_silu(float32x4_t x) {
  2280. const float32x4_t one = vdupq_n_f32(1.0f);
  2281. const float32x4_t zero = vdupq_n_f32(0.0f);
  2282. const float32x4_t neg_x = vsubq_f32(zero, x);
  2283. const float32x4_t exp_neg_x = ggml_v_expf(neg_x);
  2284. const float32x4_t one_plus_exp_neg_x = vaddq_f32(one, exp_neg_x);
  2285. return vdivq_f32(x, one_plus_exp_neg_x);
  2286. }
  2287. #elif defined(__AVX512F__) && defined(__AVX512DQ__)
  2288. // adapted from arm limited optimized routine
  2289. // the maximum error is 1.45358 plus 0.5 ulps
  2290. // numbers above 88.38 will flush to infinity
  2291. // numbers beneath -103.97 will flush to zero
  2292. inline static __m512 ggml_v_expf(__m512 x) {
  2293. const __m512 r = _mm512_set1_ps(0x1.8p23f);
  2294. const __m512 z = _mm512_fmadd_ps(x, _mm512_set1_ps(0x1.715476p+0f), r);
  2295. const __m512 n = _mm512_sub_ps(z, r);
  2296. const __m512 b =
  2297. _mm512_fnmadd_ps(n, _mm512_set1_ps(0x1.7f7d1cp-20f),
  2298. _mm512_fnmadd_ps(n, _mm512_set1_ps(0x1.62e4p-1f), x));
  2299. const __mmask16 d =
  2300. _mm512_cmp_ps_mask(_mm512_abs_ps(n), _mm512_set1_ps(192), _CMP_GT_OQ);
  2301. const __m512 u = _mm512_mul_ps(b, b);
  2302. const __m512 j = _mm512_fmadd_ps(
  2303. _mm512_fmadd_ps(_mm512_fmadd_ps(_mm512_set1_ps(0x1.0e4020p-7f), b,
  2304. _mm512_set1_ps(0x1.573e2ep-5f)),
  2305. u,
  2306. _mm512_fmadd_ps(_mm512_set1_ps(0x1.555e66p-3f), b,
  2307. _mm512_set1_ps(0x1.fffdb6p-2f))),
  2308. u,
  2309. _mm512_fmadd_ps(_mm512_set1_ps(0x1.ffffecp-1f), b, _mm512_set1_ps(1.0F)));
  2310. const __m512 res = _mm512_scalef_ps(j, n);
  2311. if (_mm512_kortestz(d, d))
  2312. return res;
  2313. const __m512 zero = _mm512_setzero_ps();
  2314. const __m512 alt = _mm512_mask_blend_ps(
  2315. _mm512_cmp_ps_mask(n, zero, _CMP_LE_OQ), _mm512_set1_ps(INFINITY), zero);
  2316. return _mm512_mask_blend_ps(d, res, alt);
  2317. }
  2318. // computes silu x/(1+exp(-x)) in single precision vector
  2319. inline static __m512 ggml_v_silu(__m512 x) {
  2320. const __m512 one = _mm512_set1_ps(1);
  2321. const __m512 zero = _mm512_setzero_ps();
  2322. const __m512 neg_x = _mm512_sub_ps(zero, x);
  2323. const __m512 exp_neg_x = ggml_v_expf(neg_x);
  2324. const __m512 one_plus_exp_neg_x = _mm512_add_ps(one, exp_neg_x);
  2325. return _mm512_div_ps(x, one_plus_exp_neg_x);
  2326. }
  2327. #elif defined(__AVX2__) && defined(__FMA__)
  2328. // adapted from arm limited optimized routine
  2329. // the maximum error is 1.45358 plus 0.5 ulps
  2330. // numbers above 88.38 will flush to infinity
  2331. // numbers beneath -103.97 will flush to zero
  2332. inline static __m256 ggml_v_expf(__m256 x) {
  2333. const __m256 r = _mm256_set1_ps(0x1.8p23f);
  2334. const __m256 z = _mm256_fmadd_ps(x, _mm256_set1_ps(0x1.715476p+0f), r);
  2335. const __m256 n = _mm256_sub_ps(z, r);
  2336. const __m256 b = _mm256_fnmadd_ps(n, _mm256_set1_ps(0x1.7f7d1cp-20f),
  2337. _mm256_fnmadd_ps(n, _mm256_set1_ps(0x1.62e4p-1f), x));
  2338. const __m256i e = _mm256_slli_epi32(_mm256_castps_si256(z), 23);
  2339. const __m256 k = _mm256_castsi256_ps(
  2340. _mm256_add_epi32(e, _mm256_castps_si256(_mm256_set1_ps(1))));
  2341. const __m256i c = _mm256_castps_si256(
  2342. _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.f), n),
  2343. _mm256_set1_ps(126), _CMP_GT_OQ));
  2344. const __m256 u = _mm256_mul_ps(b, b);
  2345. const __m256 j = _mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_set1_ps(0x1.0e4020p-7f), b,
  2346. _mm256_set1_ps(0x1.573e2ep-5f)), u,
  2347. _mm256_fmadd_ps(_mm256_set1_ps(0x1.555e66p-3f), b,
  2348. _mm256_set1_ps(0x1.fffdb6p-2f))),
  2349. u, _mm256_mul_ps(_mm256_set1_ps(0x1.ffffecp-1f), b));
  2350. if (!_mm256_movemask_ps(_mm256_castsi256_ps(c)))
  2351. return _mm256_fmadd_ps(j, k, k);
  2352. const __m256i g = _mm256_and_si256(
  2353. _mm256_castps_si256(_mm256_cmp_ps(n, _mm256_setzero_ps(), _CMP_LE_OQ)),
  2354. _mm256_set1_epi32(0x82000000u));
  2355. const __m256 s1 =
  2356. _mm256_castsi256_ps(_mm256_add_epi32(g, _mm256_set1_epi32(0x7f000000u)));
  2357. const __m256 s2 = _mm256_castsi256_ps(_mm256_sub_epi32(e, g));
  2358. const __m256i d = _mm256_castps_si256(
  2359. _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.f), n),
  2360. _mm256_set1_ps(192), _CMP_GT_OQ));
  2361. return _mm256_or_ps(
  2362. _mm256_and_ps(_mm256_castsi256_ps(d), _mm256_mul_ps(s1, s1)),
  2363. _mm256_andnot_ps(
  2364. _mm256_castsi256_ps(d),
  2365. _mm256_or_ps(
  2366. _mm256_and_ps(_mm256_castsi256_ps(c),
  2367. _mm256_mul_ps(_mm256_fmadd_ps(s2, j, s2), s1)),
  2368. _mm256_andnot_ps(_mm256_castsi256_ps(c), _mm256_fmadd_ps(k, j, k)))));
  2369. }
  2370. // computes silu x/(1+exp(-x)) in single precision vector
  2371. inline static __m256 ggml_v_silu(__m256 x) {
  2372. const __m256 one = _mm256_set1_ps(1);
  2373. const __m256 zero = _mm256_setzero_ps();
  2374. const __m256 neg_x = _mm256_sub_ps(zero, x);
  2375. const __m256 exp_neg_x = ggml_v_expf(neg_x);
  2376. const __m256 one_plus_exp_neg_x = _mm256_add_ps(one, exp_neg_x);
  2377. return _mm256_div_ps(x, one_plus_exp_neg_x);
  2378. }
  2379. #elif defined(__SSE2__) // __AVX2__ / __ARM_NEON
  2380. #if defined(__FMA__)
  2381. #define MADD128(x, y, z) _mm_fmadd_ps(x, y, z)
  2382. #define NMADD128(x, y, z) _mm_fnmadd_ps(x, y, z)
  2383. #else
  2384. #define MADD128(x, y, z) _mm_add_ps(_mm_mul_ps(x, y), z)
  2385. #define NMADD128(x, y, z) _mm_sub_ps(z, _mm_mul_ps(x, y))
  2386. #endif
  2387. // adapted from arm limited optimized routine
  2388. // the maximum error is 1.45358 plus 0.5 ulps
  2389. // numbers above 88.38 will flush to infinity
  2390. // numbers beneath -103.97 will flush to zero
  2391. inline static __m128 ggml_v_expf(__m128 x) {
  2392. const __m128 r = _mm_set1_ps(0x1.8p23f);
  2393. const __m128 z = MADD128(x, _mm_set1_ps(0x1.715476p+0f), r);
  2394. const __m128 n = _mm_sub_ps(z, r);
  2395. const __m128 b =
  2396. NMADD128(n, _mm_set1_ps(0x1.7f7d1cp-20f), NMADD128(n, _mm_set1_ps(0x1.62e4p-1f), x));
  2397. const __m128i e = _mm_slli_epi32(_mm_castps_si128(z), 23);
  2398. const __m128 k = _mm_castsi128_ps(_mm_add_epi32(e, _mm_castps_si128(_mm_set1_ps(1))));
  2399. const __m128i c =
  2400. _mm_castps_si128(_mm_cmpgt_ps(_mm_andnot_ps(_mm_set1_ps(-0.f), n), _mm_set1_ps(126)));
  2401. const __m128 u = _mm_mul_ps(b, b);
  2402. const __m128 j =
  2403. MADD128(MADD128(MADD128(_mm_set1_ps(0x1.0e4020p-7f), b, _mm_set1_ps(0x1.573e2ep-5f)), u,
  2404. MADD128(_mm_set1_ps(0x1.555e66p-3f), b, _mm_set1_ps(0x1.fffdb6p-2f))),
  2405. u, _mm_mul_ps(_mm_set1_ps(0x1.ffffecp-1f), b));
  2406. if (!_mm_movemask_epi8(c))
  2407. return MADD128(j, k, k);
  2408. const __m128i g = _mm_and_si128(_mm_castps_si128(_mm_cmple_ps(n, _mm_setzero_ps())),
  2409. _mm_set1_epi32(0x82000000u));
  2410. const __m128 s1 = _mm_castsi128_ps(_mm_add_epi32(g, _mm_set1_epi32(0x7f000000u)));
  2411. const __m128 s2 = _mm_castsi128_ps(_mm_sub_epi32(e, g));
  2412. const __m128i d =
  2413. _mm_castps_si128(_mm_cmpgt_ps(_mm_andnot_ps(_mm_set1_ps(-0.f), n), _mm_set1_ps(192)));
  2414. return _mm_or_ps(
  2415. _mm_and_ps(_mm_castsi128_ps(d), _mm_mul_ps(s1, s1)),
  2416. _mm_andnot_ps(_mm_castsi128_ps(d),
  2417. _mm_or_ps(_mm_and_ps(_mm_castsi128_ps(c), _mm_mul_ps(MADD128(s2, j, s2), s1)),
  2418. _mm_andnot_ps(_mm_castsi128_ps(c), MADD128(k, j, k)))));
  2419. }
  2420. // computes silu x/(1+exp(-x)) in single precision vector
  2421. inline static __m128 ggml_v_silu(__m128 x) {
  2422. const __m128 one = _mm_set1_ps(1);
  2423. const __m128 zero = _mm_setzero_ps();
  2424. const __m128 neg_x = _mm_sub_ps(zero, x);
  2425. const __m128 exp_neg_x = ggml_v_expf(neg_x);
  2426. const __m128 one_plus_exp_neg_x = _mm_add_ps(one, exp_neg_x);
  2427. return _mm_div_ps(x, one_plus_exp_neg_x);
  2428. }
  2429. #endif // __ARM_NEON / __AVX2__ / __SSE2__
  2430. static void ggml_vec_silu_f32(const int n, float * y, const float * x) {
  2431. int i = 0;
  2432. #if defined(__AVX512F__) && defined(__AVX512DQ__)
  2433. for (; i + 15 < n; i += 16) {
  2434. _mm512_storeu_ps(y + i, ggml_v_silu(_mm512_loadu_ps(x + i)));
  2435. }
  2436. #elif defined(__AVX2__) && defined(__FMA__)
  2437. for (; i + 7 < n; i += 8) {
  2438. _mm256_storeu_ps(y + i, ggml_v_silu(_mm256_loadu_ps(x + i)));
  2439. }
  2440. #elif defined(__SSE2__)
  2441. for (; i + 3 < n; i += 4) {
  2442. _mm_storeu_ps(y + i, ggml_v_silu(_mm_loadu_ps(x + i)));
  2443. }
  2444. #elif defined(__ARM_NEON) && defined(__aarch64__)
  2445. for (; i + 3 < n; i += 4) {
  2446. vst1q_f32(y + i, ggml_v_silu(vld1q_f32(x + i)));
  2447. }
  2448. #endif
  2449. for (; i < n; ++i) {
  2450. y[i] = ggml_silu_f32(x[i]);
  2451. }
  2452. }
  2453. static ggml_float ggml_vec_soft_max_f32(const int n, float * y, const float * x, float max) {
  2454. int i = 0;
  2455. ggml_float sum = 0;
  2456. #if defined(__AVX512F__) && defined(__AVX512DQ__)
  2457. for (; i + 15 < n; i += 16) {
  2458. __m512 val = ggml_v_expf(_mm512_sub_ps(_mm512_loadu_ps(x + i),
  2459. _mm512_set1_ps(max)));
  2460. _mm512_storeu_ps(y + i, val);
  2461. sum += (ggml_float)_mm512_reduce_add_ps(val);
  2462. }
  2463. #elif defined(__AVX2__) && defined(__FMA__)
  2464. for (; i + 7 < n; i += 8) {
  2465. __m256 val = ggml_v_expf(_mm256_sub_ps(_mm256_loadu_ps(x + i),
  2466. _mm256_set1_ps(max)));
  2467. _mm256_storeu_ps(y + i, val);
  2468. __m128 val2 = _mm_add_ps(_mm256_extractf128_ps(val, 1),
  2469. _mm256_castps256_ps128(val));
  2470. val2 = _mm_add_ps(val2, _mm_movehl_ps(val2, val2));
  2471. val2 = _mm_add_ss(val2, _mm_movehdup_ps(val2));
  2472. sum += (ggml_float)_mm_cvtss_f32(val2);
  2473. }
  2474. #elif defined(__SSE2__)
  2475. for (; i + 3 < n; i += 4) {
  2476. __m128 val = ggml_v_expf(_mm_sub_ps(_mm_loadu_ps(x + i),
  2477. _mm_set1_ps(max)));
  2478. _mm_storeu_ps(y + i, val);
  2479. #if defined(__AVX__) || defined(__AVX2__) || defined(__AVX512F__)
  2480. val = _mm_add_ps(val, _mm_movehl_ps(val, val));
  2481. val = _mm_add_ss(val, _mm_movehdup_ps(val));
  2482. #else
  2483. __m128 tmp = _mm_shuffle_ps(val, val, _MM_SHUFFLE(2, 3, 0, 1));
  2484. val = _mm_add_ps(val, tmp);
  2485. tmp = _mm_movehl_ps(tmp, val);
  2486. val = _mm_add_ss(val, tmp);
  2487. #endif
  2488. sum += (ggml_float)_mm_cvtss_f32(val);
  2489. }
  2490. #elif defined(__ARM_NEON) && defined(__aarch64__)
  2491. for (; i + 3 < n; i += 4) {
  2492. float32x4_t val = ggml_v_expf(vsubq_f32(vld1q_f32(x + i),
  2493. vdupq_n_f32(max)));
  2494. vst1q_f32(y + i, val);
  2495. sum += (ggml_float)vaddvq_f32(val);
  2496. }
  2497. #endif
  2498. for (; i < n; ++i) {
  2499. float val = expf(x[i] - max);
  2500. sum += (ggml_float)val;
  2501. y[i] = val;
  2502. }
  2503. return sum;
  2504. }
  2505. static ggml_float ggml_vec_log_soft_max_f32(const int n, float * y, const float * x, float max) {
  2506. // 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)
  2507. int i = 0;
  2508. ggml_float sum = 0;
  2509. for (; i < n; ++i) {
  2510. float val = x[i] - max;
  2511. y[i] = val;
  2512. sum += (ggml_float)expf(val);
  2513. }
  2514. return sum = (ggml_float)logf(sum);
  2515. }
  2516. inline static float ggml_silu_backward_f32(float x, float dy) {
  2517. const float s = 1.0f/(1.0f + expf(-x));
  2518. return dy*s*(1.0f + x*(1.0f - s));
  2519. }
  2520. inline static void ggml_vec_silu_backward_f32(const int n, float * dx, const float * x, const float * dy) {
  2521. for (int i = 0; i < n; ++i) {
  2522. dx[i] = ggml_silu_backward_f32(x[i], dy[i]);
  2523. }
  2524. }
  2525. inline static void ggml_vec_sum_f32(const int n, float * s, const float * x) {
  2526. #ifndef GGML_USE_ACCELERATE
  2527. ggml_float sum = 0.0;
  2528. for (int i = 0; i < n; ++i) {
  2529. sum += (ggml_float)x[i];
  2530. }
  2531. *s = sum;
  2532. #else
  2533. vDSP_sve(x, 1, s, n);
  2534. #endif
  2535. }
  2536. inline static void ggml_vec_sum_f32_ggf(const int n, ggml_float * s, const float * x) {
  2537. ggml_float sum = 0.0;
  2538. for (int i = 0; i < n; ++i) {
  2539. sum += (ggml_float)x[i];
  2540. }
  2541. *s = sum;
  2542. }
  2543. inline static void ggml_vec_sum_f16_ggf(const int n, float * s, const ggml_fp16_t * x) {
  2544. float sum = 0.0f;
  2545. for (int i = 0; i < n; ++i) {
  2546. sum += GGML_FP16_TO_FP32(x[i]);
  2547. }
  2548. *s = sum;
  2549. }
  2550. inline static void ggml_vec_sum_bf16_ggf(const int n, float * s, const ggml_bf16_t * x) {
  2551. float sum = 0.0f;
  2552. for (int i = 0; i < n; ++i) {
  2553. sum += GGML_BF16_TO_FP32(x[i]);
  2554. }
  2555. *s = sum;
  2556. }
  2557. inline static void ggml_vec_max_f32(const int n, float * s, const float * x) {
  2558. #ifndef GGML_USE_ACCELERATE
  2559. float max = -INFINITY;
  2560. for (int i = 0; i < n; ++i) {
  2561. max = MAX(max, x[i]);
  2562. }
  2563. *s = max;
  2564. #else
  2565. vDSP_maxv(x, 1, s, n);
  2566. #endif
  2567. }
  2568. inline static void ggml_vec_norm_inv_f32(const int n, float * s, const float * x) {
  2569. ggml_vec_norm_f32(n, s, x);
  2570. *s = 1.f/(*s);
  2571. }
  2572. inline static void ggml_vec_argmax_f32(const int n, int * s, const float * x) {
  2573. float max = -INFINITY;
  2574. int idx = 0;
  2575. for (int i = 0; i < n; ++i) {
  2576. max = MAX(max, x[i]);
  2577. if (max == x[i]) { idx = i; }
  2578. }
  2579. *s = idx;
  2580. }
  2581. //
  2582. // data types
  2583. //
  2584. static const char * GGML_OP_NAME[GGML_OP_COUNT] = {
  2585. "NONE",
  2586. "DUP",
  2587. "ADD",
  2588. "ADD1",
  2589. "ACC",
  2590. "SUB",
  2591. "MUL",
  2592. "DIV",
  2593. "SQR",
  2594. "SQRT",
  2595. "LOG",
  2596. "SIN",
  2597. "COS",
  2598. "SUM",
  2599. "SUM_ROWS",
  2600. "MEAN",
  2601. "ARGMAX",
  2602. "REPEAT",
  2603. "REPEAT_BACK",
  2604. "CONCAT",
  2605. "SILU_BACK",
  2606. "NORM",
  2607. "RMS_NORM",
  2608. "RMS_NORM_BACK",
  2609. "GROUP_NORM",
  2610. "MUL_MAT",
  2611. "MUL_MAT_ID",
  2612. "OUT_PROD",
  2613. "SCALE",
  2614. "SET",
  2615. "CPY",
  2616. "CONT",
  2617. "RESHAPE",
  2618. "VIEW",
  2619. "PERMUTE",
  2620. "TRANSPOSE",
  2621. "GET_ROWS",
  2622. "GET_ROWS_BACK",
  2623. "DIAG",
  2624. "DIAG_MASK_INF",
  2625. "DIAG_MASK_ZERO",
  2626. "SOFT_MAX",
  2627. "SOFT_MAX_BACK",
  2628. "ROPE",
  2629. "ROPE_BACK",
  2630. "CLAMP",
  2631. "CONV_TRANSPOSE_1D",
  2632. "IM2COL",
  2633. "IM2COL_BACK",
  2634. "CONV_TRANSPOSE_2D",
  2635. "POOL_1D",
  2636. "POOL_2D",
  2637. "POOL_2D_BACK",
  2638. "UPSCALE",
  2639. "PAD",
  2640. "UNPAD",
  2641. "ARANGE",
  2642. "TIMESTEP_EMBEDDING",
  2643. "ARGSORT",
  2644. "LEAKY_RELU",
  2645. "FLASH_ATTN_EXT",
  2646. "FLASH_ATTN_BACK",
  2647. "SSM_CONV",
  2648. "SSM_SCAN",
  2649. "WIN_PART",
  2650. "WIN_UNPART",
  2651. "GET_REL_POS",
  2652. "ADD_REL_POS",
  2653. "RWKV_WKV",
  2654. "UNARY",
  2655. "MAP_UNARY",
  2656. "MAP_BINARY",
  2657. "MAP_CUSTOM1_F32",
  2658. "MAP_CUSTOM2_F32",
  2659. "MAP_CUSTOM3_F32",
  2660. "MAP_CUSTOM1",
  2661. "MAP_CUSTOM2",
  2662. "MAP_CUSTOM3",
  2663. "CROSS_ENTROPY_LOSS",
  2664. "CROSS_ENTROPY_LOSS_BACK",
  2665. "OPT_STEP_ADAMW",
  2666. };
  2667. static_assert(GGML_OP_COUNT == 81, "GGML_OP_COUNT != 81");
  2668. static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = {
  2669. "none",
  2670. "x",
  2671. "x+y",
  2672. "x+y",
  2673. "view(x,nb,offset)+=y->x",
  2674. "x-y",
  2675. "x*y",
  2676. "x/y",
  2677. "x^2",
  2678. "√x",
  2679. "log(x)",
  2680. "sin(x)",
  2681. "cos(x)",
  2682. "Σx",
  2683. "Σx_k",
  2684. "Σx/n",
  2685. "argmax(x)",
  2686. "repeat(x)",
  2687. "repeat_back(x)",
  2688. "concat(x, y)",
  2689. "silu_back(x)",
  2690. "norm(x)",
  2691. "rms_norm(x)",
  2692. "rms_norm_back(x)",
  2693. "group_norm(x)",
  2694. "X*Y",
  2695. "X[i]*Y",
  2696. "X*Y",
  2697. "x*v",
  2698. "y-\\>view(x)",
  2699. "x-\\>y",
  2700. "cont(x)",
  2701. "reshape(x)",
  2702. "view(x)",
  2703. "permute(x)",
  2704. "transpose(x)",
  2705. "get_rows(x)",
  2706. "get_rows_back(x)",
  2707. "diag(x)",
  2708. "diag_mask_inf(x)",
  2709. "diag_mask_zero(x)",
  2710. "soft_max(x)",
  2711. "soft_max_back(x)",
  2712. "rope(x)",
  2713. "rope_back(x)",
  2714. "clamp(x)",
  2715. "conv_transpose_1d(x)",
  2716. "im2col(x)",
  2717. "im2col_back(x)",
  2718. "conv_transpose_2d(x)",
  2719. "pool_1d(x)",
  2720. "pool_2d(x)",
  2721. "pool_2d_back(x)",
  2722. "upscale(x)",
  2723. "pad(x)",
  2724. "unpad(x)",
  2725. "arange(start, stop, step)",
  2726. "timestep_embedding(timesteps, dim, max_period)",
  2727. "argsort(x)",
  2728. "leaky_relu(x)",
  2729. "flash_attn_ext(x)",
  2730. "flash_attn_back(x)",
  2731. "ssm_conv(x)",
  2732. "ssm_scan(x)",
  2733. "win_part(x)",
  2734. "win_unpart(x)",
  2735. "get_rel_pos(x)",
  2736. "add_rel_pos(x)",
  2737. "rwkv_wkv(k, v, r, tf, td, s)",
  2738. "unary(x)",
  2739. "f(x)",
  2740. "f(x,y)",
  2741. "custom_f32(x)",
  2742. "custom_f32(x,y)",
  2743. "custom_f32(x,y,z)",
  2744. "custom(x)",
  2745. "custom(x,y)",
  2746. "custom(x,y,z)",
  2747. "cross_entropy_loss(x,y)",
  2748. "cross_entropy_loss_back(x,y)",
  2749. "adamw(x)",
  2750. };
  2751. static_assert(GGML_OP_COUNT == 81, "GGML_OP_COUNT != 81");
  2752. static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2");
  2753. static const char * GGML_UNARY_OP_NAME[GGML_UNARY_OP_COUNT] = {
  2754. "ABS",
  2755. "SGN",
  2756. "NEG",
  2757. "STEP",
  2758. "TANH",
  2759. "ELU",
  2760. "RELU",
  2761. "SIGMOID",
  2762. "GELU",
  2763. "GELU_QUICK",
  2764. "SILU",
  2765. "HARDSWISH",
  2766. "HARDSIGMOID",
  2767. "EXP",
  2768. };
  2769. static_assert(GGML_UNARY_OP_COUNT == 14, "GGML_UNARY_OP_COUNT != 14");
  2770. static_assert(sizeof(struct ggml_object)%GGML_MEM_ALIGN == 0, "ggml_object size must be a multiple of GGML_MEM_ALIGN");
  2771. static_assert(sizeof(struct ggml_tensor)%GGML_MEM_ALIGN == 0, "ggml_tensor size must be a multiple of GGML_MEM_ALIGN");
  2772. // Helpers for polling loops
  2773. #if defined(__aarch64__) && ( defined(__clang__) || defined(__GNUC__) )
  2774. static inline void ggml_thread_cpu_relax(void) {
  2775. __asm__ volatile("yield" ::: "memory");
  2776. }
  2777. #elif defined(__x86_64__)
  2778. static inline void ggml_thread_cpu_relax(void) {
  2779. _mm_pause();
  2780. }
  2781. #else
  2782. static inline void ggml_thread_cpu_relax(void) {;}
  2783. #endif
  2784. //
  2785. // NUMA support
  2786. //
  2787. #define GGML_NUMA_MAX_NODES 8
  2788. #define GGML_NUMA_MAX_CPUS 512
  2789. struct ggml_numa_node {
  2790. uint32_t cpus[GGML_NUMA_MAX_CPUS]; // hardware threads on this node
  2791. uint32_t n_cpus;
  2792. };
  2793. struct ggml_numa_nodes {
  2794. enum ggml_numa_strategy numa_strategy;
  2795. struct ggml_numa_node nodes[GGML_NUMA_MAX_NODES];
  2796. uint32_t n_nodes;
  2797. uint32_t total_cpus; // hardware threads on system
  2798. uint32_t current_node; // node on which main process is execting
  2799. #if defined(__gnu_linux__)
  2800. cpu_set_t cpuset; // cpuset from numactl
  2801. #else
  2802. uint32_t cpuset; // no NUMA support outside of Linux at this time. Use a portable datatype
  2803. #endif
  2804. };
  2805. //
  2806. // ggml state
  2807. //
  2808. struct ggml_state {
  2809. struct ggml_context_container contexts[GGML_MAX_CONTEXTS];
  2810. struct ggml_numa_nodes numa;
  2811. };
  2812. // global state
  2813. static struct ggml_state g_state;
  2814. static atomic_flag g_state_critical = ATOMIC_FLAG_INIT;
  2815. // critical section via spin lock
  2816. inline static void ggml_critical_section_start(void) {
  2817. while (atomic_flag_test_and_set(&g_state_critical)) {
  2818. // spin
  2819. sched_yield();
  2820. }
  2821. }
  2822. static void ggml_barrier(struct ggml_threadpool * tp) {
  2823. int n_threads = atomic_load_explicit(&tp->n_threads_cur, memory_order_relaxed);
  2824. if (n_threads == 1) {
  2825. return;
  2826. }
  2827. #ifdef GGML_USE_OPENMP
  2828. #pragma omp barrier
  2829. #else
  2830. int n_passed = atomic_load_explicit(&tp->n_barrier_passed, memory_order_relaxed);
  2831. // enter barrier (full seq-cst fence)
  2832. int n_barrier = atomic_fetch_add_explicit(&tp->n_barrier, 1, memory_order_seq_cst);
  2833. if (n_barrier == (n_threads - 1)) {
  2834. // last thread
  2835. atomic_store_explicit(&tp->n_barrier, 0, memory_order_relaxed);
  2836. // exit barrier (fill seq-cst fence)
  2837. atomic_fetch_add_explicit(&tp->n_barrier_passed, 1, memory_order_seq_cst);
  2838. return;
  2839. }
  2840. // wait for other threads
  2841. while (atomic_load_explicit(&tp->n_barrier_passed, memory_order_relaxed) == n_passed) {
  2842. ggml_thread_cpu_relax();
  2843. }
  2844. // exit barrier (full seq-cst fence)
  2845. // TSAN doesn't support standalone fence yet, we use a dummy read-modify-write instead
  2846. #ifdef GGML_TSAN_ENABLED
  2847. atomic_fetch_add_explicit(&tp->n_barrier_passed, 0, memory_order_seq_cst);
  2848. #else
  2849. atomic_thread_fence(memory_order_seq_cst);
  2850. #endif
  2851. #endif
  2852. }
  2853. // TODO: make this somehow automatically executed
  2854. // some sort of "sentry" mechanism
  2855. inline static void ggml_critical_section_end(void) {
  2856. atomic_flag_clear(&g_state_critical);
  2857. }
  2858. #if defined(__gnu_linux__)
  2859. static cpu_set_t ggml_get_numa_affinity(void) {
  2860. cpu_set_t cpuset;
  2861. pthread_t thread;
  2862. thread = pthread_self();
  2863. CPU_ZERO(&cpuset);
  2864. pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
  2865. return cpuset;
  2866. }
  2867. #else
  2868. static uint32_t ggml_get_numa_affinity(void) {
  2869. return 0; // no NUMA support
  2870. }
  2871. #endif
  2872. void ggml_numa_init(enum ggml_numa_strategy numa_flag) {
  2873. if (g_state.numa.n_nodes > 0) {
  2874. fprintf(stderr, "ggml_numa_init: NUMA already initialized\n");
  2875. return;
  2876. }
  2877. #if defined(__gnu_linux__)
  2878. struct stat st;
  2879. char path[256];
  2880. int rv;
  2881. // set numa scheme
  2882. g_state.numa.numa_strategy = numa_flag;
  2883. GGML_PRINT_DEBUG("numa strategy %u\n",g_state.numa.numa_strategy);
  2884. g_state.numa.cpuset = ggml_get_numa_affinity();
  2885. // enumerate nodes
  2886. while (g_state.numa.n_nodes < GGML_NUMA_MAX_NODES) {
  2887. rv = snprintf(path, sizeof(path), "/sys/devices/system/node/node%u", g_state.numa.n_nodes);
  2888. GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path));
  2889. if (stat(path, &st) != 0) { break; }
  2890. ++g_state.numa.n_nodes;
  2891. }
  2892. // enumerate CPUs
  2893. while (g_state.numa.total_cpus < GGML_NUMA_MAX_CPUS) {
  2894. rv = snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%u", g_state.numa.total_cpus);
  2895. GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path));
  2896. if (stat(path, &st) != 0) { break; }
  2897. ++g_state.numa.total_cpus;
  2898. }
  2899. GGML_PRINT_DEBUG("found %u numa nodes, %u CPUs\n", g_state.numa.n_nodes, g_state.numa.total_cpus);
  2900. // figure out which node we're on
  2901. uint current_cpu;
  2902. int getcpu_ret = 0;
  2903. #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 28) || defined(__COSMOPOLITAN__)
  2904. getcpu_ret = getcpu(&current_cpu, &g_state.numa.current_node);
  2905. #else
  2906. // old glibc doesn't have a wrapper for this call. Fall back on direct syscall
  2907. # if !defined(SYS_getcpu) && defined(SYS_get_cpu)
  2908. # define SYS_getcpu SYS_get_cpu // some older glibc versions use this name
  2909. # endif
  2910. getcpu_ret = syscall(SYS_getcpu, &current_cpu, &g_state.numa.current_node);
  2911. #endif
  2912. if (g_state.numa.n_nodes < 1 || g_state.numa.total_cpus < 1 || getcpu_ret != 0) {
  2913. g_state.numa.n_nodes = 0;
  2914. return;
  2915. }
  2916. GGML_PRINT_DEBUG("found our process on numa node %u, CPU %u\n", g_state.numa.current_node, current_cpu);
  2917. for (uint32_t n = 0; n < g_state.numa.n_nodes; ++n) {
  2918. struct ggml_numa_node * node = &g_state.numa.nodes[n];
  2919. GGML_PRINT_DEBUG("CPUs on node %u:", n);
  2920. node->n_cpus = 0;
  2921. for (uint32_t c = 0; c < g_state.numa.total_cpus; ++c) {
  2922. rv = snprintf(path, sizeof(path), "/sys/devices/system/node/node%u/cpu%u", n, c);
  2923. GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path));
  2924. if (stat(path, &st) == 0) {
  2925. node->cpus[node->n_cpus++] = c;
  2926. GGML_PRINT_DEBUG(" %u", c);
  2927. }
  2928. }
  2929. GGML_PRINT_DEBUG("\n");
  2930. }
  2931. if (ggml_is_numa()) {
  2932. FILE *fptr = fopen("/proc/sys/kernel/numa_balancing", "r");
  2933. if (fptr != NULL) {
  2934. char buf[42];
  2935. if (fgets(buf, sizeof(buf), fptr) && strncmp(buf, "0\n", sizeof(buf)) != 0) {
  2936. GGML_PRINT("WARNING: /proc/sys/kernel/numa_balancing is enabled, this has been observed to impair performance\n");
  2937. }
  2938. fclose(fptr);
  2939. }
  2940. }
  2941. #else
  2942. UNUSED(numa_flag);
  2943. // TODO
  2944. #endif
  2945. }
  2946. bool ggml_is_numa(void) {
  2947. return g_state.numa.n_nodes > 1;
  2948. }
  2949. ////////////////////////////////////////////////////////////////////////////////
  2950. void ggml_print_object(const struct ggml_object * obj) {
  2951. GGML_PRINT(" - ggml_object: type = %d, offset = %zu, size = %zu, next = %p\n",
  2952. obj->type, obj->offs, obj->size, (const void *) obj->next);
  2953. }
  2954. void ggml_print_objects(const struct ggml_context * ctx) {
  2955. struct ggml_object * obj = ctx->objects_begin;
  2956. GGML_PRINT("%s: objects in context %p:\n", __func__, (const void *) ctx);
  2957. while (obj != NULL) {
  2958. ggml_print_object(obj);
  2959. obj = obj->next;
  2960. }
  2961. GGML_PRINT("%s: --- end ---\n", __func__);
  2962. }
  2963. GGML_CALL int64_t ggml_nelements(const struct ggml_tensor * tensor) {
  2964. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2965. return tensor->ne[0]*tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
  2966. }
  2967. GGML_CALL int64_t ggml_nrows(const struct ggml_tensor * tensor) {
  2968. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2969. return tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
  2970. }
  2971. GGML_CALL size_t ggml_nbytes(const struct ggml_tensor * tensor) {
  2972. size_t nbytes;
  2973. size_t blck_size = ggml_blck_size(tensor->type);
  2974. if (blck_size == 1) {
  2975. nbytes = ggml_type_size(tensor->type);
  2976. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  2977. nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
  2978. }
  2979. }
  2980. else {
  2981. nbytes = tensor->ne[0]*tensor->nb[0]/blck_size;
  2982. for (int i = 1; i < GGML_MAX_DIMS; ++i) {
  2983. nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
  2984. }
  2985. }
  2986. return nbytes;
  2987. }
  2988. size_t ggml_nbytes_pad(const struct ggml_tensor * tensor) {
  2989. return GGML_PAD(ggml_nbytes(tensor), GGML_MEM_ALIGN);
  2990. }
  2991. GGML_CALL int64_t ggml_blck_size(enum ggml_type type) {
  2992. return type_traits[type].blck_size;
  2993. }
  2994. GGML_CALL size_t ggml_type_size(enum ggml_type type) {
  2995. return type_traits[type].type_size;
  2996. }
  2997. GGML_CALL size_t ggml_row_size(enum ggml_type type, int64_t ne) {
  2998. assert(ne % ggml_blck_size(type) == 0);
  2999. return ggml_type_size(type)*ne/ggml_blck_size(type);
  3000. }
  3001. double ggml_type_sizef(enum ggml_type type) {
  3002. return ((double)(type_traits[type].type_size))/type_traits[type].blck_size;
  3003. }
  3004. GGML_CALL const char * ggml_type_name(enum ggml_type type) {
  3005. return type < GGML_TYPE_COUNT ? type_traits[type].type_name : "NONE";
  3006. }
  3007. GGML_CALL bool ggml_is_quantized(enum ggml_type type) {
  3008. return type_traits[type].is_quantized;
  3009. }
  3010. GGML_CALL const char * ggml_op_name(enum ggml_op op) {
  3011. return GGML_OP_NAME[op];
  3012. }
  3013. const char * ggml_op_symbol(enum ggml_op op) {
  3014. return GGML_OP_SYMBOL[op];
  3015. }
  3016. const char * ggml_unary_op_name(enum ggml_unary_op op) {
  3017. return GGML_UNARY_OP_NAME[op];
  3018. }
  3019. GGML_CALL const char * ggml_op_desc(const struct ggml_tensor * t) {
  3020. if (t->op == GGML_OP_UNARY) {
  3021. enum ggml_unary_op uop = ggml_get_unary_op(t);
  3022. return ggml_unary_op_name(uop);
  3023. }
  3024. return ggml_op_name(t->op);
  3025. }
  3026. GGML_CALL size_t ggml_element_size(const struct ggml_tensor * tensor) {
  3027. return ggml_type_size(tensor->type);
  3028. }
  3029. bool ggml_is_scalar(const struct ggml_tensor * tensor) {
  3030. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3031. return tensor->ne[0] == 1 && tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  3032. }
  3033. bool ggml_is_vector(const struct ggml_tensor * tensor) {
  3034. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3035. return tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  3036. }
  3037. bool ggml_is_matrix(const struct ggml_tensor * tensor) {
  3038. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3039. return tensor->ne[2] == 1 && tensor->ne[3] == 1;
  3040. }
  3041. bool ggml_is_3d(const struct ggml_tensor * tensor) {
  3042. return tensor->ne[3] == 1;
  3043. }
  3044. int ggml_n_dims(const struct ggml_tensor * tensor) {
  3045. for (int i = GGML_MAX_DIMS - 1; i >= 1; --i) {
  3046. if (tensor->ne[i] > 1) {
  3047. return i + 1;
  3048. }
  3049. }
  3050. return 1;
  3051. }
  3052. static inline bool ggml_can_mul_mat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3053. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3054. return (t0->ne[0] == t1->ne[0]) &&
  3055. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  3056. (t1->ne[3]%t0->ne[3] == 0);
  3057. }
  3058. static inline bool ggml_can_out_prod(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3059. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3060. return (t0->ne[1] == t1->ne[1]) &&
  3061. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  3062. (t1->ne[3]%t0->ne[3] == 0);
  3063. }
  3064. enum ggml_type ggml_ftype_to_ggml_type(enum ggml_ftype ftype) {
  3065. enum ggml_type wtype = GGML_TYPE_COUNT;
  3066. switch (ftype) {
  3067. case GGML_FTYPE_ALL_F32: wtype = GGML_TYPE_F32; break;
  3068. case GGML_FTYPE_MOSTLY_F16: wtype = GGML_TYPE_F16; break;
  3069. case GGML_FTYPE_MOSTLY_BF16: wtype = GGML_TYPE_BF16; break;
  3070. case GGML_FTYPE_MOSTLY_Q4_0: wtype = GGML_TYPE_Q4_0; break;
  3071. case GGML_FTYPE_MOSTLY_Q4_1: wtype = GGML_TYPE_Q4_1; break;
  3072. case GGML_FTYPE_MOSTLY_Q5_0: wtype = GGML_TYPE_Q5_0; break;
  3073. case GGML_FTYPE_MOSTLY_Q5_1: wtype = GGML_TYPE_Q5_1; break;
  3074. case GGML_FTYPE_MOSTLY_Q8_0: wtype = GGML_TYPE_Q8_0; break;
  3075. case GGML_FTYPE_MOSTLY_Q2_K: wtype = GGML_TYPE_Q2_K; break;
  3076. case GGML_FTYPE_MOSTLY_Q3_K: wtype = GGML_TYPE_Q3_K; break;
  3077. case GGML_FTYPE_MOSTLY_Q4_K: wtype = GGML_TYPE_Q4_K; break;
  3078. case GGML_FTYPE_MOSTLY_Q5_K: wtype = GGML_TYPE_Q5_K; break;
  3079. case GGML_FTYPE_MOSTLY_Q6_K: wtype = GGML_TYPE_Q6_K; break;
  3080. case GGML_FTYPE_MOSTLY_IQ2_XXS: wtype = GGML_TYPE_IQ2_XXS; break;
  3081. case GGML_FTYPE_MOSTLY_IQ2_XS: wtype = GGML_TYPE_IQ2_XS; break;
  3082. case GGML_FTYPE_MOSTLY_IQ3_XXS: wtype = GGML_TYPE_IQ3_XXS; break;
  3083. case GGML_FTYPE_MOSTLY_IQ1_S: wtype = GGML_TYPE_IQ1_S; break;
  3084. case GGML_FTYPE_MOSTLY_IQ1_M: wtype = GGML_TYPE_IQ1_M; break;
  3085. case GGML_FTYPE_MOSTLY_IQ4_NL: wtype = GGML_TYPE_IQ4_NL; break;
  3086. case GGML_FTYPE_MOSTLY_IQ4_XS: wtype = GGML_TYPE_IQ4_XS; break;
  3087. case GGML_FTYPE_MOSTLY_IQ3_S: wtype = GGML_TYPE_IQ3_S; break;
  3088. case GGML_FTYPE_MOSTLY_IQ2_S: wtype = GGML_TYPE_IQ2_S; break;
  3089. case GGML_FTYPE_MOSTLY_Q4_0_4_4: wtype = GGML_TYPE_Q4_0_4_4; break;
  3090. case GGML_FTYPE_MOSTLY_Q4_0_4_8: wtype = GGML_TYPE_Q4_0_4_8; break;
  3091. case GGML_FTYPE_MOSTLY_Q4_0_8_8: wtype = GGML_TYPE_Q4_0_8_8; break;
  3092. case GGML_FTYPE_UNKNOWN: wtype = GGML_TYPE_COUNT; break;
  3093. case GGML_FTYPE_MOSTLY_Q4_1_SOME_F16: wtype = GGML_TYPE_COUNT; break;
  3094. }
  3095. GGML_ASSERT(wtype != GGML_TYPE_COUNT);
  3096. return wtype;
  3097. }
  3098. size_t ggml_tensor_overhead(void) {
  3099. return GGML_OBJECT_SIZE + GGML_TENSOR_SIZE;
  3100. }
  3101. GGML_CALL bool ggml_is_transposed(const struct ggml_tensor * tensor) {
  3102. return tensor->nb[0] > tensor->nb[1];
  3103. }
  3104. static bool ggml_is_contiguous_n(const struct ggml_tensor * tensor, int n) {
  3105. size_t next_nb = ggml_type_size(tensor->type);
  3106. if (tensor->ne[0] != ggml_blck_size(tensor->type) && tensor->nb[0] != next_nb) {
  3107. return false;
  3108. }
  3109. next_nb *= tensor->ne[0]/ggml_blck_size(tensor->type);
  3110. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  3111. if (tensor->ne[i] != 1) {
  3112. if (i > n) {
  3113. if (tensor->nb[i] != next_nb) {
  3114. return false;
  3115. }
  3116. next_nb *= tensor->ne[i];
  3117. } else {
  3118. // this dimension does not need to be contiguous
  3119. next_nb = tensor->ne[i]*tensor->nb[i];
  3120. }
  3121. }
  3122. }
  3123. return true;
  3124. }
  3125. GGML_CALL bool ggml_is_contiguous(const struct ggml_tensor * tensor) {
  3126. return ggml_is_contiguous_0(tensor);
  3127. }
  3128. GGML_CALL bool ggml_is_contiguous_0(const struct ggml_tensor * tensor) {
  3129. return ggml_is_contiguous_n(tensor, 0);
  3130. }
  3131. GGML_CALL bool ggml_is_contiguous_1(const struct ggml_tensor * tensor) {
  3132. return ggml_is_contiguous_n(tensor, 1);
  3133. }
  3134. GGML_CALL bool ggml_is_contiguous_2(const struct ggml_tensor * tensor) {
  3135. return ggml_is_contiguous_n(tensor, 2);
  3136. }
  3137. GGML_CALL bool ggml_is_permuted(const struct ggml_tensor * tensor) {
  3138. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3139. return tensor->nb[0] > tensor->nb[1] || tensor->nb[1] > tensor->nb[2] || tensor->nb[2] > tensor->nb[3];
  3140. }
  3141. static inline bool ggml_is_padded_1d(const struct ggml_tensor * tensor) {
  3142. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3143. return
  3144. tensor->nb[0] == ggml_type_size(tensor->type) &&
  3145. tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
  3146. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  3147. }
  3148. GGML_CALL bool ggml_is_empty(const struct ggml_tensor * tensor) {
  3149. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  3150. if (tensor->ne[i] == 0) {
  3151. // empty if any dimension has no elements
  3152. return true;
  3153. }
  3154. }
  3155. return false;
  3156. }
  3157. bool ggml_are_same_shape(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3158. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3159. return
  3160. (t0->ne[0] == t1->ne[0]) &&
  3161. (t0->ne[1] == t1->ne[1]) &&
  3162. (t0->ne[2] == t1->ne[2]) &&
  3163. (t0->ne[3] == t1->ne[3]);
  3164. }
  3165. bool ggml_are_same_stride(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3166. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3167. return
  3168. (t0->nb[0] == t1->nb[0]) &&
  3169. (t0->nb[1] == t1->nb[1]) &&
  3170. (t0->nb[2] == t1->nb[2]) &&
  3171. (t0->nb[3] == t1->nb[3]);
  3172. }
  3173. // check if t1 can be represented as a repeatition of t0
  3174. bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3175. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3176. return ggml_is_empty(t0) ? ggml_is_empty(t1) :
  3177. (t1->ne[0]%t0->ne[0] == 0) &&
  3178. (t1->ne[1]%t0->ne[1] == 0) &&
  3179. (t1->ne[2]%t0->ne[2] == 0) &&
  3180. (t1->ne[3]%t0->ne[3] == 0);
  3181. }
  3182. static inline bool ggml_can_repeat_rows(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  3183. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  3184. return (t0->ne[0] == t1->ne[0]) && ggml_can_repeat(t0, t1);
  3185. }
  3186. static inline int ggml_up32(int n) {
  3187. return (n + 31) & ~31;
  3188. }
  3189. //static inline int ggml_up64(int n) {
  3190. // return (n + 63) & ~63;
  3191. //}
  3192. static inline int ggml_up(int n, int m) {
  3193. // assert m is a power of 2
  3194. GGML_ASSERT((m & (m - 1)) == 0);
  3195. return (n + m - 1) & ~(m - 1);
  3196. }
  3197. // assert that pointer is aligned to GGML_MEM_ALIGN
  3198. #define GGML_ASSERT_ALIGNED(ptr) \
  3199. GGML_ASSERT(((uintptr_t) (ptr))%GGML_MEM_ALIGN == 0)
  3200. ////////////////////////////////////////////////////////////////////////////////
  3201. #if defined(__ARM_ARCH)
  3202. #if defined(__linux__) && defined(__aarch64__)
  3203. #include <sys/auxv.h>
  3204. #elif defined(__APPLE__)
  3205. #include <sys/sysctl.h>
  3206. #endif
  3207. #if !defined(HWCAP2_I8MM)
  3208. #define HWCAP2_I8MM 0
  3209. #endif
  3210. static void ggml_init_arm_arch_features(void) {
  3211. #if defined(__linux__) && defined(__aarch64__)
  3212. uint32_t hwcap = getauxval(AT_HWCAP);
  3213. uint32_t hwcap2 = getauxval(AT_HWCAP2);
  3214. ggml_arm_arch_features.has_neon = !!(hwcap & HWCAP_ASIMD);
  3215. ggml_arm_arch_features.has_i8mm = !!(hwcap2 & HWCAP2_I8MM);
  3216. ggml_arm_arch_features.has_sve = !!(hwcap & HWCAP_SVE);
  3217. #if defined(__ARM_FEATURE_SVE)
  3218. ggml_arm_arch_features.sve_cnt = PR_SVE_VL_LEN_MASK & prctl(PR_SVE_GET_VL);
  3219. #endif
  3220. #elif defined(__APPLE__)
  3221. int oldp = 0;
  3222. size_t size = sizeof(oldp);
  3223. if (sysctlbyname("hw.optional.AdvSIMD", &oldp, &size, NULL, 0) != 0) {
  3224. oldp = 0;
  3225. }
  3226. ggml_arm_arch_features.has_neon = oldp;
  3227. if (sysctlbyname("hw.optional.arm.FEAT_I8MM", &oldp, &size, NULL, 0) != 0) {
  3228. oldp = 0;
  3229. }
  3230. ggml_arm_arch_features.has_i8mm = oldp;
  3231. ggml_arm_arch_features.has_sve = 0;
  3232. ggml_arm_arch_features.sve_cnt = 0;
  3233. #else
  3234. // Run-time CPU feature detection not implemented for this platform, fallback to compile time
  3235. #if defined(__ARM_NEON)
  3236. ggml_arm_arch_features.has_neon = 1;
  3237. #else
  3238. ggml_arm_arch_features.has_neon = 0;
  3239. #endif
  3240. #if defined(__ARM_FEATURE_MATMUL_INT8)
  3241. ggml_arm_arch_features.has_i8mm = 1;
  3242. #else
  3243. ggml_arm_arch_features.has_i8mm = 0;
  3244. #endif
  3245. #if defined(__ARM_FEATURE_SVE)
  3246. ggml_arm_arch_features.has_sve = 1;
  3247. ggml_arm_arch_features.sve_cnt = 16;
  3248. #else
  3249. ggml_arm_arch_features.has_sve = 0;
  3250. ggml_arm_arch_features.sve_cnt = 0;
  3251. #endif
  3252. #endif
  3253. }
  3254. #endif
  3255. struct ggml_context * ggml_init(struct ggml_init_params params) {
  3256. // make this function thread safe
  3257. ggml_critical_section_start();
  3258. static bool is_first_call = true;
  3259. if (is_first_call) {
  3260. // initialize time system (required on Windows)
  3261. ggml_time_init();
  3262. // initialize GELU, Quick GELU, SILU and EXP F32 tables
  3263. {
  3264. const uint64_t t_start = ggml_time_us(); UNUSED(t_start);
  3265. for (int i = 0; i < (1 << 16); ++i) {
  3266. union {
  3267. uint16_t u16;
  3268. ggml_fp16_t fp16;
  3269. } u = {i};
  3270. float f = ggml_table_f32_f16[i] = GGML_COMPUTE_FP16_TO_FP32(u.fp16);
  3271. ggml_table_gelu_f16[i] = GGML_FP32_TO_FP16(ggml_gelu_f32(f));
  3272. ggml_table_gelu_quick_f16[i] = GGML_FP32_TO_FP16(ggml_gelu_quick_f32(f));
  3273. }
  3274. const uint64_t t_end = ggml_time_us(); UNUSED(t_end);
  3275. GGML_PRINT_DEBUG("%s: GELU, Quick GELU, SILU and EXP tables initialized in %f ms\n", __func__, (t_end - t_start)/1000.0f);
  3276. }
  3277. // initialize g_state
  3278. {
  3279. const uint64_t t_start = ggml_time_us(); UNUSED(t_start);
  3280. g_state = (struct ggml_state) {
  3281. /*.contexts =*/ { { 0 } },
  3282. /*.numa =*/ {
  3283. .n_nodes = 0,
  3284. .total_cpus = 0,
  3285. },
  3286. };
  3287. for (int i = 0; i < GGML_MAX_CONTEXTS; ++i) {
  3288. g_state.contexts[i].used = false;
  3289. }
  3290. const uint64_t t_end = ggml_time_us(); UNUSED(t_end);
  3291. GGML_PRINT_DEBUG("%s: g_state initialized in %f ms\n", __func__, (t_end - t_start)/1000.0f);
  3292. }
  3293. #if defined(__ARM_ARCH)
  3294. ggml_init_arm_arch_features();
  3295. #endif
  3296. is_first_call = false;
  3297. }
  3298. // find non-used context in g_state
  3299. struct ggml_context * ctx = NULL;
  3300. for (int i = 0; i < GGML_MAX_CONTEXTS; i++) {
  3301. if (!g_state.contexts[i].used) {
  3302. g_state.contexts[i].used = true;
  3303. ctx = &g_state.contexts[i].context;
  3304. GGML_PRINT_DEBUG("%s: found unused context %d\n", __func__, i);
  3305. break;
  3306. }
  3307. }
  3308. if (ctx == NULL) {
  3309. GGML_PRINT_DEBUG("%s: no unused context found\n", __func__);
  3310. ggml_critical_section_end();
  3311. return NULL;
  3312. }
  3313. // allow to call ggml_init with 0 size
  3314. if (params.mem_size == 0) {
  3315. params.mem_size = GGML_MEM_ALIGN;
  3316. }
  3317. const size_t mem_size = params.mem_buffer ? params.mem_size : GGML_PAD(params.mem_size, GGML_MEM_ALIGN);
  3318. *ctx = (struct ggml_context) {
  3319. /*.mem_size =*/ mem_size,
  3320. /*.mem_buffer =*/ params.mem_buffer ? params.mem_buffer : GGML_ALIGNED_MALLOC(mem_size),
  3321. /*.mem_buffer_owned =*/ params.mem_buffer ? false : true,
  3322. /*.no_alloc =*/ params.no_alloc,
  3323. /*.no_alloc_save =*/ params.no_alloc,
  3324. /*.n_objects =*/ 0,
  3325. /*.objects_begin =*/ NULL,
  3326. /*.objects_end =*/ NULL,
  3327. /*.scratch =*/ { 0, 0, NULL, },
  3328. /*.scratch_save =*/ { 0, 0, NULL, },
  3329. };
  3330. GGML_ASSERT(ctx->mem_buffer != NULL);
  3331. GGML_ASSERT_ALIGNED(ctx->mem_buffer);
  3332. GGML_PRINT_DEBUG("%s: context initialized\n", __func__);
  3333. ggml_critical_section_end();
  3334. return ctx;
  3335. }
  3336. void ggml_free(struct ggml_context * ctx) {
  3337. if (ctx == NULL) {
  3338. return;
  3339. }
  3340. // make this function thread safe
  3341. ggml_critical_section_start();
  3342. bool found = false;
  3343. for (int i = 0; i < GGML_MAX_CONTEXTS; i++) {
  3344. if (&g_state.contexts[i].context == ctx) {
  3345. g_state.contexts[i].used = false;
  3346. GGML_PRINT_DEBUG("%s: context %d has been freed. memory used = %zu\n",
  3347. __func__, i, ggml_used_mem(ctx));
  3348. if (ctx->mem_buffer_owned) {
  3349. GGML_ALIGNED_FREE(ctx->mem_buffer);
  3350. }
  3351. found = true;
  3352. break;
  3353. }
  3354. }
  3355. if (!found) {
  3356. GGML_PRINT_DEBUG("%s: context not found\n", __func__);
  3357. }
  3358. ggml_critical_section_end();
  3359. }
  3360. size_t ggml_used_mem(const struct ggml_context * ctx) {
  3361. return ctx->objects_end == NULL ? 0 : ctx->objects_end->offs + ctx->objects_end->size;
  3362. }
  3363. size_t ggml_set_scratch(struct ggml_context * ctx, struct ggml_scratch scratch) {
  3364. const size_t result = ctx->scratch.data ? ctx->scratch.offs : 0;
  3365. ctx->scratch = scratch;
  3366. return result;
  3367. }
  3368. bool ggml_get_no_alloc(struct ggml_context * ctx) {
  3369. return ctx->no_alloc;
  3370. }
  3371. void ggml_set_no_alloc(struct ggml_context * ctx, bool no_alloc) {
  3372. ctx->no_alloc = no_alloc;
  3373. }
  3374. void * ggml_get_mem_buffer(const struct ggml_context * ctx) {
  3375. return ctx->mem_buffer;
  3376. }
  3377. size_t ggml_get_mem_size(const struct ggml_context * ctx) {
  3378. return ctx->mem_size;
  3379. }
  3380. size_t ggml_get_max_tensor_size(const struct ggml_context * ctx) {
  3381. size_t max_size = 0;
  3382. for (struct ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor != NULL; tensor = ggml_get_next_tensor(ctx, tensor)) {
  3383. size_t bytes = ggml_nbytes(tensor);
  3384. max_size = MAX(max_size, bytes);
  3385. }
  3386. return max_size;
  3387. }
  3388. // IMPORTANT:
  3389. // when creating "opt" tensors, always save and load the scratch buffer
  3390. // this is an error prone process, but it is necessary to support inplace
  3391. // operators when using scratch buffers
  3392. // TODO: implement a better way
  3393. static void ggml_scratch_save(struct ggml_context * ctx) {
  3394. // this is needed to allow opt tensors to store their data
  3395. // TODO: again, need to find a better way
  3396. ctx->no_alloc_save = ctx->no_alloc;
  3397. ctx->no_alloc = false;
  3398. ctx->scratch_save = ctx->scratch;
  3399. ctx->scratch.data = NULL;
  3400. }
  3401. static void ggml_scratch_load(struct ggml_context * ctx) {
  3402. ctx->no_alloc = ctx->no_alloc_save;
  3403. ctx->scratch = ctx->scratch_save;
  3404. }
  3405. ////////////////////////////////////////////////////////////////////////////////
  3406. static struct ggml_object * ggml_new_object(struct ggml_context * ctx, enum ggml_object_type type, size_t size) {
  3407. // always insert objects at the end of the context's memory pool
  3408. struct ggml_object * obj_cur = ctx->objects_end;
  3409. const size_t cur_offs = obj_cur == NULL ? 0 : obj_cur->offs;
  3410. const size_t cur_size = obj_cur == NULL ? 0 : obj_cur->size;
  3411. const size_t cur_end = cur_offs + cur_size;
  3412. // align to GGML_MEM_ALIGN
  3413. size_t size_needed = GGML_PAD(size, GGML_MEM_ALIGN);
  3414. char * const mem_buffer = ctx->mem_buffer;
  3415. struct ggml_object * const obj_new = (struct ggml_object *)(mem_buffer + cur_end);
  3416. if (cur_end + size_needed + GGML_OBJECT_SIZE > ctx->mem_size) {
  3417. GGML_PRINT("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
  3418. __func__, cur_end + size_needed + GGML_OBJECT_SIZE, ctx->mem_size);
  3419. assert(false);
  3420. return NULL;
  3421. }
  3422. *obj_new = (struct ggml_object) {
  3423. .offs = cur_end + GGML_OBJECT_SIZE,
  3424. .size = size_needed,
  3425. .next = NULL,
  3426. .type = type,
  3427. };
  3428. GGML_ASSERT_ALIGNED(mem_buffer + obj_new->offs);
  3429. if (obj_cur != NULL) {
  3430. obj_cur->next = obj_new;
  3431. } else {
  3432. // this is the first object in this context
  3433. ctx->objects_begin = obj_new;
  3434. }
  3435. ctx->objects_end = obj_new;
  3436. //printf("%s: inserted new object at %zu, size = %zu\n", __func__, cur_end, obj_new->size);
  3437. return obj_new;
  3438. }
  3439. static struct ggml_tensor * ggml_new_tensor_impl(
  3440. struct ggml_context * ctx,
  3441. enum ggml_type type,
  3442. int n_dims,
  3443. const int64_t * ne,
  3444. struct ggml_tensor * view_src,
  3445. size_t view_offs) {
  3446. GGML_ASSERT(type >= 0 && type < GGML_TYPE_COUNT);
  3447. GGML_ASSERT(n_dims >= 1 && n_dims <= GGML_MAX_DIMS);
  3448. // find the base tensor and absolute offset
  3449. if (view_src != NULL && view_src->view_src != NULL) {
  3450. view_offs += view_src->view_offs;
  3451. view_src = view_src->view_src;
  3452. }
  3453. size_t data_size = ggml_row_size(type, ne[0]);
  3454. for (int i = 1; i < n_dims; i++) {
  3455. data_size *= ne[i];
  3456. }
  3457. GGML_ASSERT(view_src == NULL || data_size == 0 || data_size + view_offs <= ggml_nbytes(view_src));
  3458. void * data = view_src != NULL ? view_src->data : NULL;
  3459. if (data != NULL) {
  3460. data = (char *) data + view_offs;
  3461. }
  3462. size_t obj_alloc_size = 0;
  3463. if (view_src == NULL && !ctx->no_alloc) {
  3464. if (ctx->scratch.data != NULL) {
  3465. // allocate tensor data in the scratch buffer
  3466. if (ctx->scratch.offs + data_size > ctx->scratch.size) {
  3467. GGML_PRINT("%s: not enough space in the scratch memory pool (needed %zu, available %zu)\n",
  3468. __func__, ctx->scratch.offs + data_size, ctx->scratch.size);
  3469. assert(false);
  3470. return NULL;
  3471. }
  3472. data = (char * const) ctx->scratch.data + ctx->scratch.offs;
  3473. ctx->scratch.offs += data_size;
  3474. } else {
  3475. // allocate tensor data in the context's memory pool
  3476. obj_alloc_size = data_size;
  3477. }
  3478. }
  3479. struct ggml_object * const obj_new = ggml_new_object(ctx, GGML_OBJECT_TYPE_TENSOR, GGML_TENSOR_SIZE + obj_alloc_size);
  3480. GGML_ASSERT(obj_new);
  3481. // TODO: for recoverable errors, we would need to free the data allocated from the scratch buffer here
  3482. struct ggml_tensor * const result = (struct ggml_tensor *)((char *)ctx->mem_buffer + obj_new->offs);
  3483. #ifdef __clang__
  3484. // temporary until ggml_tensor::backend is removed
  3485. #pragma clang diagnostic push
  3486. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  3487. #endif
  3488. *result = (struct ggml_tensor) {
  3489. /*.type =*/ type,
  3490. /*.backend =*/ GGML_BACKEND_TYPE_CPU,
  3491. /*.buffer =*/ NULL,
  3492. /*.ne =*/ { 1, 1, 1, 1 },
  3493. /*.nb =*/ { 0, 0, 0, 0 },
  3494. /*.op =*/ GGML_OP_NONE,
  3495. /*.op_params =*/ { 0 },
  3496. /*.flags =*/ 0,
  3497. /*.grad =*/ NULL,
  3498. /*.src =*/ { NULL },
  3499. /*.view_src =*/ view_src,
  3500. /*.view_offs =*/ view_offs,
  3501. /*.data =*/ obj_alloc_size > 0 ? (void *)(result + 1) : data,
  3502. /*.name =*/ { 0 },
  3503. /*.extra =*/ NULL,
  3504. ///*.padding =*/ { 0 },
  3505. };
  3506. #ifdef __clang__
  3507. #pragma clang diagnostic pop
  3508. #endif
  3509. // TODO: this should not be needed as long as we don't rely on aligned SIMD loads
  3510. //GGML_ASSERT_ALIGNED(result->data);
  3511. for (int i = 0; i < n_dims; i++) {
  3512. result->ne[i] = ne[i];
  3513. }
  3514. result->nb[0] = ggml_type_size(type);
  3515. result->nb[1] = result->nb[0]*(result->ne[0]/ggml_blck_size(type));
  3516. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  3517. result->nb[i] = result->nb[i - 1]*result->ne[i - 1];
  3518. }
  3519. ctx->n_objects++;
  3520. return result;
  3521. }
  3522. struct ggml_tensor * ggml_new_tensor(
  3523. struct ggml_context * ctx,
  3524. enum ggml_type type,
  3525. int n_dims,
  3526. const int64_t * ne) {
  3527. return ggml_new_tensor_impl(ctx, type, n_dims, ne, NULL, 0);
  3528. }
  3529. struct ggml_tensor * ggml_new_tensor_1d(
  3530. struct ggml_context * ctx,
  3531. enum ggml_type type,
  3532. int64_t ne0) {
  3533. return ggml_new_tensor(ctx, type, 1, &ne0);
  3534. }
  3535. struct ggml_tensor * ggml_new_tensor_2d(
  3536. struct ggml_context * ctx,
  3537. enum ggml_type type,
  3538. int64_t ne0,
  3539. int64_t ne1) {
  3540. const int64_t ne[2] = { ne0, ne1 };
  3541. return ggml_new_tensor(ctx, type, 2, ne);
  3542. }
  3543. struct ggml_tensor * ggml_new_tensor_3d(
  3544. struct ggml_context * ctx,
  3545. enum ggml_type type,
  3546. int64_t ne0,
  3547. int64_t ne1,
  3548. int64_t ne2) {
  3549. const int64_t ne[3] = { ne0, ne1, ne2 };
  3550. return ggml_new_tensor(ctx, type, 3, ne);
  3551. }
  3552. struct ggml_tensor * ggml_new_tensor_4d(
  3553. struct ggml_context * ctx,
  3554. enum ggml_type type,
  3555. int64_t ne0,
  3556. int64_t ne1,
  3557. int64_t ne2,
  3558. int64_t ne3) {
  3559. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  3560. return ggml_new_tensor(ctx, type, 4, ne);
  3561. }
  3562. struct ggml_tensor * ggml_new_i32(struct ggml_context * ctx, int32_t value) {
  3563. ggml_scratch_save(ctx);
  3564. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
  3565. ggml_scratch_load(ctx);
  3566. ggml_set_i32(result, value);
  3567. return result;
  3568. }
  3569. struct ggml_tensor * ggml_new_f32(struct ggml_context * ctx, float value) {
  3570. ggml_scratch_save(ctx);
  3571. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
  3572. ggml_scratch_load(ctx);
  3573. ggml_set_f32(result, value);
  3574. return result;
  3575. }
  3576. struct ggml_tensor * ggml_dup_tensor(struct ggml_context * ctx, const struct ggml_tensor * src) {
  3577. return ggml_new_tensor(ctx, src->type, GGML_MAX_DIMS, src->ne);
  3578. }
  3579. static void ggml_set_op_params(struct ggml_tensor * tensor, const void * params, size_t params_size) {
  3580. GGML_ASSERT(tensor != NULL); // silence -Warray-bounds warnings
  3581. assert(params_size <= GGML_MAX_OP_PARAMS);
  3582. memcpy(tensor->op_params, params, params_size);
  3583. }
  3584. static int32_t ggml_get_op_params_i32(const struct ggml_tensor * tensor, uint32_t i) {
  3585. assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
  3586. return ((const int32_t *)(tensor->op_params))[i];
  3587. }
  3588. static float ggml_get_op_params_f32(const struct ggml_tensor * tensor, uint32_t i) {
  3589. assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
  3590. return ((const float *)(tensor->op_params))[i];
  3591. }
  3592. static void ggml_set_op_params_i32(struct ggml_tensor * tensor, uint32_t i, int32_t value) {
  3593. assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
  3594. ((int32_t *)(tensor->op_params))[i] = value;
  3595. }
  3596. static void ggml_set_op_params_f32(struct ggml_tensor * tensor, uint32_t i, float value) {
  3597. assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
  3598. ((float *)(tensor->op_params))[i] = value;
  3599. }
  3600. struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor) {
  3601. if (tensor->buffer) {
  3602. ggml_backend_tensor_memset(tensor, 0, 0, ggml_nbytes(tensor));
  3603. } else {
  3604. memset(tensor->data, 0, ggml_nbytes(tensor));
  3605. }
  3606. return tensor;
  3607. }
  3608. struct ggml_tensor * ggml_set_i32 (struct ggml_tensor * tensor, int32_t value) {
  3609. const int n = ggml_nrows(tensor);
  3610. const int nc = tensor->ne[0];
  3611. const size_t n1 = tensor->nb[1];
  3612. char * const data = tensor->data;
  3613. switch (tensor->type) {
  3614. case GGML_TYPE_I8:
  3615. {
  3616. assert(tensor->nb[0] == sizeof(int8_t));
  3617. for (int i = 0; i < n; i++) {
  3618. ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
  3619. }
  3620. } break;
  3621. case GGML_TYPE_I16:
  3622. {
  3623. assert(tensor->nb[0] == sizeof(int16_t));
  3624. for (int i = 0; i < n; i++) {
  3625. ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
  3626. }
  3627. } break;
  3628. case GGML_TYPE_I32:
  3629. {
  3630. assert(tensor->nb[0] == sizeof(int32_t));
  3631. for (int i = 0; i < n; i++) {
  3632. ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
  3633. }
  3634. } break;
  3635. case GGML_TYPE_F16:
  3636. {
  3637. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  3638. for (int i = 0; i < n; i++) {
  3639. ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), GGML_FP32_TO_FP16(value));
  3640. }
  3641. } break;
  3642. case GGML_TYPE_BF16:
  3643. {
  3644. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  3645. for (int i = 0; i < n; i++) {
  3646. ggml_vec_set_bf16(nc, (ggml_bf16_t *)(data + i*n1), GGML_FP32_TO_BF16(value));
  3647. }
  3648. } break;
  3649. case GGML_TYPE_F32:
  3650. {
  3651. assert(tensor->nb[0] == sizeof(float));
  3652. for (int i = 0; i < n; i++) {
  3653. ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
  3654. }
  3655. } break;
  3656. default:
  3657. {
  3658. GGML_ABORT("fatal error");
  3659. }
  3660. }
  3661. return tensor;
  3662. }
  3663. struct ggml_tensor * ggml_set_f32(struct ggml_tensor * tensor, float value) {
  3664. const int n = ggml_nrows(tensor);
  3665. const int nc = tensor->ne[0];
  3666. const size_t n1 = tensor->nb[1];
  3667. char * const data = tensor->data;
  3668. switch (tensor->type) {
  3669. case GGML_TYPE_I8:
  3670. {
  3671. assert(tensor->nb[0] == sizeof(int8_t));
  3672. for (int i = 0; i < n; i++) {
  3673. ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
  3674. }
  3675. } break;
  3676. case GGML_TYPE_I16:
  3677. {
  3678. assert(tensor->nb[0] == sizeof(int16_t));
  3679. for (int i = 0; i < n; i++) {
  3680. ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
  3681. }
  3682. } break;
  3683. case GGML_TYPE_I32:
  3684. {
  3685. assert(tensor->nb[0] == sizeof(int32_t));
  3686. for (int i = 0; i < n; i++) {
  3687. ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
  3688. }
  3689. } break;
  3690. case GGML_TYPE_F16:
  3691. {
  3692. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  3693. for (int i = 0; i < n; i++) {
  3694. ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), GGML_FP32_TO_FP16(value));
  3695. }
  3696. } break;
  3697. case GGML_TYPE_BF16:
  3698. {
  3699. assert(tensor->nb[0] == sizeof(ggml_bf16_t));
  3700. for (int i = 0; i < n; i++) {
  3701. ggml_vec_set_bf16(nc, (ggml_bf16_t *)(data + i*n1), GGML_FP32_TO_BF16(value));
  3702. }
  3703. } break;
  3704. case GGML_TYPE_F32:
  3705. {
  3706. assert(tensor->nb[0] == sizeof(float));
  3707. for (int i = 0; i < n; i++) {
  3708. ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
  3709. }
  3710. } break;
  3711. default:
  3712. {
  3713. GGML_ABORT("fatal error");
  3714. }
  3715. }
  3716. return tensor;
  3717. }
  3718. void ggml_unravel_index(const struct ggml_tensor * tensor, int64_t i, int64_t * i0, int64_t * i1, int64_t * i2, int64_t * i3) {
  3719. const int64_t ne2 = tensor->ne[2];
  3720. const int64_t ne1 = tensor->ne[1];
  3721. const int64_t ne0 = tensor->ne[0];
  3722. const int64_t i3_ = (i/(ne2*ne1*ne0));
  3723. const int64_t i2_ = (i - i3_*ne2*ne1*ne0)/(ne1*ne0);
  3724. const int64_t i1_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0)/ne0;
  3725. const int64_t i0_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0 - i1_*ne0);
  3726. if (i0) {
  3727. * i0 = i0_;
  3728. }
  3729. if (i1) {
  3730. * i1 = i1_;
  3731. }
  3732. if (i2) {
  3733. * i2 = i2_;
  3734. }
  3735. if (i3) {
  3736. * i3 = i3_;
  3737. }
  3738. }
  3739. int32_t ggml_get_i32_1d(const struct ggml_tensor * tensor, int i) {
  3740. if (!ggml_is_contiguous(tensor)) {
  3741. int64_t id[4] = { 0, 0, 0, 0 };
  3742. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  3743. return ggml_get_i32_nd(tensor, id[0], id[1], id[2], id[3]);
  3744. }
  3745. switch (tensor->type) {
  3746. case GGML_TYPE_I8:
  3747. {
  3748. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  3749. return ((int8_t *)(tensor->data))[i];
  3750. }
  3751. case GGML_TYPE_I16:
  3752. {
  3753. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  3754. return ((int16_t *)(tensor->data))[i];
  3755. }
  3756. case GGML_TYPE_I32:
  3757. {
  3758. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  3759. return ((int32_t *)(tensor->data))[i];
  3760. }
  3761. case GGML_TYPE_F16:
  3762. {
  3763. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  3764. return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
  3765. }
  3766. case GGML_TYPE_BF16:
  3767. {
  3768. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_bf16_t));
  3769. return GGML_BF16_TO_FP32(((ggml_bf16_t *)(tensor->data))[i]);
  3770. }
  3771. case GGML_TYPE_F32:
  3772. {
  3773. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  3774. return ((float *)(tensor->data))[i];
  3775. }
  3776. default:
  3777. {
  3778. GGML_ABORT("fatal error");
  3779. }
  3780. }
  3781. }
  3782. void ggml_set_i32_1d(const struct ggml_tensor * tensor, int i, int32_t value) {
  3783. if (!ggml_is_contiguous(tensor)) {
  3784. int64_t id[4] = { 0, 0, 0, 0 };
  3785. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  3786. ggml_set_i32_nd(tensor, id[0], id[1], id[2], id[3], value);
  3787. return;
  3788. }
  3789. switch (tensor->type) {
  3790. case GGML_TYPE_I8:
  3791. {
  3792. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  3793. ((int8_t *)(tensor->data))[i] = value;
  3794. } break;
  3795. case GGML_TYPE_I16:
  3796. {
  3797. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  3798. ((int16_t *)(tensor->data))[i] = value;
  3799. } break;
  3800. case GGML_TYPE_I32:
  3801. {
  3802. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  3803. ((int32_t *)(tensor->data))[i] = value;
  3804. } break;
  3805. case GGML_TYPE_F16:
  3806. {
  3807. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  3808. ((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
  3809. } break;
  3810. case GGML_TYPE_BF16:
  3811. {
  3812. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_bf16_t));
  3813. ((ggml_bf16_t *)(tensor->data))[i] = GGML_FP32_TO_BF16(value);
  3814. } break;
  3815. case GGML_TYPE_F32:
  3816. {
  3817. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  3818. ((float *)(tensor->data))[i] = value;
  3819. } break;
  3820. default:
  3821. {
  3822. GGML_ABORT("fatal error");
  3823. }
  3824. }
  3825. }
  3826. int32_t ggml_get_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  3827. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  3828. switch (tensor->type) {
  3829. case GGML_TYPE_I8:
  3830. return ((int8_t *) data)[0];
  3831. case GGML_TYPE_I16:
  3832. return ((int16_t *) data)[0];
  3833. case GGML_TYPE_I32:
  3834. return ((int32_t *) data)[0];
  3835. case GGML_TYPE_F16:
  3836. return GGML_FP16_TO_FP32(((ggml_fp16_t *) data)[0]);
  3837. case GGML_TYPE_BF16:
  3838. return GGML_BF16_TO_FP32(((ggml_bf16_t *) data)[0]);
  3839. case GGML_TYPE_F32:
  3840. return ((float *) data)[0];
  3841. default:
  3842. GGML_ABORT("fatal error");
  3843. }
  3844. }
  3845. void ggml_set_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, int32_t value) {
  3846. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  3847. switch (tensor->type) {
  3848. case GGML_TYPE_I8:
  3849. {
  3850. ((int8_t *)(data))[0] = value;
  3851. } break;
  3852. case GGML_TYPE_I16:
  3853. {
  3854. ((int16_t *)(data))[0] = value;
  3855. } break;
  3856. case GGML_TYPE_I32:
  3857. {
  3858. ((int32_t *)(data))[0] = value;
  3859. } break;
  3860. case GGML_TYPE_F16:
  3861. {
  3862. ((ggml_fp16_t *)(data))[0] = GGML_FP32_TO_FP16(value);
  3863. } break;
  3864. case GGML_TYPE_BF16:
  3865. {
  3866. ((ggml_bf16_t *)(data))[0] = GGML_FP32_TO_BF16(value);
  3867. } break;
  3868. case GGML_TYPE_F32:
  3869. {
  3870. ((float *)(data))[0] = value;
  3871. } break;
  3872. default:
  3873. {
  3874. GGML_ABORT("fatal error");
  3875. }
  3876. }
  3877. }
  3878. float ggml_get_f32_1d(const struct ggml_tensor * tensor, int i) {
  3879. if (!ggml_is_contiguous(tensor)) {
  3880. int64_t id[4] = { 0, 0, 0, 0 };
  3881. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  3882. return ggml_get_f32_nd(tensor, id[0], id[1], id[2], id[3]);
  3883. }
  3884. switch (tensor->type) {
  3885. case GGML_TYPE_I8:
  3886. {
  3887. return ((int8_t *)(tensor->data))[i];
  3888. }
  3889. case GGML_TYPE_I16:
  3890. {
  3891. return ((int16_t *)(tensor->data))[i];
  3892. }
  3893. case GGML_TYPE_I32:
  3894. {
  3895. return ((int32_t *)(tensor->data))[i];
  3896. }
  3897. case GGML_TYPE_F16:
  3898. {
  3899. return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
  3900. }
  3901. case GGML_TYPE_BF16:
  3902. {
  3903. return GGML_BF16_TO_FP32(((ggml_bf16_t *)(tensor->data))[i]);
  3904. }
  3905. case GGML_TYPE_F32:
  3906. {
  3907. return ((float *)(tensor->data))[i];
  3908. }
  3909. default:
  3910. {
  3911. GGML_ABORT("fatal error");
  3912. }
  3913. }
  3914. }
  3915. void ggml_set_f32_1d(const struct ggml_tensor * tensor, int i, float value) {
  3916. if (!ggml_is_contiguous(tensor)) {
  3917. int64_t id[4] = { 0, 0, 0, 0 };
  3918. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  3919. ggml_set_f32_nd(tensor, id[0], id[1], id[2], id[3], value);
  3920. return;
  3921. }
  3922. switch (tensor->type) {
  3923. case GGML_TYPE_I8:
  3924. {
  3925. ((int8_t *)(tensor->data))[i] = value;
  3926. } break;
  3927. case GGML_TYPE_I16:
  3928. {
  3929. ((int16_t *)(tensor->data))[i] = value;
  3930. } break;
  3931. case GGML_TYPE_I32:
  3932. {
  3933. ((int32_t *)(tensor->data))[i] = value;
  3934. } break;
  3935. case GGML_TYPE_F16:
  3936. {
  3937. ((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
  3938. } break;
  3939. case GGML_TYPE_BF16:
  3940. {
  3941. ((ggml_bf16_t *)(tensor->data))[i] = GGML_FP32_TO_BF16(value);
  3942. } break;
  3943. case GGML_TYPE_F32:
  3944. {
  3945. ((float *)(tensor->data))[i] = value;
  3946. } break;
  3947. default:
  3948. {
  3949. GGML_ABORT("fatal error");
  3950. }
  3951. }
  3952. }
  3953. float ggml_get_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  3954. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  3955. switch (tensor->type) {
  3956. case GGML_TYPE_I8:
  3957. return ((int8_t *) data)[0];
  3958. case GGML_TYPE_I16:
  3959. return ((int16_t *) data)[0];
  3960. case GGML_TYPE_I32:
  3961. return ((int32_t *) data)[0];
  3962. case GGML_TYPE_F16:
  3963. return GGML_FP16_TO_FP32(((ggml_fp16_t *) data)[0]);
  3964. case GGML_TYPE_BF16:
  3965. return GGML_BF16_TO_FP32(((ggml_bf16_t *) data)[0]);
  3966. case GGML_TYPE_F32:
  3967. return ((float *) data)[0];
  3968. default:
  3969. GGML_ABORT("fatal error");
  3970. }
  3971. }
  3972. void ggml_set_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, float value) {
  3973. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  3974. switch (tensor->type) {
  3975. case GGML_TYPE_I8:
  3976. {
  3977. ((int8_t *)(data))[0] = value;
  3978. } break;
  3979. case GGML_TYPE_I16:
  3980. {
  3981. ((int16_t *)(data))[0] = value;
  3982. } break;
  3983. case GGML_TYPE_I32:
  3984. {
  3985. ((int32_t *)(data))[0] = value;
  3986. } break;
  3987. case GGML_TYPE_F16:
  3988. {
  3989. ((ggml_fp16_t *)(data))[0] = GGML_FP32_TO_FP16(value);
  3990. } break;
  3991. case GGML_TYPE_BF16:
  3992. {
  3993. ((ggml_bf16_t *)(data))[0] = GGML_FP32_TO_BF16(value);
  3994. } break;
  3995. case GGML_TYPE_F32:
  3996. {
  3997. ((float *)(data))[0] = value;
  3998. } break;
  3999. default:
  4000. {
  4001. GGML_ABORT("fatal error");
  4002. }
  4003. }
  4004. }
  4005. void * ggml_get_data(const struct ggml_tensor * tensor) {
  4006. return tensor->data;
  4007. }
  4008. float * ggml_get_data_f32(const struct ggml_tensor * tensor) {
  4009. assert(tensor->type == GGML_TYPE_F32);
  4010. return (float *)(tensor->data);
  4011. }
  4012. GGML_CALL enum ggml_unary_op ggml_get_unary_op(const struct ggml_tensor * tensor) {
  4013. GGML_ASSERT(tensor->op == GGML_OP_UNARY);
  4014. return (enum ggml_unary_op) ggml_get_op_params_i32(tensor, 0);
  4015. }
  4016. const char * ggml_get_name(const struct ggml_tensor * tensor) {
  4017. return tensor->name;
  4018. }
  4019. struct ggml_tensor * ggml_set_name(struct ggml_tensor * tensor, const char * name) {
  4020. size_t i;
  4021. for (i = 0; i < sizeof(tensor->name) - 1 && name[i] != '\0'; i++) {
  4022. tensor->name[i] = name[i];
  4023. }
  4024. tensor->name[i] = '\0';
  4025. return tensor;
  4026. }
  4027. struct ggml_tensor * ggml_format_name(struct ggml_tensor * tensor, const char * fmt, ...) {
  4028. va_list args;
  4029. va_start(args, fmt);
  4030. vsnprintf(tensor->name, sizeof(tensor->name), fmt, args);
  4031. va_end(args);
  4032. return tensor;
  4033. }
  4034. struct ggml_tensor * ggml_view_tensor(
  4035. struct ggml_context * ctx,
  4036. struct ggml_tensor * src) {
  4037. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, src->type, GGML_MAX_DIMS, src->ne, src, 0);
  4038. ggml_format_name(result, "%s (view)", src->name);
  4039. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  4040. result->nb[i] = src->nb[i];
  4041. }
  4042. return result;
  4043. }
  4044. struct ggml_tensor * ggml_get_first_tensor(const struct ggml_context * ctx) {
  4045. struct ggml_object * obj = ctx->objects_begin;
  4046. char * const mem_buffer = ctx->mem_buffer;
  4047. while (obj != NULL) {
  4048. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  4049. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  4050. }
  4051. obj = obj->next;
  4052. }
  4053. return NULL;
  4054. }
  4055. struct ggml_tensor * ggml_get_next_tensor(const struct ggml_context * ctx, struct ggml_tensor * tensor) {
  4056. struct ggml_object * obj = (struct ggml_object *) ((char *)tensor - GGML_OBJECT_SIZE);
  4057. obj = obj->next;
  4058. char * const mem_buffer = ctx->mem_buffer;
  4059. while (obj != NULL) {
  4060. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  4061. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  4062. }
  4063. obj = obj->next;
  4064. }
  4065. return NULL;
  4066. }
  4067. struct ggml_tensor * ggml_get_tensor(struct ggml_context * ctx, const char * name) {
  4068. struct ggml_object * obj = ctx->objects_begin;
  4069. char * const mem_buffer = ctx->mem_buffer;
  4070. while (obj != NULL) {
  4071. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  4072. struct ggml_tensor * cur = (struct ggml_tensor *)(mem_buffer + obj->offs);
  4073. if (strcmp(cur->name, name) == 0) {
  4074. return cur;
  4075. }
  4076. }
  4077. obj = obj->next;
  4078. }
  4079. return NULL;
  4080. }
  4081. ////////////////////////////////////////////////////////////////////////////////
  4082. // ggml_dup
  4083. static struct ggml_tensor * ggml_dup_impl(
  4084. struct ggml_context * ctx,
  4085. struct ggml_tensor * a,
  4086. bool inplace) {
  4087. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4088. result->op = GGML_OP_DUP;
  4089. result->src[0] = a;
  4090. return result;
  4091. }
  4092. struct ggml_tensor * ggml_dup(
  4093. struct ggml_context * ctx,
  4094. struct ggml_tensor * a) {
  4095. return ggml_dup_impl(ctx, a, false);
  4096. }
  4097. struct ggml_tensor * ggml_dup_inplace(
  4098. struct ggml_context * ctx,
  4099. struct ggml_tensor * a) {
  4100. return ggml_dup_impl(ctx, a, true);
  4101. }
  4102. // ggml_add
  4103. static struct ggml_tensor * ggml_add_impl(
  4104. struct ggml_context * ctx,
  4105. struct ggml_tensor * a,
  4106. struct ggml_tensor * b,
  4107. bool inplace) {
  4108. GGML_ASSERT(ggml_can_repeat(b, a));
  4109. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4110. result->op = GGML_OP_ADD;
  4111. result->src[0] = a;
  4112. result->src[1] = b;
  4113. return result;
  4114. }
  4115. struct ggml_tensor * ggml_add(
  4116. struct ggml_context * ctx,
  4117. struct ggml_tensor * a,
  4118. struct ggml_tensor * b) {
  4119. return ggml_add_impl(ctx, a, b, false);
  4120. }
  4121. struct ggml_tensor * ggml_add_inplace(
  4122. struct ggml_context * ctx,
  4123. struct ggml_tensor * a,
  4124. struct ggml_tensor * b) {
  4125. return ggml_add_impl(ctx, a, b, true);
  4126. }
  4127. // ggml_add_cast
  4128. static struct ggml_tensor * ggml_add_cast_impl(
  4129. struct ggml_context * ctx,
  4130. struct ggml_tensor * a,
  4131. struct ggml_tensor * b,
  4132. enum ggml_type type) {
  4133. // TODO: support less-strict constraint
  4134. // GGML_ASSERT(ggml_can_repeat(b, a));
  4135. GGML_ASSERT(ggml_can_repeat_rows(b, a));
  4136. // currently only supported for quantized input and f16
  4137. GGML_ASSERT(ggml_is_quantized(a->type) ||
  4138. a->type == GGML_TYPE_F16 ||
  4139. a->type == GGML_TYPE_BF16);
  4140. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  4141. result->op = GGML_OP_ADD;
  4142. result->src[0] = a;
  4143. result->src[1] = b;
  4144. return result;
  4145. }
  4146. struct ggml_tensor * ggml_add_cast(
  4147. struct ggml_context * ctx,
  4148. struct ggml_tensor * a,
  4149. struct ggml_tensor * b,
  4150. enum ggml_type type) {
  4151. return ggml_add_cast_impl(ctx, a, b, type);
  4152. }
  4153. // ggml_add1
  4154. static struct ggml_tensor * ggml_add1_impl(
  4155. struct ggml_context * ctx,
  4156. struct ggml_tensor * a,
  4157. struct ggml_tensor * b,
  4158. bool inplace) {
  4159. GGML_ASSERT(ggml_is_scalar(b));
  4160. GGML_ASSERT(ggml_is_padded_1d(a));
  4161. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4162. result->op = GGML_OP_ADD1;
  4163. result->src[0] = a;
  4164. result->src[1] = b;
  4165. return result;
  4166. }
  4167. struct ggml_tensor * ggml_add1(
  4168. struct ggml_context * ctx,
  4169. struct ggml_tensor * a,
  4170. struct ggml_tensor * b) {
  4171. return ggml_add1_impl(ctx, a, b, false);
  4172. }
  4173. struct ggml_tensor * ggml_add1_inplace(
  4174. struct ggml_context * ctx,
  4175. struct ggml_tensor * a,
  4176. struct ggml_tensor * b) {
  4177. return ggml_add1_impl(ctx, a, b, true);
  4178. }
  4179. // ggml_acc
  4180. static struct ggml_tensor * ggml_acc_impl(
  4181. struct ggml_context * ctx,
  4182. struct ggml_tensor * a,
  4183. struct ggml_tensor * b,
  4184. size_t nb1,
  4185. size_t nb2,
  4186. size_t nb3,
  4187. size_t offset,
  4188. bool inplace) {
  4189. GGML_ASSERT(ggml_nelements(b) <= ggml_nelements(a));
  4190. GGML_ASSERT(ggml_is_contiguous(a));
  4191. GGML_ASSERT(a->type == GGML_TYPE_F32);
  4192. GGML_ASSERT(b->type == GGML_TYPE_F32);
  4193. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4194. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  4195. ggml_set_op_params(result, params, sizeof(params));
  4196. result->op = GGML_OP_ACC;
  4197. result->src[0] = a;
  4198. result->src[1] = b;
  4199. return result;
  4200. }
  4201. struct ggml_tensor * ggml_acc(
  4202. struct ggml_context * ctx,
  4203. struct ggml_tensor * a,
  4204. struct ggml_tensor * b,
  4205. size_t nb1,
  4206. size_t nb2,
  4207. size_t nb3,
  4208. size_t offset) {
  4209. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  4210. }
  4211. struct ggml_tensor * ggml_acc_inplace(
  4212. struct ggml_context * ctx,
  4213. struct ggml_tensor * a,
  4214. struct ggml_tensor * b,
  4215. size_t nb1,
  4216. size_t nb2,
  4217. size_t nb3,
  4218. size_t offset) {
  4219. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  4220. }
  4221. // ggml_sub
  4222. static struct ggml_tensor * ggml_sub_impl(
  4223. struct ggml_context * ctx,
  4224. struct ggml_tensor * a,
  4225. struct ggml_tensor * b,
  4226. bool inplace) {
  4227. GGML_ASSERT(ggml_can_repeat(b, a));
  4228. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4229. result->op = GGML_OP_SUB;
  4230. result->src[0] = a;
  4231. result->src[1] = b;
  4232. return result;
  4233. }
  4234. struct ggml_tensor * ggml_sub(
  4235. struct ggml_context * ctx,
  4236. struct ggml_tensor * a,
  4237. struct ggml_tensor * b) {
  4238. return ggml_sub_impl(ctx, a, b, false);
  4239. }
  4240. struct ggml_tensor * ggml_sub_inplace(
  4241. struct ggml_context * ctx,
  4242. struct ggml_tensor * a,
  4243. struct ggml_tensor * b) {
  4244. return ggml_sub_impl(ctx, a, b, true);
  4245. }
  4246. // ggml_mul
  4247. static struct ggml_tensor * ggml_mul_impl(
  4248. struct ggml_context * ctx,
  4249. struct ggml_tensor * a,
  4250. struct ggml_tensor * b,
  4251. bool inplace) {
  4252. GGML_ASSERT(ggml_can_repeat(b, a));
  4253. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4254. result->op = GGML_OP_MUL;
  4255. result->src[0] = a;
  4256. result->src[1] = b;
  4257. return result;
  4258. }
  4259. struct ggml_tensor * ggml_mul(
  4260. struct ggml_context * ctx,
  4261. struct ggml_tensor * a,
  4262. struct ggml_tensor * b) {
  4263. return ggml_mul_impl(ctx, a, b, false);
  4264. }
  4265. struct ggml_tensor * ggml_mul_inplace(
  4266. struct ggml_context * ctx,
  4267. struct ggml_tensor * a,
  4268. struct ggml_tensor * b) {
  4269. return ggml_mul_impl(ctx, a, b, true);
  4270. }
  4271. // ggml_div
  4272. static struct ggml_tensor * ggml_div_impl(
  4273. struct ggml_context * ctx,
  4274. struct ggml_tensor * a,
  4275. struct ggml_tensor * b,
  4276. bool inplace) {
  4277. GGML_ASSERT(ggml_can_repeat(b, a));
  4278. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4279. result->op = GGML_OP_DIV;
  4280. result->src[0] = a;
  4281. result->src[1] = b;
  4282. return result;
  4283. }
  4284. struct ggml_tensor * ggml_div(
  4285. struct ggml_context * ctx,
  4286. struct ggml_tensor * a,
  4287. struct ggml_tensor * b) {
  4288. return ggml_div_impl(ctx, a, b, false);
  4289. }
  4290. struct ggml_tensor * ggml_div_inplace(
  4291. struct ggml_context * ctx,
  4292. struct ggml_tensor * a,
  4293. struct ggml_tensor * b) {
  4294. return ggml_div_impl(ctx, a, b, true);
  4295. }
  4296. // ggml_sqr
  4297. static struct ggml_tensor * ggml_sqr_impl(
  4298. struct ggml_context * ctx,
  4299. struct ggml_tensor * a,
  4300. bool inplace) {
  4301. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4302. result->op = GGML_OP_SQR;
  4303. result->src[0] = a;
  4304. return result;
  4305. }
  4306. struct ggml_tensor * ggml_sqr(
  4307. struct ggml_context * ctx,
  4308. struct ggml_tensor * a) {
  4309. return ggml_sqr_impl(ctx, a, false);
  4310. }
  4311. struct ggml_tensor * ggml_sqr_inplace(
  4312. struct ggml_context * ctx,
  4313. struct ggml_tensor * a) {
  4314. return ggml_sqr_impl(ctx, a, true);
  4315. }
  4316. // ggml_sqrt
  4317. static struct ggml_tensor * ggml_sqrt_impl(
  4318. struct ggml_context * ctx,
  4319. struct ggml_tensor * a,
  4320. bool inplace) {
  4321. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4322. result->op = GGML_OP_SQRT;
  4323. result->src[0] = a;
  4324. return result;
  4325. }
  4326. struct ggml_tensor * ggml_sqrt(
  4327. struct ggml_context * ctx,
  4328. struct ggml_tensor * a) {
  4329. return ggml_sqrt_impl(ctx, a, false);
  4330. }
  4331. struct ggml_tensor * ggml_sqrt_inplace(
  4332. struct ggml_context * ctx,
  4333. struct ggml_tensor * a) {
  4334. return ggml_sqrt_impl(ctx, a, true);
  4335. }
  4336. // ggml_log
  4337. static struct ggml_tensor * ggml_log_impl(
  4338. struct ggml_context * ctx,
  4339. struct ggml_tensor * a,
  4340. bool inplace) {
  4341. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4342. result->op = GGML_OP_LOG;
  4343. result->src[0] = a;
  4344. return result;
  4345. }
  4346. struct ggml_tensor * ggml_log(
  4347. struct ggml_context * ctx,
  4348. struct ggml_tensor * a) {
  4349. return ggml_log_impl(ctx, a, false);
  4350. }
  4351. struct ggml_tensor * ggml_log_inplace(
  4352. struct ggml_context * ctx,
  4353. struct ggml_tensor * a) {
  4354. return ggml_log_impl(ctx, a, true);
  4355. }
  4356. // ggml_sin
  4357. static struct ggml_tensor * ggml_sin_impl(
  4358. struct ggml_context * ctx,
  4359. struct ggml_tensor * a,
  4360. bool inplace) {
  4361. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4362. result->op = GGML_OP_SIN;
  4363. result->src[0] = a;
  4364. return result;
  4365. }
  4366. struct ggml_tensor * ggml_sin(
  4367. struct ggml_context * ctx,
  4368. struct ggml_tensor * a) {
  4369. return ggml_sin_impl(ctx, a, false);
  4370. }
  4371. struct ggml_tensor * ggml_sin_inplace(
  4372. struct ggml_context * ctx,
  4373. struct ggml_tensor * a) {
  4374. return ggml_sin_impl(ctx, a, true);
  4375. }
  4376. // ggml_cos
  4377. static struct ggml_tensor * ggml_cos_impl(
  4378. struct ggml_context * ctx,
  4379. struct ggml_tensor * a,
  4380. bool inplace) {
  4381. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4382. result->op = GGML_OP_COS;
  4383. result->src[0] = a;
  4384. return result;
  4385. }
  4386. struct ggml_tensor * ggml_cos(
  4387. struct ggml_context * ctx,
  4388. struct ggml_tensor * a) {
  4389. return ggml_cos_impl(ctx, a, false);
  4390. }
  4391. struct ggml_tensor * ggml_cos_inplace(
  4392. struct ggml_context * ctx,
  4393. struct ggml_tensor * a) {
  4394. return ggml_cos_impl(ctx, a, true);
  4395. }
  4396. // ggml_sum
  4397. struct ggml_tensor * ggml_sum(
  4398. struct ggml_context * ctx,
  4399. struct ggml_tensor * a) {
  4400. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  4401. result->op = GGML_OP_SUM;
  4402. result->src[0] = a;
  4403. return result;
  4404. }
  4405. // ggml_sum_rows
  4406. struct ggml_tensor * ggml_sum_rows(
  4407. struct ggml_context * ctx,
  4408. struct ggml_tensor * a) {
  4409. int64_t ne[GGML_MAX_DIMS] = { 1 };
  4410. for (int i = 1; i < GGML_MAX_DIMS; ++i) {
  4411. ne[i] = a->ne[i];
  4412. }
  4413. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  4414. result->op = GGML_OP_SUM_ROWS;
  4415. result->src[0] = a;
  4416. return result;
  4417. }
  4418. // ggml_mean
  4419. struct ggml_tensor * ggml_mean(
  4420. struct ggml_context * ctx,
  4421. struct ggml_tensor * a) {
  4422. int64_t ne[4] = { 1, a->ne[1], a->ne[2], a->ne[3] };
  4423. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  4424. result->op = GGML_OP_MEAN;
  4425. result->src[0] = a;
  4426. return result;
  4427. }
  4428. // ggml_argmax
  4429. struct ggml_tensor * ggml_argmax(
  4430. struct ggml_context * ctx,
  4431. struct ggml_tensor * a) {
  4432. GGML_ASSERT(ggml_is_matrix(a));
  4433. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, a->ne[1]);
  4434. result->op = GGML_OP_ARGMAX;
  4435. result->src[0] = a;
  4436. return result;
  4437. }
  4438. // ggml_repeat
  4439. struct ggml_tensor * ggml_repeat(
  4440. struct ggml_context * ctx,
  4441. struct ggml_tensor * a,
  4442. struct ggml_tensor * b) {
  4443. GGML_ASSERT(ggml_can_repeat(a, b));
  4444. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  4445. result->op = GGML_OP_REPEAT;
  4446. result->src[0] = a;
  4447. return result;
  4448. }
  4449. // ggml_repeat_back
  4450. struct ggml_tensor * ggml_repeat_back(
  4451. struct ggml_context * ctx,
  4452. struct ggml_tensor * a,
  4453. struct ggml_tensor * b) {
  4454. GGML_ASSERT(ggml_can_repeat(b, a));
  4455. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  4456. result->op = GGML_OP_REPEAT_BACK;
  4457. result->src[0] = a;
  4458. return result;
  4459. }
  4460. // ggml_concat
  4461. struct ggml_tensor * ggml_concat(
  4462. struct ggml_context * ctx,
  4463. struct ggml_tensor * a,
  4464. struct ggml_tensor * b,
  4465. int dim) {
  4466. GGML_ASSERT(dim >= 0 && dim < GGML_MAX_DIMS);
  4467. int64_t ne[GGML_MAX_DIMS];
  4468. for (int d = 0; d < GGML_MAX_DIMS; ++d) {
  4469. if (d == dim) {
  4470. ne[d] = a->ne[d] + b->ne[d];
  4471. continue;
  4472. }
  4473. GGML_ASSERT(a->ne[d] == b->ne[d]);
  4474. ne[d] = a->ne[d];
  4475. }
  4476. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  4477. ggml_set_op_params_i32(result, 0, dim);
  4478. result->op = GGML_OP_CONCAT;
  4479. result->src[0] = a;
  4480. result->src[1] = b;
  4481. return result;
  4482. }
  4483. // ggml_abs
  4484. struct ggml_tensor * ggml_abs(
  4485. struct ggml_context * ctx,
  4486. struct ggml_tensor * a) {
  4487. return ggml_unary(ctx, a, GGML_UNARY_OP_ABS);
  4488. }
  4489. struct ggml_tensor * ggml_abs_inplace(
  4490. struct ggml_context * ctx,
  4491. struct ggml_tensor * a) {
  4492. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ABS);
  4493. }
  4494. // ggml_sgn
  4495. struct ggml_tensor * ggml_sgn(
  4496. struct ggml_context * ctx,
  4497. struct ggml_tensor * a) {
  4498. return ggml_unary(ctx, a, GGML_UNARY_OP_SGN);
  4499. }
  4500. struct ggml_tensor * ggml_sgn_inplace(
  4501. struct ggml_context * ctx,
  4502. struct ggml_tensor * a) {
  4503. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SGN);
  4504. }
  4505. // ggml_neg
  4506. struct ggml_tensor * ggml_neg(
  4507. struct ggml_context * ctx,
  4508. struct ggml_tensor * a) {
  4509. return ggml_unary(ctx, a, GGML_UNARY_OP_NEG);
  4510. }
  4511. struct ggml_tensor * ggml_neg_inplace(
  4512. struct ggml_context * ctx,
  4513. struct ggml_tensor * a) {
  4514. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_NEG);
  4515. }
  4516. // ggml_step
  4517. struct ggml_tensor * ggml_step(
  4518. struct ggml_context * ctx,
  4519. struct ggml_tensor * a) {
  4520. return ggml_unary(ctx, a, GGML_UNARY_OP_STEP);
  4521. }
  4522. struct ggml_tensor * ggml_step_inplace(
  4523. struct ggml_context * ctx,
  4524. struct ggml_tensor * a) {
  4525. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_STEP);
  4526. }
  4527. // ggml_tanh
  4528. struct ggml_tensor * ggml_tanh(
  4529. struct ggml_context * ctx,
  4530. struct ggml_tensor * a) {
  4531. return ggml_unary(ctx, a, GGML_UNARY_OP_TANH);
  4532. }
  4533. struct ggml_tensor * ggml_tanh_inplace(
  4534. struct ggml_context * ctx,
  4535. struct ggml_tensor * a) {
  4536. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_TANH);
  4537. }
  4538. // ggml_elu
  4539. struct ggml_tensor * ggml_elu(
  4540. struct ggml_context * ctx,
  4541. struct ggml_tensor * a) {
  4542. return ggml_unary(ctx, a, GGML_UNARY_OP_ELU);
  4543. }
  4544. struct ggml_tensor * ggml_elu_inplace(
  4545. struct ggml_context * ctx,
  4546. struct ggml_tensor * a) {
  4547. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ELU);
  4548. }
  4549. // ggml_relu
  4550. struct ggml_tensor * ggml_relu(
  4551. struct ggml_context * ctx,
  4552. struct ggml_tensor * a) {
  4553. return ggml_unary(ctx, a, GGML_UNARY_OP_RELU);
  4554. }
  4555. struct ggml_tensor * ggml_relu_inplace(
  4556. struct ggml_context * ctx,
  4557. struct ggml_tensor * a) {
  4558. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_RELU);
  4559. }
  4560. // ggml_leaky_relu
  4561. struct ggml_tensor * ggml_leaky_relu(
  4562. struct ggml_context * ctx,
  4563. struct ggml_tensor * a,
  4564. float negative_slope,
  4565. bool inplace) {
  4566. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4567. ggml_set_op_params(result, &negative_slope, sizeof(negative_slope));
  4568. result->op = GGML_OP_LEAKY_RELU;
  4569. result->src[0] = a;
  4570. return result;
  4571. }
  4572. // ggml_sigmoid
  4573. struct ggml_tensor * ggml_sigmoid(
  4574. struct ggml_context * ctx,
  4575. struct ggml_tensor * a) {
  4576. return ggml_unary(ctx, a, GGML_UNARY_OP_SIGMOID);
  4577. }
  4578. struct ggml_tensor * ggml_sigmoid_inplace(
  4579. struct ggml_context * ctx,
  4580. struct ggml_tensor * a) {
  4581. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SIGMOID);
  4582. }
  4583. // ggml_gelu
  4584. struct ggml_tensor * ggml_gelu(
  4585. struct ggml_context * ctx,
  4586. struct ggml_tensor * a) {
  4587. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU);
  4588. }
  4589. struct ggml_tensor * ggml_gelu_inplace(
  4590. struct ggml_context * ctx,
  4591. struct ggml_tensor * a) {
  4592. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU);
  4593. }
  4594. // ggml_gelu_quick
  4595. struct ggml_tensor * ggml_gelu_quick(
  4596. struct ggml_context * ctx,
  4597. struct ggml_tensor * a) {
  4598. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  4599. }
  4600. struct ggml_tensor * ggml_gelu_quick_inplace(
  4601. struct ggml_context * ctx,
  4602. struct ggml_tensor * a) {
  4603. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  4604. }
  4605. // ggml_silu
  4606. struct ggml_tensor * ggml_silu(
  4607. struct ggml_context * ctx,
  4608. struct ggml_tensor * a) {
  4609. return ggml_unary(ctx, a, GGML_UNARY_OP_SILU);
  4610. }
  4611. struct ggml_tensor * ggml_silu_inplace(
  4612. struct ggml_context * ctx,
  4613. struct ggml_tensor * a) {
  4614. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SILU);
  4615. }
  4616. // ggml_silu_back
  4617. struct ggml_tensor * ggml_silu_back(
  4618. struct ggml_context * ctx,
  4619. struct ggml_tensor * a,
  4620. struct ggml_tensor * b) {
  4621. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  4622. result->op = GGML_OP_SILU_BACK;
  4623. result->src[0] = a;
  4624. result->src[1] = b;
  4625. return result;
  4626. }
  4627. // ggml hardswish
  4628. struct ggml_tensor * ggml_hardswish(
  4629. struct ggml_context * ctx,
  4630. struct ggml_tensor * a) {
  4631. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSWISH);
  4632. }
  4633. // ggml hardsigmoid
  4634. struct ggml_tensor * ggml_hardsigmoid(
  4635. struct ggml_context * ctx,
  4636. struct ggml_tensor * a) {
  4637. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSIGMOID);
  4638. }
  4639. // ggml exp
  4640. struct ggml_tensor * ggml_exp(
  4641. struct ggml_context * ctx,
  4642. struct ggml_tensor * a) {
  4643. return ggml_unary(ctx, a, GGML_UNARY_OP_EXP);
  4644. }
  4645. struct ggml_tensor * ggml_exp_inplace(
  4646. struct ggml_context * ctx,
  4647. struct ggml_tensor * a) {
  4648. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_EXP);
  4649. }
  4650. // ggml_norm
  4651. static struct ggml_tensor * ggml_norm_impl(
  4652. struct ggml_context * ctx,
  4653. struct ggml_tensor * a,
  4654. float eps,
  4655. bool inplace) {
  4656. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4657. ggml_set_op_params(result, &eps, sizeof(eps));
  4658. result->op = GGML_OP_NORM;
  4659. result->src[0] = a;
  4660. return result;
  4661. }
  4662. struct ggml_tensor * ggml_norm(
  4663. struct ggml_context * ctx,
  4664. struct ggml_tensor * a,
  4665. float eps) {
  4666. return ggml_norm_impl(ctx, a, eps, false);
  4667. }
  4668. struct ggml_tensor * ggml_norm_inplace(
  4669. struct ggml_context * ctx,
  4670. struct ggml_tensor * a,
  4671. float eps) {
  4672. return ggml_norm_impl(ctx, a, eps, true);
  4673. }
  4674. // ggml_rms_norm
  4675. static struct ggml_tensor * ggml_rms_norm_impl(
  4676. struct ggml_context * ctx,
  4677. struct ggml_tensor * a,
  4678. float eps,
  4679. bool inplace) {
  4680. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4681. ggml_set_op_params(result, &eps, sizeof(eps));
  4682. result->op = GGML_OP_RMS_NORM;
  4683. result->src[0] = a;
  4684. return result;
  4685. }
  4686. struct ggml_tensor * ggml_rms_norm(
  4687. struct ggml_context * ctx,
  4688. struct ggml_tensor * a,
  4689. float eps) {
  4690. return ggml_rms_norm_impl(ctx, a, eps, false);
  4691. }
  4692. struct ggml_tensor * ggml_rms_norm_inplace(
  4693. struct ggml_context * ctx,
  4694. struct ggml_tensor * a,
  4695. float eps) {
  4696. return ggml_rms_norm_impl(ctx, a, eps, true);
  4697. }
  4698. // ggml_rms_norm_back
  4699. struct ggml_tensor * ggml_rms_norm_back(
  4700. struct ggml_context * ctx,
  4701. struct ggml_tensor * a,
  4702. struct ggml_tensor * b,
  4703. float eps) {
  4704. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  4705. ggml_set_op_params(result, &eps, sizeof(eps));
  4706. result->op = GGML_OP_RMS_NORM_BACK;
  4707. result->src[0] = a;
  4708. result->src[1] = b;
  4709. return result;
  4710. }
  4711. // ggml_group_norm
  4712. static struct ggml_tensor * ggml_group_norm_impl(
  4713. struct ggml_context * ctx,
  4714. struct ggml_tensor * a,
  4715. int n_groups,
  4716. float eps,
  4717. bool inplace) {
  4718. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4719. ggml_set_op_params_i32(result, 0, n_groups);
  4720. ggml_set_op_params_f32(result, 1, eps);
  4721. result->op = GGML_OP_GROUP_NORM;
  4722. result->src[0] = a;
  4723. return result;
  4724. }
  4725. struct ggml_tensor * ggml_group_norm(
  4726. struct ggml_context * ctx,
  4727. struct ggml_tensor * a,
  4728. int n_groups,
  4729. float eps) {
  4730. return ggml_group_norm_impl(ctx, a, n_groups, eps, false);
  4731. }
  4732. struct ggml_tensor * ggml_group_norm_inplace(
  4733. struct ggml_context * ctx,
  4734. struct ggml_tensor * a,
  4735. int n_groups,
  4736. float eps) {
  4737. return ggml_group_norm_impl(ctx, a, n_groups, eps, true);
  4738. }
  4739. // ggml_mul_mat
  4740. struct ggml_tensor * ggml_mul_mat(
  4741. struct ggml_context * ctx,
  4742. struct ggml_tensor * a,
  4743. struct ggml_tensor * b) {
  4744. GGML_ASSERT(ggml_can_mul_mat(a, b));
  4745. GGML_ASSERT(!ggml_is_transposed(a));
  4746. const int64_t ne[4] = { a->ne[1], b->ne[1], b->ne[2], b->ne[3] };
  4747. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  4748. result->op = GGML_OP_MUL_MAT;
  4749. result->src[0] = a;
  4750. result->src[1] = b;
  4751. return result;
  4752. }
  4753. void ggml_mul_mat_set_prec(
  4754. struct ggml_tensor * a,
  4755. enum ggml_prec prec) {
  4756. GGML_ASSERT(a->op == GGML_OP_MUL_MAT);
  4757. const int32_t prec_i32 = (int32_t) prec;
  4758. ggml_set_op_params_i32(a, 0, prec_i32);
  4759. }
  4760. // ggml_mul_mat_id
  4761. /*
  4762. c = ggml_mul_mat_id(ctx, as, b, ids);
  4763. as -> [cols, rows, n_expert]
  4764. ids -> [n_experts_used, n_tokens] (i32)
  4765. b -> [cols, n_expert_used, n_tokens]
  4766. c -> [rows, n_expert_used, n_tokens]
  4767. in b, n_experts_used can be broadcasted to match the n_expert_used of ids
  4768. c ~= as[:,:,i] @ b[:,i%r,t], i = ids[e,t] for all e,t in ids
  4769. */
  4770. struct ggml_tensor * ggml_mul_mat_id(
  4771. struct ggml_context * ctx,
  4772. struct ggml_tensor * as,
  4773. struct ggml_tensor * b,
  4774. struct ggml_tensor * ids) {
  4775. GGML_ASSERT(!ggml_is_transposed(as));
  4776. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  4777. GGML_ASSERT(as->ne[3] == 1); // as is 3d (one matrix per expert)
  4778. GGML_ASSERT(b->ne[3] == 1); // b is 3d
  4779. GGML_ASSERT(ids->ne[2] == 1 && ids->ne[3] == 1); // ids is 2d
  4780. GGML_ASSERT(ids->ne[1] == b->ne[2]); // must have an expert list per b row
  4781. GGML_ASSERT(as->ne[0] == b->ne[0]); // can_mul_mat
  4782. GGML_ASSERT(ids->ne[0] % b->ne[1] == 0); // can broadcast
  4783. const int64_t ne[4] = { as->ne[1], ids->ne[0], b->ne[2], 1 };
  4784. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  4785. result->op = GGML_OP_MUL_MAT_ID;
  4786. result->src[0] = as;
  4787. result->src[1] = b;
  4788. result->src[2] = ids;
  4789. return result;
  4790. }
  4791. // ggml_out_prod
  4792. struct ggml_tensor * ggml_out_prod(
  4793. struct ggml_context * ctx,
  4794. struct ggml_tensor * a,
  4795. struct ggml_tensor * b) {
  4796. GGML_ASSERT(ggml_can_out_prod(a, b));
  4797. GGML_ASSERT(!ggml_is_transposed(a));
  4798. // a is broadcastable to b for ne[2] and ne[3] -> use b->ne[2] and b->ne[3]
  4799. const int64_t ne[4] = { a->ne[0], b->ne[0], b->ne[2], b->ne[3] };
  4800. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  4801. result->op = GGML_OP_OUT_PROD;
  4802. result->src[0] = a;
  4803. result->src[1] = b;
  4804. return result;
  4805. }
  4806. // ggml_scale
  4807. static struct ggml_tensor * ggml_scale_impl(
  4808. struct ggml_context * ctx,
  4809. struct ggml_tensor * a,
  4810. float s,
  4811. bool inplace) {
  4812. GGML_ASSERT(ggml_is_padded_1d(a));
  4813. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4814. ggml_set_op_params(result, &s, sizeof(s));
  4815. result->op = GGML_OP_SCALE;
  4816. result->src[0] = a;
  4817. return result;
  4818. }
  4819. struct ggml_tensor * ggml_scale(
  4820. struct ggml_context * ctx,
  4821. struct ggml_tensor * a,
  4822. float s) {
  4823. return ggml_scale_impl(ctx, a, s, false);
  4824. }
  4825. struct ggml_tensor * ggml_scale_inplace(
  4826. struct ggml_context * ctx,
  4827. struct ggml_tensor * a,
  4828. float s) {
  4829. return ggml_scale_impl(ctx, a, s, true);
  4830. }
  4831. // ggml_set
  4832. static struct ggml_tensor * ggml_set_impl(
  4833. struct ggml_context * ctx,
  4834. struct ggml_tensor * a,
  4835. struct ggml_tensor * b,
  4836. size_t nb1,
  4837. size_t nb2,
  4838. size_t nb3,
  4839. size_t offset,
  4840. bool inplace) {
  4841. GGML_ASSERT(ggml_nelements(a) >= ggml_nelements(b));
  4842. // make a view of the destination
  4843. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4844. GGML_ASSERT(offset < (size_t)(1 << 30));
  4845. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  4846. ggml_set_op_params(result, params, sizeof(params));
  4847. result->op = GGML_OP_SET;
  4848. result->src[0] = a;
  4849. result->src[1] = b;
  4850. return result;
  4851. }
  4852. struct ggml_tensor * ggml_set(
  4853. struct ggml_context * ctx,
  4854. struct ggml_tensor * a,
  4855. struct ggml_tensor * b,
  4856. size_t nb1,
  4857. size_t nb2,
  4858. size_t nb3,
  4859. size_t offset) {
  4860. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  4861. }
  4862. struct ggml_tensor * ggml_set_inplace(
  4863. struct ggml_context * ctx,
  4864. struct ggml_tensor * a,
  4865. struct ggml_tensor * b,
  4866. size_t nb1,
  4867. size_t nb2,
  4868. size_t nb3,
  4869. size_t offset) {
  4870. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  4871. }
  4872. struct ggml_tensor * ggml_set_1d(
  4873. struct ggml_context * ctx,
  4874. struct ggml_tensor * a,
  4875. struct ggml_tensor * b,
  4876. size_t offset) {
  4877. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, false);
  4878. }
  4879. struct ggml_tensor * ggml_set_1d_inplace(
  4880. struct ggml_context * ctx,
  4881. struct ggml_tensor * a,
  4882. struct ggml_tensor * b,
  4883. size_t offset) {
  4884. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, true);
  4885. }
  4886. struct ggml_tensor * ggml_set_2d(
  4887. struct ggml_context * ctx,
  4888. struct ggml_tensor * a,
  4889. struct ggml_tensor * b,
  4890. size_t nb1,
  4891. size_t offset) {
  4892. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, false);
  4893. }
  4894. struct ggml_tensor * ggml_set_2d_inplace(
  4895. struct ggml_context * ctx,
  4896. struct ggml_tensor * a,
  4897. struct ggml_tensor * b,
  4898. size_t nb1,
  4899. size_t offset) {
  4900. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, true);
  4901. }
  4902. // ggml_cpy
  4903. static struct ggml_tensor * ggml_cpy_impl(
  4904. struct ggml_context * ctx,
  4905. struct ggml_tensor * a,
  4906. struct ggml_tensor * b) {
  4907. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  4908. // make a view of the destination
  4909. struct ggml_tensor * result = ggml_view_tensor(ctx, b);
  4910. if (strlen(b->name) > 0) {
  4911. ggml_format_name(result, "%s (copy of %s)", b->name, a->name);
  4912. } else {
  4913. ggml_format_name(result, "%s (copy)", a->name);
  4914. }
  4915. result->op = GGML_OP_CPY;
  4916. result->src[0] = a;
  4917. result->src[1] = b;
  4918. return result;
  4919. }
  4920. struct ggml_tensor * ggml_cpy(
  4921. struct ggml_context * ctx,
  4922. struct ggml_tensor * a,
  4923. struct ggml_tensor * b) {
  4924. return ggml_cpy_impl(ctx, a, b);
  4925. }
  4926. struct ggml_tensor * ggml_cast(
  4927. struct ggml_context * ctx,
  4928. struct ggml_tensor * a,
  4929. enum ggml_type type) {
  4930. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  4931. ggml_format_name(result, "%s (copy)", a->name);
  4932. result->op = GGML_OP_CPY;
  4933. result->src[0] = a;
  4934. result->src[1] = result;
  4935. return result;
  4936. }
  4937. // ggml_cont
  4938. static struct ggml_tensor * ggml_cont_impl(
  4939. struct ggml_context * ctx,
  4940. struct ggml_tensor * a) {
  4941. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  4942. ggml_format_name(result, "%s (cont)", a->name);
  4943. result->op = GGML_OP_CONT;
  4944. result->src[0] = a;
  4945. return result;
  4946. }
  4947. struct ggml_tensor * ggml_cont(
  4948. struct ggml_context * ctx,
  4949. struct ggml_tensor * a) {
  4950. return ggml_cont_impl(ctx, a);
  4951. }
  4952. // make contiguous, with new shape
  4953. GGML_API struct ggml_tensor * ggml_cont_1d(
  4954. struct ggml_context * ctx,
  4955. struct ggml_tensor * a,
  4956. int64_t ne0) {
  4957. return ggml_cont_4d(ctx, a, ne0, 1, 1, 1);
  4958. }
  4959. GGML_API struct ggml_tensor * ggml_cont_2d(
  4960. struct ggml_context * ctx,
  4961. struct ggml_tensor * a,
  4962. int64_t ne0,
  4963. int64_t ne1) {
  4964. return ggml_cont_4d(ctx, a, ne0, ne1, 1, 1);
  4965. }
  4966. GGML_API struct ggml_tensor * ggml_cont_3d(
  4967. struct ggml_context * ctx,
  4968. struct ggml_tensor * a,
  4969. int64_t ne0,
  4970. int64_t ne1,
  4971. int64_t ne2) {
  4972. return ggml_cont_4d(ctx, a, ne0, ne1, ne2, 1);
  4973. }
  4974. struct ggml_tensor * ggml_cont_4d(
  4975. struct ggml_context * ctx,
  4976. struct ggml_tensor * a,
  4977. int64_t ne0,
  4978. int64_t ne1,
  4979. int64_t ne2,
  4980. int64_t ne3) {
  4981. GGML_ASSERT(ggml_nelements(a) == (ne0*ne1*ne2*ne3));
  4982. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  4983. ggml_format_name(result, "%s (cont)", a->name);
  4984. result->op = GGML_OP_CONT;
  4985. result->src[0] = a;
  4986. return result;
  4987. }
  4988. // ggml_reshape
  4989. struct ggml_tensor * ggml_reshape(
  4990. struct ggml_context * ctx,
  4991. struct ggml_tensor * a,
  4992. struct ggml_tensor * b) {
  4993. GGML_ASSERT(ggml_is_contiguous(a));
  4994. // as only the shape of b is relevant, and not its memory layout, b is allowed to be non contiguous.
  4995. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  4996. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, GGML_MAX_DIMS, b->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_1d(
  5003. struct ggml_context * ctx,
  5004. struct ggml_tensor * a,
  5005. int64_t ne0) {
  5006. GGML_ASSERT(ggml_is_contiguous(a));
  5007. GGML_ASSERT(ggml_nelements(a) == ne0);
  5008. const int64_t ne[1] = { ne0 };
  5009. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 1, ne, a, 0);
  5010. ggml_format_name(result, "%s (reshaped)", a->name);
  5011. result->op = GGML_OP_RESHAPE;
  5012. result->src[0] = a;
  5013. return result;
  5014. }
  5015. struct ggml_tensor * ggml_reshape_2d(
  5016. struct ggml_context * ctx,
  5017. struct ggml_tensor * a,
  5018. int64_t ne0,
  5019. int64_t ne1) {
  5020. GGML_ASSERT(ggml_is_contiguous(a));
  5021. GGML_ASSERT(ggml_nelements(a) == ne0*ne1);
  5022. const int64_t ne[2] = { ne0, ne1 };
  5023. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, a, 0);
  5024. ggml_format_name(result, "%s (reshaped)", a->name);
  5025. result->op = GGML_OP_RESHAPE;
  5026. result->src[0] = a;
  5027. return result;
  5028. }
  5029. struct ggml_tensor * ggml_reshape_3d(
  5030. struct ggml_context * ctx,
  5031. struct ggml_tensor * a,
  5032. int64_t ne0,
  5033. int64_t ne1,
  5034. int64_t ne2) {
  5035. GGML_ASSERT(ggml_is_contiguous(a));
  5036. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2);
  5037. const int64_t ne[3] = { ne0, ne1, ne2 };
  5038. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 3, ne, a, 0);
  5039. ggml_format_name(result, "%s (reshaped)", a->name);
  5040. result->op = GGML_OP_RESHAPE;
  5041. result->src[0] = a;
  5042. return result;
  5043. }
  5044. struct ggml_tensor * ggml_reshape_4d(
  5045. struct ggml_context * ctx,
  5046. struct ggml_tensor * a,
  5047. int64_t ne0,
  5048. int64_t ne1,
  5049. int64_t ne2,
  5050. int64_t ne3) {
  5051. GGML_ASSERT(ggml_is_contiguous(a));
  5052. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2*ne3);
  5053. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  5054. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 4, ne, a, 0);
  5055. ggml_format_name(result, "%s (reshaped)", a->name);
  5056. result->op = GGML_OP_RESHAPE;
  5057. result->src[0] = a;
  5058. return result;
  5059. }
  5060. static struct ggml_tensor * ggml_view_impl(
  5061. struct ggml_context * ctx,
  5062. struct ggml_tensor * a,
  5063. int n_dims,
  5064. const int64_t * ne,
  5065. size_t offset) {
  5066. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, n_dims, ne, a, offset);
  5067. ggml_format_name(result, "%s (view)", a->name);
  5068. ggml_set_op_params(result, &offset, sizeof(offset));
  5069. result->op = GGML_OP_VIEW;
  5070. result->src[0] = a;
  5071. return result;
  5072. }
  5073. // ggml_view_1d
  5074. struct ggml_tensor * ggml_view_1d(
  5075. struct ggml_context * ctx,
  5076. struct ggml_tensor * a,
  5077. int64_t ne0,
  5078. size_t offset) {
  5079. struct ggml_tensor * result = ggml_view_impl(ctx, a, 1, &ne0, offset);
  5080. return result;
  5081. }
  5082. // ggml_view_2d
  5083. struct ggml_tensor * ggml_view_2d(
  5084. struct ggml_context * ctx,
  5085. struct ggml_tensor * a,
  5086. int64_t ne0,
  5087. int64_t ne1,
  5088. size_t nb1,
  5089. size_t offset) {
  5090. const int64_t ne[2] = { ne0, ne1 };
  5091. struct ggml_tensor * result = ggml_view_impl(ctx, a, 2, ne, offset);
  5092. result->nb[1] = nb1;
  5093. result->nb[2] = result->nb[1]*ne1;
  5094. result->nb[3] = result->nb[2];
  5095. return result;
  5096. }
  5097. // ggml_view_3d
  5098. struct ggml_tensor * ggml_view_3d(
  5099. struct ggml_context * ctx,
  5100. struct ggml_tensor * a,
  5101. int64_t ne0,
  5102. int64_t ne1,
  5103. int64_t ne2,
  5104. size_t nb1,
  5105. size_t nb2,
  5106. size_t offset) {
  5107. const int64_t ne[3] = { ne0, ne1, ne2 };
  5108. struct ggml_tensor * result = ggml_view_impl(ctx, a, 3, ne, offset);
  5109. result->nb[1] = nb1;
  5110. result->nb[2] = nb2;
  5111. result->nb[3] = result->nb[2]*ne2;
  5112. return result;
  5113. }
  5114. // ggml_view_4d
  5115. struct ggml_tensor * ggml_view_4d(
  5116. struct ggml_context * ctx,
  5117. struct ggml_tensor * a,
  5118. int64_t ne0,
  5119. int64_t ne1,
  5120. int64_t ne2,
  5121. int64_t ne3,
  5122. size_t nb1,
  5123. size_t nb2,
  5124. size_t nb3,
  5125. size_t offset) {
  5126. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  5127. struct ggml_tensor * result = ggml_view_impl(ctx, a, 4, ne, offset);
  5128. result->nb[1] = nb1;
  5129. result->nb[2] = nb2;
  5130. result->nb[3] = nb3;
  5131. return result;
  5132. }
  5133. // ggml_permute
  5134. struct ggml_tensor * ggml_permute(
  5135. struct ggml_context * ctx,
  5136. struct ggml_tensor * a,
  5137. int axis0,
  5138. int axis1,
  5139. int axis2,
  5140. int axis3) {
  5141. GGML_ASSERT(axis0 >= 0 && axis0 < GGML_MAX_DIMS);
  5142. GGML_ASSERT(axis1 >= 0 && axis1 < GGML_MAX_DIMS);
  5143. GGML_ASSERT(axis2 >= 0 && axis2 < GGML_MAX_DIMS);
  5144. GGML_ASSERT(axis3 >= 0 && axis3 < GGML_MAX_DIMS);
  5145. GGML_ASSERT(axis0 != axis1);
  5146. GGML_ASSERT(axis0 != axis2);
  5147. GGML_ASSERT(axis0 != axis3);
  5148. GGML_ASSERT(axis1 != axis2);
  5149. GGML_ASSERT(axis1 != axis3);
  5150. GGML_ASSERT(axis2 != axis3);
  5151. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  5152. ggml_format_name(result, "%s (permuted)", a->name);
  5153. int ne[GGML_MAX_DIMS];
  5154. int nb[GGML_MAX_DIMS];
  5155. ne[axis0] = a->ne[0];
  5156. ne[axis1] = a->ne[1];
  5157. ne[axis2] = a->ne[2];
  5158. ne[axis3] = a->ne[3];
  5159. nb[axis0] = a->nb[0];
  5160. nb[axis1] = a->nb[1];
  5161. nb[axis2] = a->nb[2];
  5162. nb[axis3] = a->nb[3];
  5163. result->ne[0] = ne[0];
  5164. result->ne[1] = ne[1];
  5165. result->ne[2] = ne[2];
  5166. result->ne[3] = ne[3];
  5167. result->nb[0] = nb[0];
  5168. result->nb[1] = nb[1];
  5169. result->nb[2] = nb[2];
  5170. result->nb[3] = nb[3];
  5171. result->op = GGML_OP_PERMUTE;
  5172. result->src[0] = a;
  5173. int32_t params[] = { axis0, axis1, axis2, axis3 };
  5174. ggml_set_op_params(result, params, sizeof(params));
  5175. return result;
  5176. }
  5177. // ggml_transpose
  5178. struct ggml_tensor * ggml_transpose(
  5179. struct ggml_context * ctx,
  5180. struct ggml_tensor * a) {
  5181. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  5182. ggml_format_name(result, "%s (transposed)", a->name);
  5183. result->ne[0] = a->ne[1];
  5184. result->ne[1] = a->ne[0];
  5185. result->nb[0] = a->nb[1];
  5186. result->nb[1] = a->nb[0];
  5187. result->op = GGML_OP_TRANSPOSE;
  5188. result->src[0] = a;
  5189. return result;
  5190. }
  5191. // ggml_get_rows
  5192. struct ggml_tensor * ggml_get_rows(
  5193. struct ggml_context * ctx,
  5194. struct ggml_tensor * a,
  5195. struct ggml_tensor * b) {
  5196. GGML_ASSERT(a->ne[2] == b->ne[1]);
  5197. GGML_ASSERT(b->ne[3] == 1);
  5198. GGML_ASSERT(b->type == GGML_TYPE_I32);
  5199. // TODO: implement non F32 return
  5200. enum ggml_type type = GGML_TYPE_F32;
  5201. if (a->type == GGML_TYPE_I32) {
  5202. type = a->type;
  5203. }
  5204. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, type, a->ne[0], b->ne[0], b->ne[1], b->ne[2]);
  5205. result->op = GGML_OP_GET_ROWS;
  5206. result->src[0] = a;
  5207. result->src[1] = b;
  5208. return result;
  5209. }
  5210. // ggml_get_rows_back
  5211. struct ggml_tensor * ggml_get_rows_back(
  5212. struct ggml_context * ctx,
  5213. struct ggml_tensor * a,
  5214. struct ggml_tensor * b,
  5215. struct ggml_tensor * c) {
  5216. GGML_ASSERT(ggml_is_matrix(a) && ggml_is_vector(b) && b->type == GGML_TYPE_I32);
  5217. GGML_ASSERT(ggml_is_matrix(c) && (a->ne[0] == c->ne[0]));
  5218. // TODO: implement non F32 return
  5219. //struct ggml_tensor * result = ggml_new_tensor_2d(ctx, a->type, a->ne[0], b->ne[0]);
  5220. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, c->ne[0], c->ne[1]);
  5221. result->op = GGML_OP_GET_ROWS_BACK;
  5222. result->src[0] = a;
  5223. result->src[1] = b;
  5224. return result;
  5225. }
  5226. // ggml_diag
  5227. struct ggml_tensor * ggml_diag(
  5228. struct ggml_context * ctx,
  5229. struct ggml_tensor * a) {
  5230. GGML_ASSERT(a->ne[1] == 1);
  5231. const int64_t ne[4] = { a->ne[0], a->ne[0], a->ne[2], a->ne[3] };
  5232. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, 4, ne);
  5233. result->op = GGML_OP_DIAG;
  5234. result->src[0] = a;
  5235. return result;
  5236. }
  5237. // ggml_diag_mask_inf
  5238. static struct ggml_tensor * ggml_diag_mask_inf_impl(
  5239. struct ggml_context * ctx,
  5240. struct ggml_tensor * a,
  5241. int n_past,
  5242. bool inplace) {
  5243. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5244. int32_t params[] = { n_past };
  5245. ggml_set_op_params(result, params, sizeof(params));
  5246. result->op = GGML_OP_DIAG_MASK_INF;
  5247. result->src[0] = a;
  5248. return result;
  5249. }
  5250. struct ggml_tensor * ggml_diag_mask_inf(
  5251. struct ggml_context * ctx,
  5252. struct ggml_tensor * a,
  5253. int n_past) {
  5254. return ggml_diag_mask_inf_impl(ctx, a, n_past, false);
  5255. }
  5256. struct ggml_tensor * ggml_diag_mask_inf_inplace(
  5257. struct ggml_context * ctx,
  5258. struct ggml_tensor * a,
  5259. int n_past) {
  5260. return ggml_diag_mask_inf_impl(ctx, a, n_past, true);
  5261. }
  5262. // ggml_diag_mask_zero
  5263. static struct ggml_tensor * ggml_diag_mask_zero_impl(
  5264. struct ggml_context * ctx,
  5265. struct ggml_tensor * a,
  5266. int n_past,
  5267. bool inplace) {
  5268. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5269. int32_t params[] = { n_past };
  5270. ggml_set_op_params(result, params, sizeof(params));
  5271. result->op = GGML_OP_DIAG_MASK_ZERO;
  5272. result->src[0] = a;
  5273. return result;
  5274. }
  5275. struct ggml_tensor * ggml_diag_mask_zero(
  5276. struct ggml_context * ctx,
  5277. struct ggml_tensor * a,
  5278. int n_past) {
  5279. return ggml_diag_mask_zero_impl(ctx, a, n_past, false);
  5280. }
  5281. struct ggml_tensor * ggml_diag_mask_zero_inplace(
  5282. struct ggml_context * ctx,
  5283. struct ggml_tensor * a,
  5284. int n_past) {
  5285. return ggml_diag_mask_zero_impl(ctx, a, n_past, true);
  5286. }
  5287. // ggml_soft_max
  5288. static struct ggml_tensor * ggml_soft_max_impl(
  5289. struct ggml_context * ctx,
  5290. struct ggml_tensor * a,
  5291. struct ggml_tensor * mask,
  5292. float scale,
  5293. float max_bias,
  5294. bool inplace) {
  5295. GGML_ASSERT(ggml_is_contiguous(a));
  5296. if (mask) {
  5297. GGML_ASSERT(mask->type == GGML_TYPE_F16 || mask->type == GGML_TYPE_F32);
  5298. GGML_ASSERT(ggml_is_contiguous(mask));
  5299. GGML_ASSERT(ggml_is_matrix(mask));
  5300. GGML_ASSERT(mask->ne[0] == a->ne[0]);
  5301. GGML_ASSERT(mask->ne[1] >= a->ne[1]);
  5302. }
  5303. if (max_bias > 0.0f) {
  5304. GGML_ASSERT(mask);
  5305. }
  5306. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5307. float params[] = { scale, max_bias };
  5308. ggml_set_op_params(result, params, sizeof(params));
  5309. result->op = GGML_OP_SOFT_MAX;
  5310. result->src[0] = a;
  5311. result->src[1] = mask;
  5312. return result;
  5313. }
  5314. struct ggml_tensor * ggml_soft_max(
  5315. struct ggml_context * ctx,
  5316. struct ggml_tensor * a) {
  5317. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, false);
  5318. }
  5319. struct ggml_tensor * ggml_soft_max_inplace(
  5320. struct ggml_context * ctx,
  5321. struct ggml_tensor * a) {
  5322. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, true);
  5323. }
  5324. struct ggml_tensor * ggml_soft_max_ext(
  5325. struct ggml_context * ctx,
  5326. struct ggml_tensor * a,
  5327. struct ggml_tensor * mask,
  5328. float scale,
  5329. float max_bias) {
  5330. return ggml_soft_max_impl(ctx, a, mask, scale, max_bias, false);
  5331. }
  5332. // ggml_soft_max_back
  5333. static struct ggml_tensor * ggml_soft_max_back_impl(
  5334. struct ggml_context * ctx,
  5335. struct ggml_tensor * a,
  5336. struct ggml_tensor * b,
  5337. bool inplace) {
  5338. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5339. result->op = GGML_OP_SOFT_MAX_BACK;
  5340. result->src[0] = a;
  5341. result->src[1] = b;
  5342. return result;
  5343. }
  5344. struct ggml_tensor * ggml_soft_max_back(
  5345. struct ggml_context * ctx,
  5346. struct ggml_tensor * a,
  5347. struct ggml_tensor * b) {
  5348. return ggml_soft_max_back_impl(ctx, a, b, false);
  5349. }
  5350. struct ggml_tensor * ggml_soft_max_back_inplace(
  5351. struct ggml_context * ctx,
  5352. struct ggml_tensor * a,
  5353. struct ggml_tensor * b) {
  5354. return ggml_soft_max_back_impl(ctx, a, b, true);
  5355. }
  5356. // ggml_rope
  5357. static struct ggml_tensor * ggml_rope_impl(
  5358. struct ggml_context * ctx,
  5359. struct ggml_tensor * a,
  5360. struct ggml_tensor * b,
  5361. struct ggml_tensor * c,
  5362. int n_dims,
  5363. int mode,
  5364. int n_ctx_orig,
  5365. float freq_base,
  5366. float freq_scale,
  5367. float ext_factor,
  5368. float attn_factor,
  5369. float beta_fast,
  5370. float beta_slow,
  5371. bool inplace) {
  5372. GGML_ASSERT((mode & 1) == 0 && "mode & 1 == 1 is no longer supported");
  5373. GGML_ASSERT(ggml_is_vector(b));
  5374. GGML_ASSERT(b->type == GGML_TYPE_I32);
  5375. GGML_ASSERT(a->ne[2] == b->ne[0]);
  5376. if (c) {
  5377. GGML_ASSERT(c->type == GGML_TYPE_F32);
  5378. GGML_ASSERT(c->ne[0] >= n_dims / 2);
  5379. }
  5380. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  5381. int32_t params[11] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  5382. memcpy(params + 5, &freq_base, sizeof(float));
  5383. memcpy(params + 6, &freq_scale, sizeof(float));
  5384. memcpy(params + 7, &ext_factor, sizeof(float));
  5385. memcpy(params + 8, &attn_factor, sizeof(float));
  5386. memcpy(params + 9, &beta_fast, sizeof(float));
  5387. memcpy(params + 10, &beta_slow, sizeof(float));
  5388. ggml_set_op_params(result, params, sizeof(params));
  5389. result->op = GGML_OP_ROPE;
  5390. result->src[0] = a;
  5391. result->src[1] = b;
  5392. result->src[2] = c;
  5393. return result;
  5394. }
  5395. struct ggml_tensor * ggml_rope(
  5396. struct ggml_context * ctx,
  5397. struct ggml_tensor * a,
  5398. struct ggml_tensor * b,
  5399. int n_dims,
  5400. int mode) {
  5401. return ggml_rope_impl(
  5402. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, false
  5403. );
  5404. }
  5405. struct ggml_tensor * ggml_rope_inplace(
  5406. struct ggml_context * ctx,
  5407. struct ggml_tensor * a,
  5408. struct ggml_tensor * b,
  5409. int n_dims,
  5410. int mode) {
  5411. return ggml_rope_impl(
  5412. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, true
  5413. );
  5414. }
  5415. struct ggml_tensor * ggml_rope_ext(
  5416. struct ggml_context * ctx,
  5417. struct ggml_tensor * a,
  5418. struct ggml_tensor * b,
  5419. struct ggml_tensor * c,
  5420. int n_dims,
  5421. int mode,
  5422. int n_ctx_orig,
  5423. float freq_base,
  5424. float freq_scale,
  5425. float ext_factor,
  5426. float attn_factor,
  5427. float beta_fast,
  5428. float beta_slow) {
  5429. return ggml_rope_impl(
  5430. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  5431. ext_factor, attn_factor, beta_fast, beta_slow, false
  5432. );
  5433. }
  5434. struct ggml_tensor * ggml_rope_ext_inplace(
  5435. struct ggml_context * ctx,
  5436. struct ggml_tensor * a,
  5437. struct ggml_tensor * b,
  5438. struct ggml_tensor * c,
  5439. int n_dims,
  5440. int mode,
  5441. int n_ctx_orig,
  5442. float freq_base,
  5443. float freq_scale,
  5444. float ext_factor,
  5445. float attn_factor,
  5446. float beta_fast,
  5447. float beta_slow) {
  5448. return ggml_rope_impl(
  5449. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  5450. ext_factor, attn_factor, beta_fast, beta_slow, true
  5451. );
  5452. }
  5453. struct ggml_tensor * ggml_rope_custom(
  5454. struct ggml_context * ctx,
  5455. struct ggml_tensor * a,
  5456. struct ggml_tensor * b,
  5457. int n_dims,
  5458. int mode,
  5459. int n_ctx_orig,
  5460. float freq_base,
  5461. float freq_scale,
  5462. float ext_factor,
  5463. float attn_factor,
  5464. float beta_fast,
  5465. float beta_slow) {
  5466. return ggml_rope_impl(
  5467. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  5468. ext_factor, attn_factor, beta_fast, beta_slow, false
  5469. );
  5470. }
  5471. struct ggml_tensor * ggml_rope_custom_inplace(
  5472. struct ggml_context * ctx,
  5473. struct ggml_tensor * a,
  5474. struct ggml_tensor * b,
  5475. int n_dims,
  5476. int mode,
  5477. int n_ctx_orig,
  5478. float freq_base,
  5479. float freq_scale,
  5480. float ext_factor,
  5481. float attn_factor,
  5482. float beta_fast,
  5483. float beta_slow) {
  5484. return ggml_rope_impl(
  5485. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  5486. ext_factor, attn_factor, beta_fast, beta_slow, true
  5487. );
  5488. }
  5489. // ggml_rope_back
  5490. struct ggml_tensor * ggml_rope_back(
  5491. struct ggml_context * ctx,
  5492. struct ggml_tensor * a,
  5493. struct ggml_tensor * b,
  5494. struct ggml_tensor * c,
  5495. int n_dims,
  5496. int mode,
  5497. int n_ctx_orig,
  5498. float freq_base,
  5499. float freq_scale,
  5500. float ext_factor,
  5501. float attn_factor,
  5502. float beta_fast,
  5503. float beta_slow) {
  5504. GGML_ASSERT(ggml_is_vector(b));
  5505. GGML_ASSERT(b->type == GGML_TYPE_I32);
  5506. GGML_ASSERT(a->ne[2] == b->ne[0]);
  5507. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  5508. int32_t params[11] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  5509. memcpy(params + 5, &freq_base, sizeof(float));
  5510. memcpy(params + 6, &freq_scale, sizeof(float));
  5511. memcpy(params + 7, &ext_factor, sizeof(float));
  5512. memcpy(params + 8, &attn_factor, sizeof(float));
  5513. memcpy(params + 9, &beta_fast, sizeof(float));
  5514. memcpy(params + 10, &beta_slow, sizeof(float));
  5515. ggml_set_op_params(result, params, sizeof(params));
  5516. result->op = GGML_OP_ROPE_BACK;
  5517. result->src[0] = a;
  5518. result->src[1] = b;
  5519. result->src[2] = c;
  5520. return result;
  5521. }
  5522. // ggml_clamp
  5523. struct ggml_tensor * ggml_clamp(
  5524. struct ggml_context * ctx,
  5525. struct ggml_tensor * a,
  5526. float min,
  5527. float max) {
  5528. // TODO: when implement backward, fix this:
  5529. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  5530. float params[] = { min, max };
  5531. ggml_set_op_params(result, params, sizeof(params));
  5532. result->op = GGML_OP_CLAMP;
  5533. result->src[0] = a;
  5534. return result;
  5535. }
  5536. // ggml_conv_1d
  5537. static int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  5538. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  5539. }
  5540. GGML_API struct ggml_tensor * ggml_conv_1d(
  5541. struct ggml_context * ctx,
  5542. struct ggml_tensor * a,
  5543. struct ggml_tensor * b,
  5544. int s0,
  5545. int p0,
  5546. int d0) {
  5547. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, 0, p0, 0, d0, 0, false, GGML_TYPE_F16); // [N, OL, IC * K]
  5548. struct ggml_tensor * result =
  5549. ggml_mul_mat(ctx,
  5550. ggml_reshape_2d(ctx, im2col, im2col->ne[0], (im2col->ne[2] * im2col->ne[1])), // [N, OL, IC * K] => [N*OL, IC * K]
  5551. ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1]), a->ne[2])); // [OC,IC, K] => [OC, IC * K]
  5552. result = ggml_reshape_3d(ctx, result, im2col->ne[1], a->ne[2], im2col->ne[2]); // [N, OC, OL]
  5553. return result;
  5554. }
  5555. // ggml_conv_1d_ph
  5556. struct ggml_tensor* ggml_conv_1d_ph(
  5557. struct ggml_context * ctx,
  5558. struct ggml_tensor * a,
  5559. struct ggml_tensor * b,
  5560. int s,
  5561. int d) {
  5562. return ggml_conv_1d(ctx, a, b, s, a->ne[0] / 2, d);
  5563. }
  5564. // ggml_conv_transpose_1d
  5565. static int64_t ggml_calc_conv_transpose_1d_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  5566. return (ins - 1) * s - 2 * p + d * (ks - 1) + 1;
  5567. }
  5568. GGML_API struct ggml_tensor * ggml_conv_transpose_1d(
  5569. struct ggml_context * ctx,
  5570. struct ggml_tensor * a,
  5571. struct ggml_tensor * b,
  5572. int s0,
  5573. int p0,
  5574. int d0) {
  5575. GGML_ASSERT(ggml_is_matrix(b));
  5576. GGML_ASSERT(a->ne[2] == b->ne[1]);
  5577. GGML_ASSERT(a->ne[3] == 1);
  5578. GGML_ASSERT(p0 == 0);
  5579. GGML_ASSERT(d0 == 1);
  5580. const int64_t ne[4] = {
  5581. ggml_calc_conv_transpose_1d_output_size(b->ne[0], a->ne[0], s0, 0 /*p0*/, 1 /*d0*/),
  5582. a->ne[1], b->ne[2], 1,
  5583. };
  5584. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5585. int32_t params[] = { s0, p0, d0 };
  5586. ggml_set_op_params(result, params, sizeof(params));
  5587. result->op = GGML_OP_CONV_TRANSPOSE_1D;
  5588. result->src[0] = a;
  5589. result->src[1] = b;
  5590. return result;
  5591. }
  5592. // ggml_conv_depthwise
  5593. struct ggml_tensor * ggml_conv_depthwise_2d(
  5594. struct ggml_context * ctx,
  5595. struct ggml_tensor * a,
  5596. struct ggml_tensor * b,
  5597. int s0,
  5598. int s1,
  5599. int p0,
  5600. int p1,
  5601. int d0,
  5602. int d1) {
  5603. struct ggml_tensor * new_a = ggml_reshape_4d(ctx, a, a->ne[0], a->ne[1], 1, a->ne[2] * a->ne[3]);
  5604. struct ggml_tensor * im2col = ggml_im2col(ctx, new_a,
  5605. ggml_reshape_4d(ctx, b, b->ne[0], b->ne[1], 1, b->ne[2] * b->ne[3]),
  5606. s0, s1, p0, p1, d0, d1, true, GGML_TYPE_F16); // [N * IC, OH, OW, KH * KW]
  5607. 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]
  5608. 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]
  5609. struct ggml_tensor * result = ggml_mul_mat(ctx, new_a, new_b);
  5610. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], b->ne[2], b->ne[3]); // [N, OC, OH, OW]
  5611. return result;
  5612. }
  5613. // ggml_conv_2d
  5614. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  5615. // a: [OC,IC, KH, KW]
  5616. // b: [N, IC, IH, IW]
  5617. // result: [N, OH, OW, IC*KH*KW]
  5618. struct ggml_tensor * ggml_im2col(
  5619. struct ggml_context * ctx,
  5620. struct ggml_tensor * a,
  5621. struct ggml_tensor * b,
  5622. int s0,
  5623. int s1,
  5624. int p0,
  5625. int p1,
  5626. int d0,
  5627. int d1,
  5628. bool is_2D,
  5629. enum ggml_type dst_type) {
  5630. if(is_2D) {
  5631. GGML_ASSERT(a->ne[2] == b->ne[2]);
  5632. } else {
  5633. GGML_ASSERT(a->ne[1] == b->ne[1]);
  5634. GGML_ASSERT(b->ne[3] == 1);
  5635. }
  5636. const int64_t OH = is_2D ? ggml_calc_conv_output_size(b->ne[1], a->ne[1], s1, p1, d1) : 0;
  5637. const int64_t OW = ggml_calc_conv_output_size(b->ne[0], a->ne[0], s0, p0, d0);
  5638. GGML_ASSERT((!is_2D || OH > 0) && "b too small compared to a");
  5639. GGML_ASSERT((OW > 0) && "b too small compared to a");
  5640. const int64_t ne[4] = {
  5641. is_2D ? (a->ne[2] * a->ne[1] * a->ne[0]) : a->ne[1] * a->ne[0],
  5642. OW,
  5643. is_2D ? OH : b->ne[2],
  5644. is_2D ? b->ne[3] : 1,
  5645. };
  5646. struct ggml_tensor * result = ggml_new_tensor(ctx, dst_type, 4, ne);
  5647. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  5648. ggml_set_op_params(result, params, sizeof(params));
  5649. result->op = GGML_OP_IM2COL;
  5650. result->src[0] = a;
  5651. result->src[1] = b;
  5652. return result;
  5653. }
  5654. struct ggml_tensor * ggml_im2col_back(
  5655. struct ggml_context * ctx,
  5656. struct ggml_tensor * a,
  5657. struct ggml_tensor * b,
  5658. int64_t * ne,
  5659. int s0,
  5660. int s1,
  5661. int p0,
  5662. int p1,
  5663. int d0,
  5664. int d1,
  5665. bool is_2D) {
  5666. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5667. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  5668. ggml_set_op_params(result, params, sizeof(params));
  5669. result->op = GGML_OP_IM2COL_BACK;
  5670. result->src[0] = a;
  5671. result->src[1] = b;
  5672. return result;
  5673. }
  5674. // a: [OC,IC, KH, KW]
  5675. // b: [N, IC, IH, IW]
  5676. // result: [N, OC, OH, OW]
  5677. struct ggml_tensor * ggml_conv_2d(
  5678. struct ggml_context * ctx,
  5679. struct ggml_tensor * a,
  5680. struct ggml_tensor * b,
  5681. int s0,
  5682. int s1,
  5683. int p0,
  5684. int p1,
  5685. int d0,
  5686. int d1) {
  5687. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, s1, p0, p1, d0, d1, true, a->type); // [N, OH, OW, IC * KH * KW]
  5688. struct ggml_tensor * result =
  5689. ggml_mul_mat(ctx,
  5690. 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]
  5691. 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]
  5692. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], im2col->ne[3], a->ne[3]); // [OC, N, OH, OW]
  5693. result = ggml_cont(ctx, ggml_permute(ctx, result, 0, 1, 3, 2)); // [N, OC, OH, OW]
  5694. return result;
  5695. }
  5696. // ggml_conv_2d_sk_p0
  5697. struct ggml_tensor * ggml_conv_2d_sk_p0(
  5698. struct ggml_context * ctx,
  5699. struct ggml_tensor * a,
  5700. struct ggml_tensor * b) {
  5701. return ggml_conv_2d(ctx, a, b, a->ne[0], a->ne[1], 0, 0, 1, 1);
  5702. }
  5703. // ggml_conv_2d_s1_ph
  5704. struct ggml_tensor * ggml_conv_2d_s1_ph(
  5705. struct ggml_context * ctx,
  5706. struct ggml_tensor * a,
  5707. struct ggml_tensor * b) {
  5708. return ggml_conv_2d(ctx, a, b, 1, 1, a->ne[0] / 2, a->ne[1] / 2, 1, 1);
  5709. }
  5710. // ggml_conv_transpose_2d_p0
  5711. static int64_t ggml_calc_conv_transpose_output_size(int64_t ins, int64_t ks, int s, int p) {
  5712. return (ins - 1) * s - 2 * p + ks;
  5713. }
  5714. struct ggml_tensor * ggml_conv_transpose_2d_p0(
  5715. struct ggml_context * ctx,
  5716. struct ggml_tensor * a,
  5717. struct ggml_tensor * b,
  5718. int stride) {
  5719. GGML_ASSERT(a->ne[3] == b->ne[2]);
  5720. const int64_t ne[4] = {
  5721. ggml_calc_conv_transpose_output_size(b->ne[0], a->ne[0], stride, 0 /*p0*/),
  5722. ggml_calc_conv_transpose_output_size(b->ne[1], a->ne[1], stride, 0 /*p1*/),
  5723. a->ne[2], b->ne[3],
  5724. };
  5725. struct ggml_tensor* result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5726. ggml_set_op_params_i32(result, 0, stride);
  5727. result->op = GGML_OP_CONV_TRANSPOSE_2D;
  5728. result->src[0] = a;
  5729. result->src[1] = b;
  5730. return result;
  5731. }
  5732. // ggml_pool_*
  5733. static int64_t ggml_calc_pool_output_size(int64_t ins, int ks, int s, float p) {
  5734. return (ins + 2 * p - ks) / s + 1;
  5735. }
  5736. // ggml_pool_1d
  5737. struct ggml_tensor * ggml_pool_1d(
  5738. struct ggml_context * ctx,
  5739. struct ggml_tensor * a,
  5740. enum ggml_op_pool op,
  5741. int k0,
  5742. int s0,
  5743. int p0) {
  5744. const int64_t ne[4] = {
  5745. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  5746. a->ne[1],
  5747. a->ne[2],
  5748. a->ne[3],
  5749. };
  5750. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5751. int32_t params[] = { op, k0, s0, p0 };
  5752. ggml_set_op_params(result, params, sizeof(params));
  5753. result->op = GGML_OP_POOL_1D;
  5754. result->src[0] = a;
  5755. return result;
  5756. }
  5757. // ggml_pool_2d
  5758. struct ggml_tensor * ggml_pool_2d(
  5759. struct ggml_context * ctx,
  5760. struct ggml_tensor * a,
  5761. enum ggml_op_pool op,
  5762. int k0,
  5763. int k1,
  5764. int s0,
  5765. int s1,
  5766. float p0,
  5767. float p1) {
  5768. struct ggml_tensor * result;
  5769. const int64_t ne[4] = {
  5770. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  5771. ggml_calc_pool_output_size(a->ne[1], k1, s1, p1),
  5772. a->ne[2],
  5773. a->ne[3],
  5774. };
  5775. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5776. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  5777. ggml_set_op_params(result, params, sizeof(params));
  5778. result->op = GGML_OP_POOL_2D;
  5779. result->src[0] = a;
  5780. return result;
  5781. }
  5782. struct ggml_tensor * ggml_pool_2d_back(
  5783. struct ggml_context * ctx,
  5784. struct ggml_tensor * a,
  5785. struct ggml_tensor * af,
  5786. enum ggml_op_pool op,
  5787. int k0,
  5788. int k1,
  5789. int s0,
  5790. int s1,
  5791. float p0,
  5792. float p1) {
  5793. struct ggml_tensor * result;
  5794. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, af->ne);
  5795. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  5796. ggml_set_op_params(result, params, sizeof(params));
  5797. result->op = GGML_OP_POOL_2D_BACK;
  5798. result->src[0] = a;
  5799. result->src[1] = af;
  5800. return result;
  5801. }
  5802. // ggml_upscale
  5803. static struct ggml_tensor * ggml_upscale_impl(
  5804. struct ggml_context * ctx,
  5805. struct ggml_tensor * a,
  5806. int ne0,
  5807. int ne1,
  5808. int ne2,
  5809. int ne3) {
  5810. GGML_ASSERT(a->ne[0] <= ne0);
  5811. GGML_ASSERT(a->ne[1] <= ne1);
  5812. GGML_ASSERT(a->ne[2] <= ne2);
  5813. GGML_ASSERT(a->ne[3] <= ne3);
  5814. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  5815. result->op = GGML_OP_UPSCALE;
  5816. result->src[0] = a;
  5817. return result;
  5818. }
  5819. struct ggml_tensor * ggml_upscale(
  5820. struct ggml_context * ctx,
  5821. struct ggml_tensor * a,
  5822. int scale_factor) {
  5823. return ggml_upscale_impl(ctx, a, a->ne[0] * scale_factor, a->ne[1] * scale_factor, a->ne[2], a->ne[3]);
  5824. }
  5825. struct ggml_tensor * ggml_upscale_ext(
  5826. struct ggml_context * ctx,
  5827. struct ggml_tensor * a,
  5828. int ne0,
  5829. int ne1,
  5830. int ne2,
  5831. int ne3) {
  5832. return ggml_upscale_impl(ctx, a, ne0, ne1, ne2, ne3);
  5833. }
  5834. // ggml_pad
  5835. struct ggml_tensor * ggml_pad(
  5836. struct ggml_context * ctx,
  5837. struct ggml_tensor * a,
  5838. int p0,
  5839. int p1,
  5840. int p2,
  5841. int p3) {
  5842. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  5843. a->ne[0] + p0,
  5844. a->ne[1] + p1,
  5845. a->ne[2] + p2,
  5846. a->ne[3] + p3);
  5847. result->op = GGML_OP_PAD;
  5848. result->src[0] = a;
  5849. return result;
  5850. }
  5851. // ggml_unpad
  5852. struct ggml_tensor * ggml_unpad(
  5853. struct ggml_context * ctx,
  5854. struct ggml_tensor * a,
  5855. int p0, int p1, int p2, int p3) {
  5856. bool is_node = false;
  5857. if (a->grad) {
  5858. GGML_ABORT("fatal error"); // TODO: implement backward
  5859. is_node = true;
  5860. }
  5861. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  5862. a->ne[0] - p0,
  5863. a->ne[1] - p1,
  5864. a->ne[2] - p2,
  5865. a->ne[3] - p3);
  5866. result->op = GGML_OP_UNPAD;
  5867. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  5868. result->src[0] = a;
  5869. return result;
  5870. }
  5871. // ggml_arange
  5872. struct ggml_tensor * ggml_arange(
  5873. struct ggml_context * ctx,
  5874. float start,
  5875. float stop,
  5876. float step) {
  5877. GGML_ASSERT(stop > start);
  5878. const int64_t steps = (int64_t) ceilf((stop - start) / step);
  5879. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, steps);
  5880. ggml_set_op_params_f32(result, 0, start);
  5881. ggml_set_op_params_f32(result, 1, stop);
  5882. ggml_set_op_params_f32(result, 2, step);
  5883. result->op = GGML_OP_ARANGE;
  5884. return result;
  5885. }
  5886. // ggml_timestep_embedding
  5887. struct ggml_tensor * ggml_timestep_embedding(
  5888. struct ggml_context * ctx,
  5889. struct ggml_tensor * timesteps,
  5890. int dim,
  5891. int max_period) {
  5892. int actual_dim = dim;
  5893. if (dim % 2 != 0) {
  5894. actual_dim = dim + 1;
  5895. }
  5896. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, actual_dim, timesteps->ne[0]);
  5897. ggml_set_op_params_i32(result, 0, dim);
  5898. ggml_set_op_params_i32(result, 1, max_period);
  5899. result->op = GGML_OP_TIMESTEP_EMBEDDING;
  5900. result->src[0] = timesteps;
  5901. return result;
  5902. }
  5903. // ggml_argsort
  5904. struct ggml_tensor * ggml_argsort(
  5905. struct ggml_context * ctx,
  5906. struct ggml_tensor * a,
  5907. enum ggml_sort_order order) {
  5908. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_I32, GGML_MAX_DIMS, a->ne);
  5909. ggml_set_op_params_i32(result, 0, (int32_t) order);
  5910. result->op = GGML_OP_ARGSORT;
  5911. result->src[0] = a;
  5912. return result;
  5913. }
  5914. // ggml_top_k
  5915. struct ggml_tensor * ggml_top_k(
  5916. struct ggml_context * ctx,
  5917. struct ggml_tensor * a,
  5918. int k) {
  5919. GGML_ASSERT(a->ne[0] >= k);
  5920. struct ggml_tensor * result = ggml_argsort(ctx, a, GGML_SORT_ORDER_DESC);
  5921. result = ggml_view_4d(ctx, result,
  5922. k, result->ne[1], result->ne[2], result->ne[3],
  5923. result->nb[1], result->nb[2], result->nb[3],
  5924. 0);
  5925. return result;
  5926. }
  5927. // ggml_flash_attn_ext
  5928. struct ggml_tensor * ggml_flash_attn_ext(
  5929. struct ggml_context * ctx,
  5930. struct ggml_tensor * q,
  5931. struct ggml_tensor * k,
  5932. struct ggml_tensor * v,
  5933. struct ggml_tensor * mask,
  5934. float scale,
  5935. float max_bias,
  5936. float logit_softcap) {
  5937. GGML_ASSERT(ggml_can_mul_mat(k, q));
  5938. // TODO: check if vT can be multiplied by (k*qT)
  5939. if (mask) {
  5940. GGML_ASSERT(ggml_is_contiguous(mask));
  5941. GGML_ASSERT(mask->ne[2] == 1);
  5942. GGML_ASSERT(mask->ne[3] == 1);
  5943. GGML_ASSERT(mask->ne[1] >= GGML_PAD(q->ne[1], GGML_KQ_MASK_PAD) &&
  5944. "the Flash-Attention kernel requires the mask to be padded to GGML_KQ_MASK_PAD and at least n_queries big");
  5945. //GGML_ASSERT(ggml_can_repeat_rows(mask, qk));
  5946. }
  5947. if (max_bias > 0.0f) {
  5948. GGML_ASSERT(mask);
  5949. }
  5950. bool is_node = false;
  5951. // permute(0, 2, 1, 3)
  5952. int64_t ne[4] = { q->ne[0], q->ne[2], q->ne[1], q->ne[3] };
  5953. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  5954. float params[] = { scale, max_bias, logit_softcap };
  5955. ggml_set_op_params(result, params, sizeof(params));
  5956. result->op = GGML_OP_FLASH_ATTN_EXT;
  5957. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  5958. result->src[0] = q;
  5959. result->src[1] = k;
  5960. result->src[2] = v;
  5961. result->src[3] = mask;
  5962. return result;
  5963. }
  5964. void ggml_flash_attn_ext_set_prec(
  5965. struct ggml_tensor * a,
  5966. enum ggml_prec prec) {
  5967. GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
  5968. const int32_t prec_i32 = (int32_t) prec;
  5969. ggml_set_op_params_i32(a, 3, prec_i32); // scale is on first pos, max_bias on second
  5970. }
  5971. // ggml_flash_attn_back
  5972. struct ggml_tensor * ggml_flash_attn_back(
  5973. struct ggml_context * ctx,
  5974. struct ggml_tensor * q,
  5975. struct ggml_tensor * k,
  5976. struct ggml_tensor * v,
  5977. struct ggml_tensor * d,
  5978. bool masked) {
  5979. GGML_ABORT("TODO: adapt to ggml_flash_attn_ext() changes");
  5980. GGML_ASSERT(ggml_can_mul_mat(k, q));
  5981. // TODO: check if vT can be multiplied by (k*qT)
  5982. // d shape [D,N,ne2,ne3]
  5983. // q shape [D,N,ne2,ne3]
  5984. // k shape [D,M,kvne2,ne3]
  5985. // v shape [M,D,kvne2,ne3]
  5986. const int64_t D = q->ne[0];
  5987. const int64_t N = q->ne[1];
  5988. const int64_t M = k->ne[1];
  5989. const int64_t ne2 = q->ne[2];
  5990. const int64_t ne3 = q->ne[3];
  5991. const int64_t kvne2 = k->ne[2];
  5992. GGML_ASSERT(k->ne[0] == D);
  5993. GGML_ASSERT(v->ne[0] == M);
  5994. GGML_ASSERT(v->ne[1] == D);
  5995. GGML_ASSERT(d->ne[0] == D);
  5996. GGML_ASSERT(d->ne[1] == N);
  5997. GGML_ASSERT(k->ne[2] == kvne2);
  5998. GGML_ASSERT(k->ne[3] == ne3);
  5999. GGML_ASSERT(v->ne[2] == kvne2);
  6000. GGML_ASSERT(v->ne[3] == ne3);
  6001. GGML_ASSERT(d->ne[2] == ne2);
  6002. GGML_ASSERT(d->ne[3] == ne3);
  6003. GGML_ASSERT(ne2 % kvne2 == 0);
  6004. bool is_node = false;
  6005. if (q->grad || k->grad || v->grad) {
  6006. // when using this operation (in backwards pass) these grads are set.
  6007. // we don't want to create (big) grad of our result, so is_node is false.
  6008. is_node = false;
  6009. }
  6010. // store gradients of q, k and v as continuous tensors concatenated in result.
  6011. // note: v and gradv are actually transposed, i.e. v->ne[0] != D.
  6012. const int64_t elem_q = ggml_nelements(q);
  6013. const int64_t elem_k = ggml_nelements(k);
  6014. const int64_t elem_v = ggml_nelements(v);
  6015. enum ggml_type result_type = GGML_TYPE_F32;
  6016. GGML_ASSERT(ggml_blck_size(result_type) == 1);
  6017. const size_t tsize = ggml_type_size(result_type);
  6018. const size_t offs_q = 0;
  6019. const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
  6020. const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
  6021. const size_t end = offs_v + GGML_PAD(elem_v * tsize, GGML_MEM_ALIGN);
  6022. const size_t nelements = (end + tsize - 1)/tsize;
  6023. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nelements);
  6024. int32_t masked_i = masked ? 1 : 0;
  6025. ggml_set_op_params(result, &masked_i, sizeof(masked_i));
  6026. result->op = GGML_OP_FLASH_ATTN_BACK;
  6027. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  6028. result->src[0] = q;
  6029. result->src[1] = k;
  6030. result->src[2] = v;
  6031. result->src[3] = d;
  6032. return result;
  6033. }
  6034. // ggml_ssm_conv
  6035. struct ggml_tensor * ggml_ssm_conv(
  6036. struct ggml_context * ctx,
  6037. struct ggml_tensor * sx,
  6038. struct ggml_tensor * c) {
  6039. GGML_ASSERT(ggml_is_3d(sx));
  6040. GGML_ASSERT(ggml_is_matrix(c));
  6041. const int64_t d_conv = c->ne[0];
  6042. const int64_t d_inner = c->ne[1];
  6043. const int64_t n_t = sx->ne[0] - d_conv + 1; // tokens per sequence
  6044. const int64_t n_s = sx->ne[2];
  6045. // TODO: maybe support other strides than 1?
  6046. GGML_ASSERT(sx->ne[0] == d_conv - 1 + n_t);
  6047. GGML_ASSERT(sx->ne[1] == d_inner);
  6048. GGML_ASSERT(n_t >= 0);
  6049. struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_t, n_s);
  6050. result->op = GGML_OP_SSM_CONV;
  6051. result->src[0] = sx;
  6052. result->src[1] = c;
  6053. return result;
  6054. }
  6055. // ggml_ssm_scan
  6056. struct ggml_tensor * ggml_ssm_scan(
  6057. struct ggml_context * ctx,
  6058. struct ggml_tensor * s,
  6059. struct ggml_tensor * x,
  6060. struct ggml_tensor * dt,
  6061. struct ggml_tensor * A,
  6062. struct ggml_tensor * B,
  6063. struct ggml_tensor * C) {
  6064. GGML_ASSERT(ggml_is_contiguous(s));
  6065. GGML_ASSERT(ggml_is_contiguous(x));
  6066. GGML_ASSERT(ggml_is_contiguous(dt));
  6067. GGML_ASSERT(ggml_is_contiguous(A));
  6068. GGML_ASSERT(ggml_is_matrix(A));
  6069. GGML_ASSERT(ggml_is_3d(B));
  6070. GGML_ASSERT(ggml_is_3d(s));
  6071. GGML_ASSERT(B->nb[0] == ggml_type_size(B->type));
  6072. GGML_ASSERT(C->nb[0] == ggml_type_size(C->type));
  6073. GGML_ASSERT(ggml_are_same_shape(x, dt));
  6074. GGML_ASSERT(ggml_are_same_shape(B, C));
  6075. {
  6076. const int64_t d_state = s->ne[0];
  6077. const int64_t d_inner = s->ne[1];
  6078. const int64_t n_seq_tokens = x->ne[1];
  6079. const int64_t n_seqs = x->ne[2];
  6080. GGML_ASSERT(s->ne[2] == n_seqs);
  6081. GGML_ASSERT(x->ne[0] == d_inner);
  6082. GGML_ASSERT(A->ne[0] == d_state);
  6083. GGML_ASSERT(A->ne[1] == d_inner);
  6084. GGML_ASSERT(B->ne[0] == d_state);
  6085. GGML_ASSERT(B->ne[1] == n_seq_tokens);
  6086. GGML_ASSERT(B->ne[2] == n_seqs);
  6087. }
  6088. // concatenated y + ssm_states
  6089. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ggml_nelements(x) + ggml_nelements(s));
  6090. result->op = GGML_OP_SSM_SCAN;
  6091. result->src[0] = s;
  6092. result->src[1] = x;
  6093. result->src[2] = dt;
  6094. result->src[3] = A;
  6095. result->src[4] = B;
  6096. result->src[5] = C;
  6097. return result;
  6098. }
  6099. // ggml_win_part
  6100. struct ggml_tensor * ggml_win_part(
  6101. struct ggml_context * ctx,
  6102. struct ggml_tensor * a,
  6103. int w) {
  6104. GGML_ASSERT(a->ne[3] == 1);
  6105. GGML_ASSERT(a->type == GGML_TYPE_F32);
  6106. // padding
  6107. const int px = (w - a->ne[1]%w)%w;
  6108. const int py = (w - a->ne[2]%w)%w;
  6109. const int npx = (px + a->ne[1])/w;
  6110. const int npy = (py + a->ne[2])/w;
  6111. const int np = npx*npy;
  6112. const int64_t ne[4] = { a->ne[0], w, w, np, };
  6113. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  6114. int32_t params[] = { npx, npy, w };
  6115. ggml_set_op_params(result, params, sizeof(params));
  6116. result->op = GGML_OP_WIN_PART;
  6117. result->src[0] = a;
  6118. return result;
  6119. }
  6120. // ggml_win_unpart
  6121. struct ggml_tensor * ggml_win_unpart(
  6122. struct ggml_context * ctx,
  6123. struct ggml_tensor * a,
  6124. int w0,
  6125. int h0,
  6126. int w) {
  6127. GGML_ASSERT(a->type == GGML_TYPE_F32);
  6128. const int64_t ne[4] = { a->ne[0], w0, h0, 1, };
  6129. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 3, ne);
  6130. int32_t params[] = { w };
  6131. ggml_set_op_params(result, params, sizeof(params));
  6132. result->op = GGML_OP_WIN_UNPART;
  6133. result->src[0] = a;
  6134. return result;
  6135. }
  6136. // ggml_get_rel_pos
  6137. struct ggml_tensor * ggml_get_rel_pos(
  6138. struct ggml_context * ctx,
  6139. struct ggml_tensor * a,
  6140. int qh,
  6141. int kh) {
  6142. GGML_ASSERT(qh == kh);
  6143. GGML_ASSERT(2*MAX(qh, kh) - 1 == a->ne[1]);
  6144. const int64_t ne[4] = { a->ne[0], kh, qh, 1, };
  6145. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F16, 3, ne);
  6146. result->op = GGML_OP_GET_REL_POS;
  6147. result->src[0] = a;
  6148. return result;
  6149. }
  6150. // ggml_add_rel_pos
  6151. static struct ggml_tensor * ggml_add_rel_pos_impl(
  6152. struct ggml_context * ctx,
  6153. struct ggml_tensor * a,
  6154. struct ggml_tensor * pw,
  6155. struct ggml_tensor * ph,
  6156. bool inplace) {
  6157. GGML_ASSERT(ggml_are_same_shape(pw, ph));
  6158. GGML_ASSERT(ggml_is_contiguous(a));
  6159. GGML_ASSERT(ggml_is_contiguous(pw));
  6160. GGML_ASSERT(ggml_is_contiguous(ph));
  6161. GGML_ASSERT(ph->type == GGML_TYPE_F32);
  6162. GGML_ASSERT(pw->type == GGML_TYPE_F32);
  6163. GGML_ASSERT(pw->ne[3] == a->ne[2]);
  6164. GGML_ASSERT(pw->ne[0]*pw->ne[0] == a->ne[0]);
  6165. GGML_ASSERT(pw->ne[1]*pw->ne[2] == a->ne[1]);
  6166. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6167. ggml_set_op_params_i32(result, 0, inplace ? 1 : 0);
  6168. result->op = GGML_OP_ADD_REL_POS;
  6169. result->src[0] = a;
  6170. result->src[1] = pw;
  6171. result->src[2] = ph;
  6172. return result;
  6173. }
  6174. struct ggml_tensor * ggml_add_rel_pos(
  6175. struct ggml_context * ctx,
  6176. struct ggml_tensor * a,
  6177. struct ggml_tensor * pw,
  6178. struct ggml_tensor * ph) {
  6179. return ggml_add_rel_pos_impl(ctx, a, pw, ph, false);
  6180. }
  6181. struct ggml_tensor * ggml_add_rel_pos_inplace(
  6182. struct ggml_context * ctx,
  6183. struct ggml_tensor * a,
  6184. struct ggml_tensor * pw,
  6185. struct ggml_tensor * ph) {
  6186. return ggml_add_rel_pos_impl(ctx, a, pw, ph, true);
  6187. }
  6188. // ggml_rwkv_wkv
  6189. struct ggml_tensor * ggml_rwkv_wkv(
  6190. struct ggml_context * ctx,
  6191. struct ggml_tensor * k,
  6192. struct ggml_tensor * v,
  6193. struct ggml_tensor * r,
  6194. struct ggml_tensor * tf,
  6195. struct ggml_tensor * td,
  6196. struct ggml_tensor * state) {
  6197. GGML_ASSERT(ggml_is_contiguous(k));
  6198. GGML_ASSERT(ggml_is_contiguous(v));
  6199. GGML_ASSERT(ggml_is_contiguous(r));
  6200. GGML_ASSERT(ggml_is_contiguous(tf));
  6201. GGML_ASSERT(ggml_is_contiguous(td));
  6202. GGML_ASSERT(ggml_is_contiguous(state));
  6203. const int64_t S = k->ne[0];
  6204. const int64_t H = k->ne[2];
  6205. const int64_t n_tokens = k->ne[3];
  6206. const int64_t n_seqs = state->ne[1];
  6207. {
  6208. GGML_ASSERT(k->ne[1] == 1);
  6209. GGML_ASSERT(v->ne[0] == 1 && v->ne[1] == S && v->ne[2] == H && v->ne[3] == n_tokens);
  6210. GGML_ASSERT(r->ne[0] == 1 && r->ne[1] == S && r->ne[2] == H && r->ne[3] == n_tokens);
  6211. // TODO: RWKV v4 and v5
  6212. GGML_ASSERT(td->ne[0] == 1 && td->ne[1] == S && td->ne[2] == H && td->ne[3] == n_tokens);
  6213. GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
  6214. }
  6215. // concat output and new_state
  6216. const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
  6217. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  6218. result->op = GGML_OP_RWKV_WKV;
  6219. result->src[0] = k;
  6220. result->src[1] = v;
  6221. result->src[2] = r;
  6222. result->src[3] = tf;
  6223. result->src[4] = td;
  6224. result->src[5] = state;
  6225. return result;
  6226. }
  6227. // ggml_unary
  6228. static struct ggml_tensor * ggml_unary_impl(
  6229. struct ggml_context * ctx,
  6230. struct ggml_tensor * a,
  6231. enum ggml_unary_op op,
  6232. bool inplace) {
  6233. GGML_ASSERT(ggml_is_contiguous_1(a));
  6234. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6235. ggml_set_op_params_i32(result, 0, (int32_t) op);
  6236. result->op = GGML_OP_UNARY;
  6237. result->src[0] = a;
  6238. return result;
  6239. }
  6240. struct ggml_tensor * ggml_unary(
  6241. struct ggml_context * ctx,
  6242. struct ggml_tensor * a,
  6243. enum ggml_unary_op op) {
  6244. return ggml_unary_impl(ctx, a, op, false);
  6245. }
  6246. struct ggml_tensor * ggml_unary_inplace(
  6247. struct ggml_context * ctx,
  6248. struct ggml_tensor * a,
  6249. enum ggml_unary_op op) {
  6250. return ggml_unary_impl(ctx, a, op, true);
  6251. }
  6252. // ggml_map_unary
  6253. static struct ggml_tensor * ggml_map_unary_impl_f32(
  6254. struct ggml_context * ctx,
  6255. struct ggml_tensor * a,
  6256. const ggml_unary_op_f32_t fun,
  6257. bool inplace) {
  6258. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6259. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6260. result->op = GGML_OP_MAP_UNARY;
  6261. result->src[0] = a;
  6262. return result;
  6263. }
  6264. struct ggml_tensor * ggml_map_unary_f32(
  6265. struct ggml_context * ctx,
  6266. struct ggml_tensor * a,
  6267. const ggml_unary_op_f32_t fun) {
  6268. return ggml_map_unary_impl_f32(ctx, a, fun, false);
  6269. }
  6270. struct ggml_tensor * ggml_map_unary_inplace_f32(
  6271. struct ggml_context * ctx,
  6272. struct ggml_tensor * a,
  6273. const ggml_unary_op_f32_t fun) {
  6274. return ggml_map_unary_impl_f32(ctx, a, fun, true);
  6275. }
  6276. // ggml_map_binary
  6277. static struct ggml_tensor * ggml_map_binary_impl_f32(
  6278. struct ggml_context * ctx,
  6279. struct ggml_tensor * a,
  6280. struct ggml_tensor * b,
  6281. const ggml_binary_op_f32_t fun,
  6282. bool inplace) {
  6283. GGML_ASSERT(ggml_are_same_shape(a, b));
  6284. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6285. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6286. result->op = GGML_OP_MAP_BINARY;
  6287. result->src[0] = a;
  6288. result->src[1] = b;
  6289. return result;
  6290. }
  6291. struct ggml_tensor * ggml_map_binary_f32(
  6292. struct ggml_context * ctx,
  6293. struct ggml_tensor * a,
  6294. struct ggml_tensor * b,
  6295. const ggml_binary_op_f32_t fun) {
  6296. return ggml_map_binary_impl_f32(ctx, a, b, fun, false);
  6297. }
  6298. struct ggml_tensor * ggml_map_binary_inplace_f32(
  6299. struct ggml_context * ctx,
  6300. struct ggml_tensor * a,
  6301. struct ggml_tensor * b,
  6302. const ggml_binary_op_f32_t fun) {
  6303. return ggml_map_binary_impl_f32(ctx, a, b, fun, true);
  6304. }
  6305. // ggml_map_custom1_f32
  6306. static struct ggml_tensor * ggml_map_custom1_impl_f32(
  6307. struct ggml_context * ctx,
  6308. struct ggml_tensor * a,
  6309. const ggml_custom1_op_f32_t fun,
  6310. bool inplace) {
  6311. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6312. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6313. result->op = GGML_OP_MAP_CUSTOM1_F32;
  6314. result->src[0] = a;
  6315. return result;
  6316. }
  6317. struct ggml_tensor * ggml_map_custom1_f32(
  6318. struct ggml_context * ctx,
  6319. struct ggml_tensor * a,
  6320. const ggml_custom1_op_f32_t fun) {
  6321. return ggml_map_custom1_impl_f32(ctx, a, fun, false);
  6322. }
  6323. struct ggml_tensor * ggml_map_custom1_inplace_f32(
  6324. struct ggml_context * ctx,
  6325. struct ggml_tensor * a,
  6326. const ggml_custom1_op_f32_t fun) {
  6327. return ggml_map_custom1_impl_f32(ctx, a, fun, true);
  6328. }
  6329. // ggml_map_custom2_f32
  6330. static struct ggml_tensor * ggml_map_custom2_impl_f32(
  6331. struct ggml_context * ctx,
  6332. struct ggml_tensor * a,
  6333. struct ggml_tensor * b,
  6334. const ggml_custom2_op_f32_t fun,
  6335. bool inplace) {
  6336. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6337. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6338. result->op = GGML_OP_MAP_CUSTOM2_F32;
  6339. result->src[0] = a;
  6340. result->src[1] = b;
  6341. return result;
  6342. }
  6343. struct ggml_tensor * ggml_map_custom2_f32(
  6344. struct ggml_context * ctx,
  6345. struct ggml_tensor * a,
  6346. struct ggml_tensor * b,
  6347. const ggml_custom2_op_f32_t fun) {
  6348. return ggml_map_custom2_impl_f32(ctx, a, b, fun, false);
  6349. }
  6350. struct ggml_tensor * ggml_map_custom2_inplace_f32(
  6351. struct ggml_context * ctx,
  6352. struct ggml_tensor * a,
  6353. struct ggml_tensor * b,
  6354. const ggml_custom2_op_f32_t fun) {
  6355. return ggml_map_custom2_impl_f32(ctx, a, b, fun, true);
  6356. }
  6357. // ggml_map_custom3_f32
  6358. static struct ggml_tensor * ggml_map_custom3_impl_f32(
  6359. struct ggml_context * ctx,
  6360. struct ggml_tensor * a,
  6361. struct ggml_tensor * b,
  6362. struct ggml_tensor * c,
  6363. const ggml_custom3_op_f32_t fun,
  6364. bool inplace) {
  6365. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6366. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  6367. result->op = GGML_OP_MAP_CUSTOM3_F32;
  6368. result->src[0] = a;
  6369. result->src[1] = b;
  6370. result->src[2] = c;
  6371. return result;
  6372. }
  6373. struct ggml_tensor * ggml_map_custom3_f32(
  6374. struct ggml_context * ctx,
  6375. struct ggml_tensor * a,
  6376. struct ggml_tensor * b,
  6377. struct ggml_tensor * c,
  6378. const ggml_custom3_op_f32_t fun) {
  6379. return ggml_map_custom3_impl_f32(ctx, a, b, c, fun, false);
  6380. }
  6381. struct ggml_tensor * ggml_map_custom3_inplace_f32(
  6382. struct ggml_context * ctx,
  6383. struct ggml_tensor * a,
  6384. struct ggml_tensor * b,
  6385. struct ggml_tensor * c,
  6386. const ggml_custom3_op_f32_t fun) {
  6387. return ggml_map_custom3_impl_f32(ctx, a, b, c, fun, true);
  6388. }
  6389. // ggml_map_custom1
  6390. struct ggml_map_custom1_op_params {
  6391. ggml_custom1_op_t fun;
  6392. int n_tasks;
  6393. void * userdata;
  6394. };
  6395. static struct ggml_tensor * ggml_map_custom1_impl(
  6396. struct ggml_context * ctx,
  6397. struct ggml_tensor * a,
  6398. const ggml_custom1_op_t fun,
  6399. int n_tasks,
  6400. void * userdata,
  6401. bool inplace) {
  6402. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  6403. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6404. struct ggml_map_custom1_op_params params = {
  6405. /*.fun =*/ fun,
  6406. /*.n_tasks =*/ n_tasks,
  6407. /*.userdata =*/ userdata
  6408. };
  6409. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  6410. result->op = GGML_OP_MAP_CUSTOM1;
  6411. result->src[0] = a;
  6412. return result;
  6413. }
  6414. struct ggml_tensor * ggml_map_custom1(
  6415. struct ggml_context * ctx,
  6416. struct ggml_tensor * a,
  6417. const ggml_custom1_op_t fun,
  6418. int n_tasks,
  6419. void * userdata) {
  6420. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, false);
  6421. }
  6422. struct ggml_tensor * ggml_map_custom1_inplace(
  6423. struct ggml_context * ctx,
  6424. struct ggml_tensor * a,
  6425. const ggml_custom1_op_t fun,
  6426. int n_tasks,
  6427. void * userdata) {
  6428. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, true);
  6429. }
  6430. // ggml_map_custom2
  6431. struct ggml_map_custom2_op_params {
  6432. ggml_custom2_op_t fun;
  6433. int n_tasks;
  6434. void * userdata;
  6435. };
  6436. static struct ggml_tensor * ggml_map_custom2_impl(
  6437. struct ggml_context * ctx,
  6438. struct ggml_tensor * a,
  6439. struct ggml_tensor * b,
  6440. const ggml_custom2_op_t fun,
  6441. int n_tasks,
  6442. void * userdata,
  6443. bool inplace) {
  6444. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  6445. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6446. struct ggml_map_custom2_op_params params = {
  6447. /*.fun =*/ fun,
  6448. /*.n_tasks =*/ n_tasks,
  6449. /*.userdata =*/ userdata
  6450. };
  6451. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  6452. result->op = GGML_OP_MAP_CUSTOM2;
  6453. result->src[0] = a;
  6454. result->src[1] = b;
  6455. return result;
  6456. }
  6457. struct ggml_tensor * ggml_map_custom2(
  6458. struct ggml_context * ctx,
  6459. struct ggml_tensor * a,
  6460. struct ggml_tensor * b,
  6461. const ggml_custom2_op_t fun,
  6462. int n_tasks,
  6463. void * userdata) {
  6464. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, false);
  6465. }
  6466. struct ggml_tensor * ggml_map_custom2_inplace(
  6467. struct ggml_context * ctx,
  6468. struct ggml_tensor * a,
  6469. struct ggml_tensor * b,
  6470. const ggml_custom2_op_t fun,
  6471. int n_tasks,
  6472. void * userdata) {
  6473. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, true);
  6474. }
  6475. // ggml_map_custom3
  6476. struct ggml_map_custom3_op_params {
  6477. ggml_custom3_op_t fun;
  6478. int n_tasks;
  6479. void * userdata;
  6480. };
  6481. static struct ggml_tensor * ggml_map_custom3_impl(
  6482. struct ggml_context * ctx,
  6483. struct ggml_tensor * a,
  6484. struct ggml_tensor * b,
  6485. struct ggml_tensor * c,
  6486. const ggml_custom3_op_t fun,
  6487. int n_tasks,
  6488. void * userdata,
  6489. bool inplace) {
  6490. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  6491. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  6492. struct ggml_map_custom3_op_params params = {
  6493. /*.fun =*/ fun,
  6494. /*.n_tasks =*/ n_tasks,
  6495. /*.userdata =*/ userdata
  6496. };
  6497. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  6498. result->op = GGML_OP_MAP_CUSTOM3;
  6499. result->src[0] = a;
  6500. result->src[1] = b;
  6501. result->src[2] = c;
  6502. return result;
  6503. }
  6504. struct ggml_tensor * ggml_map_custom3(
  6505. struct ggml_context * ctx,
  6506. struct ggml_tensor * a,
  6507. struct ggml_tensor * b,
  6508. struct ggml_tensor * c,
  6509. const ggml_custom3_op_t fun,
  6510. int n_tasks,
  6511. void * userdata) {
  6512. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, false);
  6513. }
  6514. struct ggml_tensor * ggml_map_custom3_inplace(
  6515. struct ggml_context * ctx,
  6516. struct ggml_tensor * a,
  6517. struct ggml_tensor * b,
  6518. struct ggml_tensor * c,
  6519. const ggml_custom3_op_t fun,
  6520. int n_tasks,
  6521. void * userdata) {
  6522. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, true);
  6523. }
  6524. // ggml_cross_entropy_loss
  6525. struct ggml_tensor * ggml_cross_entropy_loss(
  6526. struct ggml_context * ctx,
  6527. struct ggml_tensor * a,
  6528. struct ggml_tensor * b) {
  6529. GGML_ASSERT(ggml_are_same_shape(a, b));
  6530. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  6531. result->op = GGML_OP_CROSS_ENTROPY_LOSS;
  6532. result->src[0] = a;
  6533. result->src[1] = b;
  6534. return result;
  6535. }
  6536. // ggml_cross_entropy_loss_back
  6537. struct ggml_tensor * ggml_cross_entropy_loss_back(
  6538. struct ggml_context * ctx,
  6539. struct ggml_tensor * a,
  6540. struct ggml_tensor * b,
  6541. struct ggml_tensor * c) {
  6542. GGML_ASSERT(ggml_are_same_shape(a, b));
  6543. GGML_ASSERT(ggml_is_scalar(c));
  6544. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  6545. result->op = GGML_OP_CROSS_ENTROPY_LOSS_BACK;
  6546. result->src[0] = a;
  6547. result->src[1] = b;
  6548. result->src[2] = c;
  6549. return result;
  6550. }
  6551. // opt_step_adamw
  6552. struct ggml_tensor * ggml_opt_step_adamw(
  6553. struct ggml_context * ctx,
  6554. struct ggml_tensor * a,
  6555. struct ggml_tensor * grad,
  6556. float alpha,
  6557. float beta1,
  6558. float beta2,
  6559. float eps,
  6560. float wd) {
  6561. GGML_ASSERT(a->flags & GGML_TENSOR_FLAG_PARAM);
  6562. GGML_ASSERT(ggml_are_same_shape(a, grad));
  6563. GGML_ASSERT(alpha > 0.0f);
  6564. GGML_ASSERT(beta1 >= 0.0f && beta1 <= 1.0f);
  6565. GGML_ASSERT(beta2 >= 0.0f && beta2 <= 1.0f);
  6566. GGML_ASSERT(eps >= 0.0f);
  6567. GGML_ASSERT(wd >= 0.0f && wd <= 1.0f);
  6568. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  6569. const int64_t iter = 1;
  6570. memcpy(&result->op_params[0], &iter, sizeof(int64_t));
  6571. ggml_set_op_params_f32(result, 2, alpha);
  6572. ggml_set_op_params_f32(result, 3, beta1);
  6573. ggml_set_op_params_f32(result, 4, beta2);
  6574. ggml_set_op_params_f32(result, 5, eps);
  6575. ggml_set_op_params_f32(result, 6, wd);
  6576. result->op = GGML_OP_OPT_STEP_ADAMW;
  6577. result->src[0] = a;
  6578. result->src[1] = grad;
  6579. result->src[2] = ggml_dup_tensor(ctx, grad);
  6580. result->src[3] = ggml_dup_tensor(ctx, grad);
  6581. return result;
  6582. }
  6583. ////////////////////////////////////////////////////////////////////////////////
  6584. // ggml_compute_forward_dup
  6585. static void ggml_compute_forward_dup_same_cont(
  6586. const struct ggml_compute_params * params,
  6587. struct ggml_tensor * dst) {
  6588. const struct ggml_tensor * src0 = dst->src[0];
  6589. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  6590. GGML_ASSERT(ggml_is_contiguous(dst) && ggml_is_contiguous(src0));
  6591. GGML_ASSERT(src0->type == dst->type);
  6592. const size_t nb0 = ggml_type_size(src0->type);
  6593. const int ith = params->ith; // thread index
  6594. const int nth = params->nth; // number of threads
  6595. // parallelize by elements
  6596. const int ne = ggml_nelements(dst);
  6597. const int dr = (ne + nth - 1) / nth;
  6598. const int ie0 = dr * ith;
  6599. const int ie1 = MIN(ie0 + dr, ne);
  6600. if (ie0 < ie1) {
  6601. memcpy(
  6602. ((char *) dst->data + ie0*nb0),
  6603. ((char *) src0->data + ie0*nb0),
  6604. (ie1 - ie0) * nb0);
  6605. }
  6606. }
  6607. static void ggml_compute_forward_dup_f16(
  6608. const struct ggml_compute_params * params,
  6609. struct ggml_tensor * dst) {
  6610. const struct ggml_tensor * src0 = dst->src[0];
  6611. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  6612. GGML_TENSOR_UNARY_OP_LOCALS
  6613. const int ith = params->ith; // thread index
  6614. const int nth = params->nth; // number of threads
  6615. // parallelize by rows
  6616. const int nr = ne01;
  6617. // number of rows per thread
  6618. const int dr = (nr + nth - 1) / nth;
  6619. // row range for this thread
  6620. const int ir0 = dr * ith;
  6621. const int ir1 = MIN(ir0 + dr, nr);
  6622. if (src0->type == dst->type &&
  6623. ne00 == ne0 &&
  6624. nb00 == ggml_type_size(src0->type) && nb0 == ggml_type_size(dst->type)) {
  6625. // copy by rows
  6626. const size_t rs = ne00*nb00;
  6627. for (int64_t i03 = 0; i03 < ne03; i03++) {
  6628. for (int64_t i02 = 0; i02 < ne02; i02++) {
  6629. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  6630. memcpy(
  6631. ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  6632. ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03),
  6633. rs);
  6634. }
  6635. }
  6636. }
  6637. return;
  6638. }
  6639. // TODO: add more special-case implementations for tensor shapes/strides that can benefit from memcpy
  6640. if (ggml_is_contiguous(dst)) {
  6641. if (nb00 == sizeof(ggml_fp16_t)) {
  6642. if (dst->type == GGML_TYPE_F16) {
  6643. size_t id = 0;
  6644. const size_t rs = ne00 * nb00;
  6645. char * dst_ptr = (char *) dst->data;
  6646. for (int i03 = 0; i03 < ne03; i03++) {
  6647. for (int i02 = 0; i02 < ne02; i02++) {
  6648. id += rs * ir0;
  6649. for (int i01 = ir0; i01 < ir1; i01++) {
  6650. const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  6651. memcpy(dst_ptr + id, src0_ptr, rs);
  6652. id += rs;
  6653. }
  6654. id += rs * (ne01 - ir1);
  6655. }
  6656. }
  6657. } else if (dst->type == GGML_TYPE_F32) {
  6658. size_t id = 0;
  6659. float * dst_ptr = (float *) dst->data;
  6660. for (int i03 = 0; i03 < ne03; i03++) {
  6661. for (int i02 = 0; i02 < ne02; i02++) {
  6662. id += ne00 * ir0;
  6663. for (int i01 = ir0; i01 < ir1; i01++) {
  6664. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6665. for (int i00 = 0; i00 < ne00; i00++) {
  6666. dst_ptr[id] = GGML_FP16_TO_FP32(src0_ptr[i00]);
  6667. id++;
  6668. }
  6669. }
  6670. id += ne00 * (ne01 - ir1);
  6671. }
  6672. }
  6673. } else if (type_traits[dst->type].from_float) {
  6674. ggml_from_float_t const quantize_row_q = type_traits[dst->type].from_float;
  6675. float * src0_f32 = (float *) params->wdata + (ne00 + CACHE_LINE_SIZE_F32) * ith;
  6676. size_t id = 0;
  6677. size_t rs = nb0 * (ne00 / ggml_blck_size(dst->type));
  6678. char * dst_ptr = (char *) dst->data;
  6679. for (int i03 = 0; i03 < ne03; i03++) {
  6680. for (int i02 = 0; i02 < ne02; i02++) {
  6681. id += rs * ir0;
  6682. for (int i01 = ir0; i01 < ir1; i01++) {
  6683. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6684. for (int i00 = 0; i00 < ne00; i00++) {
  6685. src0_f32[i00] = GGML_FP16_TO_FP32(src0_ptr[i00]);
  6686. }
  6687. quantize_row_q(src0_f32, dst_ptr + id, ne00);
  6688. id += rs;
  6689. }
  6690. id += rs * (ne01 - ir1);
  6691. }
  6692. }
  6693. } else {
  6694. GGML_ABORT("fatal error"); // TODO: implement
  6695. }
  6696. } else {
  6697. //printf("%s: this is not optimal - fix me\n", __func__);
  6698. if (dst->type == GGML_TYPE_F32) {
  6699. size_t id = 0;
  6700. float * dst_ptr = (float *) dst->data;
  6701. for (int i03 = 0; i03 < ne03; i03++) {
  6702. for (int i02 = 0; i02 < ne02; i02++) {
  6703. id += ne00 * ir0;
  6704. for (int i01 = ir0; i01 < ir1; i01++) {
  6705. for (int i00 = 0; i00 < ne00; i00++) {
  6706. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6707. dst_ptr[id] = GGML_FP16_TO_FP32(*src0_ptr);
  6708. id++;
  6709. }
  6710. }
  6711. id += ne00 * (ne01 - ir1);
  6712. }
  6713. }
  6714. } else if (dst->type == GGML_TYPE_F16) {
  6715. size_t id = 0;
  6716. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  6717. for (int i03 = 0; i03 < ne03; i03++) {
  6718. for (int i02 = 0; i02 < ne02; i02++) {
  6719. id += ne00 * ir0;
  6720. for (int i01 = ir0; i01 < ir1; i01++) {
  6721. for (int i00 = 0; i00 < ne00; i00++) {
  6722. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6723. dst_ptr[id] = *src0_ptr;
  6724. id++;
  6725. }
  6726. }
  6727. id += ne00 * (ne01 - ir1);
  6728. }
  6729. }
  6730. } else {
  6731. GGML_ABORT("fatal error"); // TODO: implement
  6732. }
  6733. }
  6734. return;
  6735. }
  6736. // dst counters
  6737. int64_t i10 = 0;
  6738. int64_t i11 = 0;
  6739. int64_t i12 = 0;
  6740. int64_t i13 = 0;
  6741. if (dst->type == GGML_TYPE_F16) {
  6742. for (int64_t i03 = 0; i03 < ne03; i03++) {
  6743. for (int64_t i02 = 0; i02 < ne02; i02++) {
  6744. i10 += ne00 * ir0;
  6745. while (i10 >= ne0) {
  6746. i10 -= ne0;
  6747. if (++i11 == ne1) {
  6748. i11 = 0;
  6749. if (++i12 == ne2) {
  6750. i12 = 0;
  6751. if (++i13 == ne3) {
  6752. i13 = 0;
  6753. }
  6754. }
  6755. }
  6756. }
  6757. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  6758. for (int64_t i00 = 0; i00 < ne00; i00++) {
  6759. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6760. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  6761. memcpy(dst_ptr, src0_ptr, sizeof(ggml_fp16_t));
  6762. if (++i10 == ne00) {
  6763. i10 = 0;
  6764. if (++i11 == ne01) {
  6765. i11 = 0;
  6766. if (++i12 == ne02) {
  6767. i12 = 0;
  6768. if (++i13 == ne03) {
  6769. i13 = 0;
  6770. }
  6771. }
  6772. }
  6773. }
  6774. }
  6775. }
  6776. i10 += ne00 * (ne01 - ir1);
  6777. while (i10 >= ne0) {
  6778. i10 -= ne0;
  6779. if (++i11 == ne1) {
  6780. i11 = 0;
  6781. if (++i12 == ne2) {
  6782. i12 = 0;
  6783. if (++i13 == ne3) {
  6784. i13 = 0;
  6785. }
  6786. }
  6787. }
  6788. }
  6789. }
  6790. }
  6791. } else if (dst->type == GGML_TYPE_F32) {
  6792. for (int64_t i03 = 0; i03 < ne03; i03++) {
  6793. for (int64_t i02 = 0; i02 < ne02; i02++) {
  6794. i10 += ne00 * ir0;
  6795. while (i10 >= ne0) {
  6796. i10 -= ne0;
  6797. if (++i11 == ne1) {
  6798. i11 = 0;
  6799. if (++i12 == ne2) {
  6800. i12 = 0;
  6801. if (++i13 == ne3) {
  6802. i13 = 0;
  6803. }
  6804. }
  6805. }
  6806. }
  6807. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  6808. for (int64_t i00 = 0; i00 < ne00; i00++) {
  6809. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6810. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  6811. *(float *) dst_ptr = GGML_FP16_TO_FP32(*(const ggml_fp16_t *) src0_ptr);
  6812. if (++i10 == ne0) {
  6813. i10 = 0;
  6814. if (++i11 == ne1) {
  6815. i11 = 0;
  6816. if (++i12 == ne2) {
  6817. i12 = 0;
  6818. if (++i13 == ne3) {
  6819. i13 = 0;
  6820. }
  6821. }
  6822. }
  6823. }
  6824. }
  6825. }
  6826. i10 += ne00 * (ne01 - ir1);
  6827. while (i10 >= ne0) {
  6828. i10 -= ne0;
  6829. if (++i11 == ne1) {
  6830. i11 = 0;
  6831. if (++i12 == ne2) {
  6832. i12 = 0;
  6833. if (++i13 == ne3) {
  6834. i13 = 0;
  6835. }
  6836. }
  6837. }
  6838. }
  6839. }
  6840. }
  6841. } else {
  6842. GGML_ABORT("fatal error"); // TODO: implement
  6843. }
  6844. }
  6845. static void ggml_compute_forward_dup_bf16(
  6846. const struct ggml_compute_params * params,
  6847. struct ggml_tensor * dst) {
  6848. const struct ggml_tensor * src0 = dst->src[0];
  6849. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  6850. GGML_TENSOR_UNARY_OP_LOCALS
  6851. const int ith = params->ith; // thread index
  6852. const int nth = params->nth; // number of threads
  6853. // parallelize by rows
  6854. const int nr = ne01;
  6855. // number of rows per thread
  6856. const int dr = (nr + nth - 1) / nth;
  6857. // row range for this thread
  6858. const int ir0 = dr * ith;
  6859. const int ir1 = MIN(ir0 + dr, nr);
  6860. if (src0->type == dst->type &&
  6861. ne00 == ne0 &&
  6862. nb00 == ggml_type_size(src0->type) && nb0 == ggml_type_size(dst->type)) {
  6863. // copy by rows
  6864. const size_t rs = ne00*nb00;
  6865. for (int64_t i03 = 0; i03 < ne03; i03++) {
  6866. for (int64_t i02 = 0; i02 < ne02; i02++) {
  6867. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  6868. memcpy(
  6869. ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  6870. ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03),
  6871. rs);
  6872. }
  6873. }
  6874. }
  6875. return;
  6876. }
  6877. // TODO: add more special-case implementations for tensor shapes/strides that can benefit from memcpy
  6878. if (ggml_is_contiguous(dst)) {
  6879. if (nb00 == sizeof(ggml_bf16_t)) {
  6880. if (dst->type == GGML_TYPE_BF16) {
  6881. size_t id = 0;
  6882. const size_t rs = ne00 * nb00;
  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 char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  6889. memcpy(dst_ptr + id, src0_ptr, rs);
  6890. id += rs;
  6891. }
  6892. id += rs * (ne01 - ir1);
  6893. }
  6894. }
  6895. } else if (dst->type == GGML_TYPE_F16) {
  6896. size_t id = 0;
  6897. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  6898. for (int i03 = 0; i03 < ne03; i03++) {
  6899. for (int i02 = 0; i02 < ne02; i02++) {
  6900. id += ne00 * ir0;
  6901. for (int i01 = ir0; i01 < ir1; i01++) {
  6902. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6903. for (int i00 = 0; i00 < ne00; i00++) {
  6904. dst_ptr[id] = GGML_FP32_TO_FP16(GGML_BF16_TO_FP32(src0_ptr[i00]));
  6905. id++;
  6906. }
  6907. }
  6908. id += ne00 * (ne01 - ir1);
  6909. }
  6910. }
  6911. } else if (dst->type == GGML_TYPE_F32) {
  6912. size_t id = 0;
  6913. float * dst_ptr = (float *) dst->data;
  6914. for (int i03 = 0; i03 < ne03; i03++) {
  6915. for (int i02 = 0; i02 < ne02; i02++) {
  6916. id += ne00 * ir0;
  6917. for (int i01 = ir0; i01 < ir1; i01++) {
  6918. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6919. for (int i00 = 0; i00 < ne00; i00++) {
  6920. dst_ptr[id] = GGML_BF16_TO_FP32(src0_ptr[i00]);
  6921. id++;
  6922. }
  6923. }
  6924. id += ne00 * (ne01 - ir1);
  6925. }
  6926. }
  6927. } else if (type_traits[dst->type].from_float) {
  6928. ggml_from_float_t const quantize_row_q = type_traits[dst->type].from_float;
  6929. float * src0_f32 = (float *) params->wdata + (ne00 + CACHE_LINE_SIZE_F32) * ith;
  6930. size_t id = 0;
  6931. size_t rs = nb0 * (ne00 / ggml_blck_size(dst->type));
  6932. char * dst_ptr = (char *) dst->data;
  6933. for (int i03 = 0; i03 < ne03; i03++) {
  6934. for (int i02 = 0; i02 < ne02; i02++) {
  6935. id += rs * ir0;
  6936. for (int i01 = ir0; i01 < ir1; i01++) {
  6937. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  6938. for (int i00 = 0; i00 < ne00; i00++) {
  6939. src0_f32[i00] = GGML_BF16_TO_FP32(src0_ptr[i00]);
  6940. }
  6941. quantize_row_q(src0_f32, dst_ptr + id, ne00);
  6942. id += rs;
  6943. }
  6944. id += rs * (ne01 - ir1);
  6945. }
  6946. }
  6947. } else {
  6948. GGML_ABORT("fatal error"); // TODO: implement
  6949. }
  6950. } else {
  6951. //printf("%s: this is not optimal - fix me\n", __func__);
  6952. if (dst->type == GGML_TYPE_F32) {
  6953. size_t id = 0;
  6954. float * dst_ptr = (float *) dst->data;
  6955. for (int i03 = 0; i03 < ne03; i03++) {
  6956. for (int i02 = 0; i02 < ne02; i02++) {
  6957. id += ne00 * ir0;
  6958. for (int i01 = ir0; i01 < ir1; i01++) {
  6959. for (int i00 = 0; i00 < ne00; i00++) {
  6960. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6961. dst_ptr[id] = GGML_BF16_TO_FP32(*src0_ptr);
  6962. id++;
  6963. }
  6964. }
  6965. id += ne00 * (ne01 - ir1);
  6966. }
  6967. }
  6968. } else if (dst->type == GGML_TYPE_BF16) {
  6969. size_t id = 0;
  6970. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) dst->data;
  6971. for (int i03 = 0; i03 < ne03; i03++) {
  6972. for (int i02 = 0; i02 < ne02; i02++) {
  6973. id += ne00 * ir0;
  6974. for (int i01 = ir0; i01 < ir1; i01++) {
  6975. for (int i00 = 0; i00 < ne00; i00++) {
  6976. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6977. dst_ptr[id] = *src0_ptr;
  6978. id++;
  6979. }
  6980. }
  6981. id += ne00 * (ne01 - ir1);
  6982. }
  6983. }
  6984. } else if (dst->type == GGML_TYPE_F16) {
  6985. size_t id = 0;
  6986. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  6987. for (int i03 = 0; i03 < ne03; i03++) {
  6988. for (int i02 = 0; i02 < ne02; i02++) {
  6989. id += ne00 * ir0;
  6990. for (int i01 = ir0; i01 < ir1; i01++) {
  6991. for (int i00 = 0; i00 < ne00; i00++) {
  6992. const ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  6993. dst_ptr[id] = GGML_FP32_TO_FP16(GGML_BF16_TO_FP32(*src0_ptr));
  6994. id++;
  6995. }
  6996. }
  6997. id += ne00 * (ne01 - ir1);
  6998. }
  6999. }
  7000. } else {
  7001. GGML_ABORT("fatal error"); // TODO: implement
  7002. }
  7003. }
  7004. return;
  7005. }
  7006. // dst counters
  7007. int64_t i10 = 0;
  7008. int64_t i11 = 0;
  7009. int64_t i12 = 0;
  7010. int64_t i13 = 0;
  7011. if (dst->type == GGML_TYPE_BF16) {
  7012. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7013. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7014. i10 += ne00 * ir0;
  7015. while (i10 >= ne0) {
  7016. i10 -= ne0;
  7017. if (++i11 == ne1) {
  7018. i11 = 0;
  7019. if (++i12 == ne2) {
  7020. i12 = 0;
  7021. if (++i13 == ne3) {
  7022. i13 = 0;
  7023. }
  7024. }
  7025. }
  7026. }
  7027. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7028. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7029. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7030. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7031. memcpy(dst_ptr, src0_ptr, sizeof(ggml_bf16_t));
  7032. if (++i10 == ne00) {
  7033. i10 = 0;
  7034. if (++i11 == ne01) {
  7035. i11 = 0;
  7036. if (++i12 == ne02) {
  7037. i12 = 0;
  7038. if (++i13 == ne03) {
  7039. i13 = 0;
  7040. }
  7041. }
  7042. }
  7043. }
  7044. }
  7045. }
  7046. i10 += ne00 * (ne01 - ir1);
  7047. while (i10 >= ne0) {
  7048. i10 -= ne0;
  7049. if (++i11 == ne1) {
  7050. i11 = 0;
  7051. if (++i12 == ne2) {
  7052. i12 = 0;
  7053. if (++i13 == ne3) {
  7054. i13 = 0;
  7055. }
  7056. }
  7057. }
  7058. }
  7059. }
  7060. }
  7061. } else if (dst->type == GGML_TYPE_F16) {
  7062. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7063. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7064. i10 += ne00 * ir0;
  7065. while (i10 >= ne0) {
  7066. i10 -= ne0;
  7067. if (++i11 == ne1) {
  7068. i11 = 0;
  7069. if (++i12 == ne2) {
  7070. i12 = 0;
  7071. if (++i13 == ne3) {
  7072. i13 = 0;
  7073. }
  7074. }
  7075. }
  7076. }
  7077. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7078. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7079. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7080. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7081. *(ggml_fp16_t *) dst_ptr = GGML_FP32_TO_FP16(GGML_BF16_TO_FP32(*(const ggml_bf16_t *) src0_ptr));
  7082. if (++i10 == ne0) {
  7083. i10 = 0;
  7084. if (++i11 == ne1) {
  7085. i11 = 0;
  7086. if (++i12 == ne2) {
  7087. i12 = 0;
  7088. if (++i13 == ne3) {
  7089. i13 = 0;
  7090. }
  7091. }
  7092. }
  7093. }
  7094. }
  7095. }
  7096. i10 += ne00 * (ne01 - ir1);
  7097. while (i10 >= ne0) {
  7098. i10 -= ne0;
  7099. if (++i11 == ne1) {
  7100. i11 = 0;
  7101. if (++i12 == ne2) {
  7102. i12 = 0;
  7103. if (++i13 == ne3) {
  7104. i13 = 0;
  7105. }
  7106. }
  7107. }
  7108. }
  7109. }
  7110. }
  7111. } else if (dst->type == GGML_TYPE_F32) {
  7112. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7113. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7114. i10 += ne00 * ir0;
  7115. while (i10 >= ne0) {
  7116. i10 -= ne0;
  7117. if (++i11 == ne1) {
  7118. i11 = 0;
  7119. if (++i12 == ne2) {
  7120. i12 = 0;
  7121. if (++i13 == ne3) {
  7122. i13 = 0;
  7123. }
  7124. }
  7125. }
  7126. }
  7127. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7128. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7129. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7130. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7131. *(float *) dst_ptr = GGML_BF16_TO_FP32(*(const ggml_bf16_t *) src0_ptr);
  7132. if (++i10 == ne0) {
  7133. i10 = 0;
  7134. if (++i11 == ne1) {
  7135. i11 = 0;
  7136. if (++i12 == ne2) {
  7137. i12 = 0;
  7138. if (++i13 == ne3) {
  7139. i13 = 0;
  7140. }
  7141. }
  7142. }
  7143. }
  7144. }
  7145. }
  7146. i10 += ne00 * (ne01 - ir1);
  7147. while (i10 >= ne0) {
  7148. i10 -= ne0;
  7149. if (++i11 == ne1) {
  7150. i11 = 0;
  7151. if (++i12 == ne2) {
  7152. i12 = 0;
  7153. if (++i13 == ne3) {
  7154. i13 = 0;
  7155. }
  7156. }
  7157. }
  7158. }
  7159. }
  7160. }
  7161. } else {
  7162. GGML_ABORT("fatal error"); // TODO: implement
  7163. }
  7164. }
  7165. static void ggml_compute_forward_dup_f32(
  7166. const struct ggml_compute_params * params,
  7167. struct ggml_tensor * dst) {
  7168. const struct ggml_tensor * src0 = dst->src[0];
  7169. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  7170. GGML_TENSOR_UNARY_OP_LOCALS
  7171. const int ith = params->ith; // thread index
  7172. const int nth = params->nth; // number of threads
  7173. // parallelize by rows
  7174. const int nr = ne01;
  7175. // number of rows per thread
  7176. const int dr = (nr + nth - 1) / nth;
  7177. // row range for this thread
  7178. const int ir0 = dr * ith;
  7179. const int ir1 = MIN(ir0 + dr, nr);
  7180. if (src0->type == dst->type &&
  7181. ne00 == ne0 &&
  7182. nb00 == ggml_type_size(src0->type) && nb0 == ggml_type_size(dst->type)) {
  7183. // copy by rows
  7184. const size_t rs = ne00*nb00;
  7185. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7186. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7187. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7188. memcpy(
  7189. ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  7190. ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03),
  7191. rs);
  7192. }
  7193. }
  7194. }
  7195. return;
  7196. }
  7197. if (ggml_is_contiguous(dst)) {
  7198. // TODO: simplify
  7199. if (nb00 == sizeof(float)) {
  7200. if (dst->type == GGML_TYPE_F32) {
  7201. size_t id = 0;
  7202. const size_t rs = ne00 * nb00;
  7203. char * dst_ptr = (char *) dst->data;
  7204. for (int i03 = 0; i03 < ne03; i03++) {
  7205. for (int i02 = 0; i02 < ne02; i02++) {
  7206. id += rs * ir0;
  7207. for (int i01 = ir0; i01 < ir1; i01++) {
  7208. const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  7209. memcpy(dst_ptr + id, src0_ptr, rs);
  7210. id += rs;
  7211. }
  7212. id += rs * (ne01 - ir1);
  7213. }
  7214. }
  7215. } else if (type_traits[dst->type].from_float) {
  7216. ggml_from_float_t const quantize_row_q = type_traits[dst->type].from_float;
  7217. size_t id = 0;
  7218. size_t rs = nb0 * (ne00 / ggml_blck_size(dst->type));
  7219. char * dst_ptr = (char *) dst->data;
  7220. for (int i03 = 0; i03 < ne03; i03++) {
  7221. for (int i02 = 0; i02 < ne02; i02++) {
  7222. id += rs * ir0;
  7223. for (int i01 = ir0; i01 < ir1; i01++) {
  7224. const float * src0_ptr = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  7225. quantize_row_q(src0_ptr, dst_ptr + id, ne00);
  7226. id += rs;
  7227. }
  7228. id += rs * (ne01 - ir1);
  7229. }
  7230. }
  7231. } else {
  7232. GGML_ABORT("fatal error"); // TODO: implement
  7233. }
  7234. } else {
  7235. //printf("%s: this is not optimal - fix me\n", __func__);
  7236. if (dst->type == GGML_TYPE_F32) {
  7237. size_t id = 0;
  7238. float * dst_ptr = (float *) dst->data;
  7239. for (int i03 = 0; i03 < ne03; i03++) {
  7240. for (int i02 = 0; i02 < ne02; i02++) {
  7241. id += ne00 * ir0;
  7242. for (int i01 = ir0; i01 < ir1; i01++) {
  7243. for (int i00 = 0; i00 < ne00; i00++) {
  7244. const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7245. dst_ptr[id] = *src0_ptr;
  7246. id++;
  7247. }
  7248. }
  7249. id += ne00 * (ne01 - ir1);
  7250. }
  7251. }
  7252. } else if (dst->type == GGML_TYPE_F16) {
  7253. size_t id = 0;
  7254. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  7255. for (int i03 = 0; i03 < ne03; i03++) {
  7256. for (int i02 = 0; i02 < ne02; i02++) {
  7257. id += ne00 * ir0;
  7258. for (int i01 = ir0; i01 < ir1; i01++) {
  7259. for (int i00 = 0; i00 < ne00; i00++) {
  7260. const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7261. dst_ptr[id] = GGML_FP32_TO_FP16(*src0_ptr);
  7262. id++;
  7263. }
  7264. }
  7265. id += ne00 * (ne01 - ir1);
  7266. }
  7267. }
  7268. } else if (dst->type == GGML_TYPE_BF16) {
  7269. size_t id = 0;
  7270. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) dst->data;
  7271. for (int i03 = 0; i03 < ne03; i03++) {
  7272. for (int i02 = 0; i02 < ne02; i02++) {
  7273. id += ne00 * ir0;
  7274. for (int i01 = ir0; i01 < ir1; i01++) {
  7275. for (int i00 = 0; i00 < ne00; i00++) {
  7276. const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7277. dst_ptr[id] = GGML_FP32_TO_BF16(*src0_ptr);
  7278. id++;
  7279. }
  7280. }
  7281. id += ne00 * (ne01 - ir1);
  7282. }
  7283. }
  7284. } else {
  7285. GGML_ABORT("fatal error"); // TODO: implement
  7286. }
  7287. }
  7288. return;
  7289. }
  7290. // dst counters
  7291. int64_t i10 = 0;
  7292. int64_t i11 = 0;
  7293. int64_t i12 = 0;
  7294. int64_t i13 = 0;
  7295. if (dst->type == GGML_TYPE_F32) {
  7296. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7297. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7298. i10 += ne00 * ir0;
  7299. while (i10 >= ne0) {
  7300. i10 -= ne0;
  7301. if (++i11 == ne1) {
  7302. i11 = 0;
  7303. if (++i12 == ne2) {
  7304. i12 = 0;
  7305. if (++i13 == ne3) {
  7306. i13 = 0;
  7307. }
  7308. }
  7309. }
  7310. }
  7311. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7312. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7313. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7314. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7315. memcpy(dst_ptr, src0_ptr, sizeof(float));
  7316. if (++i10 == ne0) {
  7317. i10 = 0;
  7318. if (++i11 == ne1) {
  7319. i11 = 0;
  7320. if (++i12 == ne2) {
  7321. i12 = 0;
  7322. if (++i13 == ne3) {
  7323. i13 = 0;
  7324. }
  7325. }
  7326. }
  7327. }
  7328. }
  7329. }
  7330. i10 += ne00 * (ne01 - ir1);
  7331. while (i10 >= ne0) {
  7332. i10 -= ne0;
  7333. if (++i11 == ne1) {
  7334. i11 = 0;
  7335. if (++i12 == ne2) {
  7336. i12 = 0;
  7337. if (++i13 == ne3) {
  7338. i13 = 0;
  7339. }
  7340. }
  7341. }
  7342. }
  7343. }
  7344. }
  7345. } else if (dst->type == GGML_TYPE_F16) {
  7346. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7347. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7348. i10 += ne00 * ir0;
  7349. while (i10 >= ne0) {
  7350. i10 -= ne0;
  7351. if (++i11 == ne1) {
  7352. i11 = 0;
  7353. if (++i12 == ne2) {
  7354. i12 = 0;
  7355. if (++i13 == ne3) {
  7356. i13 = 0;
  7357. }
  7358. }
  7359. }
  7360. }
  7361. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7362. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7363. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7364. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7365. *(ggml_fp16_t *) dst_ptr = GGML_FP32_TO_FP16(*(const float *) src0_ptr);
  7366. if (++i10 == ne0) {
  7367. i10 = 0;
  7368. if (++i11 == ne1) {
  7369. i11 = 0;
  7370. if (++i12 == ne2) {
  7371. i12 = 0;
  7372. if (++i13 == ne3) {
  7373. i13 = 0;
  7374. }
  7375. }
  7376. }
  7377. }
  7378. }
  7379. }
  7380. i10 += ne00 * (ne01 - ir1);
  7381. while (i10 >= ne0) {
  7382. i10 -= ne0;
  7383. if (++i11 == ne1) {
  7384. i11 = 0;
  7385. if (++i12 == ne2) {
  7386. i12 = 0;
  7387. if (++i13 == ne3) {
  7388. i13 = 0;
  7389. }
  7390. }
  7391. }
  7392. }
  7393. }
  7394. }
  7395. } else if (dst->type == GGML_TYPE_BF16) {
  7396. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7397. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7398. i10 += ne00 * ir0;
  7399. while (i10 >= ne0) {
  7400. i10 -= ne0;
  7401. if (++i11 == ne1) {
  7402. i11 = 0;
  7403. if (++i12 == ne2) {
  7404. i12 = 0;
  7405. if (++i13 == ne3) {
  7406. i13 = 0;
  7407. }
  7408. }
  7409. }
  7410. }
  7411. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7412. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7413. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7414. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7415. *(ggml_bf16_t *) dst_ptr = GGML_FP32_TO_BF16(*(const float *) src0_ptr);
  7416. if (++i10 == ne0) {
  7417. i10 = 0;
  7418. if (++i11 == ne1) {
  7419. i11 = 0;
  7420. if (++i12 == ne2) {
  7421. i12 = 0;
  7422. if (++i13 == ne3) {
  7423. i13 = 0;
  7424. }
  7425. }
  7426. }
  7427. }
  7428. }
  7429. }
  7430. i10 += ne00 * (ne01 - ir1);
  7431. while (i10 >= ne0) {
  7432. i10 -= ne0;
  7433. if (++i11 == ne1) {
  7434. i11 = 0;
  7435. if (++i12 == ne2) {
  7436. i12 = 0;
  7437. if (++i13 == ne3) {
  7438. i13 = 0;
  7439. }
  7440. }
  7441. }
  7442. }
  7443. }
  7444. }
  7445. } else {
  7446. GGML_ABORT("fatal error"); // TODO: implement
  7447. }
  7448. }
  7449. // A simplified version of ggml_compute_forward_dup that doesn't do float upcasting, and just plain old memcpy.
  7450. static void ggml_compute_forward_dup_bytes(
  7451. const struct ggml_compute_params * params,
  7452. struct ggml_tensor * dst) {
  7453. const struct ggml_tensor * src0 = dst->src[0];
  7454. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  7455. GGML_ASSERT(src0->type == dst->type);
  7456. GGML_TENSOR_UNARY_OP_LOCALS;
  7457. if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) {
  7458. ggml_compute_forward_dup_same_cont(params, dst);
  7459. return;
  7460. }
  7461. const size_t type_size = ggml_type_size(src0->type);
  7462. const int ith = params->ith; // thread index
  7463. const int nth = params->nth; // number of threads
  7464. // parallelize by rows
  7465. const int nr = ne01;
  7466. // number of rows per thread
  7467. const int dr = (nr + nth - 1) / nth;
  7468. // row range for this thread
  7469. const int ir0 = dr * ith;
  7470. const int ir1 = MIN(ir0 + dr, nr);
  7471. if (src0->type == dst->type &&
  7472. ne00 == ne0 &&
  7473. nb00 == type_size && nb0 == type_size) {
  7474. // copy by rows
  7475. const size_t rs = ne00 * type_size;
  7476. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7477. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7478. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7479. memcpy(
  7480. ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  7481. ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03),
  7482. rs);
  7483. }
  7484. }
  7485. }
  7486. return;
  7487. }
  7488. if (ggml_is_contiguous(dst)) {
  7489. size_t id = 0;
  7490. char * dst_ptr = (char *) dst->data;
  7491. const size_t rs = ne00 * type_size;
  7492. if (nb00 == type_size) {
  7493. // src0 is contigous on first dimension, copy by rows
  7494. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7495. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7496. id += rs * ir0;
  7497. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7498. const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  7499. memcpy(dst_ptr + id, src0_ptr, rs);
  7500. id += rs;
  7501. }
  7502. id += rs * (ne01 - ir1);
  7503. }
  7504. }
  7505. } else {
  7506. //printf("%s: this is not optimal - fix me\n", __func__);
  7507. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7508. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7509. id += rs * ir0;
  7510. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7511. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7512. const char * src0_ptr = (char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03;
  7513. memcpy(dst_ptr + id, src0_ptr, type_size);
  7514. id += type_size;
  7515. }
  7516. }
  7517. id += rs * (ne01 - ir1);
  7518. }
  7519. }
  7520. }
  7521. return;
  7522. }
  7523. // dst counters
  7524. int64_t i10 = 0;
  7525. int64_t i11 = 0;
  7526. int64_t i12 = 0;
  7527. int64_t i13 = 0;
  7528. for (int64_t i03 = 0; i03 < ne03; i03++) {
  7529. for (int64_t i02 = 0; i02 < ne02; i02++) {
  7530. i10 += ne00 * ir0;
  7531. while (i10 >= ne0) {
  7532. i10 -= ne0;
  7533. if (++i11 == ne1) {
  7534. i11 = 0;
  7535. if (++i12 == ne2) {
  7536. i12 = 0;
  7537. if (++i13 == ne3) {
  7538. i13 = 0;
  7539. }
  7540. }
  7541. }
  7542. }
  7543. for (int64_t i01 = ir0; i01 < ir1; i01++) {
  7544. for (int64_t i00 = 0; i00 < ne00; i00++) {
  7545. const char * src0_ptr = ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  7546. char * dst_ptr = ((char *) dst->data + i10*nb0 + i11*nb1 + i12*nb2 + i13*nb3);
  7547. memcpy(dst_ptr, src0_ptr, type_size);
  7548. if (++i10 == ne0) {
  7549. i10 = 0;
  7550. if (++i11 == ne1) {
  7551. i11 = 0;
  7552. if (++i12 == ne2) {
  7553. i12 = 0;
  7554. if (++i13 == ne3) {
  7555. i13 = 0;
  7556. }
  7557. }
  7558. }
  7559. }
  7560. }
  7561. }
  7562. i10 += ne00 * (ne01 - ir1);
  7563. while (i10 >= ne0) {
  7564. i10 -= ne0;
  7565. if (++i11 == ne1) {
  7566. i11 = 0;
  7567. if (++i12 == ne2) {
  7568. i12 = 0;
  7569. if (++i13 == ne3) {
  7570. i13 = 0;
  7571. }
  7572. }
  7573. }
  7574. }
  7575. }
  7576. }
  7577. }
  7578. static void ggml_compute_forward_dup(
  7579. const struct ggml_compute_params * params,
  7580. struct ggml_tensor * dst) {
  7581. const struct ggml_tensor * src0 = dst->src[0];
  7582. if (src0->type == dst->type) {
  7583. ggml_compute_forward_dup_bytes(params, dst);
  7584. return;
  7585. }
  7586. switch (src0->type) {
  7587. case GGML_TYPE_F16:
  7588. {
  7589. ggml_compute_forward_dup_f16(params, dst);
  7590. } break;
  7591. case GGML_TYPE_BF16:
  7592. {
  7593. ggml_compute_forward_dup_bf16(params, dst);
  7594. } break;
  7595. case GGML_TYPE_F32:
  7596. {
  7597. ggml_compute_forward_dup_f32(params, dst);
  7598. } break;
  7599. default:
  7600. {
  7601. GGML_ABORT("fatal error");
  7602. }
  7603. }
  7604. }
  7605. // ggml_compute_forward_add
  7606. static void ggml_compute_forward_add_f32(
  7607. const struct ggml_compute_params * params,
  7608. struct ggml_tensor * dst) {
  7609. const struct ggml_tensor * src0 = dst->src[0];
  7610. const struct ggml_tensor * src1 = dst->src[1];
  7611. GGML_ASSERT(ggml_can_repeat(src1, src0) && ggml_are_same_shape(src0, dst));
  7612. const int ith = params->ith;
  7613. const int nth = params->nth;
  7614. const int nr = ggml_nrows(src0);
  7615. GGML_TENSOR_BINARY_OP_LOCALS
  7616. GGML_ASSERT( nb0 == sizeof(float));
  7617. GGML_ASSERT(nb00 == sizeof(float));
  7618. // rows per thread
  7619. const int dr = (nr + nth - 1)/nth;
  7620. // row range for this thread
  7621. const int ir0 = dr*ith;
  7622. const int ir1 = MIN(ir0 + dr, nr);
  7623. if (nb10 == sizeof(float)) {
  7624. for (int ir = ir0; ir < ir1; ++ir) {
  7625. // src1 is broadcastable across src0 and dst in i1, i2, i3
  7626. const int64_t i03 = ir/(ne02*ne01);
  7627. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  7628. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  7629. const int64_t i13 = i03 % ne13;
  7630. const int64_t i12 = i02 % ne12;
  7631. const int64_t i11 = i01 % ne11;
  7632. const int64_t nr0 = ne00 / ne10;
  7633. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  7634. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  7635. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11);
  7636. for (int64_t r = 0; r < nr0; ++r) {
  7637. #ifdef GGML_USE_ACCELERATE
  7638. vDSP_vadd(src0_ptr + r*ne10, 1, src1_ptr, 1, dst_ptr + r*ne10, 1, ne10);
  7639. #else
  7640. ggml_vec_add_f32(ne10, dst_ptr + r*ne10, src0_ptr + r*ne10, src1_ptr);
  7641. #endif
  7642. }
  7643. }
  7644. } else {
  7645. // src1 is not contiguous
  7646. for (int ir = ir0; ir < ir1; ++ir) {
  7647. // src1 is broadcastable across src0 and dst in i1, i2, i3
  7648. const int64_t i03 = ir/(ne02*ne01);
  7649. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  7650. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  7651. const int64_t i13 = i03 % ne13;
  7652. const int64_t i12 = i02 % ne12;
  7653. const int64_t i11 = i01 % ne11;
  7654. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  7655. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  7656. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  7657. const int64_t i10 = i0 % ne10;
  7658. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10);
  7659. dst_ptr[i0] = src0_ptr[i0] + *src1_ptr;
  7660. }
  7661. }
  7662. }
  7663. }
  7664. static void ggml_compute_forward_add_f16_f32(
  7665. const struct ggml_compute_params * params,
  7666. struct ggml_tensor * dst) {
  7667. const struct ggml_tensor * src0 = dst->src[0];
  7668. const struct ggml_tensor * src1 = dst->src[1];
  7669. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7670. const int ith = params->ith;
  7671. const int nth = params->nth;
  7672. const int nr = ggml_nrows(src0);
  7673. GGML_TENSOR_BINARY_OP_LOCALS
  7674. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  7675. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  7676. if (dst->type == GGML_TYPE_F32) {
  7677. GGML_ASSERT( nb0 == sizeof(float));
  7678. }
  7679. else {
  7680. GGML_ASSERT(dst->type == GGML_TYPE_F16);
  7681. GGML_ASSERT( nb0 == sizeof(ggml_fp16_t));
  7682. }
  7683. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  7684. // rows per thread
  7685. const int dr = (nr + nth - 1)/nth;
  7686. // row range for this thread
  7687. const int ir0 = dr*ith;
  7688. const int ir1 = MIN(ir0 + dr, nr);
  7689. if (nb10 == sizeof(float)) {
  7690. if (dst->type == GGML_TYPE_F16) {
  7691. for (int ir = ir0; ir < ir1; ++ir) {
  7692. // src0, src1 and dst are same shape => same indices
  7693. const int i3 = ir/(ne2*ne1);
  7694. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7695. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7696. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7697. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7698. float * src1_ptr = (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7699. for (int i = 0; i < ne0; i++) {
  7700. dst_ptr[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(src0_ptr[i]) + src1_ptr[i]);
  7701. }
  7702. }
  7703. } else {
  7704. for (int ir = ir0; ir < ir1; ++ir) {
  7705. // src0, src1 and dst are same shape => same indices
  7706. const int i3 = ir/(ne2*ne1);
  7707. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7708. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7709. float * dst_ptr = (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7710. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7711. float * src1_ptr = (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7712. for (int i = 0; i < ne0; i++) {
  7713. dst_ptr[i] = GGML_FP16_TO_FP32(src0_ptr[i]) + src1_ptr[i];
  7714. }
  7715. }
  7716. }
  7717. }
  7718. else {
  7719. // src1 is not contiguous
  7720. GGML_ABORT("fatal error");
  7721. }
  7722. }
  7723. static void ggml_compute_forward_add_bf16_f32(
  7724. const struct ggml_compute_params * params,
  7725. struct ggml_tensor * dst) {
  7726. const struct ggml_tensor * src0 = dst->src[0];
  7727. const struct ggml_tensor * src1 = dst->src[1];
  7728. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7729. const int ith = params->ith;
  7730. const int nth = params->nth;
  7731. const int nr = ggml_nrows(src0);
  7732. GGML_TENSOR_BINARY_OP_LOCALS
  7733. GGML_ASSERT(src0->type == GGML_TYPE_BF16);
  7734. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  7735. if (dst->type == GGML_TYPE_F32) {
  7736. GGML_ASSERT( nb0 == sizeof(float));
  7737. }
  7738. else {
  7739. GGML_ASSERT(dst->type == GGML_TYPE_BF16);
  7740. GGML_ASSERT( nb0 == sizeof(ggml_bf16_t));
  7741. }
  7742. GGML_ASSERT(nb00 == sizeof(ggml_bf16_t));
  7743. // rows per thread
  7744. const int dr = (nr + nth - 1)/nth;
  7745. // row range for this thread
  7746. const int ir0 = dr*ith;
  7747. const int ir1 = MIN(ir0 + dr, nr);
  7748. if (nb10 == sizeof(float)) {
  7749. if (dst->type == GGML_TYPE_BF16) {
  7750. for (int ir = ir0; ir < ir1; ++ir) {
  7751. // src0, src1 and dst are same shape => same indices
  7752. const int i3 = ir/(ne2*ne1);
  7753. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7754. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7755. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7756. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7757. float * src1_ptr = (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7758. for (int i = 0; i < ne0; i++) {
  7759. dst_ptr[i] = GGML_FP32_TO_BF16(GGML_BF16_TO_FP32(src0_ptr[i]) + src1_ptr[i]);
  7760. }
  7761. }
  7762. } else {
  7763. for (int ir = ir0; ir < ir1; ++ir) {
  7764. // src0, src1 and dst are same shape => same indices
  7765. const int i3 = ir/(ne2*ne1);
  7766. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7767. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7768. float * dst_ptr = (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7769. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7770. float * src1_ptr = (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7771. for (int i = 0; i < ne0; i++) {
  7772. dst_ptr[i] = GGML_BF16_TO_FP32(src0_ptr[i]) + src1_ptr[i];
  7773. }
  7774. }
  7775. }
  7776. }
  7777. else {
  7778. // src1 is not contiguous
  7779. GGML_ABORT("fatal error");
  7780. }
  7781. }
  7782. static void ggml_compute_forward_add_f16_f16(
  7783. const struct ggml_compute_params * params,
  7784. struct ggml_tensor * dst) {
  7785. const struct ggml_tensor * src0 = dst->src[0];
  7786. const struct ggml_tensor * src1 = dst->src[1];
  7787. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7788. const int ith = params->ith;
  7789. const int nth = params->nth;
  7790. const int nr = ggml_nrows(src0);
  7791. GGML_TENSOR_BINARY_OP_LOCALS
  7792. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  7793. GGML_ASSERT(src1->type == GGML_TYPE_F16);
  7794. GGML_ASSERT(dst->type == GGML_TYPE_F16);
  7795. GGML_ASSERT( nb0 == sizeof(ggml_fp16_t));
  7796. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  7797. // rows per thread
  7798. const int dr = (nr + nth - 1)/nth;
  7799. // row range for this thread
  7800. const int ir0 = dr*ith;
  7801. const int ir1 = MIN(ir0 + dr, nr);
  7802. if (nb10 == sizeof(ggml_fp16_t)) {
  7803. for (int ir = ir0; ir < ir1; ++ir) {
  7804. // src0, src1 and dst are same shape => same indices
  7805. const int i3 = ir/(ne2*ne1);
  7806. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7807. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7808. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7809. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7810. ggml_fp16_t * src1_ptr = (ggml_fp16_t *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7811. for (int i = 0; i < ne0; i++) {
  7812. dst_ptr[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(src0_ptr[i]) + GGML_FP16_TO_FP32(src1_ptr[i]));
  7813. }
  7814. }
  7815. }
  7816. else {
  7817. // src1 is not contiguous
  7818. GGML_ABORT("fatal error");
  7819. }
  7820. }
  7821. static void ggml_compute_forward_add_bf16_bf16(
  7822. const struct ggml_compute_params * params,
  7823. struct ggml_tensor * dst) {
  7824. const struct ggml_tensor * src0 = dst->src[0];
  7825. const struct ggml_tensor * src1 = dst->src[1];
  7826. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7827. const int ith = params->ith;
  7828. const int nth = params->nth;
  7829. const int nr = ggml_nrows(src0);
  7830. GGML_TENSOR_BINARY_OP_LOCALS
  7831. GGML_ASSERT(src0->type == GGML_TYPE_BF16);
  7832. GGML_ASSERT(src1->type == GGML_TYPE_BF16);
  7833. GGML_ASSERT(dst->type == GGML_TYPE_BF16);
  7834. GGML_ASSERT( nb0 == sizeof(ggml_bf16_t));
  7835. GGML_ASSERT(nb00 == sizeof(ggml_bf16_t));
  7836. // rows per thread
  7837. const int dr = (nr + nth - 1)/nth;
  7838. // row range for this thread
  7839. const int ir0 = dr*ith;
  7840. const int ir1 = MIN(ir0 + dr, nr);
  7841. if (nb10 == sizeof(ggml_bf16_t)) {
  7842. for (int ir = ir0; ir < ir1; ++ir) {
  7843. // src0, src1 and dst are same shape => same indices
  7844. const int i3 = ir/(ne2*ne1);
  7845. const int i2 = (ir - i3*ne2*ne1)/ne1;
  7846. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  7847. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  7848. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  7849. ggml_bf16_t * src1_ptr = (ggml_bf16_t *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11);
  7850. for (int i = 0; i < ne0; i++) {
  7851. dst_ptr[i] = GGML_FP32_TO_BF16(GGML_BF16_TO_FP32(src0_ptr[i]) + GGML_BF16_TO_FP32(src1_ptr[i]));
  7852. }
  7853. }
  7854. }
  7855. else {
  7856. // src1 is not contiguous
  7857. GGML_ABORT("fatal error");
  7858. }
  7859. }
  7860. static void ggml_compute_forward_add_q_f32(
  7861. const struct ggml_compute_params * params,
  7862. struct ggml_tensor * dst) {
  7863. const struct ggml_tensor * src0 = dst->src[0];
  7864. const struct ggml_tensor * src1 = dst->src[1];
  7865. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  7866. const int nr = ggml_nrows(src0);
  7867. GGML_TENSOR_BINARY_OP_LOCALS
  7868. const int ith = params->ith;
  7869. const int nth = params->nth;
  7870. const enum ggml_type type = src0->type;
  7871. const enum ggml_type dtype = dst->type;
  7872. ggml_to_float_t const dequantize_row_q = type_traits[type].to_float;
  7873. ggml_from_float_t const quantize_row_q = type_traits[dtype].from_float;
  7874. // we don't support permuted src0 or src1
  7875. GGML_ASSERT(nb00 == ggml_type_size(type));
  7876. GGML_ASSERT(nb10 == sizeof(float));
  7877. // dst cannot be transposed or permuted
  7878. GGML_ASSERT(nb0 <= nb1);
  7879. GGML_ASSERT(nb1 <= nb2);
  7880. GGML_ASSERT(nb2 <= nb3);
  7881. GGML_ASSERT(ggml_is_quantized(src0->type));
  7882. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  7883. // rows per thread
  7884. const int dr = (nr + nth - 1)/nth;
  7885. // row range for this thread
  7886. const int ir0 = dr*ith;
  7887. const int ir1 = MIN(ir0 + dr, nr);
  7888. float * wdata = (float *) params->wdata + (ne00 + CACHE_LINE_SIZE_F32) * ith;
  7889. for (int ir = ir0; ir < ir1; ++ir) {
  7890. // src0 indices
  7891. const int i03 = ir/(ne02*ne01);
  7892. const int i02 = (ir - i03*ne02*ne01)/ne01;
  7893. const int i01 = (ir - i03*ne02*ne01 - i02*ne01);
  7894. // src1 and dst are same shape as src0 => same indices
  7895. const int i13 = i03;
  7896. const int i12 = i02;
  7897. const int i11 = i01;
  7898. const int i3 = i03;
  7899. const int i2 = i02;
  7900. const int i1 = i01;
  7901. void * src0_row = (void *) ((char *) src0->data + (i01*nb01 + i02*nb02 + i03*nb03));
  7902. float * src1_row = (float *)((char *) src1->data + (i11*nb11 + i12*nb12 + i13*nb13));
  7903. void * dst_row = (void *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  7904. assert(ne00 % 32 == 0);
  7905. // unquantize row from src0 to temp buffer
  7906. dequantize_row_q(src0_row, wdata, ne00);
  7907. // add src1
  7908. ggml_vec_acc_f32(ne00, wdata, src1_row);
  7909. // quantize row to dst
  7910. if (quantize_row_q != NULL) {
  7911. quantize_row_q(wdata, dst_row, ne00);
  7912. } else {
  7913. memcpy(dst_row, wdata, ne0*nb0);
  7914. }
  7915. }
  7916. }
  7917. static void ggml_compute_forward_add(
  7918. const struct ggml_compute_params * params,
  7919. struct ggml_tensor * dst) {
  7920. const struct ggml_tensor * src0 = dst->src[0];
  7921. const struct ggml_tensor * src1 = dst->src[1];
  7922. switch (src0->type) {
  7923. case GGML_TYPE_F32:
  7924. {
  7925. if (src1->type == GGML_TYPE_F32) {
  7926. ggml_compute_forward_add_f32(params, dst);
  7927. }
  7928. else {
  7929. GGML_ABORT("fatal error");
  7930. }
  7931. } break;
  7932. case GGML_TYPE_F16:
  7933. {
  7934. if (src1->type == GGML_TYPE_F16) {
  7935. ggml_compute_forward_add_f16_f16(params, dst);
  7936. }
  7937. else if (src1->type == GGML_TYPE_F32) {
  7938. ggml_compute_forward_add_f16_f32(params, dst);
  7939. }
  7940. else {
  7941. GGML_ABORT("fatal error");
  7942. }
  7943. } break;
  7944. case GGML_TYPE_BF16:
  7945. {
  7946. if (src1->type == GGML_TYPE_BF16) {
  7947. ggml_compute_forward_add_bf16_bf16(params, dst);
  7948. }
  7949. else if (src1->type == GGML_TYPE_F32) {
  7950. ggml_compute_forward_add_bf16_f32(params, dst);
  7951. }
  7952. else {
  7953. GGML_ABORT("fatal error");
  7954. }
  7955. } break;
  7956. case GGML_TYPE_Q4_0:
  7957. case GGML_TYPE_Q4_1:
  7958. case GGML_TYPE_Q5_0:
  7959. case GGML_TYPE_Q5_1:
  7960. case GGML_TYPE_Q8_0:
  7961. case GGML_TYPE_Q2_K:
  7962. case GGML_TYPE_Q3_K:
  7963. case GGML_TYPE_Q4_K:
  7964. case GGML_TYPE_Q5_K:
  7965. case GGML_TYPE_Q6_K:
  7966. case GGML_TYPE_TQ1_0:
  7967. case GGML_TYPE_TQ2_0:
  7968. case GGML_TYPE_IQ2_XXS:
  7969. case GGML_TYPE_IQ2_XS:
  7970. case GGML_TYPE_IQ3_XXS:
  7971. case GGML_TYPE_IQ1_S:
  7972. case GGML_TYPE_IQ1_M:
  7973. case GGML_TYPE_IQ4_NL:
  7974. case GGML_TYPE_IQ4_XS:
  7975. case GGML_TYPE_IQ3_S:
  7976. case GGML_TYPE_IQ2_S:
  7977. case GGML_TYPE_Q4_0_4_4:
  7978. case GGML_TYPE_Q4_0_4_8:
  7979. case GGML_TYPE_Q4_0_8_8:
  7980. {
  7981. ggml_compute_forward_add_q_f32(params, dst);
  7982. } break;
  7983. default:
  7984. {
  7985. GGML_ABORT("fatal error");
  7986. }
  7987. }
  7988. }
  7989. // ggml_compute_forward_add1
  7990. static void ggml_compute_forward_add1_f32(
  7991. const struct ggml_compute_params * params,
  7992. struct ggml_tensor * dst) {
  7993. const struct ggml_tensor * src0 = dst->src[0];
  7994. const struct ggml_tensor * src1 = dst->src[1];
  7995. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  7996. GGML_ASSERT(ggml_is_scalar(src1));
  7997. const int ith = params->ith;
  7998. const int nth = params->nth;
  7999. const int nr = ggml_nrows(src0);
  8000. GGML_TENSOR_UNARY_OP_LOCALS
  8001. GGML_ASSERT( nb0 == sizeof(float));
  8002. GGML_ASSERT(nb00 == sizeof(float));
  8003. // rows per thread
  8004. const int dr = (nr + nth - 1)/nth;
  8005. // row range for this thread
  8006. const int ir0 = dr*ith;
  8007. const int ir1 = MIN(ir0 + dr, nr);
  8008. for (int ir = ir0; ir < ir1; ++ir) {
  8009. // src0 and dst are same shape => same indices
  8010. const int i3 = ir/(ne2*ne1);
  8011. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8012. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8013. #ifdef GGML_USE_ACCELERATE
  8014. UNUSED(ggml_vec_add1_f32);
  8015. vDSP_vadd(
  8016. (float *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01), 1,
  8017. (float *) ((char *) src1->data), 0,
  8018. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 ), 1,
  8019. ne0);
  8020. #else
  8021. ggml_vec_add1_f32(ne0,
  8022. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 ),
  8023. (float *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01),
  8024. *(float *) src1->data);
  8025. #endif
  8026. }
  8027. }
  8028. static void ggml_compute_forward_add1_f16_f32(
  8029. const struct ggml_compute_params * params,
  8030. struct ggml_tensor * dst) {
  8031. const struct ggml_tensor * src0 = dst->src[0];
  8032. const struct ggml_tensor * src1 = dst->src[1];
  8033. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8034. GGML_ASSERT(ggml_is_scalar(src1));
  8035. // scalar to add
  8036. const float v = *(float *) src1->data;
  8037. const int ith = params->ith;
  8038. const int nth = params->nth;
  8039. const int nr = ggml_nrows(src0);
  8040. GGML_TENSOR_UNARY_OP_LOCALS
  8041. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  8042. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8043. GGML_ASSERT(dst->type == GGML_TYPE_F16);
  8044. GGML_ASSERT( nb0 == sizeof(ggml_fp16_t));
  8045. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  8046. // rows per thread
  8047. const int dr = (nr + nth - 1)/nth;
  8048. // row range for this thread
  8049. const int ir0 = dr*ith;
  8050. const int ir1 = MIN(ir0 + dr, nr);
  8051. for (int ir = ir0; ir < ir1; ++ir) {
  8052. // src0 and dst are same shape => same indices
  8053. const int i3 = ir/(ne2*ne1);
  8054. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8055. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8056. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 );
  8057. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  8058. for (int i = 0; i < ne0; i++) {
  8059. dst_ptr[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(src0_ptr[i]) + v);
  8060. }
  8061. }
  8062. }
  8063. static void ggml_compute_forward_add1_f16_f16(
  8064. const struct ggml_compute_params * params,
  8065. struct ggml_tensor * dst) {
  8066. const struct ggml_tensor * src0 = dst->src[0];
  8067. const struct ggml_tensor * src1 = dst->src[1];
  8068. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8069. GGML_ASSERT(ggml_is_scalar(src1));
  8070. // scalar to add
  8071. const float v = GGML_FP16_TO_FP32(*(ggml_fp16_t *) src1->data);
  8072. const int ith = params->ith;
  8073. const int nth = params->nth;
  8074. const int nr = ggml_nrows(src0);
  8075. GGML_TENSOR_UNARY_OP_LOCALS
  8076. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  8077. GGML_ASSERT(src1->type == GGML_TYPE_F16);
  8078. GGML_ASSERT(dst->type == GGML_TYPE_F16);
  8079. GGML_ASSERT( nb0 == sizeof(ggml_fp16_t));
  8080. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  8081. // rows per thread
  8082. const int dr = (nr + nth - 1)/nth;
  8083. // row range for this thread
  8084. const int ir0 = dr*ith;
  8085. const int ir1 = MIN(ir0 + dr, nr);
  8086. for (int ir = ir0; ir < ir1; ++ir) {
  8087. // src0 and dst are same shape => same indices
  8088. const int i3 = ir/(ne2*ne1);
  8089. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8090. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8091. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 );
  8092. ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  8093. for (int i = 0; i < ne0; i++) {
  8094. dst_ptr[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(src0_ptr[i]) + v);
  8095. }
  8096. }
  8097. }
  8098. static void ggml_compute_forward_add1_q_f32(
  8099. const struct ggml_compute_params * params,
  8100. struct ggml_tensor * dst) {
  8101. const struct ggml_tensor * src0 = dst->src[0];
  8102. const struct ggml_tensor * src1 = dst->src[1];
  8103. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8104. GGML_ASSERT(ggml_is_scalar(src1));
  8105. // scalar to add
  8106. const float v = *(float *) src1->data;
  8107. const int ith = params->ith;
  8108. const int nth = params->nth;
  8109. const int nr = ggml_nrows(src0);
  8110. GGML_TENSOR_UNARY_OP_LOCALS
  8111. const enum ggml_type type = src0->type;
  8112. ggml_to_float_t const dequantize_row_q = type_traits[type].to_float;
  8113. ggml_from_float_t const quantize_row_q = type_traits[type].from_float;
  8114. // we don't support permuted src0
  8115. GGML_ASSERT(nb00 == ggml_type_size(type));
  8116. // dst cannot be transposed or permuted
  8117. GGML_ASSERT(nb0 <= nb1);
  8118. GGML_ASSERT(nb1 <= nb2);
  8119. GGML_ASSERT(nb2 <= nb3);
  8120. GGML_ASSERT(ggml_is_quantized(src0->type));
  8121. GGML_ASSERT(dst->type == src0->type);
  8122. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8123. // rows per thread
  8124. const int dr = (nr + nth - 1)/nth;
  8125. // row range for this thread
  8126. const int ir0 = dr*ith;
  8127. const int ir1 = MIN(ir0 + dr, nr);
  8128. float * wdata = (float *) params->wdata + (ne0 + CACHE_LINE_SIZE_F32) * ith;
  8129. for (int ir = ir0; ir < ir1; ++ir) {
  8130. // src0 and dst are same shape => same indices
  8131. const int i3 = ir/(ne2*ne1);
  8132. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8133. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8134. void * src0_row = (void *) ((char *) src0->data + (i1*nb01 + i2*nb02 + i3*nb03));
  8135. void * dst_row = (void *) ((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb0 ));
  8136. assert(ne0 % 32 == 0);
  8137. // unquantize row from src0 to temp buffer
  8138. dequantize_row_q(src0_row, wdata, ne0);
  8139. // add src1
  8140. ggml_vec_acc1_f32(ne0, wdata, v);
  8141. // quantize row to dst
  8142. quantize_row_q(wdata, dst_row, ne0);
  8143. }
  8144. }
  8145. static void ggml_compute_forward_add1_bf16_f32(
  8146. const struct ggml_compute_params * params,
  8147. struct ggml_tensor * dst) {
  8148. const struct ggml_tensor * src0 = dst->src[0];
  8149. const struct ggml_tensor * src1 = dst->src[1];
  8150. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8151. GGML_ASSERT(ggml_is_scalar(src1));
  8152. // scalar to add
  8153. const float v = *(float *) src1->data;
  8154. const int ith = params->ith;
  8155. const int nth = params->nth;
  8156. const int nr = ggml_nrows(src0);
  8157. GGML_TENSOR_UNARY_OP_LOCALS
  8158. GGML_ASSERT(src0->type == GGML_TYPE_BF16);
  8159. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8160. GGML_ASSERT(dst->type == GGML_TYPE_BF16);
  8161. GGML_ASSERT( nb0 == sizeof(ggml_bf16_t));
  8162. GGML_ASSERT(nb00 == sizeof(ggml_bf16_t));
  8163. // rows per thread
  8164. const int dr = (nr + nth - 1)/nth;
  8165. // row range for this thread
  8166. const int ir0 = dr*ith;
  8167. const int ir1 = MIN(ir0 + dr, nr);
  8168. for (int ir = ir0; ir < ir1; ++ir) {
  8169. // src0 and dst are same shape => same indices
  8170. const int i3 = ir/(ne2*ne1);
  8171. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8172. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8173. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 );
  8174. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  8175. for (int i = 0; i < ne0; i++) {
  8176. dst_ptr[i] = GGML_FP32_TO_BF16(GGML_BF16_TO_FP32(src0_ptr[i]) + v);
  8177. }
  8178. }
  8179. }
  8180. static void ggml_compute_forward_add1_bf16_bf16(
  8181. const struct ggml_compute_params * params,
  8182. struct ggml_tensor * dst) {
  8183. const struct ggml_tensor * src0 = dst->src[0];
  8184. const struct ggml_tensor * src1 = dst->src[1];
  8185. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8186. GGML_ASSERT(ggml_is_scalar(src1));
  8187. // scalar to add
  8188. const float v = GGML_BF16_TO_FP32(*(ggml_bf16_t *) src1->data);
  8189. const int ith = params->ith;
  8190. const int nth = params->nth;
  8191. const int nr = ggml_nrows(src0);
  8192. GGML_TENSOR_UNARY_OP_LOCALS
  8193. GGML_ASSERT(src0->type == GGML_TYPE_BF16);
  8194. GGML_ASSERT(src1->type == GGML_TYPE_BF16);
  8195. GGML_ASSERT(dst->type == GGML_TYPE_BF16);
  8196. GGML_ASSERT( nb0 == sizeof(ggml_bf16_t));
  8197. GGML_ASSERT(nb00 == sizeof(ggml_bf16_t));
  8198. // rows per thread
  8199. const int dr = (nr + nth - 1)/nth;
  8200. // row range for this thread
  8201. const int ir0 = dr*ith;
  8202. const int ir1 = MIN(ir0 + dr, nr);
  8203. for (int ir = ir0; ir < ir1; ++ir) {
  8204. // src0 and dst are same shape => same indices
  8205. const int i3 = ir/(ne2*ne1);
  8206. const int i2 = (ir - i3*ne2*ne1)/ne1;
  8207. const int i1 = (ir - i3*ne2*ne1 - i2*ne1);
  8208. ggml_bf16_t * dst_ptr = (ggml_bf16_t *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 );
  8209. ggml_bf16_t * src0_ptr = (ggml_bf16_t *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01);
  8210. for (int i = 0; i < ne0; i++) {
  8211. dst_ptr[i] = GGML_FP32_TO_BF16(GGML_BF16_TO_FP32(src0_ptr[i]) + v);
  8212. }
  8213. }
  8214. }
  8215. static void ggml_compute_forward_add1(
  8216. const struct ggml_compute_params * params,
  8217. struct ggml_tensor * dst) {
  8218. const struct ggml_tensor * src0 = dst->src[0];
  8219. const struct ggml_tensor * src1 = dst->src[1];
  8220. switch (src0->type) {
  8221. case GGML_TYPE_F32:
  8222. {
  8223. ggml_compute_forward_add1_f32(params, dst);
  8224. } break;
  8225. case GGML_TYPE_F16:
  8226. {
  8227. if (src1->type == GGML_TYPE_F16) {
  8228. ggml_compute_forward_add1_f16_f16(params, dst);
  8229. }
  8230. else if (src1->type == GGML_TYPE_F32) {
  8231. ggml_compute_forward_add1_f16_f32(params, dst);
  8232. }
  8233. else {
  8234. GGML_ABORT("fatal error");
  8235. }
  8236. } break;
  8237. case GGML_TYPE_BF16:
  8238. {
  8239. if (src1->type == GGML_TYPE_BF16) {
  8240. ggml_compute_forward_add1_bf16_bf16(params, dst);
  8241. }
  8242. else if (src1->type == GGML_TYPE_F32) {
  8243. ggml_compute_forward_add1_bf16_f32(params, dst);
  8244. }
  8245. else {
  8246. GGML_ABORT("fatal error");
  8247. }
  8248. } break;
  8249. case GGML_TYPE_Q4_0:
  8250. case GGML_TYPE_Q4_1:
  8251. case GGML_TYPE_Q5_0:
  8252. case GGML_TYPE_Q5_1:
  8253. case GGML_TYPE_Q8_0:
  8254. case GGML_TYPE_Q8_1:
  8255. case GGML_TYPE_Q2_K:
  8256. case GGML_TYPE_Q3_K:
  8257. case GGML_TYPE_Q4_K:
  8258. case GGML_TYPE_Q5_K:
  8259. case GGML_TYPE_Q6_K:
  8260. case GGML_TYPE_TQ1_0:
  8261. case GGML_TYPE_TQ2_0:
  8262. case GGML_TYPE_IQ2_XXS:
  8263. case GGML_TYPE_IQ2_XS:
  8264. case GGML_TYPE_IQ3_XXS:
  8265. case GGML_TYPE_IQ1_S:
  8266. case GGML_TYPE_IQ1_M:
  8267. case GGML_TYPE_IQ4_NL:
  8268. case GGML_TYPE_IQ4_XS:
  8269. case GGML_TYPE_IQ3_S:
  8270. case GGML_TYPE_IQ2_S:
  8271. case GGML_TYPE_Q4_0_4_4:
  8272. case GGML_TYPE_Q4_0_4_8:
  8273. case GGML_TYPE_Q4_0_8_8:
  8274. {
  8275. ggml_compute_forward_add1_q_f32(params, dst);
  8276. } break;
  8277. default:
  8278. {
  8279. GGML_ABORT("fatal error");
  8280. }
  8281. }
  8282. }
  8283. // ggml_compute_forward_acc
  8284. static void ggml_compute_forward_acc_f32(
  8285. const struct ggml_compute_params * params,
  8286. struct ggml_tensor * dst) {
  8287. const struct ggml_tensor * src0 = dst->src[0];
  8288. const struct ggml_tensor * src1 = dst->src[1];
  8289. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8290. GGML_ASSERT(ggml_is_contiguous(dst) && ggml_is_contiguous(src0));
  8291. // view src0 and dst with these strides and data offset inbytes during acc
  8292. // nb0 is implicitly element_size because src0 and dst are contiguous
  8293. size_t nb1 = ((int32_t *) dst->op_params)[0];
  8294. size_t nb2 = ((int32_t *) dst->op_params)[1];
  8295. size_t nb3 = ((int32_t *) dst->op_params)[2];
  8296. size_t offset = ((int32_t *) dst->op_params)[3];
  8297. bool inplace = (bool) ((int32_t *) dst->op_params)[4];
  8298. if (!inplace) {
  8299. if (params->ith == 0) {
  8300. // memcpy needs to be synchronized across threads to avoid race conditions.
  8301. // => do it in INIT phase
  8302. memcpy(
  8303. ((char *) dst->data),
  8304. ((char *) src0->data),
  8305. ggml_nbytes(dst));
  8306. }
  8307. ggml_barrier(params->threadpool);
  8308. }
  8309. const int ith = params->ith;
  8310. const int nth = params->nth;
  8311. const int nr = ggml_nrows(src1);
  8312. const int nc = src1->ne[0];
  8313. GGML_TENSOR_LOCALS(int64_t, ne1, src1, ne)
  8314. GGML_TENSOR_LOCALS(size_t, nb1, src1, nb)
  8315. // src0 and dst as viewed during acc
  8316. const size_t nb0 = ggml_element_size(src0);
  8317. const size_t nb00 = nb0;
  8318. const size_t nb01 = nb1;
  8319. const size_t nb02 = nb2;
  8320. const size_t nb03 = nb3;
  8321. 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));
  8322. 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));
  8323. GGML_ASSERT(nb10 == sizeof(float));
  8324. // rows per thread
  8325. const int dr = (nr + nth - 1)/nth;
  8326. // row range for this thread
  8327. const int ir0 = dr*ith;
  8328. const int ir1 = MIN(ir0 + dr, nr);
  8329. for (int ir = ir0; ir < ir1; ++ir) {
  8330. // src0 and dst are viewed with shape of src1 and offset
  8331. // => same indices
  8332. const int i3 = ir/(ne12*ne11);
  8333. const int i2 = (ir - i3*ne12*ne11)/ne11;
  8334. const int i1 = (ir - i3*ne12*ne11 - i2*ne11);
  8335. #ifdef GGML_USE_ACCELERATE
  8336. vDSP_vadd(
  8337. (float *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + offset), 1,
  8338. (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11), 1,
  8339. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + offset), 1, nc);
  8340. #else
  8341. ggml_vec_add_f32(nc,
  8342. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + offset),
  8343. (float *) ((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + offset),
  8344. (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11));
  8345. #endif
  8346. }
  8347. }
  8348. static void ggml_compute_forward_acc(
  8349. const struct ggml_compute_params * params,
  8350. struct ggml_tensor * dst) {
  8351. const struct ggml_tensor * src0 = dst->src[0];
  8352. switch (src0->type) {
  8353. case GGML_TYPE_F32:
  8354. {
  8355. ggml_compute_forward_acc_f32(params, dst);
  8356. } break;
  8357. case GGML_TYPE_F16:
  8358. case GGML_TYPE_BF16:
  8359. case GGML_TYPE_Q4_0:
  8360. case GGML_TYPE_Q4_1:
  8361. case GGML_TYPE_Q5_0:
  8362. case GGML_TYPE_Q5_1:
  8363. case GGML_TYPE_Q8_0:
  8364. case GGML_TYPE_Q8_1:
  8365. case GGML_TYPE_Q2_K:
  8366. case GGML_TYPE_Q3_K:
  8367. case GGML_TYPE_Q4_K:
  8368. case GGML_TYPE_Q5_K:
  8369. case GGML_TYPE_Q6_K:
  8370. case GGML_TYPE_TQ1_0:
  8371. case GGML_TYPE_TQ2_0:
  8372. case GGML_TYPE_IQ2_XXS:
  8373. case GGML_TYPE_IQ2_XS:
  8374. case GGML_TYPE_IQ3_XXS:
  8375. case GGML_TYPE_IQ1_S:
  8376. case GGML_TYPE_IQ1_M:
  8377. case GGML_TYPE_IQ4_NL:
  8378. case GGML_TYPE_IQ4_XS:
  8379. case GGML_TYPE_IQ3_S:
  8380. case GGML_TYPE_IQ2_S:
  8381. case GGML_TYPE_Q4_0_4_4:
  8382. case GGML_TYPE_Q4_0_4_8:
  8383. case GGML_TYPE_Q4_0_8_8:
  8384. default:
  8385. {
  8386. GGML_ABORT("fatal error");
  8387. }
  8388. }
  8389. }
  8390. // ggml_compute_forward_sub
  8391. static void ggml_compute_forward_sub_f32(
  8392. const struct ggml_compute_params * params,
  8393. struct ggml_tensor * dst) {
  8394. const struct ggml_tensor * src0 = dst->src[0];
  8395. const struct ggml_tensor * src1 = dst->src[1];
  8396. assert(ggml_can_repeat(src1, src0) && ggml_are_same_shape(src0, dst));
  8397. const int ith = params->ith;
  8398. const int nth = params->nth;
  8399. const int nr = ggml_nrows(src0);
  8400. GGML_TENSOR_BINARY_OP_LOCALS
  8401. GGML_ASSERT( nb0 == sizeof(float));
  8402. GGML_ASSERT(nb00 == sizeof(float));
  8403. // rows per thread
  8404. const int dr = (nr + nth - 1)/nth;
  8405. // row range for this thread
  8406. const int ir0 = dr*ith;
  8407. const int ir1 = MIN(ir0 + dr, nr);
  8408. if (nb10 == sizeof(float)) {
  8409. for (int ir = ir0; ir < ir1; ++ir) {
  8410. // src1 is broadcastable across src0 and dst in i1, i2, i3
  8411. const int64_t i03 = ir/(ne02*ne01);
  8412. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8413. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8414. const int64_t i13 = i03 % ne13;
  8415. const int64_t i12 = i02 % ne12;
  8416. const int64_t i11 = i01 % ne11;
  8417. const int64_t nr0 = ne00 / ne10;
  8418. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8419. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8420. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11);
  8421. for (int64_t r = 0; r < nr0; ++r) {
  8422. #ifdef GGML_USE_ACCELERATE
  8423. vDSP_vsub(src1_ptr, 1, src0_ptr + r*ne10, 1, dst_ptr + r*ne10, 1, ne10);
  8424. #else
  8425. ggml_vec_sub_f32(ne10, dst_ptr + r*ne10, src0_ptr + r*ne10, src1_ptr);
  8426. #endif
  8427. }
  8428. }
  8429. } else {
  8430. // src1 is not contiguous
  8431. for (int ir = ir0; ir < ir1; ++ir) {
  8432. // src1 is broadcastable across src0 and dst in i1, i2, i3
  8433. const int64_t i03 = ir/(ne02*ne01);
  8434. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8435. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8436. const int64_t i13 = i03 % ne13;
  8437. const int64_t i12 = i02 % ne12;
  8438. const int64_t i11 = i01 % ne11;
  8439. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8440. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8441. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  8442. const int64_t i10 = i0 % ne10;
  8443. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10);
  8444. dst_ptr[i0] = src0_ptr[i0] - *src1_ptr;
  8445. }
  8446. }
  8447. }
  8448. }
  8449. static void ggml_compute_forward_sub(
  8450. const struct ggml_compute_params * params,
  8451. struct ggml_tensor * dst) {
  8452. const struct ggml_tensor * src0 = dst->src[0];
  8453. switch (src0->type) {
  8454. case GGML_TYPE_F32:
  8455. {
  8456. ggml_compute_forward_sub_f32(params, dst);
  8457. } break;
  8458. default:
  8459. {
  8460. GGML_ABORT("fatal error");
  8461. }
  8462. }
  8463. }
  8464. // ggml_compute_forward_mul
  8465. static void ggml_compute_forward_mul_f32(
  8466. const struct ggml_compute_params * params,
  8467. struct ggml_tensor * dst) {
  8468. const struct ggml_tensor * src0 = dst->src[0];
  8469. const struct ggml_tensor * src1 = dst->src[1];
  8470. GGML_ASSERT(ggml_can_repeat(src1, src0) && ggml_are_same_shape(src0, dst));
  8471. const int ith = params->ith;
  8472. const int nth = params->nth;
  8473. const int64_t nr = ggml_nrows(src0);
  8474. GGML_TENSOR_BINARY_OP_LOCALS
  8475. GGML_ASSERT( nb0 == sizeof(float));
  8476. GGML_ASSERT(nb00 == sizeof(float));
  8477. if (nb10 == sizeof(float)) {
  8478. for (int64_t ir = ith; ir < nr; ir += nth) {
  8479. // src0 and dst are same shape => same indices
  8480. const int64_t i03 = ir/(ne02*ne01);
  8481. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8482. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8483. const int64_t i13 = i03 % ne13;
  8484. const int64_t i12 = i02 % ne12;
  8485. const int64_t i11 = i01 % ne11;
  8486. const int64_t nr0 = ne00 / ne10;
  8487. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8488. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8489. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11);
  8490. for (int64_t r = 0 ; r < nr0; ++r) {
  8491. #ifdef GGML_USE_ACCELERATE
  8492. UNUSED(ggml_vec_mul_f32);
  8493. vDSP_vmul(src0_ptr + r*ne10, 1, src1_ptr, 1, dst_ptr + r*ne10, 1, ne10);
  8494. #else
  8495. ggml_vec_mul_f32(ne10, dst_ptr + r*ne10, src0_ptr + r*ne10, src1_ptr);
  8496. #endif
  8497. }
  8498. }
  8499. } else {
  8500. // src1 is not contiguous
  8501. for (int64_t ir = ith; ir < nr; ir += nth) {
  8502. // src0 and dst are same shape => same indices
  8503. // src1 is broadcastable across src0 and dst in i1, i2, i3
  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. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8511. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8512. for (int64_t i0 = 0; i0 < ne00; ++i0) {
  8513. const int64_t i10 = i0 % ne10;
  8514. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10);
  8515. dst_ptr[i0] = src0_ptr[i0] * (*src1_ptr);
  8516. }
  8517. }
  8518. }
  8519. }
  8520. static void ggml_compute_forward_mul(
  8521. const struct ggml_compute_params * params,
  8522. struct ggml_tensor * dst) {
  8523. const struct ggml_tensor * src0 = dst->src[0];
  8524. const struct ggml_tensor * src1 = dst->src[1];
  8525. GGML_ASSERT(src1->type == GGML_TYPE_F32 && "only f32 src1 supported for now");
  8526. switch (src0->type) {
  8527. case GGML_TYPE_F32:
  8528. {
  8529. ggml_compute_forward_mul_f32(params, dst);
  8530. } break;
  8531. default:
  8532. {
  8533. GGML_ABORT("fatal error");
  8534. }
  8535. }
  8536. }
  8537. // ggml_compute_forward_div
  8538. static void ggml_compute_forward_div_f32(
  8539. const struct ggml_compute_params * params,
  8540. struct ggml_tensor * dst) {
  8541. const struct ggml_tensor * src0 = dst->src[0];
  8542. const struct ggml_tensor * src1 = dst->src[1];
  8543. GGML_ASSERT(ggml_can_repeat(src1, src0) && ggml_are_same_shape(src0, dst));
  8544. const int ith = params->ith;
  8545. const int nth = params->nth;
  8546. const int64_t nr = ggml_nrows(src0);
  8547. GGML_TENSOR_BINARY_OP_LOCALS
  8548. GGML_ASSERT( nb0 == sizeof(float));
  8549. GGML_ASSERT(nb00 == sizeof(float));
  8550. if (nb10 == sizeof(float)) {
  8551. for (int64_t ir = ith; ir < nr; ir += nth) {
  8552. // src0 and dst are same shape => same indices
  8553. const int64_t i03 = ir/(ne02*ne01);
  8554. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8555. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8556. const int64_t i13 = i03 % ne13;
  8557. const int64_t i12 = i02 % ne12;
  8558. const int64_t i11 = i01 % ne11;
  8559. const int64_t nr0 = ne00 / ne10;
  8560. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8561. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8562. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11);
  8563. for (int64_t r = 0; r < nr0; ++r) {
  8564. #ifdef GGML_USE_ACCELERATE
  8565. UNUSED(ggml_vec_div_f32);
  8566. vDSP_vdiv(src1_ptr, 1, src0_ptr + r*ne10, 1, dst_ptr + r*ne10, 1, ne10);
  8567. #else
  8568. ggml_vec_div_f32(ne10, dst_ptr + r*ne10, src0_ptr + r*ne10, src1_ptr);
  8569. #endif
  8570. }
  8571. }
  8572. } else {
  8573. // src1 is not contiguous
  8574. for (int64_t ir = ith; ir < nr; ir += nth) {
  8575. // src0 and dst are same shape => same indices
  8576. // src1 is broadcastable across src0 and dst in i1, i2, i3
  8577. const int64_t i03 = ir/(ne02*ne01);
  8578. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  8579. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  8580. const int64_t i13 = i03 % ne13;
  8581. const int64_t i12 = i02 % ne12;
  8582. const int64_t i11 = i01 % ne11;
  8583. float * dst_ptr = (float *) ((char *) dst->data + i03*nb3 + i02*nb2 + i01*nb1 );
  8584. float * src0_ptr = (float *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01);
  8585. for (int64_t i0 = 0; i0 < ne00; ++i0) {
  8586. const int64_t i10 = i0 % ne10;
  8587. float * src1_ptr = (float *) ((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10);
  8588. dst_ptr[i0] = src0_ptr[i0] / (*src1_ptr);
  8589. }
  8590. }
  8591. }
  8592. }
  8593. static void ggml_compute_forward_div(
  8594. const struct ggml_compute_params * params,
  8595. struct ggml_tensor * dst) {
  8596. const struct ggml_tensor * src0 = dst->src[0];
  8597. switch (src0->type) {
  8598. case GGML_TYPE_F32:
  8599. {
  8600. ggml_compute_forward_div_f32(params, dst);
  8601. } break;
  8602. default:
  8603. {
  8604. GGML_ABORT("fatal error");
  8605. }
  8606. }
  8607. }
  8608. // ggml_compute_forward_sqr
  8609. static void ggml_compute_forward_sqr_f32(
  8610. const struct ggml_compute_params * params,
  8611. struct ggml_tensor * dst) {
  8612. const struct ggml_tensor * src0 = dst->src[0];
  8613. if (params->ith != 0) {
  8614. return;
  8615. }
  8616. assert(ggml_are_same_shape(src0, dst));
  8617. const int n = ggml_nrows(src0);
  8618. const int nc = src0->ne[0];
  8619. assert( dst->nb[0] == sizeof(float));
  8620. assert(src0->nb[0] == sizeof(float));
  8621. for (int i = 0; i < n; i++) {
  8622. ggml_vec_sqr_f32(nc,
  8623. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8624. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8625. }
  8626. }
  8627. static void ggml_compute_forward_sqr(
  8628. const struct ggml_compute_params * params,
  8629. struct ggml_tensor * dst) {
  8630. const struct ggml_tensor * src0 = dst->src[0];
  8631. switch (src0->type) {
  8632. case GGML_TYPE_F32:
  8633. {
  8634. ggml_compute_forward_sqr_f32(params, dst);
  8635. } break;
  8636. default:
  8637. {
  8638. GGML_ABORT("fatal error");
  8639. }
  8640. }
  8641. }
  8642. // ggml_compute_forward_sqrt
  8643. static void ggml_compute_forward_sqrt_f32(
  8644. const struct ggml_compute_params * params,
  8645. struct ggml_tensor * dst) {
  8646. const struct ggml_tensor * src0 = dst->src[0];
  8647. if (params->ith != 0) {
  8648. return;
  8649. }
  8650. assert(ggml_are_same_shape(src0, dst));
  8651. const int n = ggml_nrows(src0);
  8652. const int nc = src0->ne[0];
  8653. assert( dst->nb[0] == sizeof(float));
  8654. assert(src0->nb[0] == sizeof(float));
  8655. for (int i = 0; i < n; i++) {
  8656. ggml_vec_sqrt_f32(nc,
  8657. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8658. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8659. }
  8660. }
  8661. static void ggml_compute_forward_sqrt(
  8662. const struct ggml_compute_params * params,
  8663. struct ggml_tensor * dst) {
  8664. const struct ggml_tensor * src0 = dst->src[0];
  8665. switch (src0->type) {
  8666. case GGML_TYPE_F32:
  8667. {
  8668. ggml_compute_forward_sqrt_f32(params, dst);
  8669. } break;
  8670. default:
  8671. {
  8672. GGML_ABORT("fatal error");
  8673. }
  8674. }
  8675. }
  8676. // ggml_compute_forward_log
  8677. static void ggml_compute_forward_log_f32(
  8678. const struct ggml_compute_params * params,
  8679. struct ggml_tensor * dst) {
  8680. const struct ggml_tensor * src0 = dst->src[0];
  8681. if (params->ith != 0) {
  8682. return;
  8683. }
  8684. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8685. const int n = ggml_nrows(src0);
  8686. const int nc = src0->ne[0];
  8687. GGML_ASSERT( dst->nb[0] == sizeof(float));
  8688. GGML_ASSERT(src0->nb[0] == sizeof(float));
  8689. for (int i = 0; i < n; i++) {
  8690. ggml_vec_log_f32(nc,
  8691. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8692. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8693. }
  8694. }
  8695. static void ggml_compute_forward_log(
  8696. const struct ggml_compute_params * params,
  8697. struct ggml_tensor * dst) {
  8698. const struct ggml_tensor * src0 = dst->src[0];
  8699. switch (src0->type) {
  8700. case GGML_TYPE_F32:
  8701. {
  8702. ggml_compute_forward_log_f32(params, dst);
  8703. } break;
  8704. default:
  8705. {
  8706. GGML_ABORT("fatal error");
  8707. }
  8708. }
  8709. }
  8710. // ggml_compute_forward_sin
  8711. static void ggml_compute_forward_sin_f32(
  8712. const struct ggml_compute_params * params,
  8713. struct ggml_tensor * dst) {
  8714. const struct ggml_tensor * src0 = dst->src[0];
  8715. if (params->ith != 0) {
  8716. return;
  8717. }
  8718. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8719. const int n = ggml_nrows(src0);
  8720. const int nc = src0->ne[0];
  8721. GGML_ASSERT( dst->nb[0] == sizeof(float));
  8722. GGML_ASSERT(src0->nb[0] == sizeof(float));
  8723. for (int i = 0; i < n; i++) {
  8724. ggml_vec_sin_f32(nc,
  8725. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8726. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8727. }
  8728. }
  8729. static void ggml_compute_forward_sin(
  8730. const struct ggml_compute_params * params,
  8731. struct ggml_tensor * dst) {
  8732. const struct ggml_tensor * src0 = dst->src[0];
  8733. switch (src0->type) {
  8734. case GGML_TYPE_F32:
  8735. {
  8736. ggml_compute_forward_sin_f32(params, dst);
  8737. } break;
  8738. default:
  8739. {
  8740. GGML_ABORT("fatal error");
  8741. }
  8742. }
  8743. }
  8744. // ggml_compute_forward_cos
  8745. static void ggml_compute_forward_cos_f32(
  8746. const struct ggml_compute_params * params,
  8747. struct ggml_tensor * dst) {
  8748. const struct ggml_tensor * src0 = dst->src[0];
  8749. if (params->ith != 0) {
  8750. return;
  8751. }
  8752. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  8753. const int n = ggml_nrows(src0);
  8754. const int nc = src0->ne[0];
  8755. GGML_ASSERT( dst->nb[0] == sizeof(float));
  8756. GGML_ASSERT(src0->nb[0] == sizeof(float));
  8757. for (int i = 0; i < n; i++) {
  8758. ggml_vec_cos_f32(nc,
  8759. (float *) ((char *) dst->data + i*( dst->nb[1])),
  8760. (float *) ((char *) src0->data + i*(src0->nb[1])));
  8761. }
  8762. }
  8763. static void ggml_compute_forward_cos(
  8764. const struct ggml_compute_params * params,
  8765. struct ggml_tensor * dst) {
  8766. const struct ggml_tensor * src0 = dst->src[0];
  8767. switch (src0->type) {
  8768. case GGML_TYPE_F32:
  8769. {
  8770. ggml_compute_forward_cos_f32(params, dst);
  8771. } break;
  8772. default:
  8773. {
  8774. GGML_ABORT("fatal error");
  8775. }
  8776. }
  8777. }
  8778. // ggml_compute_forward_sum
  8779. static void ggml_compute_forward_sum_f32(
  8780. const struct ggml_compute_params * params,
  8781. struct ggml_tensor * dst) {
  8782. const struct ggml_tensor * src0 = dst->src[0];
  8783. if (params->ith != 0) {
  8784. return;
  8785. }
  8786. assert(ggml_is_scalar(dst));
  8787. assert(src0->nb[0] == sizeof(float));
  8788. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  8789. GGML_TENSOR_LOCALS(size_t, nb0, src0, nb)
  8790. ggml_float sum = 0;
  8791. ggml_float row_sum = 0;
  8792. for (int64_t i03 = 0; i03 < ne03; i03++) {
  8793. for (int64_t i02 = 0; i02 < ne02; i02++) {
  8794. for (int64_t i01 = 0; i01 < ne01; i01++) {
  8795. ggml_vec_sum_f32_ggf(ne00,
  8796. &row_sum,
  8797. (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
  8798. sum += row_sum;
  8799. }
  8800. }
  8801. }
  8802. ((float *) dst->data)[0] = sum;
  8803. }
  8804. static void ggml_compute_forward_sum_f16(
  8805. const struct ggml_compute_params * params,
  8806. struct ggml_tensor * dst) {
  8807. const struct ggml_tensor * src0 = dst->src[0];
  8808. if (params->ith != 0) {
  8809. return;
  8810. }
  8811. assert(ggml_is_scalar(dst));
  8812. assert(src0->nb[0] == sizeof(ggml_fp16_t));
  8813. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  8814. GGML_TENSOR_LOCALS(size_t, nb0, src0, nb)
  8815. float sum = 0;
  8816. float row_sum = 0;
  8817. for (int64_t i03 = 0; i03 < ne03; i03++) {
  8818. for (int64_t i02 = 0; i02 < ne02; i02++) {
  8819. for (int64_t i01 = 0; i01 < ne01; i01++) {
  8820. ggml_vec_sum_f16_ggf(ne00,
  8821. &row_sum,
  8822. (ggml_fp16_t *) ((char *) src0->data + i01 * nb01 + i02 * nb02 + i03 * nb03));
  8823. sum += row_sum;
  8824. }
  8825. }
  8826. }
  8827. ((ggml_fp16_t *) dst->data)[0] = GGML_FP32_TO_FP16(sum);
  8828. }
  8829. static void ggml_compute_forward_sum_bf16(
  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. assert(ggml_is_scalar(dst));
  8837. assert(src0->nb[0] == sizeof(ggml_bf16_t));
  8838. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  8839. GGML_TENSOR_LOCALS(size_t, nb0, src0, nb)
  8840. float sum = 0;
  8841. float row_sum = 0;
  8842. for (int64_t i03 = 0; i03 < ne03; i03++) {
  8843. for (int64_t i02 = 0; i02 < ne02; i02++) {
  8844. for (int64_t i01 = 0; i01 < ne01; i01++) {
  8845. ggml_vec_sum_bf16_ggf(ne00,
  8846. &row_sum,
  8847. (ggml_bf16_t *) ((char *) src0->data + i01 * nb01 + i02 * nb02 + i03 * nb03));
  8848. sum += row_sum;
  8849. }
  8850. }
  8851. }
  8852. ((ggml_bf16_t *) dst->data)[0] = GGML_FP32_TO_BF16(sum);
  8853. }
  8854. static void ggml_compute_forward_sum(
  8855. const struct ggml_compute_params * params,
  8856. struct ggml_tensor * dst) {
  8857. const struct ggml_tensor * src0 = dst->src[0];
  8858. switch (src0->type) {
  8859. case GGML_TYPE_F32:
  8860. {
  8861. ggml_compute_forward_sum_f32(params, dst);
  8862. } break;
  8863. case GGML_TYPE_F16:
  8864. {
  8865. ggml_compute_forward_sum_f16(params, dst);
  8866. } break;
  8867. case GGML_TYPE_BF16:
  8868. {
  8869. ggml_compute_forward_sum_bf16(params, dst);
  8870. } break;
  8871. default:
  8872. {
  8873. GGML_ABORT("fatal error");
  8874. }
  8875. }
  8876. }
  8877. // ggml_compute_forward_sum_rows
  8878. static void ggml_compute_forward_sum_rows_f32(
  8879. const struct ggml_compute_params * params,
  8880. struct ggml_tensor * dst) {
  8881. const struct ggml_tensor * src0 = dst->src[0];
  8882. if (params->ith != 0) {
  8883. return;
  8884. }
  8885. GGML_ASSERT(src0->nb[0] == sizeof(float));
  8886. GGML_ASSERT(dst->nb[0] == sizeof(float));
  8887. GGML_TENSOR_UNARY_OP_LOCALS
  8888. GGML_ASSERT(ne0 == 1);
  8889. GGML_ASSERT(ne1 == ne01);
  8890. GGML_ASSERT(ne2 == ne02);
  8891. GGML_ASSERT(ne3 == ne03);
  8892. for (int64_t i3 = 0; i3 < ne03; i3++) {
  8893. for (int64_t i2 = 0; i2 < ne02; i2++) {
  8894. for (int64_t i1 = 0; i1 < ne01; i1++) {
  8895. float * src_row = (float *) ((char *) src0->data + i1*nb01 + i2*nb02 + i3*nb03);
  8896. float * dst_row = (float *) ((char *) dst->data + i1*nb1 + i2*nb2 + i3*nb3);
  8897. float row_sum = 0;
  8898. ggml_vec_sum_f32(ne00, &row_sum, src_row);
  8899. dst_row[0] = row_sum;
  8900. }
  8901. }
  8902. }
  8903. }
  8904. static void ggml_compute_forward_sum_rows(
  8905. const struct ggml_compute_params * params,
  8906. struct ggml_tensor * dst) {
  8907. const struct ggml_tensor * src0 = dst->src[0];
  8908. switch (src0->type) {
  8909. case GGML_TYPE_F32:
  8910. {
  8911. ggml_compute_forward_sum_rows_f32(params, dst);
  8912. } break;
  8913. default:
  8914. {
  8915. GGML_ABORT("fatal error");
  8916. }
  8917. }
  8918. }
  8919. // ggml_compute_forward_mean
  8920. static void ggml_compute_forward_mean_f32(
  8921. const struct ggml_compute_params * params,
  8922. struct ggml_tensor * dst) {
  8923. const struct ggml_tensor * src0 = dst->src[0];
  8924. if (params->ith != 0) {
  8925. return;
  8926. }
  8927. assert(src0->nb[0] == sizeof(float));
  8928. GGML_TENSOR_UNARY_OP_LOCALS
  8929. assert(ne0 == 1);
  8930. assert(ne1 == ne01);
  8931. assert(ne2 == ne02);
  8932. assert(ne3 == ne03);
  8933. UNUSED(ne0);
  8934. UNUSED(ne1);
  8935. UNUSED(ne2);
  8936. UNUSED(ne3);
  8937. for (int64_t i03 = 0; i03 < ne03; i03++) {
  8938. for (int64_t i02 = 0; i02 < ne02; i02++) {
  8939. for (int64_t i01 = 0; i01 < ne01; i01++) {
  8940. ggml_vec_sum_f32(ne00,
  8941. (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  8942. (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
  8943. *(float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3) /= (float) ne00;
  8944. }
  8945. }
  8946. }
  8947. }
  8948. static void ggml_compute_forward_mean(
  8949. const struct ggml_compute_params * params,
  8950. struct ggml_tensor * dst) {
  8951. const struct ggml_tensor * src0 = dst->src[0];
  8952. switch (src0->type) {
  8953. case GGML_TYPE_F32:
  8954. {
  8955. ggml_compute_forward_mean_f32(params, dst);
  8956. } break;
  8957. default:
  8958. {
  8959. GGML_ABORT("fatal error");
  8960. }
  8961. }
  8962. }
  8963. // ggml_compute_forward_argmax
  8964. static void ggml_compute_forward_argmax_f32(
  8965. const struct ggml_compute_params * params,
  8966. struct ggml_tensor * dst) {
  8967. const struct ggml_tensor * src0 = dst->src[0];
  8968. if (params->ith != 0) {
  8969. return;
  8970. }
  8971. assert(src0->nb[0] == sizeof(float));
  8972. assert(dst->nb[0] == sizeof(float));
  8973. const int64_t ne00 = src0->ne[0];
  8974. const int64_t ne01 = src0->ne[1];
  8975. const size_t nb01 = src0->nb[1];
  8976. const size_t nb0 = dst->nb[0];
  8977. for (int64_t i1 = 0; i1 < ne01; i1++) {
  8978. float * src = (float *) ((char *) src0->data + i1*nb01);
  8979. int32_t * dst_ = (int32_t *) ((char *) dst->data + i1*nb0);
  8980. int v = 0;
  8981. ggml_vec_argmax_f32(ne00, &v, src);
  8982. dst_[0] = v;
  8983. }
  8984. }
  8985. static void ggml_compute_forward_argmax(
  8986. const struct ggml_compute_params * params,
  8987. struct ggml_tensor * dst) {
  8988. const struct ggml_tensor * src0 = dst->src[0];
  8989. switch (src0->type) {
  8990. case GGML_TYPE_F32:
  8991. {
  8992. ggml_compute_forward_argmax_f32(params, dst);
  8993. } break;
  8994. default:
  8995. {
  8996. GGML_ABORT("fatal error");
  8997. }
  8998. }
  8999. }
  9000. // ggml_compute_forward_repeat
  9001. static void ggml_compute_forward_repeat_f32(
  9002. const struct ggml_compute_params * params,
  9003. struct ggml_tensor * dst) {
  9004. const struct ggml_tensor * src0 = dst->src[0];
  9005. if (params->ith != 0) {
  9006. return;
  9007. }
  9008. GGML_ASSERT(ggml_can_repeat(src0, dst));
  9009. GGML_TENSOR_UNARY_OP_LOCALS
  9010. // guaranteed to be an integer due to the check in ggml_can_repeat
  9011. const int nr0 = (int)(ne0/ne00);
  9012. const int nr1 = (int)(ne1/ne01);
  9013. const int nr2 = (int)(ne2/ne02);
  9014. const int nr3 = (int)(ne3/ne03);
  9015. // TODO: support for transposed / permuted tensors
  9016. GGML_ASSERT(nb0 == sizeof(float));
  9017. GGML_ASSERT(nb00 == sizeof(float));
  9018. // TODO: maybe this is not optimal?
  9019. for (int i3 = 0; i3 < nr3; i3++) {
  9020. for (int k3 = 0; k3 < ne03; k3++) {
  9021. for (int i2 = 0; i2 < nr2; i2++) {
  9022. for (int k2 = 0; k2 < ne02; k2++) {
  9023. for (int i1 = 0; i1 < nr1; i1++) {
  9024. for (int k1 = 0; k1 < ne01; k1++) {
  9025. for (int i0 = 0; i0 < nr0; i0++) {
  9026. ggml_vec_cpy_f32(ne00,
  9027. (float *) ((char *) dst->data + (i3*ne03 + k3)*nb3 + (i2*ne02 + k2)*nb2 + (i1*ne01 + k1)*nb1 + (i0*ne00)*nb0),
  9028. (float *) ((char *) src0->data + ( k3)*nb03 + ( k2)*nb02 + ( k1)*nb01));
  9029. }
  9030. }
  9031. }
  9032. }
  9033. }
  9034. }
  9035. }
  9036. }
  9037. static void ggml_compute_forward_repeat_f16(
  9038. const struct ggml_compute_params * params,
  9039. struct ggml_tensor * dst) {
  9040. const struct ggml_tensor * src0 = dst->src[0];
  9041. if (params->ith != 0) {
  9042. return;
  9043. }
  9044. GGML_ASSERT(ggml_can_repeat(src0, dst));
  9045. GGML_TENSOR_UNARY_OP_LOCALS
  9046. // guaranteed to be an integer due to the check in ggml_can_repeat
  9047. const int nr0 = (int)(ne0/ne00);
  9048. const int nr1 = (int)(ne1/ne01);
  9049. const int nr2 = (int)(ne2/ne02);
  9050. const int nr3 = (int)(ne3/ne03);
  9051. // TODO: support for transposed / permuted tensors
  9052. GGML_ASSERT(nb0 == sizeof(ggml_fp16_t));
  9053. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  9054. // TODO: maybe this is not optimal?
  9055. for (int i3 = 0; i3 < nr3; i3++) {
  9056. for (int k3 = 0; k3 < ne03; k3++) {
  9057. for (int i2 = 0; i2 < nr2; i2++) {
  9058. for (int k2 = 0; k2 < ne02; k2++) {
  9059. for (int i1 = 0; i1 < nr1; i1++) {
  9060. for (int k1 = 0; k1 < ne01; k1++) {
  9061. for (int i0 = 0; i0 < nr0; i0++) {
  9062. 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);
  9063. ggml_fp16_t * x = (ggml_fp16_t *) ((char *) src0->data + ( k3)*nb03 + ( k2)*nb02 + ( k1)*nb01);
  9064. // ggml_vec_cpy_f16(ne00, y, x)
  9065. for (int i = 0; i < ne00; ++i) {
  9066. y[i] = x[i];
  9067. }
  9068. }
  9069. }
  9070. }
  9071. }
  9072. }
  9073. }
  9074. }
  9075. }
  9076. static void ggml_compute_forward_repeat(
  9077. const struct ggml_compute_params * params,
  9078. struct ggml_tensor * dst) {
  9079. const struct ggml_tensor * src0 = dst->src[0];
  9080. switch (src0->type) {
  9081. case GGML_TYPE_F16:
  9082. case GGML_TYPE_BF16:
  9083. case GGML_TYPE_I16:
  9084. {
  9085. ggml_compute_forward_repeat_f16(params, dst);
  9086. } break;
  9087. case GGML_TYPE_F32:
  9088. case GGML_TYPE_I32:
  9089. {
  9090. ggml_compute_forward_repeat_f32(params, dst);
  9091. } break;
  9092. default:
  9093. {
  9094. GGML_ABORT("fatal error");
  9095. }
  9096. }
  9097. }
  9098. // ggml_compute_forward_repeat_back
  9099. static void ggml_compute_forward_repeat_back_f32(
  9100. const struct ggml_compute_params * params,
  9101. struct ggml_tensor * dst) {
  9102. const struct ggml_tensor * src0 = dst->src[0];
  9103. if (params->ith != 0) {
  9104. return;
  9105. }
  9106. GGML_ASSERT(ggml_can_repeat(dst, src0));
  9107. GGML_TENSOR_UNARY_OP_LOCALS
  9108. // guaranteed to be an integer due to the check in ggml_can_repeat
  9109. const int nr0 = (int)(ne00/ne0);
  9110. const int nr1 = (int)(ne01/ne1);
  9111. const int nr2 = (int)(ne02/ne2);
  9112. const int nr3 = (int)(ne03/ne3);
  9113. // TODO: support for transposed / permuted tensors
  9114. GGML_ASSERT(nb0 == sizeof(float));
  9115. GGML_ASSERT(nb00 == sizeof(float));
  9116. if (ggml_is_contiguous(dst)) {
  9117. ggml_vec_set_f32(ne0*ne1*ne2*ne3, dst->data, 0);
  9118. } else {
  9119. for (int k3 = 0; k3 < ne3; k3++) {
  9120. for (int k2 = 0; k2 < ne2; k2++) {
  9121. for (int k1 = 0; k1 < ne1; k1++) {
  9122. ggml_vec_set_f32(ne0,
  9123. (float *) ((char *) dst->data + k1*nb1 + k2*nb2 + k3*nb3),
  9124. 0);
  9125. }
  9126. }
  9127. }
  9128. }
  9129. // TODO: maybe this is not optimal?
  9130. for (int i3 = 0; i3 < nr3; i3++) {
  9131. for (int k3 = 0; k3 < ne3; k3++) {
  9132. for (int i2 = 0; i2 < nr2; i2++) {
  9133. for (int k2 = 0; k2 < ne2; k2++) {
  9134. for (int i1 = 0; i1 < nr1; i1++) {
  9135. for (int k1 = 0; k1 < ne1; k1++) {
  9136. for (int i0 = 0; i0 < nr0; i0++) {
  9137. ggml_vec_acc_f32(ne0,
  9138. (float *) ((char *) dst->data + ( k3)*nb3 + ( k2)*nb2 + ( k1)*nb1),
  9139. (float *) ((char *) src0->data + (i3*ne3 + k3)*nb03 + (i2*ne2 + k2)*nb02 + (i1*ne1 + k1)*nb01 + (i0*ne0)*nb00));
  9140. }
  9141. }
  9142. }
  9143. }
  9144. }
  9145. }
  9146. }
  9147. }
  9148. static void ggml_compute_forward_repeat_back(
  9149. const struct ggml_compute_params * params,
  9150. struct ggml_tensor * dst) {
  9151. const struct ggml_tensor * src0 = dst->src[0];
  9152. switch (src0->type) {
  9153. case GGML_TYPE_F32:
  9154. {
  9155. ggml_compute_forward_repeat_back_f32(params, dst);
  9156. } break;
  9157. default:
  9158. {
  9159. GGML_ABORT("fatal error");
  9160. }
  9161. }
  9162. }
  9163. // ggml_compute_forward_concat
  9164. static void ggml_compute_forward_concat_f32(
  9165. const struct ggml_compute_params * params,
  9166. struct ggml_tensor * dst) {
  9167. const struct ggml_tensor * src0 = dst->src[0];
  9168. const struct ggml_tensor * src1 = dst->src[1];
  9169. GGML_ASSERT(src0->nb[0] == sizeof(float));
  9170. const int ith = params->ith;
  9171. const int nth = params->nth;
  9172. GGML_TENSOR_BINARY_OP_LOCALS
  9173. const int32_t dim = ggml_get_op_params_i32(dst, 0);
  9174. GGML_ASSERT(dim >= 0 && dim < 4);
  9175. int64_t o[4] = {0, 0, 0, 0};
  9176. o[dim] = src0->ne[dim];
  9177. const float * x;
  9178. // TODO: smarter multi-theading
  9179. for (int i3 = 0; i3 < ne3; i3++) {
  9180. for (int i2 = ith; i2 < ne2; i2 += nth) {
  9181. for (int i1 = 0; i1 < ne1; i1++) {
  9182. for (int i0 = 0; i0 < ne0; i0++) {
  9183. if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
  9184. x = (const float *) ((const char *)src0->data + (i0 )*nb00 + (i1 )*nb01 + (i2 )*nb02 + (i3 )*nb03);
  9185. } else {
  9186. x = (const float *) ((const char *)src1->data + (i0 - o[0])*nb10 + (i1 - o[1])*nb11 + (i2 - o[2])*nb12 + (i3 - o[3])*nb13);
  9187. }
  9188. float * y = (float *)((char *)dst->data + i0*nb0 + i1*nb1 + i2*nb2 + i3*nb3);
  9189. *y = *x;
  9190. }
  9191. }
  9192. }
  9193. }
  9194. }
  9195. static void ggml_compute_forward_concat(
  9196. const struct ggml_compute_params * params,
  9197. struct ggml_tensor * dst) {
  9198. const struct ggml_tensor * src0 = dst->src[0];
  9199. switch (src0->type) {
  9200. case GGML_TYPE_F32:
  9201. case GGML_TYPE_I32:
  9202. {
  9203. ggml_compute_forward_concat_f32(params, dst);
  9204. } break;
  9205. default:
  9206. {
  9207. GGML_ABORT("fatal error");
  9208. }
  9209. }
  9210. }
  9211. // ggml_compute_forward_abs
  9212. static void ggml_compute_forward_abs_f32(
  9213. const struct ggml_compute_params * params,
  9214. struct ggml_tensor * dst) {
  9215. const struct ggml_tensor * src0 = dst->src[0];
  9216. if (params->ith != 0) {
  9217. return;
  9218. }
  9219. assert(ggml_is_contiguous_1(src0));
  9220. assert(ggml_is_contiguous_1(dst));
  9221. assert(ggml_are_same_shape(src0, dst));
  9222. const int n = ggml_nrows(src0);
  9223. const int nc = src0->ne[0];
  9224. for (int i = 0; i < n; i++) {
  9225. ggml_vec_abs_f32(nc,
  9226. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9227. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9228. }
  9229. }
  9230. static void ggml_compute_forward_abs(
  9231. const struct ggml_compute_params * params,
  9232. struct ggml_tensor * dst) {
  9233. const struct ggml_tensor * src0 = dst->src[0];
  9234. switch (src0->type) {
  9235. case GGML_TYPE_F32:
  9236. {
  9237. ggml_compute_forward_abs_f32(params, dst);
  9238. } break;
  9239. default:
  9240. {
  9241. GGML_ABORT("fatal error");
  9242. }
  9243. }
  9244. }
  9245. // ggml_compute_forward_sgn
  9246. static void ggml_compute_forward_sgn_f32(
  9247. const struct ggml_compute_params * params,
  9248. struct ggml_tensor * dst) {
  9249. const struct ggml_tensor * src0 = dst->src[0];
  9250. if (params->ith != 0) {
  9251. return;
  9252. }
  9253. assert(ggml_is_contiguous_1(src0));
  9254. assert(ggml_is_contiguous_1(dst));
  9255. assert(ggml_are_same_shape(src0, dst));
  9256. const int n = ggml_nrows(src0);
  9257. const int nc = src0->ne[0];
  9258. for (int i = 0; i < n; i++) {
  9259. ggml_vec_sgn_f32(nc,
  9260. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9261. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9262. }
  9263. }
  9264. static void ggml_compute_forward_sgn(
  9265. const struct ggml_compute_params * params,
  9266. struct ggml_tensor * dst) {
  9267. const struct ggml_tensor * src0 = dst->src[0];
  9268. switch (src0->type) {
  9269. case GGML_TYPE_F32:
  9270. {
  9271. ggml_compute_forward_sgn_f32(params, dst);
  9272. } break;
  9273. default:
  9274. {
  9275. GGML_ABORT("fatal error");
  9276. }
  9277. }
  9278. }
  9279. // ggml_compute_forward_neg
  9280. static void ggml_compute_forward_neg_f32(
  9281. const struct ggml_compute_params * params,
  9282. struct ggml_tensor * dst) {
  9283. const struct ggml_tensor * src0 = dst->src[0];
  9284. if (params->ith != 0) {
  9285. return;
  9286. }
  9287. assert(ggml_is_contiguous_1(src0));
  9288. assert(ggml_is_contiguous_1(dst));
  9289. assert(ggml_are_same_shape(src0, dst));
  9290. const int n = ggml_nrows(src0);
  9291. const int nc = src0->ne[0];
  9292. for (int i = 0; i < n; i++) {
  9293. ggml_vec_neg_f32(nc,
  9294. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9295. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9296. }
  9297. }
  9298. static void ggml_compute_forward_neg(
  9299. const struct ggml_compute_params * params,
  9300. struct ggml_tensor * dst) {
  9301. const struct ggml_tensor * src0 = dst->src[0];
  9302. switch (src0->type) {
  9303. case GGML_TYPE_F32:
  9304. {
  9305. ggml_compute_forward_neg_f32(params, dst);
  9306. } break;
  9307. default:
  9308. {
  9309. GGML_ABORT("fatal error");
  9310. }
  9311. }
  9312. }
  9313. // ggml_compute_forward_step
  9314. static void ggml_compute_forward_step_f32(
  9315. const struct ggml_compute_params * params,
  9316. struct ggml_tensor * dst) {
  9317. const struct ggml_tensor * src0 = dst->src[0];
  9318. if (params->ith != 0) {
  9319. return;
  9320. }
  9321. assert(ggml_is_contiguous_1(src0));
  9322. assert(ggml_is_contiguous_1(dst));
  9323. assert(ggml_are_same_shape(src0, dst));
  9324. const int n = ggml_nrows(src0);
  9325. const int nc = src0->ne[0];
  9326. for (int i = 0; i < n; i++) {
  9327. ggml_vec_step_f32(nc,
  9328. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9329. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9330. }
  9331. }
  9332. static void ggml_compute_forward_step(
  9333. const struct ggml_compute_params * params,
  9334. struct ggml_tensor * dst) {
  9335. const struct ggml_tensor * src0 = dst->src[0];
  9336. switch (src0->type) {
  9337. case GGML_TYPE_F32:
  9338. {
  9339. ggml_compute_forward_step_f32(params, dst);
  9340. } break;
  9341. default:
  9342. {
  9343. GGML_ABORT("fatal error");
  9344. }
  9345. }
  9346. }
  9347. // ggml_compute_forward_tanh
  9348. static void ggml_compute_forward_tanh_f32(
  9349. const struct ggml_compute_params * params,
  9350. struct ggml_tensor * dst) {
  9351. const struct ggml_tensor * src0 = dst->src[0];
  9352. if (params->ith != 0) {
  9353. return;
  9354. }
  9355. assert(ggml_is_contiguous_1(src0));
  9356. assert(ggml_is_contiguous_1(dst));
  9357. assert(ggml_are_same_shape(src0, dst));
  9358. const int n = ggml_nrows(src0);
  9359. const int nc = src0->ne[0];
  9360. for (int i = 0; i < n; i++) {
  9361. ggml_vec_tanh_f32(nc,
  9362. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9363. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9364. }
  9365. }
  9366. static void ggml_compute_forward_tanh(
  9367. const struct ggml_compute_params * params,
  9368. struct ggml_tensor * dst) {
  9369. const struct ggml_tensor * src0 = dst->src[0];
  9370. switch (src0->type) {
  9371. case GGML_TYPE_F32:
  9372. {
  9373. ggml_compute_forward_tanh_f32(params, dst);
  9374. } break;
  9375. default:
  9376. {
  9377. GGML_ABORT("fatal error");
  9378. }
  9379. }
  9380. }
  9381. // ggml_compute_forward_elu
  9382. static void ggml_compute_forward_elu_f32(
  9383. const struct ggml_compute_params * params,
  9384. struct ggml_tensor * dst) {
  9385. const struct ggml_tensor * src0 = dst->src[0];
  9386. if (params->ith != 0) {
  9387. return;
  9388. }
  9389. assert(ggml_is_contiguous_1(src0));
  9390. assert(ggml_is_contiguous_1(dst));
  9391. assert(ggml_are_same_shape(src0, dst));
  9392. const int n = ggml_nrows(src0);
  9393. const int nc = src0->ne[0];
  9394. for (int i = 0; i < n; i++) {
  9395. ggml_vec_elu_f32(nc,
  9396. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9397. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9398. }
  9399. }
  9400. static void ggml_compute_forward_elu(
  9401. const struct ggml_compute_params * params,
  9402. struct ggml_tensor * dst) {
  9403. const struct ggml_tensor * src0 = dst->src[0];
  9404. switch (src0->type) {
  9405. case GGML_TYPE_F32:
  9406. {
  9407. ggml_compute_forward_elu_f32(params, dst);
  9408. } break;
  9409. default:
  9410. {
  9411. GGML_ABORT("fatal error");
  9412. }
  9413. }
  9414. }
  9415. // ggml_compute_forward_relu
  9416. static void ggml_compute_forward_relu_f32(
  9417. const struct ggml_compute_params * params,
  9418. struct ggml_tensor * dst) {
  9419. const struct ggml_tensor * src0 = dst->src[0];
  9420. if (params->ith != 0) {
  9421. return;
  9422. }
  9423. assert(ggml_is_contiguous_1(src0));
  9424. assert(ggml_is_contiguous_1(dst));
  9425. assert(ggml_are_same_shape(src0, dst));
  9426. const int n = ggml_nrows(src0);
  9427. const int nc = src0->ne[0];
  9428. for (int i = 0; i < n; i++) {
  9429. ggml_vec_relu_f32(nc,
  9430. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9431. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9432. }
  9433. }
  9434. static void ggml_compute_forward_relu(
  9435. const struct ggml_compute_params * params,
  9436. struct ggml_tensor * dst) {
  9437. const struct ggml_tensor * src0 = dst->src[0];
  9438. switch (src0->type) {
  9439. case GGML_TYPE_F32:
  9440. {
  9441. ggml_compute_forward_relu_f32(params, dst);
  9442. } break;
  9443. default:
  9444. {
  9445. GGML_ABORT("fatal error");
  9446. }
  9447. }
  9448. }
  9449. // ggml_compute_forward_sigmoid
  9450. static void ggml_compute_forward_sigmoid_f32(
  9451. const struct ggml_compute_params * params,
  9452. struct ggml_tensor * dst) {
  9453. const struct ggml_tensor * src0 = dst->src[0];
  9454. if (params->ith != 0) {
  9455. return;
  9456. }
  9457. assert(ggml_is_contiguous_1(src0));
  9458. assert(ggml_is_contiguous_1(dst));
  9459. assert(ggml_are_same_shape(src0, dst));
  9460. const int n = ggml_nrows(src0);
  9461. const int nc = src0->ne[0];
  9462. for (int i = 0; i < n; i++) {
  9463. ggml_vec_sigmoid_f32(nc,
  9464. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9465. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9466. }
  9467. }
  9468. static void ggml_compute_forward_sigmoid(
  9469. const struct ggml_compute_params * params,
  9470. struct ggml_tensor * dst) {
  9471. const struct ggml_tensor * src0 = dst->src[0];
  9472. switch (src0->type) {
  9473. case GGML_TYPE_F32:
  9474. {
  9475. ggml_compute_forward_sigmoid_f32(params, dst);
  9476. } break;
  9477. default:
  9478. {
  9479. GGML_ABORT("fatal error");
  9480. }
  9481. }
  9482. }
  9483. // ggml_compute_forward_gelu
  9484. static void ggml_compute_forward_gelu_f32(
  9485. const struct ggml_compute_params * params,
  9486. struct ggml_tensor * dst) {
  9487. const struct ggml_tensor * src0 = dst->src[0];
  9488. assert(ggml_is_contiguous_1(src0));
  9489. assert(ggml_is_contiguous_1(dst));
  9490. assert(ggml_are_same_shape(src0, dst));
  9491. const int ith = params->ith;
  9492. const int nth = params->nth;
  9493. const int nc = src0->ne[0];
  9494. const int nr = ggml_nrows(src0);
  9495. // rows per thread
  9496. const int dr = (nr + nth - 1)/nth;
  9497. // row range for this thread
  9498. const int ir0 = dr*ith;
  9499. const int ir1 = MIN(ir0 + dr, nr);
  9500. for (int i1 = ir0; i1 < ir1; i1++) {
  9501. ggml_vec_gelu_f32(nc,
  9502. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  9503. (float *) ((char *) src0->data + i1*(src0->nb[1])));
  9504. #ifndef NDEBUG
  9505. for (int k = 0; k < nc; k++) {
  9506. const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
  9507. UNUSED(x);
  9508. assert(!isnan(x));
  9509. assert(!isinf(x));
  9510. }
  9511. #endif
  9512. }
  9513. }
  9514. static void ggml_compute_forward_gelu(
  9515. const struct ggml_compute_params * params,
  9516. struct ggml_tensor * dst) {
  9517. const struct ggml_tensor * src0 = dst->src[0];
  9518. switch (src0->type) {
  9519. case GGML_TYPE_F32:
  9520. {
  9521. ggml_compute_forward_gelu_f32(params, dst);
  9522. } break;
  9523. default:
  9524. {
  9525. GGML_ABORT("fatal error");
  9526. }
  9527. }
  9528. }
  9529. // ggml_compute_forward_gelu_quick
  9530. static void ggml_compute_forward_gelu_quick_f32(
  9531. const struct ggml_compute_params * params,
  9532. struct ggml_tensor * dst) {
  9533. const struct ggml_tensor * src0 = dst->src[0];
  9534. assert(ggml_is_contiguous_1(src0));
  9535. assert(ggml_is_contiguous_1(dst));
  9536. assert(ggml_are_same_shape(src0, dst));
  9537. const int ith = params->ith;
  9538. const int nth = params->nth;
  9539. const int nc = src0->ne[0];
  9540. const int nr = ggml_nrows(src0);
  9541. // rows per thread
  9542. const int dr = (nr + nth - 1)/nth;
  9543. // row range for this thread
  9544. const int ir0 = dr*ith;
  9545. const int ir1 = MIN(ir0 + dr, nr);
  9546. for (int i1 = ir0; i1 < ir1; i1++) {
  9547. ggml_vec_gelu_quick_f32(nc,
  9548. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  9549. (float *) ((char *) src0->data + i1*(src0->nb[1])));
  9550. #ifndef NDEBUG
  9551. for (int k = 0; k < nc; k++) {
  9552. const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
  9553. UNUSED(x);
  9554. assert(!isnan(x));
  9555. assert(!isinf(x));
  9556. }
  9557. #endif
  9558. }
  9559. }
  9560. static void ggml_compute_forward_gelu_quick(
  9561. const struct ggml_compute_params * params,
  9562. struct ggml_tensor * dst) {
  9563. const struct ggml_tensor * src0 = dst->src[0];
  9564. switch (src0->type) {
  9565. case GGML_TYPE_F32:
  9566. {
  9567. ggml_compute_forward_gelu_quick_f32(params, dst);
  9568. } break;
  9569. default:
  9570. {
  9571. GGML_ABORT("fatal error");
  9572. }
  9573. }
  9574. }
  9575. // ggml_compute_forward_silu
  9576. static void ggml_compute_forward_silu_f32(
  9577. const struct ggml_compute_params * params,
  9578. struct ggml_tensor * dst) {
  9579. const struct ggml_tensor * src0 = dst->src[0];
  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 ith = params->ith;
  9584. const int nth = params->nth;
  9585. const int nc = src0->ne[0];
  9586. const int nr = ggml_nrows(src0);
  9587. // rows per thread
  9588. const int dr = (nr + nth - 1)/nth;
  9589. // row range for this thread
  9590. const int ir0 = dr*ith;
  9591. const int ir1 = MIN(ir0 + dr, nr);
  9592. for (int i1 = ir0; i1 < ir1; i1++) {
  9593. ggml_vec_silu_f32(nc,
  9594. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  9595. (float *) ((char *) src0->data + i1*(src0->nb[1])));
  9596. #ifndef NDEBUG
  9597. for (int k = 0; k < nc; k++) {
  9598. const float x = ((float *) ((char *) dst->data + i1*(dst->nb[1])))[k];
  9599. UNUSED(x);
  9600. assert(!isnan(x));
  9601. assert(!isinf(x));
  9602. }
  9603. #endif
  9604. }
  9605. }
  9606. static void ggml_compute_forward_silu(
  9607. const struct ggml_compute_params * params,
  9608. struct ggml_tensor * dst) {
  9609. const struct ggml_tensor * src0 = dst->src[0];
  9610. switch (src0->type) {
  9611. case GGML_TYPE_F32:
  9612. {
  9613. ggml_compute_forward_silu_f32(params, dst);
  9614. } break;
  9615. default:
  9616. {
  9617. GGML_ABORT("fatal error");
  9618. }
  9619. }
  9620. }
  9621. // ggml_compute_forward_leaky_relu
  9622. static void ggml_compute_forward_leaky_relu_f32(
  9623. const struct ggml_compute_params * params,
  9624. struct ggml_tensor * dst) {
  9625. const struct ggml_tensor * src0 = dst->src[0];
  9626. if (params->ith != 0) {
  9627. return;
  9628. }
  9629. assert(ggml_is_contiguous_1(src0));
  9630. assert(ggml_is_contiguous_1(dst));
  9631. assert(ggml_are_same_shape(src0, dst));
  9632. const int n = ggml_nrows(src0);
  9633. const int nc = src0->ne[0];
  9634. float negative_slope;
  9635. memcpy(&negative_slope, dst->op_params, sizeof(float));
  9636. assert(dst->nb[0] == sizeof(float));
  9637. assert(src0->nb[0] == sizeof(float));
  9638. for (int i = 0; i < n; i++) {
  9639. ggml_vec_leaky_relu_f32(nc,
  9640. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9641. (float *) ((char *) src0->data + i*(src0->nb[1])), negative_slope);
  9642. }
  9643. }
  9644. static void ggml_compute_forward_leaky_relu(
  9645. const struct ggml_compute_params * params,
  9646. struct ggml_tensor * dst) {
  9647. const struct ggml_tensor * src0 = dst->src[0];
  9648. switch (src0->type) {
  9649. case GGML_TYPE_F32:
  9650. {
  9651. ggml_compute_forward_leaky_relu_f32(params, dst);
  9652. } break;
  9653. default:
  9654. {
  9655. GGML_ABORT("fatal error");
  9656. }
  9657. }
  9658. }
  9659. // ggml_compute_forward_silu_back
  9660. static void ggml_compute_forward_silu_back_f32(
  9661. const struct ggml_compute_params * params,
  9662. struct ggml_tensor * dst) {
  9663. const struct ggml_tensor * src0 = dst->src[0];
  9664. const struct ggml_tensor * grad = dst->src[1];
  9665. assert(ggml_is_contiguous_1(grad));
  9666. assert(ggml_is_contiguous_1(src0));
  9667. assert(ggml_is_contiguous_1(dst));
  9668. assert(ggml_are_same_shape(src0, dst));
  9669. assert(ggml_are_same_shape(src0, grad));
  9670. const int ith = params->ith;
  9671. const int nth = params->nth;
  9672. const int nc = src0->ne[0];
  9673. const int nr = ggml_nrows(src0);
  9674. // rows per thread
  9675. const int dr = (nr + nth - 1)/nth;
  9676. // row range for this thread
  9677. const int ir0 = dr*ith;
  9678. const int ir1 = MIN(ir0 + dr, nr);
  9679. for (int i1 = ir0; i1 < ir1; i1++) {
  9680. ggml_vec_silu_backward_f32(nc,
  9681. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  9682. (float *) ((char *) src0->data + i1*(src0->nb[1])),
  9683. (float *) ((char *) grad->data + i1*(grad->nb[1])));
  9684. #ifndef NDEBUG
  9685. for (int k = 0; k < nc; k++) {
  9686. const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
  9687. UNUSED(x);
  9688. assert(!isnan(x));
  9689. assert(!isinf(x));
  9690. }
  9691. #endif
  9692. }
  9693. }
  9694. static void ggml_compute_forward_silu_back(
  9695. const struct ggml_compute_params * params,
  9696. struct ggml_tensor * dst) {
  9697. const struct ggml_tensor * src0 = dst->src[0];
  9698. switch (src0->type) {
  9699. case GGML_TYPE_F32:
  9700. {
  9701. ggml_compute_forward_silu_back_f32(params, dst);
  9702. } break;
  9703. default:
  9704. {
  9705. GGML_ABORT("fatal error");
  9706. }
  9707. }
  9708. }
  9709. static void ggml_compute_forward_hardswish_f32(
  9710. const struct ggml_compute_params * params,
  9711. struct ggml_tensor * dst) {
  9712. const struct ggml_tensor * src0 = dst->src[0];
  9713. if (params->ith != 0) {
  9714. return;
  9715. }
  9716. assert(ggml_is_contiguous_1(src0));
  9717. assert(ggml_is_contiguous_1(dst));
  9718. assert(ggml_are_same_shape(src0, dst));
  9719. const int n = ggml_nrows(src0);
  9720. const int nc = src0->ne[0];
  9721. for (int i = 0; i < n; i++) {
  9722. ggml_vec_hardswish_f32(nc,
  9723. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9724. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9725. }
  9726. }
  9727. static void ggml_compute_forward_hardswish(
  9728. const struct ggml_compute_params * params,
  9729. struct ggml_tensor * dst) {
  9730. const struct ggml_tensor * src0 = dst->src[0];
  9731. switch (src0->type) {
  9732. case GGML_TYPE_F32:
  9733. {
  9734. ggml_compute_forward_hardswish_f32(params, dst);
  9735. } break;
  9736. default:
  9737. {
  9738. GGML_ABORT("fatal error");
  9739. }
  9740. }
  9741. }
  9742. static void ggml_compute_forward_hardsigmoid_f32(
  9743. const struct ggml_compute_params * params,
  9744. struct ggml_tensor * dst) {
  9745. const struct ggml_tensor * src0 = dst->src[0];
  9746. if (params->ith != 0) {
  9747. return;
  9748. }
  9749. assert(ggml_is_contiguous_1(src0));
  9750. assert(ggml_is_contiguous_1(dst));
  9751. assert(ggml_are_same_shape(src0, dst));
  9752. const int n = ggml_nrows(src0);
  9753. const int nc = src0->ne[0];
  9754. for (int i = 0; i < n; i++) {
  9755. ggml_vec_hardsigmoid_f32(nc,
  9756. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9757. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9758. }
  9759. }
  9760. static void ggml_compute_forward_hardsigmoid(
  9761. const struct ggml_compute_params * params,
  9762. struct ggml_tensor * dst) {
  9763. const struct ggml_tensor * src0 = dst->src[0];
  9764. switch (src0->type) {
  9765. case GGML_TYPE_F32:
  9766. {
  9767. ggml_compute_forward_hardsigmoid_f32(params, dst);
  9768. } break;
  9769. default:
  9770. {
  9771. GGML_ABORT("fatal error");
  9772. }
  9773. }
  9774. }
  9775. static void ggml_compute_forward_exp_f32(
  9776. const struct ggml_compute_params * params,
  9777. struct ggml_tensor * dst) {
  9778. const struct ggml_tensor * src0 = dst->src[0];
  9779. if (params->ith != 0) {
  9780. return;
  9781. }
  9782. assert(ggml_is_contiguous_1(src0));
  9783. assert(ggml_is_contiguous_1(dst));
  9784. assert(ggml_are_same_shape(src0, dst));
  9785. const int n = ggml_nrows(src0);
  9786. const int nc = src0->ne[0];
  9787. for (int i = 0; i < n; i++) {
  9788. ggml_vec_exp_f32(nc,
  9789. (float *) ((char *) dst->data + i*( dst->nb[1])),
  9790. (float *) ((char *) src0->data + i*(src0->nb[1])));
  9791. }
  9792. }
  9793. static void ggml_compute_forward_exp(
  9794. const struct ggml_compute_params * params,
  9795. struct ggml_tensor * dst) {
  9796. const struct ggml_tensor * src0 = dst->src[0];
  9797. switch (src0->type) {
  9798. case GGML_TYPE_F32:
  9799. {
  9800. ggml_compute_forward_exp_f32(params, dst);
  9801. } break;
  9802. default:
  9803. {
  9804. GGML_ABORT("fatal error");
  9805. }
  9806. }
  9807. }
  9808. // ggml_compute_forward_norm
  9809. static void ggml_compute_forward_norm_f32(
  9810. const struct ggml_compute_params * params,
  9811. struct ggml_tensor * dst) {
  9812. const struct ggml_tensor * src0 = dst->src[0];
  9813. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  9814. GGML_ASSERT(src0->nb[0] == sizeof(float));
  9815. const int ith = params->ith;
  9816. const int nth = params->nth;
  9817. GGML_TENSOR_UNARY_OP_LOCALS
  9818. float eps;
  9819. memcpy(&eps, dst->op_params, sizeof(float));
  9820. GGML_ASSERT(eps > 0.0f);
  9821. // TODO: optimize
  9822. for (int64_t i03 = 0; i03 < ne03; i03++) {
  9823. for (int64_t i02 = 0; i02 < ne02; i02++) {
  9824. for (int64_t i01 = ith; i01 < ne01; i01 += nth) {
  9825. const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  9826. ggml_float sum = 0.0;
  9827. for (int64_t i00 = 0; i00 < ne00; i00++) {
  9828. sum += (ggml_float)x[i00];
  9829. }
  9830. float mean = sum/ne00;
  9831. float * y = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
  9832. ggml_float sum2 = 0.0;
  9833. for (int64_t i00 = 0; i00 < ne00; i00++) {
  9834. float v = x[i00] - mean;
  9835. y[i00] = v;
  9836. sum2 += (ggml_float)(v*v);
  9837. }
  9838. float variance = sum2/ne00;
  9839. const float scale = 1.0f/sqrtf(variance + eps);
  9840. ggml_vec_scale_f32(ne00, y, scale);
  9841. }
  9842. }
  9843. }
  9844. }
  9845. static void ggml_compute_forward_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_norm_f32(params, dst);
  9853. } break;
  9854. default:
  9855. {
  9856. GGML_ABORT("fatal error");
  9857. }
  9858. }
  9859. }
  9860. // ggml_compute_forward_group_rms_norm
  9861. static void ggml_compute_forward_rms_norm_f32(
  9862. const struct ggml_compute_params * params,
  9863. struct ggml_tensor * dst) {
  9864. const struct ggml_tensor * src0 = dst->src[0];
  9865. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  9866. GGML_ASSERT(src0->nb[0] == sizeof(float));
  9867. const int ith = params->ith;
  9868. const int nth = params->nth;
  9869. GGML_TENSOR_UNARY_OP_LOCALS
  9870. float eps;
  9871. memcpy(&eps, dst->op_params, sizeof(float));
  9872. GGML_ASSERT(eps > 0.0f);
  9873. // TODO: optimize
  9874. for (int64_t i03 = 0; i03 < ne03; i03++) {
  9875. for (int64_t i02 = 0; i02 < ne02; i02++) {
  9876. for (int64_t i01 = ith; i01 < ne01; i01 += nth) {
  9877. const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  9878. ggml_float sum = 0.0;
  9879. for (int64_t i00 = 0; i00 < ne00; i00++) {
  9880. sum += (ggml_float)(x[i00] * x[i00]);
  9881. }
  9882. const float mean = sum/ne00;
  9883. float * y = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
  9884. memcpy(y, x, ne00 * sizeof(float));
  9885. // for (int i00 = 0; i00 < ne00; i00++) {
  9886. // y[i00] = x[i00];
  9887. // }
  9888. const float scale = 1.0f/sqrtf(mean + eps);
  9889. ggml_vec_scale_f32(ne00, y, scale);
  9890. }
  9891. }
  9892. }
  9893. }
  9894. static void ggml_compute_forward_rms_norm(
  9895. const struct ggml_compute_params * params,
  9896. struct ggml_tensor * dst) {
  9897. const struct ggml_tensor * src0 = dst->src[0];
  9898. switch (src0->type) {
  9899. case GGML_TYPE_F32:
  9900. {
  9901. ggml_compute_forward_rms_norm_f32(params, dst);
  9902. } break;
  9903. default:
  9904. {
  9905. GGML_ABORT("fatal error");
  9906. }
  9907. }
  9908. }
  9909. static void ggml_compute_forward_rms_norm_back_f32(
  9910. const struct ggml_compute_params * params,
  9911. struct ggml_tensor * dst) {
  9912. const struct ggml_tensor * src0 = dst->src[0];
  9913. const struct ggml_tensor * src1 = dst->src[1];
  9914. GGML_ASSERT(ggml_are_same_shape(src0, dst) && ggml_are_same_shape(src0, src1));
  9915. GGML_ASSERT(src0->nb[0] == sizeof(float));
  9916. const int ith = params->ith;
  9917. const int nth = params->nth;
  9918. GGML_TENSOR_BINARY_OP_LOCALS
  9919. float eps;
  9920. memcpy(&eps, dst->op_params, sizeof(float));
  9921. // TODO: optimize
  9922. for (int64_t i03 = 0; i03 < ne03; i03++) {
  9923. for (int64_t i02 = 0; i02 < ne02; i02++) {
  9924. for (int64_t i01 = ith; i01 < ne01; i01 += nth) {
  9925. // src1 is same shape as src0 => same indices
  9926. const int64_t i11 = i01;
  9927. const int64_t i12 = i02;
  9928. const int64_t i13 = i03;
  9929. const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  9930. const float * dz = (float *) ((char *) src1->data + i11*nb11 + i12*nb12 + i13*nb13);
  9931. ggml_float sum_xx = 0.0;
  9932. ggml_float sum_xdz = 0.0;
  9933. for (int64_t i00 = 0; i00 < ne00; i00++) {
  9934. sum_xx += (ggml_float)(x[i00] * x[i00]);
  9935. sum_xdz += (ggml_float)(x[i00] * dz[i00]);
  9936. }
  9937. //const float mean = (float)(sum_xx)/ne00;
  9938. const float mean_eps = (float)(sum_xx)/ne00 + eps;
  9939. const float sum_eps = (float)(sum_xx) + eps*ne00;
  9940. //const float mean_xdz = (float)(sum_xdz)/ne00;
  9941. // we could cache rms from forward pass to improve performance.
  9942. // to do this implement ggml_rms and compose ggml_rms_norm using ggml_rms.
  9943. //const float rms = sqrtf(mean_eps);
  9944. const float rrms = 1.0f / sqrtf(mean_eps);
  9945. //const float scale = -rrms/(ne00 * mean_eps); // -1/(n*rms**3)
  9946. {
  9947. // z = rms_norm(x)
  9948. //
  9949. // rms_norm(src0) =
  9950. // scale(
  9951. // src0,
  9952. // div(
  9953. // 1,
  9954. // sqrt(
  9955. // add(
  9956. // scale(
  9957. // sum(
  9958. // sqr(
  9959. // src0)),
  9960. // (1.0/N)),
  9961. // eps))));
  9962. // postorder:
  9963. // ## op args grad
  9964. // 00 param src0 grad[#00]
  9965. // 01 const 1
  9966. // 02 sqr (#00) grad[#02]
  9967. // 03 sum (#02) grad[#03]
  9968. // 04 const 1/N
  9969. // 05 scale (#03, #04) grad[#05]
  9970. // 06 const eps
  9971. // 07 add (#05, #06) grad[#07]
  9972. // 08 sqrt (#07) grad[#08]
  9973. // 09 div (#01,#08) grad[#09]
  9974. // 10 scale (#00,#09) grad[#10]
  9975. //
  9976. // backward pass, given grad[#10]
  9977. // #10: scale
  9978. // grad[#00] += scale(grad[#10],#09)
  9979. // grad[#09] += sum(mul(grad[#10],#00))
  9980. // #09: div
  9981. // grad[#08] += neg(mul(grad[#09], div(#09,#08)))
  9982. // #08: sqrt
  9983. // grad[#07] += mul(grad[#08], div(0.5, #08))
  9984. // #07: add
  9985. // grad[#05] += grad[#07]
  9986. // #05: scale
  9987. // grad[#03] += scale(grad[#05],#04)
  9988. // #03: sum
  9989. // grad[#02] += repeat(grad[#03], #02)
  9990. // #02:
  9991. // grad[#00] += scale(mul(#00, grad[#02]), 2.0)
  9992. //
  9993. // substitute and simplify:
  9994. // grad[#00] = scale(grad(#10), #09) + scale(mul(#00, grad[#02]), 2.0)
  9995. // grad[#02] = repeat(grad[#03], #02)
  9996. // grad[#02] = repeat(scale(grad[#05],#04), #02)
  9997. // grad[#02] = repeat(scale(grad[#07],#04), #02)
  9998. // grad[#02] = repeat(scale(mul(grad[#08], div(0.5, #08)),#04), #02)
  9999. // grad[#02] = repeat(scale(mul(neg(mul(grad[#09], div(#09,#08))), div(0.5, #08)),#04), #02)
  10000. // grad[#02] = repeat(scale(mul(neg(mul(sum(mul(grad[#10],#00)), div(#09,#08))), div(0.5, #08)),#04), #02)
  10001. // grad[#02] = repeat(-(sum(mul(grad[#10],#00)) * div(#09,#08) * div(0.5, #08) * (1/N)), #02)
  10002. // grad[#02] = repeat(-(sum(mul(grad[#10],#00)) * div(div(#01,#08),#08) * div(0.5, #08) * (1/N)), #02)
  10003. // grad[#02] = repeat(-(sum(mul(grad[#10],#00)) * div(1,#08*#08) * div(0.5, #08) * (1/N)), #02)
  10004. // grad[#02] = repeat(-(sum(mul(grad[#10],#00)) * div(1,#07) * div(0.5, #08) * (1/N)), #02)
  10005. // grad[#00] = scale(grad(#10), #09) + scale(mul(#00, grad[#02]), 2.0)
  10006. // 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)
  10007. // 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)
  10008. // grad[#00] = scale(grad(#10), #09) + scale(#00, -(sum(mul(grad[#10],#00)) * div(1,#07) * div(1,#08) * (1/N)))
  10009. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(1,#07*#08) * (-1/N))
  10010. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(1,#07*#08) * (-1/N))
  10011. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(1,mean_eps*rms) * (-1/N))
  10012. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(-1,rms*N*mean_eps))
  10013. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(-1,rms*N*(sum_xx/N+eps)))
  10014. // grad[#00] = scale(grad(#10), #09) + scale(#00, sum(mul(grad[#10],#00)) * div(-1,rms*N*sum_xx+rms*N*eps))
  10015. // grad[#00] = scale(dz, rrms) + scale(x, sum(mul(dz,x)) * div(-1,rms*N*mean_eps))
  10016. // grad[#00] = scale(dz, rrms) + scale(x, sum_xdz * div(-1,rms*N*mean_eps))
  10017. // a = b*c + d*e
  10018. // a = b*c*f/f + d*e*f/f
  10019. // a = (b*c*f + d*e*f)*(1/f)
  10020. // a = (b*c*(1/c) + d*e*(1/c))*(1/(1/c))
  10021. // a = (b + d*e/c)*c
  10022. // b = dz, c = rrms, d = x, e = sum_xdz * div(-1,rms*N*mean_eps)
  10023. // a = (dz + x*sum_xdz * div(-1,rms*N*mean_eps)/rrms)*rrms
  10024. // a = (dz + x*sum_xdz * div(-1,rms*N*mean_eps)*rms)*rrms
  10025. // a = (dz + x*sum_xdz * div(-rms,rms*N*mean_eps))*rrms
  10026. // a = (dz + x*sum_xdz * div(-1,N*mean_eps))*rrms
  10027. // a = (dz + x*div(-sum_xdz,N*mean_eps))*rrms
  10028. // a = (dz + x*div(-mean_xdz,mean_eps))*rrms
  10029. // grad[#00] = scale(dz + scale(x, div(-mean_xdz,mean_eps)),rrms)
  10030. // grad[#00] = scale(dz + scale(x, -mean_xdz/mean_eps),rrms)
  10031. // dx = scale(dz + scale(x, -mean_xdz/mean_eps),rrms)
  10032. }
  10033. // dx = scale(dz + scale(x, -mean_xdz/mean_eps),rrms)
  10034. // post-order:
  10035. // dx := x
  10036. // dx := scale(dx,-mean_xdz/mean_eps)
  10037. // dx := add(dx, dz)
  10038. // dx := scale(dx, rrms)
  10039. float * dx = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
  10040. ggml_vec_cpy_f32 (ne00, dx, x);
  10041. // ggml_vec_scale_f32(ne00, dx, -mean_xdz/mean_eps);
  10042. ggml_vec_scale_f32(ne00, dx, (float)(-sum_xdz)/sum_eps);
  10043. ggml_vec_acc_f32 (ne00, dx, dz);
  10044. ggml_vec_scale_f32(ne00, dx, rrms);
  10045. }
  10046. }
  10047. }
  10048. }
  10049. static void ggml_compute_forward_rms_norm_back(
  10050. const struct ggml_compute_params * params,
  10051. struct ggml_tensor * dst) {
  10052. const struct ggml_tensor * src0 = dst->src[0];
  10053. switch (src0->type) {
  10054. case GGML_TYPE_F32:
  10055. {
  10056. ggml_compute_forward_rms_norm_back_f32(params, dst);
  10057. } break;
  10058. default:
  10059. {
  10060. GGML_ABORT("fatal error");
  10061. }
  10062. }
  10063. }
  10064. // ggml_compute_forward_group_norm
  10065. static void ggml_compute_forward_group_norm_f32(
  10066. const struct ggml_compute_params * params,
  10067. struct ggml_tensor * dst) {
  10068. const struct ggml_tensor * src0 = dst->src[0];
  10069. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  10070. GGML_ASSERT(src0->nb[0] == sizeof(float));
  10071. const int ith = params->ith;
  10072. const int nth = params->nth;
  10073. GGML_TENSOR_UNARY_OP_LOCALS
  10074. // TODO: optimize
  10075. float eps;
  10076. memcpy(&eps, dst->op_params + 1, sizeof(float));
  10077. int n_channels = src0->ne[2];
  10078. int n_groups = dst->op_params[0];
  10079. int n_channels_per_group = (n_channels + n_groups - 1) / n_groups;
  10080. for (int i = ith; i < n_groups; i += nth) {
  10081. int start = i * n_channels_per_group;
  10082. int end = start + n_channels_per_group;
  10083. if (end > n_channels) {
  10084. end = n_channels;
  10085. }
  10086. int step = end - start;
  10087. for (int64_t i03 = 0; i03 < ne03; i03++) {
  10088. ggml_float sum = 0.0;
  10089. for (int64_t i02 = start; i02 < end; i02++) {
  10090. for (int64_t i01 = 0; i01 < ne01; i01++) {
  10091. const float * x = (float *)((char *) src0->data + i01 * nb01 + i02 * nb02 + i03 * nb03);
  10092. ggml_float sumr = 0.0;
  10093. for (int64_t i00 = 0; i00 < ne00; i00++) {
  10094. sumr += (ggml_float)x[i00];
  10095. }
  10096. sum += sumr;
  10097. }
  10098. }
  10099. const float mean = sum / (ne00 * ne01 * step);
  10100. ggml_float sum2 = 0.0;
  10101. for (int64_t i02 = start; i02 < end; i02++) {
  10102. for (int64_t i01 = 0; i01 < ne01; i01++) {
  10103. const float * x = (float *)((char *) src0->data + i01 * nb01 + i02 * nb02 + i03 * nb03);
  10104. float * y = (float *)((char *) dst->data + i01 * nb1 + i02 * nb2 + i03 * nb3);
  10105. ggml_float sumr = 0.0;
  10106. for (int64_t i00 = 0; i00 < ne00; i00++) {
  10107. float v = x[i00] - mean;
  10108. y[i00] = v;
  10109. sumr += (ggml_float)(v * v);
  10110. }
  10111. sum2 += sumr;
  10112. }
  10113. }
  10114. const float variance = sum2 / (ne00 * ne01 * step);
  10115. const float scale = 1.0f / sqrtf(variance + eps);
  10116. for (int64_t i02 = start; i02 < end; i02++) {
  10117. for (int64_t i01 = 0; i01 < ne01; i01++) {
  10118. float * y = (float *)((char *) dst->data + i01 * nb1 + i02 * nb2 + i03 * nb3);
  10119. ggml_vec_scale_f32(ne00, y, scale);
  10120. }
  10121. }
  10122. }
  10123. }
  10124. }
  10125. static void ggml_compute_forward_group_norm(
  10126. const struct ggml_compute_params * params,
  10127. struct ggml_tensor * dst) {
  10128. const struct ggml_tensor * src0 = dst->src[0];
  10129. switch (src0->type) {
  10130. case GGML_TYPE_F32:
  10131. {
  10132. ggml_compute_forward_group_norm_f32(params, dst);
  10133. } break;
  10134. default:
  10135. {
  10136. GGML_ABORT("fatal error");
  10137. }
  10138. }
  10139. }
  10140. // ggml_compute_forward_mul_mat
  10141. static void ggml_compute_forward_mul_mat_one_chunk(
  10142. const struct ggml_compute_params * params,
  10143. struct ggml_tensor * dst,
  10144. const int64_t num_rows_per_vec_dot,
  10145. const int64_t ir0_start,
  10146. const int64_t ir0_end,
  10147. const int64_t ir1_start,
  10148. const int64_t ir1_end) {
  10149. const struct ggml_tensor * src0 = dst->src[0];
  10150. const struct ggml_tensor * src1 = dst->src[1];
  10151. GGML_TENSOR_BINARY_OP_LOCALS
  10152. const enum ggml_type type = src0->type;
  10153. const bool src1_cont = ggml_is_contiguous(src1);
  10154. ggml_vec_dot_t const vec_dot = type_traits[type].vec_dot;
  10155. enum ggml_type const vec_dot_type = type_traits[type].vec_dot_type;
  10156. // broadcast factors
  10157. const int64_t r2 = ne12 / ne02;
  10158. const int64_t r3 = ne13 / ne03;
  10159. //printf("ir0_start = %6lld, ir0_end = %6lld, ir1_start = %6lld, ir1_end = %6lld\n", ir0_start, ir0_end, ir1_start, ir1_end);
  10160. // threads with no work simply yield (not sure if it helps)
  10161. if (ir0_start >= ir0_end || ir1_start >= ir1_end) {
  10162. return;
  10163. }
  10164. const void * wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  10165. const size_t row_size = ggml_row_size(vec_dot_type, ne10);
  10166. assert(ne12 % ne02 == 0);
  10167. assert(ne13 % ne03 == 0);
  10168. // block-tiling attempt
  10169. const int64_t blck_0 = 16;
  10170. const int64_t blck_1 = 16;
  10171. const size_t src1_col_stride = src1_cont || src1->type != vec_dot_type ? row_size : nb11;
  10172. // attempt to reduce false-sharing (does not seem to make a difference)
  10173. // 16 * 2, accounting for mmla kernels
  10174. float tmp[32];
  10175. for (int64_t iir1 = ir1_start; iir1 < ir1_end; iir1 += blck_1) {
  10176. for (int64_t iir0 = ir0_start; iir0 < ir0_end; iir0 += blck_0) {
  10177. for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir1_end; ir1 += num_rows_per_vec_dot) {
  10178. const int64_t i13 = (ir1 / (ne12 * ne1));
  10179. const int64_t i12 = (ir1 - i13 * ne12 * ne1) / ne1;
  10180. const int64_t i11 = (ir1 - i13 * ne12 * ne1 - i12 * ne1);
  10181. // broadcast src0 into src1
  10182. const int64_t i03 = i13 / r3;
  10183. const int64_t i02 = i12 / r2;
  10184. const int64_t i1 = i11;
  10185. const int64_t i2 = i12;
  10186. const int64_t i3 = i13;
  10187. const char * src0_row = (const char*)src0->data + (0 + i02 * nb02 + i03 * nb03);
  10188. // desc: when src1 is not a contiguous memory block we have to calculate the offset using the strides
  10189. // if it is, then we have either copied the data to params->wdata and made it contiguous or we are using
  10190. // the original src1 data pointer, so we should index using the indices directly
  10191. // TODO: this is a bit of a hack, we should probably have a better way to handle this
  10192. const char * src1_col = (const char*)wdata +
  10193. (src1_cont || src1->type != vec_dot_type
  10194. ? (i11 + i12 * ne11 + i13 * ne12 * ne11) * row_size
  10195. : (i11 * nb11 + i12 * nb12 + i13 * nb13));
  10196. float * dst_col = (float*)((char*)dst->data + (i1 * nb1 + i2 * nb2 + i3 * nb3));
  10197. //for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ++ir0) {
  10198. // vec_dot(ne00, &dst_col[ir0], src0_row + ir0*nb01, src1_col);
  10199. //}
  10200. for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ir0 += num_rows_per_vec_dot) {
  10201. 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);
  10202. }
  10203. for (int cn = 0; cn < num_rows_per_vec_dot; ++cn) {
  10204. memcpy(&dst_col[iir0 + cn * nb1 / nb0], tmp + (cn * 16), (MIN(iir0 + blck_0, ir0_end) - iir0) * sizeof(float));
  10205. }
  10206. }
  10207. }
  10208. }
  10209. }
  10210. static void ggml_compute_forward_mul_mat(
  10211. const struct ggml_compute_params * params,
  10212. struct ggml_tensor * dst) {
  10213. const struct ggml_tensor * src0 = dst->src[0];
  10214. const struct ggml_tensor * src1 = dst->src[1];
  10215. GGML_TENSOR_BINARY_OP_LOCALS
  10216. const int ith = params->ith;
  10217. const int nth = params->nth;
  10218. const enum ggml_type type = src0->type;
  10219. enum ggml_type const vec_dot_type = type_traits[type].vec_dot_type;
  10220. ggml_from_float_t const from_float = type_traits[vec_dot_type].from_float;
  10221. ggml_from_float_to_mat_t const from_float_to_mat = type_traits[vec_dot_type].from_float_to_mat;
  10222. int64_t const vec_dot_num_rows = type_traits[type].nrows;
  10223. int64_t const matmul_num_cols = type_traits[type].ncols;
  10224. int64_t const blck_size_interleave = type_traits[type].blck_size_interleave;
  10225. ggml_gemv_t const gemv = type_traits[type].gemv;
  10226. ggml_gemm_t const gemm = type_traits[type].gemm;
  10227. GGML_ASSERT(ne0 == ne01);
  10228. GGML_ASSERT(ne1 == ne11);
  10229. GGML_ASSERT(ne2 == ne12);
  10230. GGML_ASSERT(ne3 == ne13);
  10231. // we don't support permuted src0 or src1
  10232. GGML_ASSERT(nb00 == ggml_type_size(type));
  10233. GGML_ASSERT(nb10 == ggml_type_size(src1->type));
  10234. // dst cannot be transposed or permuted
  10235. GGML_ASSERT(nb0 == sizeof(float));
  10236. GGML_ASSERT(nb0 <= nb1);
  10237. GGML_ASSERT(nb1 <= nb2);
  10238. GGML_ASSERT(nb2 <= nb3);
  10239. // nb01 >= nb00 - src0 is not transposed
  10240. // compute by src0 rows
  10241. #if GGML_USE_LLAMAFILE
  10242. // broadcast factors
  10243. const int64_t r2 = ne12 / ne02;
  10244. const int64_t r3 = ne13 / ne03;
  10245. const bool src1_cont = ggml_is_contiguous(src1);
  10246. if (src1_cont) {
  10247. for (int64_t i13 = 0; i13 < ne13; i13++)
  10248. for (int64_t i12 = 0; i12 < ne12; i12++)
  10249. if (!llamafile_sgemm(ne01, ne11, ne00/ggml_blck_size(src0->type),
  10250. (const char *)src0->data + i12/r2*nb02 + i13/r3*nb03,
  10251. nb01/ggml_type_size(src0->type),
  10252. (const char *)src1->data + i12*nb12 + i13*nb13,
  10253. nb11/ggml_type_size(src1->type),
  10254. (char *)dst->data + i12*nb2 + i13*nb3,
  10255. nb1/ggml_type_size(dst->type),
  10256. ith, nth,
  10257. src0->type,
  10258. src1->type,
  10259. dst->type))
  10260. goto UseGgmlGemm1;
  10261. return;
  10262. }
  10263. UseGgmlGemm1:;
  10264. #endif
  10265. if (src1->type != vec_dot_type) {
  10266. char * wdata = params->wdata;
  10267. const size_t nbw1 = ggml_row_size(vec_dot_type, ne10);
  10268. const size_t nbw2 = nbw1*ne11;
  10269. const size_t nbw3 = nbw2*ne12;
  10270. assert(params->wsize >= ne13*nbw3);
  10271. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  10272. for (int64_t i13 = 0; i13 < ne13; ++i13) {
  10273. for (int64_t i12 = 0; i12 < ne12; ++i12) {
  10274. int64_t i11_processed = 0;
  10275. if ((ggml_n_dims(src1) == 2) && from_float_to_mat && gemm) {
  10276. for (int64_t i11 = ith * 4; i11 < ne11 - ne11 % 4; i11 += nth * 4) {
  10277. from_float_to_mat((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11),
  10278. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1),
  10279. 4, ne10, blck_size_interleave);
  10280. }
  10281. i11_processed = ne11 - ne11 % 4;
  10282. }
  10283. for (int64_t i11 = i11_processed + ith; i11 < ne11; i11 += nth) {
  10284. from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11),
  10285. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1),
  10286. ne10);
  10287. }
  10288. }
  10289. }
  10290. }
  10291. if (ith == 0) {
  10292. // Every thread starts at ith, so the first unprocessed chunk is nth. This save a bit of coordination right at the start.
  10293. atomic_store_explicit(&params->threadpool->current_chunk, nth, memory_order_relaxed);
  10294. }
  10295. ggml_barrier(params->threadpool);
  10296. #if GGML_USE_LLAMAFILE
  10297. if (src1->type != vec_dot_type) {
  10298. const void* wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  10299. const size_t row_size = ggml_row_size(vec_dot_type, ne10);
  10300. for (int64_t i13 = 0; i13 < ne13; i13++)
  10301. for (int64_t i12 = 0; i12 < ne12; i12++)
  10302. if (!llamafile_sgemm(ne01, ne11, ne00/ggml_blck_size(src0->type),
  10303. (const char *)src0->data + i12/r2*nb02 + i13/r3*nb03,
  10304. nb01/ggml_type_size(src0->type),
  10305. (const char *)wdata + (i12*ne11 + i13*ne12*ne11)*row_size,
  10306. row_size/ggml_type_size(vec_dot_type),
  10307. (char *)dst->data + i12*nb2 + i13*nb3,
  10308. nb1/ggml_type_size(dst->type),
  10309. ith, nth,
  10310. src0->type,
  10311. vec_dot_type,
  10312. dst->type))
  10313. goto UseGgmlGemm2;
  10314. return;
  10315. }
  10316. UseGgmlGemm2:;
  10317. #endif
  10318. // 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)
  10319. const int64_t nr0 = ne0;
  10320. // This is the size of the rest of the dimensions of the result
  10321. const int64_t nr1 = ne1 * ne2 * ne3;
  10322. // dot kernels can handle 1 row and col at a time, but mmla kernels can process 2 rows and cols
  10323. int64_t num_rows_per_vec_dot = vec_dot_num_rows;
  10324. // TODO: currently the mmla kernels support only even numbered rows/cols.
  10325. // this check can be removed once they are extended to support odd numbered rows/cols too
  10326. if ((nr0 % 2 != 0) || (ne11 % 2 != 0)) {
  10327. num_rows_per_vec_dot = 1;
  10328. }
  10329. // Now select a reasonable chunk size.
  10330. int chunk_size = 16;
  10331. // We need to step up the size if it's small
  10332. if (nr0 == 1 || nr1 == 1) {
  10333. chunk_size = 64;
  10334. }
  10335. // distribute the work across the inner or outer loop based on which one is larger
  10336. // The number of chunks in the 0/1 dim.
  10337. // CEIL(nr0/chunk_size)
  10338. int64_t nchunk0 = (nr0 + chunk_size - 1) / chunk_size;
  10339. int64_t nchunk1 = (nr1 + chunk_size - 1) / chunk_size;
  10340. // If the chunking is poor for the number of threads on this setup, scrap the whole plan. Re-chunk it by thread.
  10341. // Also, chunking by thread was measured to have perform better on NUMA systems. See https://github.com/ggerganov/llama.cpp/pull/6915
  10342. // In theory, chunking should be just as useful on NUMA and non NUMA systems, but testing disagreed with that.
  10343. if (nchunk0 * nchunk1 < nth * 4 || ggml_is_numa()) {
  10344. // distribute the thread work across the inner or outer loop based on which one is larger
  10345. nchunk0 = nr0 > nr1 ? nth : 1; // parallelize by src0 rows
  10346. nchunk1 = nr0 > nr1 ? 1 : nth; // parallelize by src1 rows
  10347. }
  10348. // The number of elements in each chunk
  10349. const int64_t dr0 = (nr0 + nchunk0 - 1) / nchunk0;
  10350. const int64_t dr1 = (nr1 + nchunk1 - 1) / nchunk1;
  10351. if ((ggml_n_dims(src0) == 2) && gemv) {
  10352. const void * src1_wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  10353. const size_t src1_col_stride = ggml_is_contiguous(src1) || src1->type != vec_dot_type ? ggml_row_size(vec_dot_type, ne10) : nb11;
  10354. int64_t src0_start = (ith * ne01) / nth;
  10355. int64_t src0_end = ((ith + 1) * ne01) / nth;
  10356. src0_start = (src0_start % matmul_num_cols) ? src0_start + matmul_num_cols - (src0_start % matmul_num_cols): src0_start;
  10357. src0_end = (src0_end % matmul_num_cols) ? src0_end + matmul_num_cols - (src0_end % matmul_num_cols): src0_end;
  10358. if (src0_start >= src0_end) return;
  10359. // If there are more than three rows in src1, use gemm; otherwise, use gemv.
  10360. if (gemm && (ne11 > 3)) {
  10361. gemm(ne00, (float *)((char *) dst->data) + src0_start, ne01, (const char *) src0->data + src0_start * nb01,
  10362. (const char *) src1_wdata, ne11 - ne11 % 4, src0_end - src0_start);
  10363. }
  10364. for (int iter = gemm ? ne11 - ne11 % 4 : 0; iter < ne11; iter++) {
  10365. gemv(ne00, (float *)((char *) dst->data + (iter * nb1)) + src0_start, ne01,
  10366. (const char *) src0->data + src0_start * nb01, (const char *) src1_wdata + (src1_col_stride * iter), 1,
  10367. src0_end - src0_start);
  10368. }
  10369. return;
  10370. }
  10371. // The first chunk comes from our thread_id, the rest will get auto-assigned.
  10372. int current_chunk = ith;
  10373. while (current_chunk < nchunk0 * nchunk1) {
  10374. const int64_t ith0 = current_chunk % nchunk0;
  10375. const int64_t ith1 = current_chunk / nchunk0;
  10376. const int64_t ir0_start = dr0 * ith0;
  10377. const int64_t ir0_end = MIN(ir0_start + dr0, nr0);
  10378. const int64_t ir1_start = dr1 * ith1;
  10379. const int64_t ir1_end = MIN(ir1_start + dr1, nr1);
  10380. ggml_compute_forward_mul_mat_one_chunk(params, dst, num_rows_per_vec_dot, ir0_start, ir0_end, ir1_start, ir1_end);
  10381. if (nth >= nchunk0 * nchunk1) {
  10382. break;
  10383. }
  10384. current_chunk = atomic_fetch_add_explicit(&params->threadpool->current_chunk, 1, memory_order_relaxed);
  10385. }
  10386. }
  10387. // ggml_compute_forward_mul_mat_id
  10388. static void ggml_compute_forward_mul_mat_id(
  10389. const struct ggml_compute_params * params,
  10390. struct ggml_tensor * dst) {
  10391. const struct ggml_tensor * src0 = dst->src[0];
  10392. const struct ggml_tensor * src1 = dst->src[1];
  10393. const struct ggml_tensor * ids = dst->src[2];
  10394. GGML_TENSOR_BINARY_OP_LOCALS
  10395. const int ith = params->ith;
  10396. const int nth = params->nth;
  10397. const enum ggml_type type = src0->type;
  10398. const bool src1_cont = ggml_is_contiguous(src1);
  10399. ggml_vec_dot_t const vec_dot = type_traits[type].vec_dot;
  10400. enum ggml_type const vec_dot_type = type_traits[type].vec_dot_type;
  10401. ggml_from_float_t const from_float = type_traits[vec_dot_type].from_float;
  10402. int64_t const matmul_num_cols = type_traits[type].ncols;
  10403. ggml_gemv_t const gemv = type_traits[type].gemv;
  10404. // we don't support permuted src0 or src1
  10405. GGML_ASSERT(nb00 == ggml_type_size(type));
  10406. GGML_ASSERT(nb10 == ggml_type_size(src1->type));
  10407. // dst cannot be transposed or permuted
  10408. GGML_ASSERT(nb0 == sizeof(float));
  10409. GGML_ASSERT(nb0 <= nb1);
  10410. GGML_ASSERT(nb1 <= nb2);
  10411. GGML_ASSERT(nb2 <= nb3);
  10412. // row groups
  10413. const int n_ids = ids->ne[0]; // n_expert_used
  10414. const int n_as = ne02; // n_expert
  10415. char * wdata_src1_end = (src1->type == vec_dot_type) ?
  10416. (char *) params->wdata :
  10417. (char *) params->wdata + GGML_PAD(ggml_row_size(vec_dot_type, ggml_nelements(src1)), sizeof(int64_t));
  10418. struct mmid_row_mapping {
  10419. int32_t i1;
  10420. int32_t i2;
  10421. };
  10422. int64_t * matrix_row_counts = (int64_t *) (wdata_src1_end); // [n_as]
  10423. struct mmid_row_mapping * matrix_rows = (struct mmid_row_mapping *)(matrix_row_counts + n_as); // [n_as][ne11]
  10424. if (src1->type != vec_dot_type) {
  10425. char * wdata = params->wdata;
  10426. const size_t nbw1 = ggml_row_size(vec_dot_type, ne10);
  10427. const size_t nbw2 = nbw1*ne11;
  10428. const size_t nbw3 = nbw2*ne12;
  10429. assert(params->wsize >= ne13*nbw3);
  10430. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  10431. for (int64_t i13 = 0; i13 < ne13; ++i13) {
  10432. for (int64_t i12 = 0; i12 < ne12; ++i12) {
  10433. for (int64_t i11 = ith; i11 < ne11; i11 += nth) {
  10434. from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11),
  10435. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1),
  10436. ne10);
  10437. }
  10438. }
  10439. }
  10440. }
  10441. #define MMID_MATRIX_ROW(row_id, i1) matrix_rows[(row_id)*ne12 + (i1)]
  10442. if (ith == 0) {
  10443. // initialize matrix_row_counts
  10444. memset(matrix_row_counts, 0, n_as*sizeof(int64_t));
  10445. // group rows by src0 matrix
  10446. for (int64_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) {
  10447. for (int id = 0; id < n_ids; ++id) {
  10448. const int32_t i02 = *(const int32_t *) ((const char *) ids->data + iid1*ids->nb[1] + id*ids->nb[0]);
  10449. assert(i02 >= 0 && i02 < n_as);
  10450. MMID_MATRIX_ROW(i02, matrix_row_counts[i02]) = (struct mmid_row_mapping) {id, iid1};
  10451. matrix_row_counts[i02] += 1;
  10452. }
  10453. }
  10454. }
  10455. ggml_barrier(params->threadpool);
  10456. // compute each matrix multiplication in sequence
  10457. for (int cur_a = 0; cur_a < n_as; ++cur_a) {
  10458. const int64_t cne1 = matrix_row_counts[cur_a];
  10459. if (cne1 == 0) {
  10460. continue;
  10461. }
  10462. const char * src0_cur = (const char *) src0->data + cur_a*nb02;
  10463. const void * wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  10464. const size_t row_size = ggml_row_size(vec_dot_type, ne10);
  10465. const int64_t nr0 = ne01; // src0 rows
  10466. const int64_t nr1 = cne1; // src1 rows
  10467. if (((ggml_n_dims(src0) - 1) == 2) && gemv) {
  10468. int64_t src0_cur_start = (ith * ne01) / nth;
  10469. int64_t src0_cur_end = ((ith + 1) * ne01) / nth;
  10470. src0_cur_start = (src0_cur_start % matmul_num_cols) ? src0_cur_start + matmul_num_cols - (src0_cur_start % matmul_num_cols): src0_cur_start;
  10471. src0_cur_end = (src0_cur_end % matmul_num_cols) ? src0_cur_end + matmul_num_cols - (src0_cur_end % matmul_num_cols): src0_cur_end;
  10472. if (src0_cur_start >= src0_cur_end) return;
  10473. for (int ir1 = 0; ir1 < nr1; ir1++) {
  10474. struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, ir1);
  10475. const int id = row_mapping.i1; // selected expert index
  10476. const int64_t i11 = id % ne11;
  10477. const int64_t i12 = row_mapping.i2; // row index in src1
  10478. const int64_t i1 = id; // selected expert index
  10479. const int64_t i2 = i12; // row
  10480. const char * src1_col = (const char *) wdata +
  10481. (src1_cont || src1->type != vec_dot_type
  10482. ? (i11 + i12 * ne11) * row_size
  10483. : (i11 * nb11 + i12 * nb12));
  10484. gemv(ne00, (float *)((char *) dst->data + (i1 * nb1 + i2 * nb2)) + src0_cur_start, ne01,
  10485. (const char *) src0_cur + src0_cur_start * nb01, src1_col, 1, src0_cur_end - src0_cur_start);
  10486. }
  10487. continue;
  10488. }
  10489. // distribute the thread work across the inner or outer loop based on which one is larger
  10490. const int64_t nth0 = nr0 > nr1 ? nth : 1; // parallelize by src0 rows
  10491. const int64_t nth1 = nr0 > nr1 ? 1 : nth; // parallelize by src1 rows
  10492. const int64_t ith0 = ith % nth0;
  10493. const int64_t ith1 = ith / nth0;
  10494. const int64_t dr0 = (nr0 + nth0 - 1)/nth0;
  10495. const int64_t dr1 = (nr1 + nth1 - 1)/nth1;
  10496. const int64_t ir010 = dr0*ith0;
  10497. const int64_t ir011 = MIN(ir010 + dr0, nr0);
  10498. const int64_t ir110 = dr1*ith1;
  10499. const int64_t ir111 = MIN(ir110 + dr1, nr1);
  10500. // threads with no work simply yield (not sure if it helps)
  10501. //if (ir010 >= ir011 || ir110 >= ir111) {
  10502. // sched_yield();
  10503. // continue;
  10504. //}
  10505. // block-tiling attempt
  10506. const int64_t blck_0 = 16;
  10507. const int64_t blck_1 = 16;
  10508. // attempt to reduce false-sharing (does not seem to make a difference)
  10509. float tmp[16];
  10510. for (int64_t iir1 = ir110; iir1 < ir111; iir1 += blck_1) {
  10511. for (int64_t iir0 = ir010; iir0 < ir011; iir0 += blck_0) {
  10512. for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir111; ++ir1) {
  10513. const int64_t _i12 = ir1; // logical row index for this expert
  10514. struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, _i12);
  10515. const int id = row_mapping.i1; // selected expert index
  10516. const int64_t i11 = id % ne11;
  10517. const int64_t i12 = row_mapping.i2; // row index in src1
  10518. const int64_t i1 = id; // selected expert index
  10519. const int64_t i2 = i12; // row
  10520. // desc: when src1 is not a contiguous memory block we have to calculate the offset using the strides
  10521. // if it is, then we have either copied the data to params->wdata and made it contiguous or we are using
  10522. // the original src1 data pointer, so we should index using the indices directly
  10523. // TODO: this is a bit of a hack, we should probably have a better way to handle this
  10524. const char * src1_col = (const char *) wdata +
  10525. (src1_cont || src1->type != vec_dot_type
  10526. ? (i11 + i12*ne11)*row_size
  10527. : (i11*nb11 + i12*nb12));
  10528. float * dst_col = (float *) ((char *) dst->data + (i1*nb1 + i2*nb2));
  10529. //for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir011; ++ir0) {
  10530. // vec_dot(ne00, &dst_col[ir0], src0_row + ir0*nb01, src1_col);
  10531. //}
  10532. for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir011; ++ir0) {
  10533. vec_dot(ne00, &tmp[ir0 - iir0], 0, src0_cur + ir0*nb01, 0, src1_col, 0, 1);
  10534. }
  10535. memcpy(&dst_col[iir0], tmp, (MIN(iir0 + blck_0, ir011) - iir0)*sizeof(float));
  10536. }
  10537. }
  10538. }
  10539. }
  10540. #undef MMID_MATRIX_ROW
  10541. }
  10542. // ggml_compute_forward_out_prod
  10543. static void ggml_compute_forward_out_prod_f32(
  10544. const struct ggml_compute_params * params,
  10545. struct ggml_tensor * dst) {
  10546. const struct ggml_tensor * src0 = dst->src[0];
  10547. const struct ggml_tensor * src1 = dst->src[1];
  10548. GGML_TENSOR_BINARY_OP_LOCALS
  10549. const int ith = params->ith;
  10550. const int nth = params->nth;
  10551. GGML_ASSERT(ne0 == ne00);
  10552. GGML_ASSERT(ne1 == ne10);
  10553. GGML_ASSERT(ne2 == ne02);
  10554. GGML_ASSERT(ne02 == ne12);
  10555. GGML_ASSERT(ne3 == ne13);
  10556. GGML_ASSERT(ne03 == ne13);
  10557. // we don't support permuted src0 or src1
  10558. GGML_ASSERT(nb00 == sizeof(float));
  10559. // dst cannot be transposed or permuted
  10560. GGML_ASSERT(nb0 == sizeof(float));
  10561. // GGML_ASSERT(nb0 <= nb1);
  10562. // GGML_ASSERT(nb1 <= nb2);
  10563. // GGML_ASSERT(nb2 <= nb3);
  10564. // nb01 >= nb00 - src0 is not transposed
  10565. // compute by src0 rows
  10566. if (ith == 0) {
  10567. ggml_vec_set_f32(ne0*ne1*ne2*ne3, dst->data, 0);
  10568. }
  10569. ggml_barrier(params->threadpool);
  10570. // dst[:,:,:,:] = 0
  10571. // for i2,i3:
  10572. // for i1:
  10573. // for i01:
  10574. // for i0:
  10575. // dst[i0,i1,i2,i3] += src0[i0,i01,i2,i3] * src1[i1,i01,i2,i3]
  10576. // parallelize by last three dimensions
  10577. // total rows in dst
  10578. const int64_t nr = ne1*ne2*ne3;
  10579. // rows per thread
  10580. const int64_t dr = (nr + nth - 1)/nth;
  10581. // row range for this thread
  10582. const int64_t ir0 = dr*ith;
  10583. const int64_t ir1 = MIN(ir0 + dr, nr);
  10584. // block-tiling attempt
  10585. const int64_t blck_0 = MAX(GGML_VEC_MAD_UNROLL, 32);
  10586. const int64_t blck_1 = 16;
  10587. for (int64_t bir = ir0; bir < ir1; bir += blck_1) {
  10588. const int64_t bir1 = MIN(bir + blck_1, ir1);
  10589. for (int64_t bi01 = 0; bi01 < ne01; bi01 += blck_0) {
  10590. const int64_t bne01 = MIN(bi01 + blck_0, ne01);
  10591. for (int64_t ir = bir; ir < bir1; ++ir) {
  10592. // dst indices
  10593. const int64_t i3 = ir/(ne2*ne1);
  10594. const int64_t i2 = (ir - i3*ne2*ne1)/ne1;
  10595. const int64_t i1 = (ir - i3*ne2*ne1 - i2*ne1);
  10596. const int64_t i02 = i2;
  10597. const int64_t i03 = i3;
  10598. //const int64_t i10 = i1;
  10599. const int64_t i12 = i2;
  10600. const int64_t i13 = i3;
  10601. #if GGML_VEC_MAD_UNROLL > 2
  10602. const int64_t bne01_unroll = bne01 - (bne01 % GGML_VEC_MAD_UNROLL);
  10603. for (int64_t i01 = bi01; i01 < bne01_unroll; i01 += GGML_VEC_MAD_UNROLL) {
  10604. const int64_t i11 = i01;
  10605. float * s0 = (float *) ((char *) src0->data + ( i01*nb01 + i02*nb02 + i03*nb03));
  10606. float * s1 = (float *) ((char *) src1->data + (i1*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  10607. float * d = (float *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  10608. ggml_vec_mad_f32_unroll(ne0, nb01, nb11, d, s0, s1);
  10609. }
  10610. for (int64_t i01 = bne01_unroll; i01 < bne01; ++i01) {
  10611. const int64_t i11 = i01;
  10612. float * s0 = (float *) ((char *) src0->data + ( i01*nb01 + i02*nb02 + i03*nb03));
  10613. float * s1 = (float *) ((char *) src1->data + (i1*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  10614. float * d = (float *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  10615. ggml_vec_mad_f32(ne0, d, s0, *s1);
  10616. }
  10617. #else
  10618. for (int64_t i01 = bi01; i01 < bne01; ++i01) {
  10619. const int64_t i11 = i01;
  10620. float * s0 = (float *) ((char *) src0->data + ( i01*nb01 + i02*nb02 + i03*nb03));
  10621. float * s1 = (float *) ((char *) src1->data + (i1*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  10622. float * d = (float *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  10623. ggml_vec_mad_f32(ne0, d, s0, *s1);
  10624. }
  10625. #endif
  10626. }
  10627. }
  10628. }
  10629. }
  10630. static void ggml_compute_forward_out_prod_q_f32(
  10631. const struct ggml_compute_params * params,
  10632. struct ggml_tensor * dst) {
  10633. const struct ggml_tensor * src0 = dst->src[0];
  10634. const struct ggml_tensor * src1 = dst->src[1];
  10635. GGML_TENSOR_BINARY_OP_LOCALS;
  10636. const int ith = params->ith;
  10637. const int nth = params->nth;
  10638. const enum ggml_type type = src0->type;
  10639. ggml_to_float_t const dequantize_row_q = type_traits[type].to_float;
  10640. GGML_ASSERT(ne02 == ne12);
  10641. GGML_ASSERT(ne03 == ne13);
  10642. GGML_ASSERT(ne2 == ne12);
  10643. GGML_ASSERT(ne3 == ne13);
  10644. // we don't support permuted src0 dim0
  10645. GGML_ASSERT(nb00 == ggml_type_size(type));
  10646. // dst dim0 cannot be transposed or permuted
  10647. GGML_ASSERT(nb0 == sizeof(float));
  10648. // GGML_ASSERT(nb0 <= nb1);
  10649. // GGML_ASSERT(nb1 <= nb2);
  10650. // GGML_ASSERT(nb2 <= nb3);
  10651. GGML_ASSERT(ne0 == ne00);
  10652. GGML_ASSERT(ne1 == ne10);
  10653. GGML_ASSERT(ne2 == ne02);
  10654. GGML_ASSERT(ne3 == ne03);
  10655. // nb01 >= nb00 - src0 is not transposed
  10656. // compute by src0 rows
  10657. if (ith == 0) {
  10658. ggml_vec_set_f32(ne0*ne1*ne2*ne3, dst->data, 0);
  10659. }
  10660. ggml_barrier(params->threadpool);
  10661. // parallelize by last three dimensions
  10662. // total rows in dst
  10663. const int64_t nr = ne1*ne2*ne3;
  10664. // rows per thread
  10665. const int64_t dr = (nr + nth - 1)/nth;
  10666. // row range for this thread
  10667. const int64_t ir0 = dr*ith;
  10668. const int64_t ir1 = MIN(ir0 + dr, nr);
  10669. // dst[:,:,:,:] = 0
  10670. // for i2,i3:
  10671. // for i1:
  10672. // for i01:
  10673. // for i0:
  10674. // dst[i0,i1,i2,i3] += src0[i0,i01,i2,i3] * src1[i1,i01,i2,i3]
  10675. float * wdata = (float *) params->wdata + (ne0 + CACHE_LINE_SIZE_F32) * ith;
  10676. for (int64_t ir = ir0; ir < ir1; ++ir) {
  10677. // dst indices
  10678. const int64_t i3 = ir/(ne2*ne1);
  10679. const int64_t i2 = (ir - i3*ne2*ne1)/ne1;
  10680. const int64_t i1 = (ir - i3*ne2*ne1 - i2*ne1);
  10681. const int64_t i02 = i2;
  10682. const int64_t i03 = i3;
  10683. //const int64_t i10 = i1;
  10684. const int64_t i12 = i2;
  10685. const int64_t i13 = i3;
  10686. for (int64_t i01 = 0; i01 < ne01; ++i01) {
  10687. const int64_t i11 = i01;
  10688. float * s0 = (float *) ((char *) src0->data + ( i01*nb01 + i02*nb02 + i03*nb03));
  10689. float * s1 = (float *) ((char *) src1->data + (i1*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  10690. float * d = (float *) ((char *) dst->data + ( i1*nb1 + i2*nb2 + i3*nb3));
  10691. dequantize_row_q(s0, wdata, ne0);
  10692. ggml_vec_mad_f32(ne0, d, wdata, *s1);
  10693. }
  10694. }
  10695. }
  10696. static void ggml_compute_forward_out_prod(
  10697. const struct ggml_compute_params * params,
  10698. struct ggml_tensor * dst) {
  10699. const struct ggml_tensor * src0 = dst->src[0];
  10700. switch (src0->type) {
  10701. case GGML_TYPE_Q4_0:
  10702. case GGML_TYPE_Q4_1:
  10703. case GGML_TYPE_Q5_0:
  10704. case GGML_TYPE_Q5_1:
  10705. case GGML_TYPE_Q8_0:
  10706. case GGML_TYPE_Q2_K:
  10707. case GGML_TYPE_Q3_K:
  10708. case GGML_TYPE_Q4_K:
  10709. case GGML_TYPE_Q5_K:
  10710. case GGML_TYPE_Q6_K:
  10711. case GGML_TYPE_TQ1_0:
  10712. case GGML_TYPE_TQ2_0:
  10713. case GGML_TYPE_IQ2_XXS:
  10714. case GGML_TYPE_IQ2_XS:
  10715. case GGML_TYPE_IQ3_XXS:
  10716. case GGML_TYPE_IQ1_S:
  10717. case GGML_TYPE_IQ1_M:
  10718. case GGML_TYPE_IQ4_NL:
  10719. case GGML_TYPE_IQ4_XS:
  10720. case GGML_TYPE_IQ3_S:
  10721. case GGML_TYPE_IQ2_S:
  10722. case GGML_TYPE_Q4_0_4_4:
  10723. case GGML_TYPE_Q4_0_4_8:
  10724. case GGML_TYPE_Q4_0_8_8:
  10725. {
  10726. ggml_compute_forward_out_prod_q_f32(params, dst);
  10727. } break;
  10728. case GGML_TYPE_F16:
  10729. {
  10730. GGML_ABORT("fatal error"); // todo
  10731. // ggml_compute_forward_out_prod_f16_f32(params, dst);
  10732. }
  10733. case GGML_TYPE_F32:
  10734. {
  10735. ggml_compute_forward_out_prod_f32(params, dst);
  10736. } break;
  10737. default:
  10738. {
  10739. GGML_ABORT("fatal error");
  10740. }
  10741. }
  10742. }
  10743. // ggml_compute_forward_scale
  10744. static void ggml_compute_forward_scale_f32(
  10745. const struct ggml_compute_params * params,
  10746. struct ggml_tensor * dst) {
  10747. const struct ggml_tensor * src0 = dst->src[0];
  10748. GGML_ASSERT(ggml_is_contiguous(src0));
  10749. GGML_ASSERT(ggml_is_contiguous(dst));
  10750. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  10751. // scale factor
  10752. float v;
  10753. memcpy(&v, dst->op_params, sizeof(float));
  10754. const int ith = params->ith;
  10755. const int nth = params->nth;
  10756. const int nc = src0->ne[0];
  10757. const int nr = ggml_nrows(src0);
  10758. // rows per thread
  10759. const int dr = (nr + nth - 1)/nth;
  10760. // row range for this thread
  10761. const int ir0 = dr*ith;
  10762. const int ir1 = MIN(ir0 + dr, nr);
  10763. const size_t nb01 = src0->nb[1];
  10764. const size_t nb1 = dst->nb[1];
  10765. for (int i1 = ir0; i1 < ir1; i1++) {
  10766. if (dst->data != src0->data) {
  10767. // src0 is same shape as dst => same indices
  10768. memcpy((char *)dst->data + i1*nb1, (char *)src0->data + i1*nb01, nc * sizeof(float));
  10769. }
  10770. ggml_vec_scale_f32(nc, (float *) ((char *) dst->data + i1*nb1), v);
  10771. }
  10772. }
  10773. static void ggml_compute_forward_scale(
  10774. const struct ggml_compute_params * params,
  10775. struct ggml_tensor * dst) {
  10776. const struct ggml_tensor * src0 = dst->src[0];
  10777. switch (src0->type) {
  10778. case GGML_TYPE_F32:
  10779. {
  10780. ggml_compute_forward_scale_f32(params, dst);
  10781. } break;
  10782. default:
  10783. {
  10784. GGML_ABORT("fatal error");
  10785. }
  10786. }
  10787. }
  10788. // ggml_compute_forward_set
  10789. static void ggml_compute_forward_set_f32(
  10790. const struct ggml_compute_params * params,
  10791. struct ggml_tensor * dst) {
  10792. const struct ggml_tensor * src0 = dst->src[0];
  10793. const struct ggml_tensor * src1 = dst->src[1];
  10794. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  10795. GGML_ASSERT(ggml_is_contiguous(dst) && ggml_is_contiguous(src0));
  10796. // view src0 and dst with these strides and data offset inbytes during set
  10797. // nb0 is implicitly element_size because src0 and dst are contiguous
  10798. size_t nb1 = ((int32_t *) dst->op_params)[0];
  10799. size_t nb2 = ((int32_t *) dst->op_params)[1];
  10800. size_t nb3 = ((int32_t *) dst->op_params)[2];
  10801. size_t offset = ((int32_t *) dst->op_params)[3];
  10802. bool inplace = (bool) ((int32_t *) dst->op_params)[4];
  10803. if (!inplace) {
  10804. if (params->ith == 0) {
  10805. // memcpy needs to be synchronized across threads to avoid race conditions.
  10806. // => do it in INIT phase
  10807. memcpy(
  10808. ((char *) dst->data),
  10809. ((char *) src0->data),
  10810. ggml_nbytes(dst));
  10811. }
  10812. ggml_barrier(params->threadpool);
  10813. }
  10814. const int ith = params->ith;
  10815. const int nth = params->nth;
  10816. const int nr = ggml_nrows(src1);
  10817. const int nc = src1->ne[0];
  10818. GGML_TENSOR_LOCALS(int64_t, ne1, src1, ne)
  10819. GGML_TENSOR_LOCALS(size_t, nb1, src1, nb)
  10820. // src0 and dst as viewed during set
  10821. const size_t nb0 = ggml_element_size(src0);
  10822. const int im0 = (ne10 == 0 ? 0 : ne10-1);
  10823. const int im1 = (ne11 == 0 ? 0 : ne11-1);
  10824. const int im2 = (ne12 == 0 ? 0 : ne12-1);
  10825. const int im3 = (ne13 == 0 ? 0 : ne13-1);
  10826. GGML_ASSERT(offset + im0*nb0 + im1*nb1 + im2*nb2 + im3*nb3 <= ggml_nbytes(dst));
  10827. GGML_ASSERT(nb10 == sizeof(float));
  10828. // rows per thread
  10829. const int dr = (nr + nth - 1)/nth;
  10830. // row range for this thread
  10831. const int ir0 = dr*ith;
  10832. const int ir1 = MIN(ir0 + dr, nr);
  10833. for (int ir = ir0; ir < ir1; ++ir) {
  10834. // src0 and dst are viewed with shape of src1 and offset
  10835. // => same indices
  10836. const int i3 = ir/(ne12*ne11);
  10837. const int i2 = (ir - i3*ne12*ne11)/ne11;
  10838. const int i1 = (ir - i3*ne12*ne11 - i2*ne11);
  10839. ggml_vec_cpy_f32(nc,
  10840. (float *) ((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + offset),
  10841. (float *) ((char *) src1->data + i3*nb13 + i2*nb12 + i1*nb11));
  10842. }
  10843. }
  10844. static void ggml_compute_forward_set(
  10845. const struct ggml_compute_params * params,
  10846. struct ggml_tensor * dst) {
  10847. const struct ggml_tensor * src0 = dst->src[0];
  10848. switch (src0->type) {
  10849. case GGML_TYPE_F32:
  10850. {
  10851. ggml_compute_forward_set_f32(params, dst);
  10852. } break;
  10853. case GGML_TYPE_F16:
  10854. case GGML_TYPE_BF16:
  10855. case GGML_TYPE_Q4_0:
  10856. case GGML_TYPE_Q4_1:
  10857. case GGML_TYPE_Q5_0:
  10858. case GGML_TYPE_Q5_1:
  10859. case GGML_TYPE_Q8_0:
  10860. case GGML_TYPE_Q8_1:
  10861. case GGML_TYPE_Q2_K:
  10862. case GGML_TYPE_Q3_K:
  10863. case GGML_TYPE_Q4_K:
  10864. case GGML_TYPE_Q5_K:
  10865. case GGML_TYPE_Q6_K:
  10866. case GGML_TYPE_TQ1_0:
  10867. case GGML_TYPE_TQ2_0:
  10868. case GGML_TYPE_IQ2_XXS:
  10869. case GGML_TYPE_IQ2_XS:
  10870. case GGML_TYPE_IQ3_XXS:
  10871. case GGML_TYPE_IQ1_S:
  10872. case GGML_TYPE_IQ1_M:
  10873. case GGML_TYPE_IQ4_NL:
  10874. case GGML_TYPE_IQ4_XS:
  10875. case GGML_TYPE_IQ3_S:
  10876. case GGML_TYPE_IQ2_S:
  10877. case GGML_TYPE_Q4_0_4_4:
  10878. case GGML_TYPE_Q4_0_4_8:
  10879. case GGML_TYPE_Q4_0_8_8:
  10880. default:
  10881. {
  10882. GGML_ABORT("fatal error");
  10883. }
  10884. }
  10885. }
  10886. // ggml_compute_forward_cpy
  10887. static void ggml_compute_forward_cpy(
  10888. const struct ggml_compute_params * params,
  10889. struct ggml_tensor * dst) {
  10890. ggml_compute_forward_dup(params, dst);
  10891. }
  10892. // ggml_compute_forward_cont
  10893. static void ggml_compute_forward_cont(
  10894. const struct ggml_compute_params * params,
  10895. struct ggml_tensor * dst) {
  10896. ggml_compute_forward_dup(params, dst);
  10897. }
  10898. // ggml_compute_forward_reshape
  10899. static void ggml_compute_forward_reshape(
  10900. const struct ggml_compute_params * params,
  10901. struct ggml_tensor * dst) {
  10902. // NOP
  10903. UNUSED(params);
  10904. UNUSED(dst);
  10905. }
  10906. // ggml_compute_forward_view
  10907. static void ggml_compute_forward_view(
  10908. const struct ggml_compute_params * params,
  10909. const struct ggml_tensor * dst) {
  10910. // NOP
  10911. UNUSED(params);
  10912. UNUSED(dst);
  10913. }
  10914. // ggml_compute_forward_permute
  10915. static void ggml_compute_forward_permute(
  10916. const struct ggml_compute_params * params,
  10917. const struct ggml_tensor * dst) {
  10918. // NOP
  10919. UNUSED(params);
  10920. UNUSED(dst);
  10921. }
  10922. // ggml_compute_forward_transpose
  10923. static void ggml_compute_forward_transpose(
  10924. const struct ggml_compute_params * params,
  10925. const struct ggml_tensor * dst) {
  10926. // NOP
  10927. UNUSED(params);
  10928. UNUSED(dst);
  10929. }
  10930. // ggml_compute_forward_get_rows
  10931. static void ggml_compute_forward_get_rows_q(
  10932. const struct ggml_compute_params * params,
  10933. struct ggml_tensor * dst) {
  10934. const struct ggml_tensor * src0 = dst->src[0];
  10935. const struct ggml_tensor * src1 = dst->src[1];
  10936. GGML_TENSOR_BINARY_OP_LOCALS
  10937. const int64_t nc = ne00;
  10938. const int64_t nr = ggml_nelements(src1);
  10939. const enum ggml_type type = src0->type;
  10940. ggml_to_float_t const dequantize_row_q = type_traits[type].to_float;
  10941. assert(ne0 == nc);
  10942. assert(ne02 == ne11);
  10943. assert(nb00 == ggml_type_size(type));
  10944. assert(ggml_nrows(dst) == nr);
  10945. const int ith = params->ith;
  10946. const int nth = params->nth;
  10947. // rows per thread
  10948. const int dr = (nr + nth - 1)/nth;
  10949. // row range for this thread
  10950. const int ir0 = dr*ith;
  10951. const int ir1 = MIN(ir0 + dr, nr);
  10952. for (int64_t i = ir0; i < ir1; ++i) {
  10953. const int64_t i12 = i/(ne11*ne10);
  10954. const int64_t i11 = (i - i12*ne11*ne10)/ne10;
  10955. const int64_t i10 = (i - i12*ne11*ne10 - i11*ne10);
  10956. const int64_t i01 = *(int32_t *) ((char *) src1->data + i10*nb10 + i11*nb11 + i12*nb12);
  10957. GGML_ASSERT(i01 >= 0 && i01 < ne01);
  10958. dequantize_row_q(
  10959. (const void *) ((char *) src0->data + i01*nb01 + i11*nb02 + i12*nb03),
  10960. (float *) ((char *) dst->data + i10*nb1 + i11*nb2 + i12*nb3), nc);
  10961. }
  10962. }
  10963. static void ggml_compute_forward_get_rows_f16(
  10964. const struct ggml_compute_params * params,
  10965. struct ggml_tensor * dst) {
  10966. const struct ggml_tensor * src0 = dst->src[0];
  10967. const struct ggml_tensor * src1 = dst->src[1];
  10968. GGML_TENSOR_BINARY_OP_LOCALS
  10969. const int64_t nc = ne00;
  10970. const int64_t nr = ggml_nelements(src1);
  10971. assert(ne0 == nc);
  10972. assert(ne02 == ne11);
  10973. assert(nb00 == sizeof(ggml_fp16_t));
  10974. assert(ggml_nrows(dst) == nr);
  10975. const int ith = params->ith;
  10976. const int nth = params->nth;
  10977. // rows per thread
  10978. const int dr = (nr + nth - 1)/nth;
  10979. // row range for this thread
  10980. const int ir0 = dr*ith;
  10981. const int ir1 = MIN(ir0 + dr, nr);
  10982. for (int64_t i = ir0; i < ir1; ++i) {
  10983. const int64_t i12 = i/(ne11*ne10);
  10984. const int64_t i11 = (i - i12*ne11*ne10)/ne10;
  10985. const int64_t i10 = (i - i12*ne11*ne10 - i11*ne10);
  10986. const int64_t i01 = *(int32_t *) ((char *) src1->data + i10*nb10 + i11*nb11 + i12*nb12);
  10987. GGML_ASSERT(i01 >= 0 && i01 < ne01);
  10988. ggml_fp16_to_fp32_row(
  10989. (const void *) ((char *) src0->data + i01*nb01 + i11*nb02 + i12*nb03),
  10990. (float *) ((char *) dst->data + i10*nb1 + i11*nb2 + i12*nb3), nc);
  10991. }
  10992. }
  10993. static void ggml_compute_forward_get_rows_bf16(
  10994. const struct ggml_compute_params * params,
  10995. struct ggml_tensor * dst) {
  10996. const struct ggml_tensor * src0 = dst->src[0];
  10997. const struct ggml_tensor * src1 = dst->src[1];
  10998. GGML_TENSOR_BINARY_OP_LOCALS
  10999. const int64_t nc = ne00;
  11000. const int64_t nr = ggml_nelements(src1);
  11001. assert(ne0 == nc);
  11002. assert(ne02 == ne11);
  11003. assert(nb00 == sizeof(ggml_bf16_t));
  11004. assert(ggml_nrows(dst) == nr);
  11005. const int ith = params->ith;
  11006. const int nth = params->nth;
  11007. // rows per thread
  11008. const int dr = (nr + nth - 1)/nth;
  11009. // row range for this thread
  11010. const int ir0 = dr*ith;
  11011. const int ir1 = MIN(ir0 + dr, nr);
  11012. for (int64_t i = ir0; i < ir1; ++i) {
  11013. const int64_t i12 = i/(ne11*ne10);
  11014. const int64_t i11 = (i - i12*ne11*ne10)/ne10;
  11015. const int64_t i10 = (i - i12*ne11*ne10 - i11*ne10);
  11016. const int64_t i01 = *(int32_t *) ((char *) src1->data + i10*nb10 + i11*nb11 + i12*nb12);
  11017. GGML_ASSERT(i01 >= 0 && i01 < ne01);
  11018. ggml_bf16_to_fp32_row(
  11019. (const void *) ((char *) src0->data + i01*nb01 + i11*nb02 + i12*nb03),
  11020. (float *) ((char *) dst->data + i10*nb1 + i11*nb2 + i12*nb3), nc);
  11021. }
  11022. }
  11023. static void ggml_compute_forward_get_rows_f32(
  11024. const struct ggml_compute_params * params,
  11025. struct ggml_tensor * dst) {
  11026. const struct ggml_tensor * src0 = dst->src[0];
  11027. const struct ggml_tensor * src1 = dst->src[1];
  11028. GGML_TENSOR_BINARY_OP_LOCALS
  11029. const int64_t nc = ne00;
  11030. const int64_t nr = ggml_nelements(src1);
  11031. assert(ne0 == nc);
  11032. assert(ne02 == ne11);
  11033. assert(nb00 == sizeof(float));
  11034. assert(ggml_nrows(dst) == nr);
  11035. const int ith = params->ith;
  11036. const int nth = params->nth;
  11037. // rows per thread
  11038. const int dr = (nr + nth - 1)/nth;
  11039. // row range for this thread
  11040. const int ir0 = dr*ith;
  11041. const int ir1 = MIN(ir0 + dr, nr);
  11042. for (int64_t i = ir0; i < ir1; ++i) {
  11043. const int64_t i12 = i/(ne11*ne10);
  11044. const int64_t i11 = (i - i12*ne11*ne10)/ne10;
  11045. const int64_t i10 = (i - i12*ne11*ne10 - i11*ne10);
  11046. const int64_t i01 = *(int32_t *) ((char *) src1->data + i10*nb10 + i11*nb11 + i12*nb12);
  11047. GGML_ASSERT(i01 >= 0 && i01 < ne01);
  11048. ggml_vec_cpy_f32(nc,
  11049. (float *) ((char *) dst->data + i10*nb1 + i11*nb2 + i12*nb3),
  11050. (float *) ((char *) src0->data + i01*nb01 + i11*nb02 + i12*nb03));
  11051. }
  11052. }
  11053. static void ggml_compute_forward_get_rows(
  11054. const struct ggml_compute_params * params,
  11055. struct ggml_tensor * dst) {
  11056. const struct ggml_tensor * src0 = dst->src[0];
  11057. switch (src0->type) {
  11058. case GGML_TYPE_Q4_0:
  11059. case GGML_TYPE_Q4_1:
  11060. case GGML_TYPE_Q5_0:
  11061. case GGML_TYPE_Q5_1:
  11062. case GGML_TYPE_Q8_0:
  11063. case GGML_TYPE_Q8_1:
  11064. case GGML_TYPE_Q2_K:
  11065. case GGML_TYPE_Q3_K:
  11066. case GGML_TYPE_Q4_K:
  11067. case GGML_TYPE_Q5_K:
  11068. case GGML_TYPE_Q6_K:
  11069. case GGML_TYPE_TQ1_0:
  11070. case GGML_TYPE_TQ2_0:
  11071. case GGML_TYPE_IQ2_XXS:
  11072. case GGML_TYPE_IQ2_XS:
  11073. case GGML_TYPE_IQ3_XXS:
  11074. case GGML_TYPE_IQ1_S:
  11075. case GGML_TYPE_IQ1_M:
  11076. case GGML_TYPE_IQ4_NL:
  11077. case GGML_TYPE_IQ4_XS:
  11078. case GGML_TYPE_IQ3_S:
  11079. case GGML_TYPE_IQ2_S:
  11080. case GGML_TYPE_Q4_0_4_4:
  11081. case GGML_TYPE_Q4_0_4_8:
  11082. case GGML_TYPE_Q4_0_8_8:
  11083. {
  11084. ggml_compute_forward_get_rows_q(params, dst);
  11085. } break;
  11086. case GGML_TYPE_F16:
  11087. {
  11088. ggml_compute_forward_get_rows_f16(params, dst);
  11089. } break;
  11090. case GGML_TYPE_BF16:
  11091. {
  11092. ggml_compute_forward_get_rows_bf16(params, dst);
  11093. } break;
  11094. case GGML_TYPE_F32:
  11095. case GGML_TYPE_I32:
  11096. {
  11097. ggml_compute_forward_get_rows_f32(params, dst);
  11098. } break;
  11099. default:
  11100. {
  11101. GGML_ABORT("fatal error");
  11102. }
  11103. }
  11104. //static bool first = true;
  11105. //printf("ne0 = %d, ne1 = %d, ne2 = %d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
  11106. //if (first) {
  11107. // first = false;
  11108. //} else {
  11109. // for (int k = 0; k < dst->ne[1]; ++k) {
  11110. // for (int j = 0; j < dst->ne[0]/16; ++j) {
  11111. // for (int i = 0; i < 16; ++i) {
  11112. // printf("%8.4f ", ((float *) dst->data)[k*dst->ne[0] + j*16 + i]);
  11113. // }
  11114. // printf("\n");
  11115. // }
  11116. // printf("\n");
  11117. // }
  11118. // printf("\n");
  11119. // exit(0);
  11120. //}
  11121. }
  11122. // ggml_compute_forward_get_rows_back
  11123. static void ggml_compute_forward_get_rows_back_f32_f16(
  11124. const struct ggml_compute_params * params,
  11125. struct ggml_tensor * dst) {
  11126. const struct ggml_tensor * src0 = dst->src[0];
  11127. const struct ggml_tensor * src1 = dst->src[1];
  11128. if (params->ith != 0) {
  11129. return;
  11130. }
  11131. GGML_ASSERT(ggml_is_contiguous(dst));
  11132. // ggml_compute_forward_dup_same_cont(params, opt0, dst);
  11133. memset(dst->data, 0, ggml_nbytes(dst));
  11134. const int nc = src0->ne[0];
  11135. const int nr = ggml_nelements(src1);
  11136. GGML_ASSERT( dst->ne[0] == nc);
  11137. GGML_ASSERT(src0->nb[0] == sizeof(ggml_fp16_t));
  11138. for (int i = 0; i < nr; ++i) {
  11139. const int r = ((int32_t *) src1->data)[i];
  11140. for (int j = 0; j < nc; ++j) {
  11141. ggml_fp16_t v = ((ggml_fp16_t *) ((char *) src0->data + i*src0->nb[1]))[j];
  11142. ((float *) ((char *) dst->data + r*dst->nb[1]))[j] += GGML_FP16_TO_FP32(v);
  11143. }
  11144. }
  11145. }
  11146. static void ggml_compute_forward_get_rows_back_f32(
  11147. const struct ggml_compute_params * params,
  11148. struct ggml_tensor * dst) {
  11149. const struct ggml_tensor * src0 = dst->src[0];
  11150. const struct ggml_tensor * src1 = dst->src[1];
  11151. if (params->ith != 0) {
  11152. return;
  11153. }
  11154. GGML_ASSERT(ggml_is_contiguous(dst));
  11155. // ggml_compute_forward_dup_same_cont(params, opt0, dst);
  11156. memset(dst->data, 0, ggml_nbytes(dst));
  11157. const int nc = src0->ne[0];
  11158. const int nr = ggml_nelements(src1);
  11159. GGML_ASSERT( dst->ne[0] == nc);
  11160. GGML_ASSERT(src0->nb[0] == sizeof(float));
  11161. for (int i = 0; i < nr; ++i) {
  11162. const int r = ((int32_t *) src1->data)[i];
  11163. ggml_vec_add_f32(nc,
  11164. (float *) ((char *) dst->data + r*dst->nb[1]),
  11165. (float *) ((char *) dst->data + r*dst->nb[1]),
  11166. (float *) ((char *) src0->data + i*src0->nb[1]));
  11167. }
  11168. }
  11169. static void ggml_compute_forward_get_rows_back(
  11170. const struct ggml_compute_params * params,
  11171. struct ggml_tensor * dst) {
  11172. const struct ggml_tensor * src0 = dst->src[0];
  11173. switch (src0->type) {
  11174. case GGML_TYPE_F16:
  11175. {
  11176. ggml_compute_forward_get_rows_back_f32_f16(params, dst);
  11177. } break;
  11178. case GGML_TYPE_F32:
  11179. {
  11180. ggml_compute_forward_get_rows_back_f32(params, dst);
  11181. } break;
  11182. default:
  11183. {
  11184. GGML_ABORT("fatal error");
  11185. }
  11186. }
  11187. //static bool first = true;
  11188. //printf("ne0 = %d, ne1 = %d, ne2 = %d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
  11189. //if (first) {
  11190. // first = false;
  11191. //} else {
  11192. // for (int k = 0; k < dst->ne[1]; ++k) {
  11193. // for (int j = 0; j < dst->ne[0]/16; ++j) {
  11194. // for (int i = 0; i < 16; ++i) {
  11195. // printf("%8.4f ", ((float *) dst->data)[k*dst->ne[0] + j*16 + i]);
  11196. // }
  11197. // printf("\n");
  11198. // }
  11199. // printf("\n");
  11200. // }
  11201. // printf("\n");
  11202. // exit(0);
  11203. //}
  11204. }
  11205. // ggml_compute_forward_diag
  11206. static void ggml_compute_forward_diag_f32(
  11207. const struct ggml_compute_params * params,
  11208. struct ggml_tensor * dst) {
  11209. const struct ggml_tensor * src0 = dst->src[0];
  11210. if (params->ith != 0) {
  11211. return;
  11212. }
  11213. // TODO: handle transposed/permuted matrices
  11214. GGML_TENSOR_UNARY_OP_LOCALS
  11215. GGML_ASSERT(ne00 == ne0);
  11216. GGML_ASSERT(ne00 == ne1);
  11217. GGML_ASSERT(ne01 == 1);
  11218. GGML_ASSERT(ne02 == ne2);
  11219. GGML_ASSERT(ne03 == ne3);
  11220. GGML_ASSERT(nb00 == sizeof(float));
  11221. GGML_ASSERT(nb0 == sizeof(float));
  11222. for (int i3 = 0; i3 < ne3; i3++) {
  11223. for (int i2 = 0; i2 < ne2; i2++) {
  11224. for (int i1 = 0; i1 < ne1; i1++) {
  11225. float * d = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1);
  11226. float * s = (float *)((char *) src0->data + i3*nb03 + i2*nb02);
  11227. for (int i0 = 0; i0 < i1; i0++) {
  11228. d[i0] = 0;
  11229. }
  11230. d[i1] = s[i1];
  11231. for (int i0 = i1+1; i0 < ne0; i0++) {
  11232. d[i0] = 0;
  11233. }
  11234. }
  11235. }
  11236. }
  11237. }
  11238. static void ggml_compute_forward_diag(
  11239. const struct ggml_compute_params * params,
  11240. struct ggml_tensor * dst) {
  11241. const struct ggml_tensor * src0 = dst->src[0];
  11242. switch (src0->type) {
  11243. case GGML_TYPE_F32:
  11244. {
  11245. ggml_compute_forward_diag_f32(params, dst);
  11246. } break;
  11247. default:
  11248. {
  11249. GGML_ABORT("fatal error");
  11250. }
  11251. }
  11252. }
  11253. // ggml_compute_forward_diag_mask_inf
  11254. static void ggml_compute_forward_diag_mask_f32(
  11255. const struct ggml_compute_params * params,
  11256. struct ggml_tensor * dst,
  11257. const float value) {
  11258. const struct ggml_tensor * src0 = dst->src[0];
  11259. const int ith = params->ith;
  11260. const int nth = params->nth;
  11261. const int n_past = ((int32_t *) dst->op_params)[0];
  11262. const bool inplace = src0->data == dst->data;
  11263. GGML_ASSERT(n_past >= 0);
  11264. if (!inplace) {
  11265. if (ith == 0) {
  11266. // memcpy needs to be synchronized across threads to avoid race conditions.
  11267. // => do it in INIT phase
  11268. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  11269. GGML_ASSERT(ggml_is_contiguous(dst) && ggml_is_contiguous(src0));
  11270. memcpy(
  11271. ((char *) dst->data),
  11272. ((char *) src0->data),
  11273. ggml_nbytes(dst));
  11274. }
  11275. ggml_barrier(params->threadpool);
  11276. }
  11277. // TODO: handle transposed/permuted matrices
  11278. const int n = ggml_nrows(src0);
  11279. const int nc = src0->ne[0];
  11280. const int nr = src0->ne[1];
  11281. const int nz = n/nr;
  11282. GGML_ASSERT( dst->nb[0] == sizeof(float));
  11283. GGML_ASSERT(src0->nb[0] == sizeof(float));
  11284. for (int k = 0; k < nz; k++) {
  11285. for (int j = ith; j < nr; j += nth) {
  11286. for (int i = n_past; i < nc; i++) {
  11287. if (i > n_past + j) {
  11288. *(float *)((char *) dst->data + k*dst->nb[2] + j*dst->nb[1] + i*dst->nb[0]) = value;
  11289. }
  11290. }
  11291. }
  11292. }
  11293. }
  11294. static void ggml_compute_forward_diag_mask_inf(
  11295. const struct ggml_compute_params * params,
  11296. struct ggml_tensor * dst) {
  11297. const struct ggml_tensor * src0 = dst->src[0];
  11298. switch (src0->type) {
  11299. case GGML_TYPE_F32:
  11300. {
  11301. ggml_compute_forward_diag_mask_f32(params, dst, -INFINITY);
  11302. } break;
  11303. default:
  11304. {
  11305. GGML_ABORT("fatal error");
  11306. }
  11307. }
  11308. }
  11309. static void ggml_compute_forward_diag_mask_zero(
  11310. const struct ggml_compute_params * params,
  11311. struct ggml_tensor * dst) {
  11312. const struct ggml_tensor * src0 = dst->src[0];
  11313. switch (src0->type) {
  11314. case GGML_TYPE_F32:
  11315. {
  11316. ggml_compute_forward_diag_mask_f32(params, dst, 0);
  11317. } break;
  11318. default:
  11319. {
  11320. GGML_ABORT("fatal error");
  11321. }
  11322. }
  11323. }
  11324. // ggml_compute_forward_soft_max
  11325. static void ggml_compute_forward_soft_max_f32(
  11326. const struct ggml_compute_params * params,
  11327. struct ggml_tensor * dst) {
  11328. const struct ggml_tensor * src0 = dst->src[0];
  11329. const struct ggml_tensor * src1 = dst->src[1];
  11330. assert(ggml_is_contiguous(dst));
  11331. assert(ggml_are_same_shape(src0, dst));
  11332. float scale = 1.0f;
  11333. float max_bias = 0.0f;
  11334. memcpy(&scale, (float *) dst->op_params + 0, sizeof(float));
  11335. memcpy(&max_bias, (float *) dst->op_params + 1, sizeof(float));
  11336. // TODO: handle transposed/permuted matrices
  11337. const int ith = params->ith;
  11338. const int nth = params->nth;
  11339. GGML_TENSOR_UNARY_OP_LOCALS
  11340. //const int64_t ne11 = src1 ? src1->ne[1] : 1;
  11341. // TODO: is this supposed to be ceil instead of floor?
  11342. // https://huggingface.co/mosaicml/mpt-7b/blob/main/attention.py#L370
  11343. const uint32_t n_head = ne02;
  11344. const uint32_t n_head_log2 = 1u << (uint32_t) floor(log2(n_head));
  11345. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  11346. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  11347. const int nc = src0->ne[0];
  11348. const int nr = ggml_nrows(src0);
  11349. // rows per thread
  11350. const int dr = (nr + nth - 1)/nth;
  11351. // row range for this thread
  11352. const int ir0 = dr*ith;
  11353. const int ir1 = MIN(ir0 + dr, nr);
  11354. float * wp = (float *) params->wdata + (nc + CACHE_LINE_SIZE_F32) * ith;
  11355. const bool use_f16 = (src1 && src1->type == GGML_TYPE_F16);
  11356. for (int i1 = ir0; i1 < ir1; i1++) {
  11357. // ALiBi
  11358. const uint32_t h = (i1/ne01)%ne02; // head
  11359. 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;
  11360. float * sp = (float *)((char *) src0->data + i1*src0->nb[1]);
  11361. float * dp = (float *)((char *) dst->data + i1*dst->nb[1]);
  11362. // broadcast the mask across rows
  11363. ggml_fp16_t * mp_f16 = src1 ? (ggml_fp16_t *)((char *) src1->data) + (i1%ne01)*ne00 : NULL;
  11364. float * mp_f32 = src1 ? (float *)((char *) src1->data) + (i1%ne01)*ne00 : NULL;
  11365. ggml_vec_cpy_f32 (nc, wp, sp);
  11366. ggml_vec_scale_f32(nc, wp, scale);
  11367. if (mp_f32) {
  11368. if (use_f16) {
  11369. for (int i = 0; i < nc; ++i) {
  11370. wp[i] += slope*GGML_FP16_TO_FP32(mp_f16[i]);
  11371. }
  11372. } else {
  11373. for (int i = 0; i < nc; ++i) {
  11374. wp[i] += slope*mp_f32[i];
  11375. }
  11376. }
  11377. }
  11378. #ifndef NDEBUG
  11379. for (int i = 0; i < nc; ++i) {
  11380. //printf("p[%d] = %f\n", i, p[i]);
  11381. assert(!isnan(wp[i]));
  11382. }
  11383. #endif
  11384. float max = -INFINITY;
  11385. ggml_vec_max_f32(nc, &max, wp);
  11386. ggml_float sum = ggml_vec_soft_max_f32(nc, dp, wp, max);
  11387. assert(sum > 0.0);
  11388. sum = 1.0/sum;
  11389. ggml_vec_scale_f32(nc, dp, sum);
  11390. #ifndef NDEBUG
  11391. for (int i = 0; i < nc; ++i) {
  11392. assert(!isnan(dp[i]));
  11393. assert(!isinf(dp[i]));
  11394. }
  11395. #endif
  11396. }
  11397. }
  11398. static void ggml_compute_forward_soft_max(
  11399. const struct ggml_compute_params * params,
  11400. struct ggml_tensor * dst) {
  11401. const struct ggml_tensor * src0 = dst->src[0];
  11402. switch (src0->type) {
  11403. case GGML_TYPE_F32:
  11404. {
  11405. ggml_compute_forward_soft_max_f32(params, dst);
  11406. } break;
  11407. default:
  11408. {
  11409. GGML_ABORT("fatal error");
  11410. }
  11411. }
  11412. }
  11413. // ggml_compute_forward_soft_max_back
  11414. static void ggml_compute_forward_soft_max_back_f32(
  11415. const struct ggml_compute_params * params,
  11416. struct ggml_tensor * dst) {
  11417. const struct ggml_tensor * src0 = dst->src[0];
  11418. const struct ggml_tensor * src1 = dst->src[1];
  11419. GGML_ASSERT(ggml_is_contiguous(src0));
  11420. GGML_ASSERT(ggml_is_contiguous(src1));
  11421. GGML_ASSERT(ggml_is_contiguous(dst));
  11422. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  11423. GGML_ASSERT(ggml_are_same_shape(src1, dst));
  11424. // TODO: handle transposed/permuted matrices
  11425. const int ith = params->ith;
  11426. const int nth = params->nth;
  11427. const int nc = src0->ne[0];
  11428. const int nr = ggml_nrows(src0);
  11429. // rows per thread
  11430. const int dr = (nr + nth - 1)/nth;
  11431. // row range for this thread
  11432. const int ir0 = dr*ith;
  11433. const int ir1 = MIN(ir0 + dr, nr);
  11434. for (int i1 = ir0; i1 < ir1; i1++) {
  11435. float *dy = (float *)((char *) src0->data + i1*src0->nb[1]);
  11436. float *y = (float *)((char *) src1->data + i1*src1->nb[1]);
  11437. float *dx = (float *)((char *) dst->data + i1*dst->nb[1]);
  11438. #ifndef NDEBUG
  11439. for (int i = 0; i < nc; ++i) {
  11440. //printf("p[%d] = %f\n", i, p[i]);
  11441. assert(!isnan(dy[i]));
  11442. assert(!isnan(y[i]));
  11443. }
  11444. #endif
  11445. // Jii = yi - yi*yi
  11446. // Jij = -yi*yj
  11447. // J = diag(y)-y.T*y
  11448. // dx = J * dy
  11449. // dxk = sum_i(Jki * dyi)
  11450. // dxk = sum_i(-yk*yi * dyi) - (-yk*yk)*dyk + (yk - yk*yk)*dyk
  11451. // dxk = sum_i(-yk*yi * dyi) + yk*yk*dyk + yk*dyk - yk*yk*dyk
  11452. // dxk = sum_i(-yk*yi * dyi) + yk*dyk
  11453. // dxk = -yk * sum_i(yi * dyi) + yk*dyk
  11454. // dxk = -yk * dot(y, dy) + yk*dyk
  11455. // dxk = yk * (- dot(y, dy) + dyk)
  11456. // dxk = yk * (dyk - dot(y, dy))
  11457. //
  11458. // post-order:
  11459. // dot_y_dy := dot(y, dy)
  11460. // dx := dy
  11461. // dx := dx - dot_y_dy
  11462. // dx := dx * y
  11463. // linear runtime, no additional memory
  11464. float dot_y_dy = 0;
  11465. ggml_vec_dot_f32 (nc, &dot_y_dy, 0, y, 0, dy, 0, 1);
  11466. ggml_vec_cpy_f32 (nc, dx, dy);
  11467. ggml_vec_acc1_f32(nc, dx, -dot_y_dy);
  11468. ggml_vec_mul_f32 (nc, dx, dx, y);
  11469. #ifndef NDEBUG
  11470. for (int i = 0; i < nc; ++i) {
  11471. assert(!isnan(dx[i]));
  11472. assert(!isinf(dx[i]));
  11473. }
  11474. #endif
  11475. }
  11476. }
  11477. static void ggml_compute_forward_soft_max_back(
  11478. const struct ggml_compute_params * params,
  11479. struct ggml_tensor * dst) {
  11480. const struct ggml_tensor * src0 = dst->src[0];
  11481. switch (src0->type) {
  11482. case GGML_TYPE_F32:
  11483. {
  11484. ggml_compute_forward_soft_max_back_f32(params, dst);
  11485. } break;
  11486. default:
  11487. {
  11488. GGML_ABORT("fatal error");
  11489. }
  11490. }
  11491. }
  11492. // ggml_compute_forward_clamp
  11493. static void ggml_compute_forward_clamp_f32(
  11494. const struct ggml_compute_params * params,
  11495. struct ggml_tensor * dst) {
  11496. const struct ggml_tensor * src0 = dst->src[0];
  11497. if (params->ith != 0) {
  11498. return;
  11499. }
  11500. float min;
  11501. float max;
  11502. memcpy(&min, (float *) dst->op_params + 0, sizeof(float));
  11503. memcpy(&max, (float *) dst->op_params + 1, sizeof(float));
  11504. const int ith = params->ith;
  11505. const int nth = params->nth;
  11506. const int n = ggml_nrows(src0);
  11507. const int nc = src0->ne[0];
  11508. const size_t nb00 = src0->nb[0];
  11509. const size_t nb01 = src0->nb[1];
  11510. const size_t nb0 = dst->nb[0];
  11511. const size_t nb1 = dst->nb[1];
  11512. GGML_ASSERT( nb0 == sizeof(float));
  11513. GGML_ASSERT(nb00 == sizeof(float));
  11514. for (int j = ith; j < n; j += nth) {
  11515. float * dst_ptr = (float *) ((char *) dst->data + j*nb1);
  11516. float * src0_ptr = (float *) ((char *) src0->data + j*nb01);
  11517. for (int i = 0; i < nc; i++) {
  11518. dst_ptr[i] = MAX(MIN(src0_ptr[i], max), min);
  11519. }
  11520. }
  11521. }
  11522. static void ggml_compute_forward_clamp(
  11523. const struct ggml_compute_params * params,
  11524. struct ggml_tensor * dst) {
  11525. const struct ggml_tensor * src0 = dst->src[0];
  11526. switch (src0->type) {
  11527. case GGML_TYPE_F32:
  11528. {
  11529. ggml_compute_forward_clamp_f32(params, dst);
  11530. } break;
  11531. case GGML_TYPE_F16:
  11532. case GGML_TYPE_BF16:
  11533. case GGML_TYPE_Q4_0:
  11534. case GGML_TYPE_Q4_1:
  11535. case GGML_TYPE_Q5_0:
  11536. case GGML_TYPE_Q5_1:
  11537. case GGML_TYPE_Q8_0:
  11538. case GGML_TYPE_Q8_1:
  11539. case GGML_TYPE_Q2_K:
  11540. case GGML_TYPE_Q3_K:
  11541. case GGML_TYPE_Q4_K:
  11542. case GGML_TYPE_Q5_K:
  11543. case GGML_TYPE_Q6_K:
  11544. case GGML_TYPE_TQ1_0:
  11545. case GGML_TYPE_TQ2_0:
  11546. case GGML_TYPE_IQ2_XXS:
  11547. case GGML_TYPE_IQ2_XS:
  11548. case GGML_TYPE_IQ3_XXS:
  11549. case GGML_TYPE_IQ1_S:
  11550. case GGML_TYPE_IQ1_M:
  11551. case GGML_TYPE_IQ4_NL:
  11552. case GGML_TYPE_IQ4_XS:
  11553. case GGML_TYPE_IQ3_S:
  11554. case GGML_TYPE_IQ2_S:
  11555. case GGML_TYPE_Q8_K:
  11556. case GGML_TYPE_Q4_0_4_4:
  11557. case GGML_TYPE_Q4_0_4_8:
  11558. case GGML_TYPE_Q4_0_8_8:
  11559. case GGML_TYPE_I8:
  11560. case GGML_TYPE_I16:
  11561. case GGML_TYPE_I32:
  11562. case GGML_TYPE_I64:
  11563. case GGML_TYPE_F64:
  11564. case GGML_TYPE_COUNT:
  11565. {
  11566. GGML_ABORT("fatal error");
  11567. }
  11568. }
  11569. }
  11570. // ggml_compute_forward_rope
  11571. static float rope_yarn_ramp(const float low, const float high, const int i0) {
  11572. const float y = (i0 / 2 - low) / MAX(0.001f, high - low);
  11573. return 1 - MIN(1, MAX(0, y));
  11574. }
  11575. // YaRN algorithm based on LlamaYaRNScaledRotaryEmbedding.py from https://github.com/jquesnelle/yarn
  11576. // MIT licensed. Copyright (c) 2023 Jeffrey Quesnelle and Bowen Peng.
  11577. static void rope_yarn(
  11578. float theta_extrap, float freq_scale, float corr_dims[2], int64_t i0, float ext_factor, float mscale,
  11579. float * cos_theta, float * sin_theta) {
  11580. // Get n-d rotational scaling corrected for extrapolation
  11581. float theta_interp = freq_scale * theta_extrap;
  11582. float theta = theta_interp;
  11583. if (ext_factor != 0.0f) {
  11584. float ramp_mix = rope_yarn_ramp(corr_dims[0], corr_dims[1], i0) * ext_factor;
  11585. theta = theta_interp * (1 - ramp_mix) + theta_extrap * ramp_mix;
  11586. // Get n-d magnitude scaling corrected for interpolation
  11587. mscale *= 1.0f + 0.1f * logf(1.0f / freq_scale);
  11588. }
  11589. *cos_theta = cosf(theta) * mscale;
  11590. *sin_theta = sinf(theta) * mscale;
  11591. }
  11592. // Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` for x, we get
  11593. // `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`
  11594. static float ggml_rope_yarn_corr_dim(int n_dims, int n_ctx_orig, float n_rot, float base) {
  11595. return n_dims * logf(n_ctx_orig / (n_rot * 2 * (float)M_PI)) / (2 * logf(base));
  11596. }
  11597. static void ggml_rope_cache_init(
  11598. float theta_base, float freq_scale, const float * freq_factors, float corr_dims[2], int64_t ne0, float ext_factor, float mscale,
  11599. float * cache, float sin_sign, float theta_scale) {
  11600. // ref: https://github.com/jquesnelle/yarn/blob/master/scaled_rope/LlamaYaRNScaledRotaryEmbedding.py
  11601. float theta = theta_base;
  11602. for (int64_t i0 = 0; i0 < ne0; i0 += 2) {
  11603. const float ff = freq_factors ? freq_factors[i0/2] : 1.0f;
  11604. rope_yarn(
  11605. theta/ff, freq_scale, corr_dims, i0, ext_factor, mscale, &cache[i0 + 0], &cache[i0 + 1]
  11606. );
  11607. cache[i0 + 1] *= sin_sign;
  11608. theta *= theta_scale;
  11609. }
  11610. }
  11611. GGML_CALL void ggml_rope_yarn_corr_dims(
  11612. int n_dims, int n_ctx_orig, float freq_base, float beta_fast, float beta_slow, float dims[2]
  11613. ) {
  11614. // start and end correction dims
  11615. float start = floorf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_fast, freq_base));
  11616. float end = ceilf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_slow, freq_base));
  11617. dims[0] = MAX(0, start);
  11618. dims[1] = MIN(n_dims - 1, end);
  11619. }
  11620. static void ggml_compute_forward_rope_f32(
  11621. const struct ggml_compute_params * params,
  11622. struct ggml_tensor * dst,
  11623. const bool forward) {
  11624. const struct ggml_tensor * src0 = dst->src[0];
  11625. const struct ggml_tensor * src1 = dst->src[1];
  11626. const struct ggml_tensor * src2 = dst->src[2];
  11627. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  11628. //const int n_past = ((int32_t *) dst->op_params)[0];
  11629. const int n_dims = ((int32_t *) dst->op_params)[1];
  11630. const int mode = ((int32_t *) dst->op_params)[2];
  11631. //const int n_ctx = ((int32_t *) dst->op_params)[3];
  11632. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  11633. memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
  11634. memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
  11635. memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
  11636. memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
  11637. memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
  11638. memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
  11639. GGML_TENSOR_UNARY_OP_LOCALS
  11640. //printf("ne0: %d, ne1: %d, ne2: %d, ne3: %d\n", ne0, ne1, ne2, ne3);
  11641. //printf("n_past = %d, ne2 = %d\n", n_past, ne2);
  11642. GGML_ASSERT(nb00 == sizeof(float));
  11643. const int ith = params->ith;
  11644. const int nth = params->nth;
  11645. const int nr = ggml_nrows(dst);
  11646. GGML_ASSERT(n_dims <= ne0);
  11647. GGML_ASSERT(n_dims % 2 == 0);
  11648. // rows per thread
  11649. const int dr = (nr + nth - 1)/nth;
  11650. // row range for this thread
  11651. const int ir0 = dr*ith;
  11652. const int ir1 = MIN(ir0 + dr, nr);
  11653. // row index used to determine which thread to use
  11654. int ir = 0;
  11655. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  11656. float corr_dims[2];
  11657. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  11658. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  11659. const float * freq_factors = NULL;
  11660. if (src2 != NULL) {
  11661. GGML_ASSERT(src2->type == GGML_TYPE_F32);
  11662. GGML_ASSERT(src2->ne[0] >= n_dims / 2);
  11663. freq_factors = (const float *) src2->data;
  11664. }
  11665. // backward process uses inverse rotation by cos and sin.
  11666. // cos and sin build a rotation matrix, where the inverse is the transpose.
  11667. // this essentially just switches the sign of sin.
  11668. const float sin_sign = forward ? 1.0f : -1.0f;
  11669. const int32_t * pos = (const int32_t *) src1->data;
  11670. for (int64_t i3 = 0; i3 < ne3; i3++) {
  11671. for (int64_t i2 = 0; i2 < ne2; i2++) {
  11672. const int64_t p = pos[i2];
  11673. float * cache = (float *) params->wdata + (ne0 + CACHE_LINE_SIZE_F32)*ith;
  11674. ggml_rope_cache_init(p, freq_scale, freq_factors, corr_dims, ne0, ext_factor, attn_factor, cache, sin_sign, theta_scale);
  11675. for (int64_t i1 = 0; i1 < ne1; i1++) {
  11676. if (ir++ < ir0) continue;
  11677. if (ir > ir1) break;
  11678. if (!is_neox) {
  11679. for (int64_t i0 = 0; i0 < n_dims; i0 += 2) {
  11680. const float cos_theta = cache[i0 + 0];
  11681. const float sin_theta = cache[i0 + 1];
  11682. const float * const src = (float *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  11683. float * dst_data = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  11684. const float x0 = src[0];
  11685. const float x1 = src[1];
  11686. dst_data[0] = x0*cos_theta - x1*sin_theta;
  11687. dst_data[1] = x0*sin_theta + x1*cos_theta;
  11688. }
  11689. } else {
  11690. for (int64_t i0 = 0; i0 < n_dims; i0 += 2) {
  11691. const int64_t ic = i0/2;
  11692. const float cos_theta = cache[i0 + 0];
  11693. const float sin_theta = cache[i0 + 1];
  11694. const float * const src = (float *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + ic*nb00);
  11695. float * dst_data = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + ic*nb0);
  11696. const float x0 = src[0];
  11697. const float x1 = src[n_dims/2];
  11698. dst_data[0] = x0*cos_theta - x1*sin_theta;
  11699. dst_data[n_dims/2] = x0*sin_theta + x1*cos_theta;
  11700. }
  11701. }
  11702. for (int64_t i0 = n_dims; i0 < ne0; i0 += 2) {
  11703. const float * const src = (float *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  11704. float * dst_data = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  11705. dst_data[0] = src[0];
  11706. dst_data[1] = src[1];
  11707. }
  11708. }
  11709. }
  11710. }
  11711. }
  11712. // TODO: deduplicate f16/f32 code
  11713. static void ggml_compute_forward_rope_f16(
  11714. const struct ggml_compute_params * params,
  11715. struct ggml_tensor * dst,
  11716. const bool forward) {
  11717. const struct ggml_tensor * src0 = dst->src[0];
  11718. const struct ggml_tensor * src1 = dst->src[1];
  11719. const struct ggml_tensor * src2 = dst->src[2];
  11720. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  11721. //const int n_past = ((int32_t *) dst->op_params)[0];
  11722. const int n_dims = ((int32_t *) dst->op_params)[1];
  11723. const int mode = ((int32_t *) dst->op_params)[2];
  11724. //const int n_ctx = ((int32_t *) dst->op_params)[3];
  11725. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  11726. memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
  11727. memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
  11728. memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
  11729. memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
  11730. memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
  11731. memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
  11732. GGML_TENSOR_UNARY_OP_LOCALS
  11733. //printf("ne0: %d, ne1: %d, ne2: %d, ne3: %d\n", ne0, ne1, ne2, ne3);
  11734. //printf("n_past = %d, ne2 = %d\n", n_past, ne2);
  11735. GGML_ASSERT(nb0 == sizeof(ggml_fp16_t));
  11736. const int ith = params->ith;
  11737. const int nth = params->nth;
  11738. const int nr = ggml_nrows(dst);
  11739. GGML_ASSERT(n_dims <= ne0);
  11740. GGML_ASSERT(n_dims % 2 == 0);
  11741. // rows per thread
  11742. const int dr = (nr + nth - 1)/nth;
  11743. // row range for this thread
  11744. const int ir0 = dr*ith;
  11745. const int ir1 = MIN(ir0 + dr, nr);
  11746. // row index used to determine which thread to use
  11747. int ir = 0;
  11748. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  11749. float corr_dims[2];
  11750. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  11751. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  11752. const float * freq_factors = NULL;
  11753. if (src2 != NULL) {
  11754. GGML_ASSERT(src2->type == GGML_TYPE_F32);
  11755. GGML_ASSERT(src2->ne[0] >= n_dims / 2);
  11756. freq_factors = (const float *) src2->data;
  11757. }
  11758. // backward process uses inverse rotation by cos and sin.
  11759. // cos and sin build a rotation matrix, where the inverse is the transpose.
  11760. // this essentially just switches the sign of sin.
  11761. const float sin_sign = forward ? 1.0f : -1.0f;
  11762. const int32_t * pos = (const int32_t *) src1->data;
  11763. for (int64_t i3 = 0; i3 < ne3; i3++) {
  11764. for (int64_t i2 = 0; i2 < ne2; i2++) {
  11765. const int64_t p = pos[i2];
  11766. float * cache = (float *) params->wdata + (ne0 + CACHE_LINE_SIZE_F32)*ith;
  11767. ggml_rope_cache_init(p, freq_scale, freq_factors, corr_dims, ne0, ext_factor, attn_factor, cache, sin_sign, theta_scale);
  11768. for (int64_t i1 = 0; i1 < ne1; i1++) {
  11769. if (ir++ < ir0) continue;
  11770. if (ir > ir1) break;
  11771. if (!is_neox) {
  11772. for (int64_t i0 = 0; i0 < n_dims; i0 += 2) {
  11773. const float cos_theta = cache[i0 + 0];
  11774. const float sin_theta = cache[i0 + 1];
  11775. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  11776. ggml_fp16_t * dst_data = (ggml_fp16_t *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  11777. const float x0 = GGML_FP16_TO_FP32(src[0]);
  11778. const float x1 = GGML_FP16_TO_FP32(src[1]);
  11779. dst_data[0] = GGML_FP32_TO_FP16(x0*cos_theta - x1*sin_theta);
  11780. dst_data[1] = GGML_FP32_TO_FP16(x0*sin_theta + x1*cos_theta);
  11781. }
  11782. } else {
  11783. for (int64_t i0 = 0; i0 < n_dims; i0 += 2) {
  11784. const int64_t ic = i0/2;
  11785. const float cos_theta = cache[i0 + 0];
  11786. const float sin_theta = cache[i0 + 1];
  11787. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + ic*nb00);
  11788. ggml_fp16_t * dst_data = (ggml_fp16_t *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + ic*nb0);
  11789. const float x0 = GGML_FP16_TO_FP32(src[0]);
  11790. const float x1 = GGML_FP16_TO_FP32(src[n_dims/2]);
  11791. dst_data[0] = GGML_FP32_TO_FP16(x0*cos_theta - x1*sin_theta);
  11792. dst_data[n_dims/2] = GGML_FP32_TO_FP16(x0*sin_theta + x1*cos_theta);
  11793. }
  11794. }
  11795. for (int64_t i0 = n_dims; i0 < ne0; i0 += 2) {
  11796. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  11797. ggml_fp16_t * dst_data = (ggml_fp16_t *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  11798. dst_data[0] = src[0];
  11799. dst_data[1] = src[1];
  11800. }
  11801. }
  11802. }
  11803. }
  11804. }
  11805. static void ggml_compute_forward_rope(
  11806. const struct ggml_compute_params * params,
  11807. struct ggml_tensor * dst) {
  11808. const struct ggml_tensor * src0 = dst->src[0];
  11809. switch (src0->type) {
  11810. case GGML_TYPE_F16:
  11811. {
  11812. ggml_compute_forward_rope_f16(params, dst, true);
  11813. } break;
  11814. case GGML_TYPE_F32:
  11815. {
  11816. ggml_compute_forward_rope_f32(params, dst, true);
  11817. } break;
  11818. default:
  11819. {
  11820. GGML_ABORT("fatal error");
  11821. }
  11822. }
  11823. }
  11824. // ggml_compute_forward_rope_back
  11825. static void ggml_compute_forward_rope_back(
  11826. const struct ggml_compute_params * params,
  11827. struct ggml_tensor * dst) {
  11828. const struct ggml_tensor * src0 = dst->src[0];
  11829. switch (src0->type) {
  11830. case GGML_TYPE_F16:
  11831. {
  11832. ggml_compute_forward_rope_f16(params, dst, false);
  11833. } break;
  11834. case GGML_TYPE_F32:
  11835. {
  11836. ggml_compute_forward_rope_f32(params, dst, false);
  11837. } break;
  11838. default:
  11839. {
  11840. GGML_ABORT("fatal error");
  11841. }
  11842. }
  11843. }
  11844. // ggml_compute_forward_conv_transpose_1d
  11845. static void ggml_compute_forward_conv_transpose_1d_f16_f32(
  11846. const struct ggml_compute_params * params,
  11847. struct ggml_tensor * dst) {
  11848. const struct ggml_tensor * src0 = dst->src[0];
  11849. const struct ggml_tensor * src1 = dst->src[1];
  11850. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  11851. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  11852. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  11853. GGML_TENSOR_BINARY_OP_LOCALS
  11854. const int ith = params->ith;
  11855. const int nth = params->nth;
  11856. const int nk = ne00*ne01*ne02;
  11857. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  11858. GGML_ASSERT(nb10 == sizeof(float));
  11859. if (ith == 0) {
  11860. memset(params->wdata, 0, params->wsize);
  11861. // permute kernel data (src0) from (K x Cout x Cin) to (Cin x K x Cout)
  11862. {
  11863. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  11864. for (int64_t i02 = 0; i02 < ne02; i02++) {
  11865. for (int64_t i01 = 0; i01 < ne01; i01++) {
  11866. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i02*nb02 + i01*nb01);
  11867. ggml_fp16_t * dst_data = wdata + i01*ne00*ne02;
  11868. for (int64_t i00 = 0; i00 < ne00; i00++) {
  11869. dst_data[i00*ne02 + i02] = src[i00];
  11870. }
  11871. }
  11872. }
  11873. }
  11874. // permute source data (src1) from (L x Cin) to (Cin x L)
  11875. {
  11876. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + nk;
  11877. ggml_fp16_t * dst_data = wdata;
  11878. for (int64_t i11 = 0; i11 < ne11; i11++) {
  11879. const float * const src = (float *)((char *) src1->data + i11*nb11);
  11880. for (int64_t i10 = 0; i10 < ne10; i10++) {
  11881. dst_data[i10*ne11 + i11] = GGML_FP32_TO_FP16(src[i10]);
  11882. }
  11883. }
  11884. }
  11885. // need to zero dst since we are accumulating into it
  11886. memset(dst->data, 0, ggml_nbytes(dst));
  11887. }
  11888. ggml_barrier(params->threadpool);
  11889. const int32_t s0 = ((const int32_t*)(dst->op_params))[0];
  11890. // total rows in dst
  11891. const int nr = ne1;
  11892. // rows per thread
  11893. const int dr = (nr + nth - 1)/nth;
  11894. // row range for this thread
  11895. const int ir0 = dr*ith;
  11896. const int ir1 = MIN(ir0 + dr, nr);
  11897. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  11898. ggml_fp16_t * const wdata_src = wdata + nk;
  11899. for (int i1 = ir0; i1 < ir1; i1++) {
  11900. float * dst_data = (float *)((char *) dst->data + i1*nb1);
  11901. ggml_fp16_t * wdata_kernel = wdata + i1*ne02*ne00;
  11902. for (int i10 = 0; i10 < ne10; i10++) {
  11903. const int i1n = i10*ne11;
  11904. for (int i00 = 0; i00 < ne00; i00++) {
  11905. float v = 0;
  11906. ggml_vec_dot_f16(ne02, &v, 0,
  11907. (ggml_fp16_t *) wdata_src + i1n, 0,
  11908. (ggml_fp16_t *) wdata_kernel + i00*ne02, 0, 1);
  11909. dst_data[i10*s0 + i00] += v;
  11910. }
  11911. }
  11912. }
  11913. }
  11914. static void ggml_compute_forward_conv_transpose_1d_f32(
  11915. const struct ggml_compute_params * params,
  11916. struct ggml_tensor * dst) {
  11917. const struct ggml_tensor * src0 = dst->src[0];
  11918. const struct ggml_tensor * src1 = dst->src[1];
  11919. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  11920. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  11921. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  11922. GGML_TENSOR_BINARY_OP_LOCALS
  11923. const int ith = params->ith;
  11924. const int nth = params->nth;
  11925. const int nk = ne00*ne01*ne02;
  11926. GGML_ASSERT(nb00 == sizeof(float));
  11927. GGML_ASSERT(nb10 == sizeof(float));
  11928. if (ith == 0) {
  11929. memset(params->wdata, 0, params->wsize);
  11930. // prepare kernel data (src0) from (K x Cout x Cin) to (Cin x K x Cout)
  11931. {
  11932. float * const wdata = (float *) params->wdata + 0;
  11933. for (int64_t i02 = 0; i02 < ne02; i02++) {
  11934. for (int64_t i01 = 0; i01 < ne01; i01++) {
  11935. const float * const src = (float *)((char *) src0->data + i02*nb02 + i01*nb01);
  11936. float * dst_data = wdata + i01*ne00*ne02;
  11937. for (int64_t i00 = 0; i00 < ne00; i00++) {
  11938. dst_data[i00*ne02 + i02] = src[i00];
  11939. }
  11940. }
  11941. }
  11942. }
  11943. // prepare source data (src1)
  11944. {
  11945. float * const wdata = (float *) params->wdata + nk;
  11946. float * dst_data = wdata;
  11947. for (int64_t i11 = 0; i11 < ne11; i11++) {
  11948. const float * const src = (float *)((char *) src1->data + i11*nb11);
  11949. for (int64_t i10 = 0; i10 < ne10; i10++) {
  11950. dst_data[i10*ne11 + i11] = src[i10];
  11951. }
  11952. }
  11953. }
  11954. // need to zero dst since we are accumulating into it
  11955. memset(dst->data, 0, ggml_nbytes(dst));
  11956. }
  11957. ggml_barrier(params->threadpool);
  11958. const int32_t s0 = ((const int32_t*)(dst->op_params))[0];
  11959. // total rows in dst
  11960. const int nr = ne1;
  11961. // rows per thread
  11962. const int dr = (nr + nth - 1)/nth;
  11963. // row range for this thread
  11964. const int ir0 = dr*ith;
  11965. const int ir1 = MIN(ir0 + dr, nr);
  11966. float * const wdata = (float *) params->wdata + 0;
  11967. float * const wdata_src = wdata + nk;
  11968. for (int i1 = ir0; i1 < ir1; i1++) {
  11969. float * dst_data = (float *)((char *) dst->data + i1*nb1);
  11970. float * wdata_kernel = wdata + i1*ne02*ne00;
  11971. for (int i10 = 0; i10 < ne10; i10++) {
  11972. const int i1n = i10*ne11;
  11973. for (int i00 = 0; i00 < ne00; i00++) {
  11974. float v = 0;
  11975. ggml_vec_dot_f32(ne02, &v, 0,
  11976. wdata_src + i1n, 0,
  11977. wdata_kernel + i00*ne02, 0, 1);
  11978. dst_data[i10*s0 + i00] += v;
  11979. }
  11980. }
  11981. }
  11982. }
  11983. static void ggml_compute_forward_conv_transpose_1d(
  11984. const struct ggml_compute_params * params,
  11985. struct ggml_tensor * dst) {
  11986. const struct ggml_tensor * src0 = dst->src[0];
  11987. switch (src0->type) {
  11988. case GGML_TYPE_F16:
  11989. {
  11990. ggml_compute_forward_conv_transpose_1d_f16_f32(params, dst);
  11991. } break;
  11992. case GGML_TYPE_F32:
  11993. {
  11994. ggml_compute_forward_conv_transpose_1d_f32(params, dst);
  11995. } break;
  11996. default:
  11997. {
  11998. GGML_ABORT("fatal error");
  11999. }
  12000. }
  12001. }
  12002. // ggml_compute_forward_im2col_f32
  12003. // src0: kernel [OC, IC, KH, KW]
  12004. // src1: image [N, IC, IH, IW]
  12005. // dst: result [N, OH, OW, IC*KH*KW]
  12006. static void ggml_compute_forward_im2col_f32(
  12007. const struct ggml_compute_params * params,
  12008. struct ggml_tensor * dst) {
  12009. const struct ggml_tensor * src0 = dst->src[0];
  12010. const struct ggml_tensor * src1 = dst->src[1];
  12011. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  12012. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  12013. GGML_TENSOR_BINARY_OP_LOCALS;
  12014. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  12015. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  12016. const int32_t p0 = ((const int32_t *)(dst->op_params))[2];
  12017. const int32_t p1 = ((const int32_t *)(dst->op_params))[3];
  12018. const int32_t d0 = ((const int32_t *)(dst->op_params))[4];
  12019. const int32_t d1 = ((const int32_t *)(dst->op_params))[5];
  12020. const bool is_2D = ((const int32_t *)(dst->op_params))[6] == 1;
  12021. const int ith = params->ith;
  12022. const int nth = params->nth;
  12023. const int64_t N = is_2D ? ne13 : ne12;
  12024. const int64_t IC = is_2D ? ne12 : ne11;
  12025. const int64_t IH = is_2D ? ne11 : 1;
  12026. const int64_t IW = ne10;
  12027. const int64_t KH = is_2D ? ne01 : 1;
  12028. const int64_t KW = ne00;
  12029. const int64_t OH = is_2D ? ne2 : 1;
  12030. const int64_t OW = ne1;
  12031. int ofs0 = is_2D ? nb13 : nb12;
  12032. int ofs1 = is_2D ? nb12 : nb11;
  12033. GGML_ASSERT(nb10 == sizeof(float));
  12034. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  12035. {
  12036. float * const wdata = (float *) dst->data;
  12037. for (int64_t in = 0; in < N; in++) {
  12038. for (int64_t ioh = 0; ioh < OH; ioh++) { // 1
  12039. for (int64_t iow = 0; iow < OW; iow++) {
  12040. for (int64_t iic = ith; iic < IC; iic += nth) {
  12041. // micro kernel
  12042. float * dst_data = wdata + (in*OH*OW + ioh*OW + iow)*(IC*KH*KW); // [IC, KH, KW]
  12043. const float * const src_data = (float *)((char *) src1->data + in*ofs0 + iic*ofs1); // [IH, IW]
  12044. for (int64_t ikh = 0; ikh < KH; ikh++) { // 1
  12045. for (int64_t ikw = 0; ikw < KW; ikw++) {
  12046. const int64_t iiw = iow*s0 + ikw*d0 - p0;
  12047. const int64_t iih = ioh*s1 + ikh*d1 - p1;
  12048. if (iih < 0 || iih >= IH || iiw < 0 || iiw >= IW) {
  12049. dst_data[iic*(KH*KW) + ikh*KW + ikw] = 0;
  12050. } else {
  12051. dst_data[iic*(KH*KW) + ikh*KW + ikw] = (src_data[iih*IW + iiw]);
  12052. }
  12053. }
  12054. }
  12055. }
  12056. }
  12057. }
  12058. }
  12059. }
  12060. }
  12061. // ggml_compute_forward_im2col_f16
  12062. // src0: kernel [OC, IC, KH, KW]
  12063. // src1: image [N, IC, IH, IW]
  12064. // dst: result [N, OH, OW, IC*KH*KW]
  12065. static void ggml_compute_forward_im2col_f16(
  12066. const struct ggml_compute_params * params,
  12067. struct ggml_tensor * dst) {
  12068. const struct ggml_tensor * src0 = dst->src[0];
  12069. const struct ggml_tensor * src1 = dst->src[1];
  12070. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  12071. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  12072. GGML_ASSERT( dst->type == GGML_TYPE_F16);
  12073. GGML_TENSOR_BINARY_OP_LOCALS;
  12074. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  12075. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  12076. const int32_t p0 = ((const int32_t *)(dst->op_params))[2];
  12077. const int32_t p1 = ((const int32_t *)(dst->op_params))[3];
  12078. const int32_t d0 = ((const int32_t *)(dst->op_params))[4];
  12079. const int32_t d1 = ((const int32_t *)(dst->op_params))[5];
  12080. const bool is_2D = ((const int32_t *)(dst->op_params))[6] == 1;
  12081. const int ith = params->ith;
  12082. const int nth = params->nth;
  12083. const int64_t N = is_2D ? ne13 : ne12;
  12084. const int64_t IC = is_2D ? ne12 : ne11;
  12085. const int64_t IH = is_2D ? ne11 : 1;
  12086. const int64_t IW = ne10;
  12087. const int64_t KH = is_2D ? ne01 : 1;
  12088. const int64_t KW = ne00;
  12089. const int64_t OH = is_2D ? ne2 : 1;
  12090. const int64_t OW = ne1;
  12091. int ofs0 = is_2D ? nb13 : nb12;
  12092. int ofs1 = is_2D ? nb12 : nb11;
  12093. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  12094. GGML_ASSERT(nb10 == sizeof(float));
  12095. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  12096. {
  12097. ggml_fp16_t * const wdata = (ggml_fp16_t *) dst->data;
  12098. for (int64_t in = 0; in < N; in++) {
  12099. for (int64_t ioh = 0; ioh < OH; ioh++) { // 1
  12100. for (int64_t iow = 0; iow < OW; iow++) {
  12101. for (int64_t iic = ith; iic < IC; iic += nth) {
  12102. // micro kernel
  12103. ggml_fp16_t * dst_data = wdata + (in*OH*OW + ioh*OW + iow)*(IC*KH*KW); // [IC, KH, KW]
  12104. const float * const src_data = (float *)((char *) src1->data + in*ofs0 + iic*ofs1); // [IH, IW]
  12105. for (int64_t ikh = 0; ikh < KH; ikh++) { // 1
  12106. for (int64_t ikw = 0; ikw < KW; ikw++) {
  12107. const int64_t iiw = iow*s0 + ikw*d0 - p0;
  12108. const int64_t iih = ioh*s1 + ikh*d1 - p1;
  12109. if (iih < 0 || iih >= IH || iiw < 0 || iiw >= IW) {
  12110. dst_data[iic*(KH*KW) + ikh*KW + ikw] = 0;
  12111. } else {
  12112. dst_data[iic*(KH*KW) + ikh*KW + ikw] = GGML_FP32_TO_FP16(src_data[iih*IW + iiw]);
  12113. }
  12114. }
  12115. }
  12116. }
  12117. }
  12118. }
  12119. }
  12120. }
  12121. }
  12122. static void ggml_compute_forward_im2col(
  12123. const struct ggml_compute_params * params,
  12124. struct ggml_tensor * dst) {
  12125. switch (dst->type) {
  12126. case GGML_TYPE_F16:
  12127. {
  12128. ggml_compute_forward_im2col_f16(params, dst);
  12129. } break;
  12130. case GGML_TYPE_F32:
  12131. {
  12132. ggml_compute_forward_im2col_f32(params, dst);
  12133. } break;
  12134. default:
  12135. {
  12136. GGML_ABORT("fatal error");
  12137. }
  12138. }
  12139. }
  12140. // ggml_compute_forward_im2col_back_f32
  12141. static void ggml_compute_forward_im2col_back_f32(
  12142. const struct ggml_compute_params * params,
  12143. struct ggml_tensor * dst) {
  12144. const struct ggml_tensor * src0 = dst->src[0];
  12145. const struct ggml_tensor * src1 = dst->src[1];
  12146. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  12147. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  12148. GGML_TENSOR_BINARY_OP_LOCALS;
  12149. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  12150. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  12151. const int32_t p0 = ((const int32_t *)(dst->op_params))[2];
  12152. const int32_t p1 = ((const int32_t *)(dst->op_params))[3];
  12153. const int32_t d0 = ((const int32_t *)(dst->op_params))[4];
  12154. const int32_t d1 = ((const int32_t *)(dst->op_params))[5];
  12155. const bool is_2D = ((const int32_t *)(dst->op_params))[6] == 1;
  12156. const int ith = params->ith;
  12157. const int nth = params->nth;
  12158. const int64_t N = is_2D ? ne3 : ne2;
  12159. const int64_t IC = is_2D ? ne2 : ne1;
  12160. const int64_t IH = is_2D ? ne1 : 1;
  12161. const int64_t IW = ne0;
  12162. const int64_t KH = is_2D ? ne01 : 1;
  12163. const int64_t KW = ne00;
  12164. const int64_t OH = is_2D ? ne12 : 1;
  12165. const int64_t OW = ne11;
  12166. int ofs0 = is_2D ? nb3 : nb2;
  12167. int ofs1 = is_2D ? nb2 : nb1;
  12168. GGML_ASSERT(nb0 == sizeof(float));
  12169. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  12170. {
  12171. float * const wdata = (float *) dst->data;
  12172. for (int64_t in = 0; in < N; in++) {
  12173. for (int64_t iic = ith; iic < IC; iic += nth) {
  12174. for (int64_t iih = 0; iih < IH; iih++) {
  12175. for (int64_t iiw = 0; iiw < IW; iiw++) {
  12176. // micro kernel
  12177. float grad = 0.0f;
  12178. for (int64_t ikh = 0; ikh < KH; ikh++) {
  12179. for (int64_t ikw = 0; ikw < KW; ikw++) {
  12180. // For s0 > 1 some values were skipped over in the forward pass.
  12181. // These values have tmpw % s0 != 0 and need to be skipped in the backwards pass as well.
  12182. const int64_t tmpw = (iiw + p0 - ikw*d0);
  12183. if (tmpw % s0 != 0) {
  12184. continue;
  12185. }
  12186. const int64_t iow = tmpw / s0;
  12187. // Equivalent logic as above except for s1.
  12188. int64_t ioh;
  12189. if (is_2D) {
  12190. const int64_t tmph = iih + p1 - ikh*d1;
  12191. if (tmph % s1 != 0) {
  12192. continue;
  12193. }
  12194. ioh = tmph / s1;
  12195. } else {
  12196. ioh = 0;
  12197. }
  12198. if (iow < 0 || iow >= OW || ioh < 0 || ioh >= OH) {
  12199. continue;
  12200. }
  12201. const float * const src_data = (const float *) src1->data
  12202. + (in*OH*OW + ioh*OW + iow)*(IC*KH*KW); // [IC, KH, KW]
  12203. grad += src_data[iic*(KH*KW) + ikh*KW + ikw];
  12204. }
  12205. }
  12206. float * dst_data = (float *)((char *) wdata + (in*ofs0 + iic*ofs1)); // [IH, IW]
  12207. dst_data[iih*IW + iiw] = grad;
  12208. }
  12209. }
  12210. }
  12211. }
  12212. }
  12213. }
  12214. // ggml_compute_forward_conv_transpose_2d
  12215. static void ggml_compute_forward_conv_transpose_2d(
  12216. const struct ggml_compute_params * params,
  12217. struct ggml_tensor * dst) {
  12218. const struct ggml_tensor * src0 = dst->src[0];
  12219. const struct ggml_tensor * src1 = dst->src[1];
  12220. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  12221. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  12222. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  12223. GGML_TENSOR_BINARY_OP_LOCALS
  12224. const int ith = params->ith;
  12225. const int nth = params->nth;
  12226. const int nk = ne00*ne01*ne02*ne03;
  12227. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  12228. GGML_ASSERT(nb10 == sizeof(float));
  12229. if (ith == 0) {
  12230. memset(params->wdata, 0, params->wsize);
  12231. // permute kernel data (src0) from (Kw x Kh x Cout x Cin) to (Cin x Kw x Kh x Cout)
  12232. {
  12233. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  12234. for (int64_t i03 = 0; i03 < ne03; i03++) {
  12235. for (int64_t i02 = 0; i02 < ne02; i02++) {
  12236. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i03*nb03 + i02*nb02);
  12237. ggml_fp16_t * dst_data = wdata + i02*ne01*ne00*ne03;
  12238. for (int64_t i01 = 0; i01 < ne01; i01++) {
  12239. for (int64_t i00 = 0; i00 < ne00; i00++) {
  12240. dst_data[i01*ne00*ne03 + i00*ne03 + i03] = src[i01 * ne00 + i00];
  12241. }
  12242. }
  12243. }
  12244. }
  12245. }
  12246. // permute source data (src1) from (Sw x Sh x Cin) to (Cin x Sw x Sh)
  12247. {
  12248. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + nk;
  12249. for (int i12 = 0; i12 < ne12; i12++) {
  12250. for (int i11 = 0; i11 < ne11; i11++) {
  12251. const float * const src = (float *)((char *) src1->data + i12*nb12 + i11*nb11);
  12252. ggml_fp16_t * dst_data = wdata + i11*ne10*ne12;
  12253. for (int i10 = 0; i10 < ne10; i10++) {
  12254. dst_data[i10*ne12 + i12] = GGML_FP32_TO_FP16(src[i10]);
  12255. }
  12256. }
  12257. }
  12258. }
  12259. memset(dst->data, 0, ggml_nbytes(dst));
  12260. }
  12261. ggml_barrier(params->threadpool);
  12262. const int32_t stride = ggml_get_op_params_i32(dst, 0);
  12263. // total patches in dst
  12264. const int np = ne2;
  12265. // patches per thread
  12266. const int dp = (np + nth - 1)/nth;
  12267. // patch range for this thread
  12268. const int ip0 = dp*ith;
  12269. const int ip1 = MIN(ip0 + dp, np);
  12270. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  12271. ggml_fp16_t * const wdata_src = wdata + nk;
  12272. for (int i2 = ip0; i2 < ip1; i2++) { // Cout
  12273. float * dst_data = (float *)((char *) dst->data + i2*nb2);
  12274. ggml_fp16_t * wdata_kernel = wdata + i2*ne01*ne00*ne03;
  12275. for (int i11 = 0; i11 < ne11; i11++) {
  12276. for (int i10 = 0; i10 < ne10; i10++) {
  12277. const int i1n = i11*ne10*ne12 + i10*ne12;
  12278. for (int i01 = 0; i01 < ne01; i01++) {
  12279. for (int i00 = 0; i00 < ne00; i00++) {
  12280. float v = 0;
  12281. ggml_vec_dot_f16(ne03, &v, 0,
  12282. wdata_src + i1n, 0,
  12283. wdata_kernel + i01*ne00*ne03 + i00*ne03, 0, 1);
  12284. dst_data[(i11*stride + i01)*ne0 + i10*stride + i00] += v;
  12285. }
  12286. }
  12287. }
  12288. }
  12289. }
  12290. }
  12291. // ggml_compute_forward_pool_1d_sk_p0
  12292. static void ggml_compute_forward_pool_1d_sk_p0(
  12293. const struct ggml_compute_params * params,
  12294. const enum ggml_op_pool op,
  12295. const int k,
  12296. struct ggml_tensor * dst) {
  12297. const struct ggml_tensor * src = dst->src[0];
  12298. assert(src->type == GGML_TYPE_F32 || src->type == GGML_TYPE_F16);
  12299. if (params->ith != 0) {
  12300. return;
  12301. }
  12302. const char * cdata = (const char *)src->data;
  12303. const char * const data_end = cdata + ggml_nbytes(src);
  12304. float * drow = (float *)dst->data;
  12305. const int64_t rs = dst->ne[0];
  12306. while (cdata < data_end) {
  12307. const void * srow = (const void *)cdata;
  12308. int j = 0;
  12309. for (int64_t i = 0; i < rs; ++i) {
  12310. switch (op) {
  12311. case GGML_OP_POOL_AVG: drow[i] = 0; break;
  12312. case GGML_OP_POOL_MAX: drow[i] = -FLT_MAX; break;
  12313. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12314. }
  12315. for (int ki = 0; ki < k; ++ki) {
  12316. const float srow_j = (src->type == GGML_TYPE_F32) ? ((const float*)srow)[j] : GGML_FP16_TO_FP32(((const ggml_fp16_t*)srow)[j]);
  12317. switch (op) {
  12318. case GGML_OP_POOL_AVG: drow[i] += srow_j; break;
  12319. case GGML_OP_POOL_MAX: if (srow_j > drow[i]) drow[i] = srow_j; break;
  12320. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12321. }
  12322. ++j;
  12323. }
  12324. switch (op) {
  12325. case GGML_OP_POOL_AVG: drow[i] /= k; break;
  12326. case GGML_OP_POOL_MAX: break;
  12327. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12328. }
  12329. }
  12330. cdata += src->nb[1];
  12331. drow += rs;
  12332. }
  12333. }
  12334. // ggml_compute_forward_pool_1d
  12335. static void ggml_compute_forward_pool_1d(
  12336. const struct ggml_compute_params * params,
  12337. struct ggml_tensor * dst) {
  12338. const int32_t * opts = (const int32_t *)dst->op_params;
  12339. enum ggml_op_pool op = opts[0];
  12340. const int k0 = opts[1];
  12341. const int s0 = opts[2];
  12342. const int p0 = opts[3];
  12343. GGML_ASSERT(p0 == 0); // padding not supported
  12344. GGML_ASSERT(k0 == s0); // only s = k supported
  12345. ggml_compute_forward_pool_1d_sk_p0(params, op, k0, dst);
  12346. }
  12347. // ggml_compute_forward_pool_2d
  12348. static void ggml_compute_forward_pool_2d(
  12349. const struct ggml_compute_params * params,
  12350. struct ggml_tensor * dst) {
  12351. const struct ggml_tensor * src = dst->src[0];
  12352. assert(src->type == GGML_TYPE_F32 || src->type == GGML_TYPE_F16);
  12353. if (params->ith != 0) {
  12354. return;
  12355. }
  12356. const int32_t * opts = (const int32_t *)dst->op_params;
  12357. enum ggml_op_pool op = opts[0];
  12358. const int k0 = opts[1];
  12359. const int k1 = opts[2];
  12360. const int s0 = opts[3];
  12361. const int s1 = opts[4];
  12362. const int p0 = opts[5];
  12363. const int p1 = opts[6];
  12364. const char * cdata = (const char*)src->data;
  12365. const char * const data_end = cdata + ggml_nbytes(src);
  12366. const int64_t px = dst->ne[0];
  12367. const int64_t py = dst->ne[1];
  12368. const int64_t pa = px * py;
  12369. float * dplane = (float *)dst->data;
  12370. const int ka = k0 * k1;
  12371. const int offset0 = -p0;
  12372. const int offset1 = -p1;
  12373. while (cdata < data_end) {
  12374. for (int oy = 0; oy < py; ++oy) {
  12375. float * const drow = dplane + oy * px;
  12376. for (int ox = 0; ox < px; ++ox) {
  12377. float * const out = drow + ox;
  12378. switch (op) {
  12379. case GGML_OP_POOL_AVG: *out = 0; break;
  12380. case GGML_OP_POOL_MAX: *out = -FLT_MAX; break;
  12381. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12382. }
  12383. const int ix = offset0 + ox * s0;
  12384. const int iy = offset1 + oy * s1;
  12385. for (int ky = 0; ky < k1; ++ky) {
  12386. if (iy + ky < 0 || iy + ky >= src->ne[1]) continue;
  12387. const void * srow = (const void *)(cdata + src->nb[1] * (iy + ky));
  12388. for (int kx = 0; kx < k0; ++kx) {
  12389. int j = ix + kx;
  12390. if (j < 0 || j >= src->ne[0]) continue;
  12391. const float srow_j = (src->type == GGML_TYPE_F32) ? ((const float*)srow)[j] : GGML_FP16_TO_FP32(((const ggml_fp16_t*)srow)[j]);
  12392. switch (op) {
  12393. case GGML_OP_POOL_AVG: *out += srow_j; break;
  12394. case GGML_OP_POOL_MAX: if (srow_j > *out) *out = srow_j; break;
  12395. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12396. }
  12397. }
  12398. }
  12399. switch (op) {
  12400. case GGML_OP_POOL_AVG: *out /= ka; break;
  12401. case GGML_OP_POOL_MAX: break;
  12402. case GGML_OP_POOL_COUNT: GGML_ABORT("fatal error");
  12403. }
  12404. }
  12405. }
  12406. cdata += src->nb[2];
  12407. dplane += pa;
  12408. }
  12409. }
  12410. // ggml_compute_forward_pool_2d_back
  12411. static void ggml_compute_forward_pool_2d_back(
  12412. const struct ggml_compute_params * params,
  12413. struct ggml_tensor * dst) {
  12414. const struct ggml_tensor * src = dst->src[0];
  12415. const struct ggml_tensor * dstf = dst->src[1]; // forward tensor of dst
  12416. assert(dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16);
  12417. if (params->ith != 0) {
  12418. return;
  12419. }
  12420. const int32_t * opts = (const int32_t *)dst->op_params;
  12421. enum ggml_op_pool op = opts[0];
  12422. const int k0 = opts[1];
  12423. const int k1 = opts[2];
  12424. const int s0 = opts[3];
  12425. const int s1 = opts[4];
  12426. const int p0 = opts[5];
  12427. const int p1 = opts[6];
  12428. char * cdata = (char *) dst->data;
  12429. const char * cdataf = (const char *) dstf->data;
  12430. const char * const data_end = cdata + ggml_nbytes(dst);
  12431. GGML_ASSERT(params->ith == 0);
  12432. memset(cdata, 0, ggml_nbytes(dst));
  12433. const int64_t px = src->ne[0];
  12434. const int64_t py = src->ne[1];
  12435. const int64_t pa = px * py;
  12436. const float * splane = (const float *) src->data;
  12437. const int ka = k0 * k1;
  12438. const int offset0 = -p0;
  12439. const int offset1 = -p1;
  12440. while (cdata < data_end) {
  12441. for (int oy = 0; oy < py; ++oy) {
  12442. const float * const srow = splane + oy * px;
  12443. for (int ox = 0; ox < px; ++ox) {
  12444. const float grad0 = srow[ox];
  12445. const int ix = offset0 + ox * s0;
  12446. const int iy = offset1 + oy * s1;
  12447. if (op == GGML_OP_POOL_MAX) {
  12448. float maxval = -FLT_MAX;
  12449. int kxmax = -1;
  12450. int kymax = -1;
  12451. for (int ky = 0; ky < k1; ++ky) {
  12452. if (iy + ky < 0 || iy + ky >= dst->ne[1]) {
  12453. continue;
  12454. }
  12455. const void * drowf = (const void *)(cdataf + dst->nb[1] * (iy + ky));
  12456. for (int kx = 0; kx < k0; ++kx) {
  12457. int j = ix + kx;
  12458. if (j < 0 || j >= dst->ne[0]) {
  12459. continue;
  12460. }
  12461. const float val = dst->type == GGML_TYPE_F32 ?
  12462. ((const float *) drowf)[j] : GGML_FP16_TO_FP32(((const ggml_fp16_t *) drowf)[j]);
  12463. if (val <= maxval) {
  12464. continue;
  12465. }
  12466. maxval = val;
  12467. kxmax = kx;
  12468. kymax = ky;
  12469. }
  12470. }
  12471. if (kxmax == -1 || kymax == -1) {
  12472. continue;
  12473. }
  12474. void * drow = (void *)(cdata + dst->nb[1] * (iy + kymax));
  12475. const int j = ix + kxmax;
  12476. if (dst->type == GGML_TYPE_F32) {
  12477. ((float *) drow)[j] += grad0;
  12478. } else {
  12479. ((ggml_fp16_t *) drow)[j] = GGML_FP32_TO_FP16(grad0 + GGML_FP16_TO_FP32(((const ggml_fp16_t *) drow)[j]));
  12480. }
  12481. } else if (op == GGML_OP_POOL_AVG) {
  12482. const float grad = grad0 / ka;
  12483. for (int ky = 0; ky < k1; ++ky) {
  12484. if (iy + ky < 0 || iy + ky >= dst->ne[1]) {
  12485. continue;
  12486. }
  12487. void * drow = (void *)(cdata + dst->nb[1] * (iy + ky));
  12488. for (int kx = 0; kx < k0; ++kx) {
  12489. int j = ix + kx;
  12490. if (j < 0 || j >= dst->ne[0]) {
  12491. continue;
  12492. }
  12493. if (dst->type == GGML_TYPE_F32) {
  12494. ((float *) drow)[j] += grad;
  12495. } else {
  12496. ((ggml_fp16_t *) drow)[j] += GGML_FP32_TO_FP16(grad);
  12497. }
  12498. }
  12499. }
  12500. } else {
  12501. GGML_ASSERT(false);
  12502. }
  12503. }
  12504. }
  12505. cdata += dst->nb[2];
  12506. cdataf += dst->nb[2];
  12507. splane += pa;
  12508. }
  12509. }
  12510. // ggml_compute_forward_upscale
  12511. static void ggml_compute_forward_upscale_f32(
  12512. const struct ggml_compute_params * params,
  12513. struct ggml_tensor * dst) {
  12514. const struct ggml_tensor * src0 = dst->src[0];
  12515. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  12516. const int ith = params->ith;
  12517. const int nth = params->nth;
  12518. GGML_TENSOR_UNARY_OP_LOCALS
  12519. const float sf0 = (float)ne0/src0->ne[0];
  12520. const float sf1 = (float)ne1/src0->ne[1];
  12521. const float sf2 = (float)ne2/src0->ne[2];
  12522. const float sf3 = (float)ne3/src0->ne[3];
  12523. // TODO: optimize
  12524. for (int64_t i3 = 0; i3 < ne3; i3++) {
  12525. const int64_t i03 = i3 / sf3;
  12526. for (int64_t i2 = ith; i2 < ne2; i2 += nth) {
  12527. const int64_t i02 = i2 / sf2;
  12528. for (int64_t i1 = 0; i1 < ne1; i1++) {
  12529. const int64_t i01 = i1 / sf1;
  12530. for (int64_t i0 = 0; i0 < ne0; i0++) {
  12531. const int64_t i00 = i0 / sf0;
  12532. const float * x = (float *)((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  12533. float * y = (float *)((char *) dst->data + i0*nb0 + i1*nb1 + i2*nb2 + i3*nb3);
  12534. *y = *x;
  12535. }
  12536. }
  12537. }
  12538. }
  12539. }
  12540. static void ggml_compute_forward_upscale(
  12541. const struct ggml_compute_params * params,
  12542. struct ggml_tensor * dst) {
  12543. const struct ggml_tensor * src0 = dst->src[0];
  12544. switch (src0->type) {
  12545. case GGML_TYPE_F32:
  12546. {
  12547. ggml_compute_forward_upscale_f32(params, dst);
  12548. } break;
  12549. default:
  12550. {
  12551. GGML_ABORT("fatal error");
  12552. }
  12553. }
  12554. }
  12555. // ggml_compute_forward_pad
  12556. static void ggml_compute_forward_pad_f32(
  12557. const struct ggml_compute_params * params,
  12558. struct ggml_tensor * dst) {
  12559. const struct ggml_tensor * src0 = dst->src[0];
  12560. GGML_ASSERT(src0->nb[0] == sizeof(float));
  12561. GGML_ASSERT( dst->nb[0] == sizeof(float));
  12562. const int ith = params->ith;
  12563. const int nth = params->nth;
  12564. GGML_TENSOR_UNARY_OP_LOCALS
  12565. float * dst_ptr = (float *) dst->data;
  12566. // TODO: optimize
  12567. for (int64_t i2 = 0; i2 < ne2; ++i2) {
  12568. for (int64_t i1 = ith; i1 < ne1; i1 += nth) {
  12569. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  12570. for (int64_t i3 = 0; i3 < ne3; ++i3) {
  12571. const int64_t dst_idx = i3*(ne0*ne1*ne2) + i2*(ne0*ne1) + i1*ne0 + i0;
  12572. const float * src_ptr = (const float *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  12573. if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
  12574. dst_ptr[dst_idx] = *src_ptr;
  12575. } else {
  12576. dst_ptr[dst_idx] = 0;
  12577. }
  12578. }
  12579. }
  12580. }
  12581. }
  12582. }
  12583. static void ggml_compute_forward_pad(
  12584. const struct ggml_compute_params * params,
  12585. struct ggml_tensor * dst) {
  12586. const struct ggml_tensor * src0 = dst->src[0];
  12587. switch (src0->type) {
  12588. case GGML_TYPE_F32:
  12589. {
  12590. ggml_compute_forward_pad_f32(params, dst);
  12591. } break;
  12592. default:
  12593. {
  12594. GGML_ABORT("fatal error");
  12595. }
  12596. }
  12597. }
  12598. static void ggml_compute_forward_unpad_f32(
  12599. const struct ggml_compute_params *params,
  12600. struct ggml_tensor *dst) {
  12601. const struct ggml_tensor * src0 = dst->src[0];
  12602. GGML_ASSERT(src0->nb[0] == sizeof(float));
  12603. GGML_ASSERT( dst->nb[0] == sizeof(float));
  12604. const int ith = params->ith;
  12605. const int nth = params->nth;
  12606. GGML_TENSOR_UNARY_OP_LOCALS
  12607. float * dst_ptr = (float *) dst->data;
  12608. // TODO: optimize
  12609. for (int64_t i2 = 0; i2 < ne2; ++i2) {
  12610. for (int64_t i1 = ith; i1 < ne1; i1 += nth) {
  12611. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  12612. for (int64_t i3 = 0; i3 < ne3; ++i3) {
  12613. const int64_t dst_idx = i3*(ne0*ne1*ne2) + i2*(ne0*ne1) + i1*ne0 + i0;
  12614. const float * src_ptr = (const float *)((char *) src0->data + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
  12615. if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
  12616. dst_ptr[dst_idx] = *src_ptr;
  12617. }
  12618. }
  12619. }
  12620. }
  12621. }
  12622. }
  12623. static void ggml_compute_forward_unpad(
  12624. const struct ggml_compute_params * params,
  12625. struct ggml_tensor * dst) {
  12626. const struct ggml_tensor * src0 = dst->src[0];
  12627. switch (src0->type) {
  12628. case GGML_TYPE_F32:
  12629. {
  12630. ggml_compute_forward_unpad_f32(params, dst);
  12631. } break;
  12632. default:
  12633. {
  12634. GGML_ABORT("fatal error");
  12635. }
  12636. }
  12637. }
  12638. // ggml_compute_forward_arange
  12639. static void ggml_compute_forward_arange_f32(
  12640. const struct ggml_compute_params * params,
  12641. struct ggml_tensor * dst) {
  12642. GGML_ASSERT(dst->nb[0] == sizeof(float));
  12643. const int ith = params->ith;
  12644. const int nth = params->nth;
  12645. const float start = ggml_get_op_params_f32(dst, 0);
  12646. const float stop = ggml_get_op_params_f32(dst, 1);
  12647. const float step = ggml_get_op_params_f32(dst, 2);
  12648. const int64_t steps = (int64_t) ceilf((stop - start) / step);
  12649. GGML_ASSERT(ggml_nelements(dst) == steps);
  12650. for (int64_t i = ith; i < steps; i+= nth) {
  12651. float value = start + step * i;
  12652. ((float *)dst->data)[i] = value;
  12653. }
  12654. }
  12655. static void ggml_compute_forward_arange(
  12656. const struct ggml_compute_params * params,
  12657. struct ggml_tensor * dst) {
  12658. switch (dst->type) {
  12659. case GGML_TYPE_F32:
  12660. {
  12661. ggml_compute_forward_arange_f32(params, dst);
  12662. } break;
  12663. default:
  12664. {
  12665. GGML_ABORT("fatal error");
  12666. }
  12667. }
  12668. }
  12669. static void ggml_compute_forward_timestep_embedding_f32(
  12670. const struct ggml_compute_params * params,
  12671. struct ggml_tensor * dst) {
  12672. const struct ggml_tensor * src0 = dst->src[0];
  12673. GGML_ASSERT(src0->nb[0] == sizeof(float));
  12674. const int ith = params->ith;
  12675. const int nth = params->nth;
  12676. GGML_TENSOR_UNARY_OP_LOCALS
  12677. const int dim = ggml_get_op_params_i32(dst, 0);
  12678. const int max_period = ggml_get_op_params_i32(dst, 1);
  12679. int half = dim / 2;
  12680. for (int64_t i = 0; i < ne00; i++) {
  12681. float * embed_data = (float *)((char *) dst->data + i*nb1);
  12682. for (int64_t j = ith; j < half; j += nth) {
  12683. float timestep = ((float *)src0->data)[i];
  12684. float freq = (float)expf(-logf(max_period) * j / half);
  12685. float arg = timestep * freq;
  12686. embed_data[j] = cosf(arg);
  12687. embed_data[j + half] = sinf(arg);
  12688. }
  12689. if (dim % 2 != 0 && ith == 0) {
  12690. embed_data[dim] = 0.f;
  12691. }
  12692. }
  12693. }
  12694. static void ggml_compute_forward_timestep_embedding(
  12695. const struct ggml_compute_params * params,
  12696. struct ggml_tensor * dst) {
  12697. const struct ggml_tensor * src0 = dst->src[0];
  12698. switch (src0->type) {
  12699. case GGML_TYPE_F32:
  12700. {
  12701. ggml_compute_forward_timestep_embedding_f32(params, dst);
  12702. } break;
  12703. default:
  12704. {
  12705. GGML_ABORT("fatal error");
  12706. }
  12707. }
  12708. }
  12709. // ggml_compute_forward_argsort
  12710. static void ggml_compute_forward_argsort_f32(
  12711. const struct ggml_compute_params * params,
  12712. struct ggml_tensor * dst) {
  12713. const struct ggml_tensor * src0 = dst->src[0];
  12714. GGML_TENSOR_UNARY_OP_LOCALS
  12715. GGML_ASSERT(nb0 == sizeof(float));
  12716. const int ith = params->ith;
  12717. const int nth = params->nth;
  12718. const int64_t nr = ggml_nrows(src0);
  12719. enum ggml_sort_order order = (enum ggml_sort_order) ggml_get_op_params_i32(dst, 0);
  12720. for (int64_t i = ith; i < nr; i += nth) {
  12721. int32_t * dst_data = (int32_t *)((char *) dst->data + i*nb1);
  12722. const float * src_data = (float *)((char *) src0->data + i*nb01);
  12723. for (int64_t j = 0; j < ne0; j++) {
  12724. dst_data[j] = j;
  12725. }
  12726. // C doesn't have a functional sort, so we do a bubble sort instead
  12727. for (int64_t j = 0; j < ne0; j++) {
  12728. for (int64_t k = j + 1; k < ne0; k++) {
  12729. if ((order == GGML_SORT_ORDER_ASC && src_data[dst_data[j]] > src_data[dst_data[k]]) ||
  12730. (order == GGML_SORT_ORDER_DESC && src_data[dst_data[j]] < src_data[dst_data[k]])) {
  12731. int32_t tmp = dst_data[j];
  12732. dst_data[j] = dst_data[k];
  12733. dst_data[k] = tmp;
  12734. }
  12735. }
  12736. }
  12737. }
  12738. }
  12739. static void ggml_compute_forward_argsort(
  12740. const struct ggml_compute_params * params,
  12741. struct ggml_tensor * dst) {
  12742. const struct ggml_tensor * src0 = dst->src[0];
  12743. switch (src0->type) {
  12744. case GGML_TYPE_F32:
  12745. {
  12746. ggml_compute_forward_argsort_f32(params, dst);
  12747. } break;
  12748. default:
  12749. {
  12750. GGML_ABORT("fatal error");
  12751. }
  12752. }
  12753. }
  12754. // ggml_compute_forward_flash_attn_ext
  12755. static void ggml_compute_forward_flash_attn_ext_f16(
  12756. const struct ggml_compute_params * params,
  12757. const struct ggml_tensor * q,
  12758. const struct ggml_tensor * k,
  12759. const struct ggml_tensor * v,
  12760. const struct ggml_tensor * mask,
  12761. struct ggml_tensor * dst) {
  12762. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  12763. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  12764. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  12765. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  12766. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  12767. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  12768. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  12769. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  12770. const int ith = params->ith;
  12771. const int nth = params->nth;
  12772. const int64_t D = neq0;
  12773. const int64_t N = neq1;
  12774. GGML_ASSERT(ne0 == D);
  12775. GGML_ASSERT(ne2 == N);
  12776. // input tensor rows must be contiguous
  12777. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  12778. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  12779. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  12780. GGML_ASSERT(neq0 == D);
  12781. GGML_ASSERT(nek0 == D);
  12782. GGML_ASSERT(nev0 == D);
  12783. GGML_ASSERT(neq1 == N);
  12784. GGML_ASSERT(nev0 == D);
  12785. // dst cannot be transposed or permuted
  12786. GGML_ASSERT(nb0 == sizeof(float));
  12787. GGML_ASSERT(nb0 <= nb1);
  12788. GGML_ASSERT(nb1 <= nb2);
  12789. GGML_ASSERT(nb2 <= nb3);
  12790. // broadcast factors
  12791. const int64_t rk2 = neq2/nek2;
  12792. const int64_t rk3 = neq3/nek3;
  12793. const int64_t rv2 = neq2/nev2;
  12794. const int64_t rv3 = neq3/nev3;
  12795. // parallelize by q rows using ggml_vec_dot_f32
  12796. // total rows in q
  12797. const int nr = neq1*neq2*neq3;
  12798. // rows per thread
  12799. const int dr = (nr + nth - 1)/nth;
  12800. // row range for this thread
  12801. const int ir0 = dr*ith;
  12802. const int ir1 = MIN(ir0 + dr, nr);
  12803. float scale = 1.0f;
  12804. float max_bias = 0.0f;
  12805. float logit_softcap = 0.0f;
  12806. memcpy(&scale, (float *) dst->op_params + 0, sizeof(float));
  12807. memcpy(&max_bias, (float *) dst->op_params + 1, sizeof(float));
  12808. memcpy(&logit_softcap, (float *) dst->op_params + 2, sizeof(float));
  12809. if (logit_softcap != 0) {
  12810. scale /= logit_softcap;
  12811. }
  12812. const uint32_t n_head = neq2;
  12813. const uint32_t n_head_log2 = 1u << (uint32_t) floor(log2(n_head));
  12814. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  12815. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  12816. enum ggml_type const k_vec_dot_type = type_traits[k->type].vec_dot_type;
  12817. ggml_from_float_t const q_to_vec_dot = type_traits[k_vec_dot_type].from_float;
  12818. ggml_vec_dot_t const kq_vec_dot = type_traits[k->type].vec_dot;
  12819. ggml_to_float_t const v_to_float = type_traits[v->type].to_float;
  12820. // loop over n_batch and n_head
  12821. for (int ir = ir0; ir < ir1; ++ir) {
  12822. // q indices
  12823. const int iq3 = ir/(neq2*neq1);
  12824. const int iq2 = (ir - iq3*neq2*neq1)/neq1;
  12825. const int iq1 = (ir - iq3*neq2*neq1 - iq2*neq1);
  12826. const uint32_t h = iq2; // head index
  12827. 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;
  12828. float S = 0.0f; // sum
  12829. float M = -INFINITY; // maximum KQ value
  12830. float * VKQ32 = (float *) params->wdata + ith*(3*D + CACHE_LINE_SIZE_F32); // FP32 VKQ accumulator
  12831. float * V32 = (VKQ32 + 1*D); // (temporary) FP32 V buffer
  12832. ggml_fp16_t * VKQ16 = (ggml_fp16_t *) (VKQ32 + 1*D); // (temporary) FP16 VKQ accumulator
  12833. ggml_fp16_t * Q_q = (ggml_fp16_t *) (VKQ32 + 2*D); // (temporary) buffer for Q converted to quantized/FP16
  12834. if (v->type == GGML_TYPE_F16) {
  12835. memset(VKQ16, 0, D*sizeof(ggml_fp16_t));
  12836. } else {
  12837. memset(VKQ32, 0, D*sizeof(float));
  12838. }
  12839. const ggml_fp16_t * mp = mask ? (ggml_fp16_t *)((char *) mask->data + iq1*mask->nb[1]) : NULL;
  12840. // k indices
  12841. const int ik3 = iq3 / rk3;
  12842. const int ik2 = iq2 / rk2;
  12843. // v indices
  12844. const int iv3 = iq3 / rv3;
  12845. const int iv2 = iq2 / rv2;
  12846. const float * pq = (const float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3));
  12847. q_to_vec_dot(pq, Q_q, D);
  12848. // online softmax / attention
  12849. // loop over n_kv and n_head_kv
  12850. // ref: https://arxiv.org/pdf/2112.05682.pdf
  12851. for (int64_t ic = 0; ic < nek1; ++ic) {
  12852. const float mv = mp ? slope*GGML_FP16_TO_FP32(mp[ic]) : 0.0f;
  12853. if (mv == -INFINITY) {
  12854. continue;
  12855. }
  12856. float s; // KQ value
  12857. const char * k_data = (const char *) k->data + ( ic*nbk1 + ik2*nbk2 + ik3*nbk3);
  12858. kq_vec_dot(D, &s, 0, k_data, 0, Q_q, 0, 1);
  12859. s = s*scale; // scale KQ value
  12860. if (logit_softcap != 0.0f) {
  12861. s = logit_softcap*tanhf(s);
  12862. }
  12863. s += mv; // apply mask
  12864. const float Mold = M;
  12865. float ms = 1.0f; // upon new higher max val, scale VKQ and KQ sum with this value
  12866. float vs = 1.0f; // post-softmax KQ value, expf(s - M)
  12867. const char * v_data = ((const char *) v->data + (ic*nbv1 + iv2*nbv2 + iv3*nbv3));
  12868. if (v->type == GGML_TYPE_F16) {
  12869. if (s > M) {
  12870. // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f
  12871. M = s;
  12872. ms = expf(Mold - M);
  12873. // V = V*expf(Mold - M)
  12874. ggml_vec_scale_f16(D, VKQ16, ms);
  12875. } else {
  12876. // no new maximum, ms == 1.0f, vs != 1.0f
  12877. vs = expf(s - M);
  12878. }
  12879. // V += v*expf(s - M)
  12880. ggml_vec_mad_f16(D, VKQ16, (const ggml_fp16_t *) v_data, vs);
  12881. } else {
  12882. if (s > M) {
  12883. // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f
  12884. M = s;
  12885. ms = expf(Mold - M);
  12886. // V = V*expf(Mold - M)
  12887. ggml_vec_scale_f32(D, VKQ32, ms);
  12888. } else {
  12889. // no new maximum, ms == 1.0f, vs != 1.0f
  12890. vs = expf(s - M);
  12891. }
  12892. v_to_float(v_data, V32, D);
  12893. // V += v*expf(s - M)
  12894. ggml_vec_mad_f32(D, VKQ32, V32, vs);
  12895. }
  12896. S = S*ms + vs; // scale and increment sum with partial sum
  12897. }
  12898. if (v->type == GGML_TYPE_F16) {
  12899. for (int64_t d = 0; d < D; ++d) {
  12900. VKQ32[d] = GGML_FP16_TO_FP32(VKQ16[d]);
  12901. }
  12902. }
  12903. // V /= S
  12904. const float S_inv = 1.0f/S;
  12905. ggml_vec_scale_f32(D, VKQ32, S_inv);
  12906. // dst indices
  12907. const int i1 = iq1;
  12908. const int i2 = iq2;
  12909. const int i3 = iq3;
  12910. // original
  12911. //memcpy((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb3), V, nev0*sizeof(float));
  12912. // permute(0, 2, 1, 3)
  12913. memcpy((char *) dst->data + (i3*ne2*ne1 + i2 + i1*ne1)*nb1, VKQ32, nb1);
  12914. }
  12915. }
  12916. static void ggml_compute_forward_flash_attn_ext(
  12917. const struct ggml_compute_params * params,
  12918. const struct ggml_tensor * q,
  12919. const struct ggml_tensor * k,
  12920. const struct ggml_tensor * v,
  12921. const struct ggml_tensor * mask,
  12922. struct ggml_tensor * dst) {
  12923. switch (dst->op_params[3]) {
  12924. case GGML_PREC_DEFAULT:
  12925. case GGML_PREC_F32:
  12926. {
  12927. // uses F32 accumulators
  12928. ggml_compute_forward_flash_attn_ext_f16(params, q, k, v, mask, dst);
  12929. } break;
  12930. default:
  12931. {
  12932. GGML_ABORT("fatal error");
  12933. }
  12934. }
  12935. }
  12936. // ggml_compute_forward_flash_attn_back
  12937. static void ggml_compute_forward_flash_attn_back_f32(
  12938. const struct ggml_compute_params * params,
  12939. const bool masked,
  12940. struct ggml_tensor * dst) {
  12941. const struct ggml_tensor * q = dst->src[0];
  12942. const struct ggml_tensor * k = dst->src[1];
  12943. const struct ggml_tensor * v = dst->src[2];
  12944. const struct ggml_tensor * d = dst->src[3];
  12945. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  12946. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  12947. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  12948. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  12949. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  12950. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  12951. GGML_TENSOR_LOCALS(int64_t, ned, d, ne)
  12952. GGML_TENSOR_LOCALS(size_t, nbd, d, nb)
  12953. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  12954. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  12955. const int ith = params->ith;
  12956. const int nth = params->nth;
  12957. const int64_t D = neq0;
  12958. const int64_t N = neq1;
  12959. const int64_t P = nek1 - N;
  12960. const int64_t M = P + N;
  12961. const int Mup = ggml_up(M, GGML_SOFT_MAX_UNROLL);
  12962. const int mxDM = MAX(D, Mup);
  12963. // GGML_ASSERT(ne0 == D);
  12964. // GGML_ASSERT(ne1 == N);
  12965. GGML_ASSERT(P >= 0);
  12966. GGML_ASSERT(nbq0 == sizeof(float));
  12967. GGML_ASSERT(nbk0 == sizeof(float));
  12968. GGML_ASSERT(nbv0 == sizeof(float));
  12969. GGML_ASSERT(neq0 == D);
  12970. GGML_ASSERT(nek0 == D);
  12971. GGML_ASSERT(nev1 == D);
  12972. GGML_ASSERT(ned0 == D);
  12973. GGML_ASSERT(neq1 == N);
  12974. GGML_ASSERT(nek1 == N + P);
  12975. GGML_ASSERT(nev1 == D);
  12976. GGML_ASSERT(ned1 == N);
  12977. // dst cannot be transposed or permuted
  12978. GGML_ASSERT(nb0 == sizeof(float));
  12979. GGML_ASSERT(nb0 <= nb1);
  12980. GGML_ASSERT(nb1 <= nb2);
  12981. GGML_ASSERT(nb2 <= nb3);
  12982. if (ith == 0) {
  12983. memset(dst->data, 0, nb0*ne0*ne1*ne2*ne3);
  12984. }
  12985. ggml_barrier(params->threadpool);
  12986. const int64_t elem_q = ggml_nelements(q);
  12987. const int64_t elem_k = ggml_nelements(k);
  12988. enum ggml_type result_type = dst->type;
  12989. GGML_ASSERT(ggml_blck_size(result_type) == 1);
  12990. const size_t tsize = ggml_type_size(result_type);
  12991. const size_t offs_q = 0;
  12992. const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
  12993. const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
  12994. void * grad_q = (char *) dst->data;
  12995. void * grad_k = (char *) dst->data + offs_k;
  12996. void * grad_v = (char *) dst->data + offs_v;
  12997. const size_t nbgq1 = nb0*neq0;
  12998. const size_t nbgq2 = nb0*neq0*neq1;
  12999. const size_t nbgq3 = nb0*neq0*neq1*neq2;
  13000. const size_t nbgk1 = nb0*nek0;
  13001. const size_t nbgk2 = nb0*nek0*nek1;
  13002. const size_t nbgk3 = nb0*nek0*nek1*neq2;
  13003. const size_t nbgv1 = nb0*nev0;
  13004. const size_t nbgv2 = nb0*nev0*nev1;
  13005. const size_t nbgv3 = nb0*nev0*nev1*neq2;
  13006. // parallelize by k rows using ggml_vec_dot_f32
  13007. // total rows in k
  13008. const int nr = nek2*nek3;
  13009. // rows per thread
  13010. const int dr = (nr + nth - 1)/nth;
  13011. // row range for this thread
  13012. const int ir0 = dr*ith;
  13013. const int ir1 = MIN(ir0 + dr, nr);
  13014. const float scale = 1.0f/sqrtf(D);
  13015. //printf("P=%d N=%d D=%d ir0=%d ir1=%d scale = %f\n", P, N, D, ir0, ir1, scale);
  13016. // how often k2 (and v2) is repeated in q2
  13017. int nrep = neq2/nek2;
  13018. for (int ir = ir0; ir < ir1; ++ir) {
  13019. // q indices
  13020. const int ik3 = ir/(nek2);
  13021. const int ik2 = ir - ik3*nek2;
  13022. const int iq3 = ik3;
  13023. const int id3 = ik3;
  13024. const int iv3 = ik3;
  13025. const int iv2 = ik2;
  13026. for (int irep = 0; irep < nrep; ++irep) {
  13027. const int iq2 = ik2 + irep*nek2;
  13028. const int id2 = iq2;
  13029. // (ik2 + irep*nek2) % nek2 == ik2
  13030. for (int iq1 = 0; iq1 < neq1; ++iq1) {
  13031. const int id1 = iq1;
  13032. // not sure about CACHE_LINE_SIZE_F32..
  13033. // - maybe it must not be multiplied by 2 and excluded from .. in SM 1*(..) offset?
  13034. float * S = (float *) params->wdata + ith*2*(mxDM + CACHE_LINE_SIZE_F32) + 0*(mxDM+CACHE_LINE_SIZE_F32);
  13035. float * SM = (float *) params->wdata + ith*2*(mxDM + CACHE_LINE_SIZE_F32) + 1*(mxDM+CACHE_LINE_SIZE_F32);
  13036. for (int i = M; i < Mup; ++i) {
  13037. S[i] = -INFINITY;
  13038. }
  13039. const int64_t masked_begin = masked ? (P + iq1 + 1) : M;
  13040. for (int64_t ic = 0; ic < masked_begin; ++ic) {
  13041. // k indices
  13042. const int ik1 = ic;
  13043. // S indices
  13044. const int i1 = ik1;
  13045. ggml_vec_dot_f32(neq0,
  13046. S + i1, 0,
  13047. (float *) ((char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3)), 0,
  13048. (float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)), 0, 1);
  13049. }
  13050. // scale
  13051. ggml_vec_scale_f32(masked_begin, S, scale);
  13052. for (int64_t i = masked_begin; i < M; i++) {
  13053. S[i] = -INFINITY;
  13054. }
  13055. // softmax
  13056. // exclude known -INF S[..] values from max and loop
  13057. // dont forget to set their SM values to zero
  13058. {
  13059. float max = -INFINITY;
  13060. ggml_vec_max_f32(masked_begin, &max, S);
  13061. ggml_float sum = 0.0;
  13062. {
  13063. #ifdef GGML_SOFT_MAX_ACCELERATE
  13064. max = -max;
  13065. vDSP_vsadd(SM, 1, &max, SM, 1, Mup);
  13066. vvexpf(SM, SM, &Mup);
  13067. ggml_vec_sum_f32(Mup, &sum, SM);
  13068. #else
  13069. sum = ggml_vec_soft_max_f32(Mup, SM, S, max);
  13070. #endif
  13071. }
  13072. assert(sum > 0.0);
  13073. sum = 1.0/sum;
  13074. ggml_vec_scale_f32(masked_begin, SM, sum);
  13075. }
  13076. // step-by-step explanation
  13077. {
  13078. // forward-process shape grads from backward process
  13079. // parallel_for ik2,ik3:
  13080. // for irep:
  13081. // iq2 = ik2 + irep*nek2
  13082. // k[:D,:M,:,:] [D,M,:,:] grad[k][:D,:M,ik2,ik3] += grad[kcur]
  13083. // q[:D,:N,:,:] [D,N,:,:] grad[q][:D,iq1,iq2,iq3] += grad[qcur]
  13084. // v[:M,:D,:,:] [M,D,:,:] grad[v][:M,:D,iv2,iv3] += grad[vcur]
  13085. // for iq1:
  13086. // kcur = k[:D,:M,ik2,ik3] [D,M,1,1] grad[kcur] = grad[S1].T @ qcur
  13087. // qcur = q[:D,iq1,iq2,iq3] [D,1,1,1] grad[qcur] = grad[S1] @ kcur
  13088. // vcur = v[:M,:D,iv2,iv3] [M,D,1,1] grad[vcur] = grad[S5].T @ S4
  13089. // S0 = -Inf [D,1,1,1]
  13090. // ~S1[i] = dot(kcur[:D,i], qcur)
  13091. // S1 = qcur @ kcur.T [M,1,1,1] grad[S1] = grad[S2] * scale
  13092. // S2 = S1 * scale [M,1,1,1] grad[S2] = diag_mask_zero(grad[S3], P)
  13093. // S3 = diag_mask_inf(S2, P) [M,1,1,1] grad[S3] = S4 * (grad[S4] - dot(S4, grad[S4]))
  13094. // S4 = softmax(S3) [M,1,1,1] grad[S4] = grad[S5] @ vcur
  13095. // ~S5[i] = dot(vcur[:,i], S4)
  13096. // S5 = S4 @ vcur.T [D,1,1,1] grad[S5] = d[:D,id1,id2,id3]
  13097. // ~dst[i,iq1,iq2,iq3] = S5[i] ^
  13098. // dst[:D,iq1,iq2,iq3] = S5 | grad[dst[:D,iq1,iq2,iq3]] = d[:D,id1,id2,id3]
  13099. // dst backward-/ grad[dst] = d
  13100. //
  13101. // output gradients with their dependencies:
  13102. //
  13103. // grad[kcur] = grad[S1].T @ qcur
  13104. // grad[S1] = diag_mask_zero(grad[S3], P) * scale
  13105. // grad[S3] = S4 * (grad[S4] - dot(S4, grad[S4]))
  13106. // grad[S4] = grad[S5] @ vcur
  13107. // grad[S4] = d[:D,id1,id2,id3] @ vcur
  13108. // grad[qcur] = grad[S1] @ kcur
  13109. // grad[vcur] = grad[S5].T @ S4
  13110. // grad[vcur] = d[:D,id1,id2,id3].T @ S4
  13111. //
  13112. // in post-order:
  13113. //
  13114. // S1 = qcur @ kcur.T
  13115. // S2 = S1 * scale
  13116. // S3 = diag_mask_inf(S2, P)
  13117. // S4 = softmax(S3)
  13118. // grad[S4] = d[:D,id1,id2,id3] @ vcur
  13119. // grad[S3] = S4 * (grad[S4] - dot(S4, grad[S4]))
  13120. // grad[S1] = diag_mask_zero(grad[S3], P) * scale
  13121. // grad[qcur] = grad[S1] @ kcur
  13122. // grad[kcur] = grad[S1].T @ qcur
  13123. // grad[vcur] = d[:D,id1,id2,id3].T @ S4
  13124. //
  13125. // using less variables (SM=S4):
  13126. //
  13127. // S = diag_mask_inf(qcur @ kcur.T * scale, P)
  13128. // SM = softmax(S)
  13129. // S = d[:D,iq1,iq2,iq3] @ vcur
  13130. // dot_SM_gradSM = dot(SM, S)
  13131. // S = SM * (S - dot(SM, S))
  13132. // S = diag_mask_zero(S, P) * scale
  13133. //
  13134. // grad[q][:D,iq1,iq2,iq3] += S @ kcur
  13135. // grad[k][:D,:M,ik2,ik3] += S.T @ qcur
  13136. // grad[v][:M,:D,iv2,iv3] += d[:D,id1,id2,id3].T @ SM
  13137. }
  13138. // S = gradSM = d[:D,id1,id2,id3] @ vcur[:,:,iv2,iv3]
  13139. // S = d[:D,id1,id2,id3] @ vcur[:,:,iv2,iv3]
  13140. // for ic:
  13141. // S[:M] += vcur[:M,ic,iv2,iv3] * d[ic,id1,id2,id3]
  13142. // exclude known future zero S[..] values from operation
  13143. ggml_vec_set_f32(masked_begin, S, 0);
  13144. for (int64_t ic = 0; ic < D; ++ic) {
  13145. ggml_vec_mad_f32(masked_begin,
  13146. S,
  13147. (float *) ((char *) v->data + ( ic*nbv1 + iv2*nbv2 + iv3*nbv3)),
  13148. *(float *) ((char *) d->data + (ic*nbd0 + id1*nbd1 + id2*nbd2 + id3*nbd3)));
  13149. }
  13150. // S = SM * (S - dot(SM, S))
  13151. float dot_SM_gradSM = 0;
  13152. ggml_vec_dot_f32 (masked_begin, &dot_SM_gradSM, 0, SM, 0, S, 0, 1);
  13153. ggml_vec_acc1_f32(M, S, -dot_SM_gradSM);
  13154. ggml_vec_mul_f32 (masked_begin, S, S, SM);
  13155. // S = diag_mask_zero(S, P) * scale
  13156. // already done by above ggml_vec_set_f32
  13157. // exclude known zero S[..] values from operation
  13158. ggml_vec_scale_f32(masked_begin, S, scale);
  13159. // S shape [M,1]
  13160. // SM shape [M,1]
  13161. // kcur shape [D,M]
  13162. // qcur shape [D,1]
  13163. // vcur shape [M,D]
  13164. // grad[q][:D,iq1,iq2,iq3] += S @ kcur
  13165. // grad[q][:D,iq1,iq2,iq3] += shape[M,1] @ shape[D,M]
  13166. // for ic:
  13167. // grad[q][:D,iq1,iq2,iq3] += S[ic] * kcur[:D,ic,ik2,ik3]
  13168. // exclude known zero S[..] values from loop
  13169. for (int64_t ic = 0; ic < masked_begin; ++ic) {
  13170. ggml_vec_mad_f32(D,
  13171. (float *) ((char *) grad_q + (iq1*nbgq1 + iq2*nbgq2 + iq3*nbgq3)),
  13172. (float *) ((char *) k->data + (ic*nbk1 + ik2*nbk2 + ik3*nbk3)),
  13173. S[ic]);
  13174. }
  13175. // grad[k][:D,:M,iq2,iq3] += S.T @ qcur
  13176. // for ic:
  13177. // grad[k][:D,ic,iq2,iq3] += S.T[0,ic] * qcur[:D,0]
  13178. // grad[k][:D,ic,iq2,iq3] += S[ic] * qcur[:D,0]
  13179. // exclude known zero S[..] values from loop
  13180. for (int64_t ic = 0; ic < masked_begin; ++ic) {
  13181. ggml_vec_mad_f32(D,
  13182. (float *) ((char *) grad_k + (ic*nbgk1 + ik2*nbgk2 + ik3*nbgk3)),
  13183. (float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)),
  13184. S[ic]);
  13185. }
  13186. // grad[v][:M,:D,iv2,iv3] += d[:D,id1,id2,id3].T @ SM
  13187. // for ic:
  13188. // grad[v][:M,ic,iv2,iv3] += d[:D,id1,id2,id3].T[0,ic] * SM[:M]
  13189. // grad[v][:M,ic,iv2,iv3] += d[ic,id1,id2,id3] * SM[:M]
  13190. // exclude known zero SM[..] values from mad
  13191. for (int64_t ic = 0; ic < D; ++ic) {
  13192. ggml_vec_mad_f32(masked_begin,
  13193. (float *) ((char *) grad_v + ( ic*nbgv1 + iv2*nbgv2 + iv3*nbgv3)),
  13194. SM,
  13195. *(float *) ((char *) d->data + (ic*nbd0 + id1*nbd1 + id2*nbd2 + id3*nbd3)));
  13196. }
  13197. }
  13198. }
  13199. }
  13200. }
  13201. static void ggml_compute_forward_flash_attn_back(
  13202. const struct ggml_compute_params * params,
  13203. const bool masked,
  13204. struct ggml_tensor * dst) {
  13205. const struct ggml_tensor * q = dst->src[0];
  13206. switch (q->type) {
  13207. case GGML_TYPE_F32:
  13208. {
  13209. ggml_compute_forward_flash_attn_back_f32(params, masked, dst);
  13210. } break;
  13211. default:
  13212. {
  13213. GGML_ABORT("fatal error");
  13214. }
  13215. }
  13216. }
  13217. // ggml_compute_forward_ssm_conv
  13218. static void ggml_compute_forward_ssm_conv_f32(
  13219. const struct ggml_compute_params * params,
  13220. struct ggml_tensor * dst) {
  13221. const struct ggml_tensor * src0 = dst->src[0]; // conv_x
  13222. const struct ggml_tensor * src1 = dst->src[1]; // conv1d.weight
  13223. const int ith = params->ith;
  13224. const int nth = params->nth;
  13225. const int nc = src1->ne[0]; // d_conv
  13226. const int ncs = src0->ne[0]; // d_conv - 1 + n_t
  13227. const int nr = src0->ne[1]; // d_inner
  13228. const int n_t = dst->ne[1]; // tokens per sequence
  13229. const int n_s = dst->ne[2]; // number of sequences in the batch
  13230. GGML_ASSERT( dst->ne[0] == nr);
  13231. GGML_ASSERT(src0->nb[0] == sizeof(float));
  13232. GGML_ASSERT(src1->nb[0] == sizeof(float));
  13233. GGML_ASSERT(src0->nb[1] == src0->ne[0]*sizeof(float));
  13234. // rows per thread
  13235. const int dr = (nr + nth - 1)/nth;
  13236. // row range for this thread
  13237. const int ir0 = dr*ith;
  13238. const int ir1 = MIN(ir0 + dr, nr);
  13239. const int ir = ir1 - ir0;
  13240. for (int i3 = 0; i3 < n_s; ++i3) {
  13241. for (int i2 = 0; i2 < n_t; ++i2) {
  13242. // {d_conv - 1 + n_t, d_inner, n_seqs}
  13243. // sliding window
  13244. 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}
  13245. const float * c = (const float *) ((const char *) src1->data + ir0*(src1->nb[1])); // {d_conv, d_inner}
  13246. float * x = (float *) ((char *) dst->data + ir0*(dst->nb[0]) + i2*(dst->nb[1]) + i3*(dst->nb[2])); // {d_inner, n_t, n_s}
  13247. // TODO: transpose the output for smaller strides for big batches?
  13248. // d_inner
  13249. for (int i1 = 0; i1 < ir; ++i1) {
  13250. // rowwise dot product
  13251. // NOTE: not using ggml_vec_dot_f32, because its sum is in double precision
  13252. float sumf = 0.0f;
  13253. // d_conv
  13254. for (int i0 = 0; i0 < nc; ++i0) {
  13255. sumf += s[i0 + i1*ncs] * c[i0 + i1*nc];
  13256. }
  13257. x[i1] = sumf;
  13258. }
  13259. }
  13260. }
  13261. }
  13262. static void ggml_compute_forward_ssm_conv(
  13263. const struct ggml_compute_params * params,
  13264. struct ggml_tensor * dst) {
  13265. switch (dst->src[0]->type) {
  13266. case GGML_TYPE_F32:
  13267. {
  13268. ggml_compute_forward_ssm_conv_f32(params, dst);
  13269. } break;
  13270. default:
  13271. {
  13272. GGML_ABORT("fatal error");
  13273. }
  13274. }
  13275. }
  13276. // ggml_compute_forward_ssm_scan
  13277. static void ggml_compute_forward_ssm_scan_f32(
  13278. const struct ggml_compute_params * params,
  13279. struct ggml_tensor * dst) {
  13280. const struct ggml_tensor * src0 = dst->src[0]; // s
  13281. const struct ggml_tensor * src1 = dst->src[1]; // x
  13282. const struct ggml_tensor * src2 = dst->src[2]; // dt
  13283. const struct ggml_tensor * src3 = dst->src[3]; // A
  13284. const struct ggml_tensor * src4 = dst->src[4]; // B
  13285. const struct ggml_tensor * src5 = dst->src[5]; // C
  13286. const int ith = params->ith;
  13287. const int nth = params->nth;
  13288. const int64_t nc = src0->ne[0]; // d_state
  13289. const int64_t nr = src0->ne[1]; // d_inner
  13290. const int64_t n_t = src1->ne[1]; // number of tokens per sequence
  13291. const int64_t n_s = src0->ne[2]; // number of sequences in the batch
  13292. GGML_ASSERT(ggml_nelements(src1) + ggml_nelements(src0) == ggml_nelements(dst));
  13293. GGML_ASSERT(src0->nb[0] == sizeof(float));
  13294. GGML_ASSERT(src1->nb[0] == sizeof(float));
  13295. GGML_ASSERT(src2->nb[0] == sizeof(float));
  13296. GGML_ASSERT(src3->nb[0] == sizeof(float));
  13297. GGML_ASSERT(src4->nb[0] == sizeof(float));
  13298. GGML_ASSERT(src5->nb[0] == sizeof(float));
  13299. // required for the dot product between s and C
  13300. GGML_ASSERT(src0->nb[1] == src0->ne[0]*sizeof(float));
  13301. // required for per-sequence offsets for states
  13302. GGML_ASSERT(src0->nb[2] == src0->ne[0]*src0->ne[1]*sizeof(float));
  13303. // required to get correct offset for state destination (i.e. src1->nb[3])
  13304. GGML_ASSERT(src1->nb[3] == src1->ne[0]*src1->ne[1]*src1->ne[2]*sizeof(float));
  13305. // rows per thread
  13306. const int dr = (nr + nth - 1)/nth;
  13307. // row range for this thread
  13308. const int ir0 = dr*ith;
  13309. const int ir1 = MIN(ir0 + dr, nr);
  13310. const int ir = ir1 - ir0;
  13311. for (int i3 = 0; i3 < n_s; ++i3) {
  13312. for (int i2 = 0; i2 < n_t; ++i2) {
  13313. const float * s0 = (const float *) ((const char *) src0->data + ir0*(src0->nb[1]) + i3*(src0->nb[2])); // {d_state, d_inner, n_s}
  13314. 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}
  13315. 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}
  13316. const float * A = (const float *) ((const char *) src3->data + ir0*(src3->nb[1])); // {d_state, d_inner}
  13317. const float * B = (const float *) ((const char *) src4->data + i2*(src4->nb[1]) + i3*(src4->nb[2])); // {d_state, n_t, n_s}
  13318. const float * C = (const float *) ((const char *) src5->data + i2*(src5->nb[1]) + i3*(src5->nb[2])); // {d_state, n_t, n_s}
  13319. float * y = ( float *) (( char *) dst->data + ir0*(src1->nb[0]) + i2*(src1->nb[1]) + i3*(src1->nb[2])); // {d_inner, n_t, n_s}
  13320. float * s = ( float *) (( char *) dst->data + ir0*(src0->nb[1]) + i3*(src0->nb[2]) + src1->nb[3]); // {d_state, d_inner, n_s}
  13321. // use the output as the source for the next token-wise iterations
  13322. if (i2 > 0) { s0 = s; }
  13323. // d_inner
  13324. for (int i1 = 0; i1 < ir; ++i1) {
  13325. // ref: https://github.com/state-spaces/mamba/blob/34076d664838588a3c97727b263478ab9f621a07/mamba_ssm/ops/triton/selective_state_update.py#L78
  13326. float dt_soft_plus = dt[i1] <= 20.0f ? log1pf(expf(dt[i1])) : dt[i1];
  13327. float x_dt = x[i1] * dt_soft_plus;
  13328. float sumf = 0.0f;
  13329. // d_state
  13330. for (int i0 = 0; i0 < nc; ++i0) {
  13331. int i = i0 + i1*nc;
  13332. // state = prev_state * dA + dB * x
  13333. float state = (s0[i] * expf(dt_soft_plus * A[i])) + (B[i0] * x_dt);
  13334. // y = rowwise_dotprod(state, C)
  13335. sumf += state * C[i0];
  13336. s[i] = state;
  13337. }
  13338. y[i1] = sumf;
  13339. }
  13340. }
  13341. }
  13342. }
  13343. static void ggml_compute_forward_ssm_scan(
  13344. const struct ggml_compute_params * params,
  13345. struct ggml_tensor * dst) {
  13346. switch (dst->src[0]->type) {
  13347. case GGML_TYPE_F32:
  13348. {
  13349. ggml_compute_forward_ssm_scan_f32(params, dst);
  13350. } break;
  13351. default:
  13352. {
  13353. GGML_ABORT("fatal error");
  13354. }
  13355. }
  13356. }
  13357. // ggml_compute_forward_win_part
  13358. static void ggml_compute_forward_win_part_f32(
  13359. const struct ggml_compute_params * params,
  13360. struct ggml_tensor * dst) {
  13361. UNUSED(params);
  13362. const struct ggml_tensor * src0 = dst->src[0];
  13363. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  13364. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  13365. const int32_t nep0 = ((const int32_t *)(dst->op_params))[0];
  13366. const int32_t nep1 = ((const int32_t *)(dst->op_params))[1];
  13367. const int32_t w = ((const int32_t *)(dst->op_params))[2];
  13368. assert(ne00 == ne0);
  13369. assert(ne3 == nep0*nep1);
  13370. // TODO: optimize / multi-thread
  13371. for (int py = 0; py < nep1; ++py) {
  13372. for (int px = 0; px < nep0; ++px) {
  13373. const int64_t i3 = py*nep0 + px;
  13374. for (int64_t i2 = 0; i2 < ne2; ++i2) {
  13375. for (int64_t i1 = 0; i1 < ne1; ++i1) {
  13376. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  13377. const int64_t i02 = py*w + i2;
  13378. const int64_t i01 = px*w + i1;
  13379. const int64_t i00 = i0;
  13380. const int64_t i = i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0 + i0;
  13381. const int64_t j = i02*ne01*ne00 + i01*ne00 + i00;
  13382. if (py*w + i2 >= ne02 || px*w + i1 >= ne01) {
  13383. ((float *) dst->data)[i] = 0.0f;
  13384. } else {
  13385. ((float *) dst->data)[i] = ((float *) src0->data)[j];
  13386. }
  13387. }
  13388. }
  13389. }
  13390. }
  13391. }
  13392. }
  13393. static void ggml_compute_forward_win_part(
  13394. const struct ggml_compute_params * params,
  13395. struct ggml_tensor * dst) {
  13396. const struct ggml_tensor * src0 = dst->src[0];
  13397. switch (src0->type) {
  13398. case GGML_TYPE_F32:
  13399. {
  13400. ggml_compute_forward_win_part_f32(params, dst);
  13401. } break;
  13402. default:
  13403. {
  13404. GGML_ABORT("fatal error");
  13405. }
  13406. }
  13407. }
  13408. // ggml_compute_forward_win_unpart
  13409. static void ggml_compute_forward_win_unpart_f32(
  13410. const struct ggml_compute_params * params,
  13411. struct ggml_tensor * dst) {
  13412. UNUSED(params);
  13413. const struct ggml_tensor * src0 = dst->src[0];
  13414. GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne)
  13415. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  13416. const int32_t w = ((const int32_t *)(dst->op_params))[0];
  13417. // padding
  13418. const int px = (w - ne1%w)%w;
  13419. //const int py = (w - ne2%w)%w;
  13420. const int npx = (px + ne1)/w;
  13421. //const int npy = (py + ne2)/w;
  13422. assert(ne0 == ne00);
  13423. // TODO: optimize / multi-thread
  13424. for (int64_t i2 = 0; i2 < ne2; ++i2) {
  13425. for (int64_t i1 = 0; i1 < ne1; ++i1) {
  13426. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  13427. const int ip2 = i2/w;
  13428. const int ip1 = i1/w;
  13429. const int64_t i02 = i2%w;
  13430. const int64_t i01 = i1%w;
  13431. const int64_t i00 = i0;
  13432. const int64_t i = (ip2*npx + ip1)*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00 + i00;
  13433. const int64_t j = i2*ne1*ne0 + i1*ne0 + i0;
  13434. ((float *) dst->data)[j] = ((float *) src0->data)[i];
  13435. }
  13436. }
  13437. }
  13438. }
  13439. static void ggml_compute_forward_win_unpart(
  13440. const struct ggml_compute_params * params,
  13441. struct ggml_tensor * dst) {
  13442. const struct ggml_tensor * src0 = dst->src[0];
  13443. switch (src0->type) {
  13444. case GGML_TYPE_F32:
  13445. {
  13446. ggml_compute_forward_win_unpart_f32(params, dst);
  13447. } break;
  13448. default:
  13449. {
  13450. GGML_ABORT("fatal error");
  13451. }
  13452. }
  13453. }
  13454. //gmml_compute_forward_unary
  13455. static void ggml_compute_forward_unary(
  13456. const struct ggml_compute_params * params,
  13457. struct ggml_tensor * dst) {
  13458. const enum ggml_unary_op op = ggml_get_unary_op(dst);
  13459. switch (op) {
  13460. case GGML_UNARY_OP_ABS:
  13461. {
  13462. ggml_compute_forward_abs(params, dst);
  13463. } break;
  13464. case GGML_UNARY_OP_SGN:
  13465. {
  13466. ggml_compute_forward_sgn(params, dst);
  13467. } break;
  13468. case GGML_UNARY_OP_NEG:
  13469. {
  13470. ggml_compute_forward_neg(params, dst);
  13471. } break;
  13472. case GGML_UNARY_OP_STEP:
  13473. {
  13474. ggml_compute_forward_step(params, dst);
  13475. } break;
  13476. case GGML_UNARY_OP_TANH:
  13477. {
  13478. ggml_compute_forward_tanh(params, dst);
  13479. } break;
  13480. case GGML_UNARY_OP_ELU:
  13481. {
  13482. ggml_compute_forward_elu(params, dst);
  13483. } break;
  13484. case GGML_UNARY_OP_RELU:
  13485. {
  13486. ggml_compute_forward_relu(params, dst);
  13487. } break;
  13488. case GGML_UNARY_OP_SIGMOID:
  13489. {
  13490. ggml_compute_forward_sigmoid(params, dst);
  13491. } break;
  13492. case GGML_UNARY_OP_GELU:
  13493. {
  13494. ggml_compute_forward_gelu(params, dst);
  13495. } break;
  13496. case GGML_UNARY_OP_GELU_QUICK:
  13497. {
  13498. ggml_compute_forward_gelu_quick(params, dst);
  13499. } break;
  13500. case GGML_UNARY_OP_SILU:
  13501. {
  13502. ggml_compute_forward_silu(params, dst);
  13503. } break;
  13504. case GGML_UNARY_OP_HARDSWISH:
  13505. {
  13506. ggml_compute_forward_hardswish(params, dst);
  13507. } break;
  13508. case GGML_UNARY_OP_HARDSIGMOID:
  13509. {
  13510. ggml_compute_forward_hardsigmoid(params, dst);
  13511. } break;
  13512. case GGML_UNARY_OP_EXP:
  13513. {
  13514. ggml_compute_forward_exp(params, dst);
  13515. } break;
  13516. default:
  13517. {
  13518. GGML_ABORT("fatal error");
  13519. }
  13520. }
  13521. }
  13522. // ggml_compute_forward_get_rel_pos
  13523. static void ggml_compute_forward_get_rel_pos_f16(
  13524. const struct ggml_compute_params * params,
  13525. struct ggml_tensor * dst) {
  13526. UNUSED(params);
  13527. const struct ggml_tensor * src0 = dst->src[0];
  13528. // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L292-L322
  13529. GGML_TENSOR_UNARY_OP_LOCALS
  13530. const int64_t w = ne1;
  13531. ggml_fp16_t * src0_data = (ggml_fp16_t *) src0->data;
  13532. ggml_fp16_t * dst_data = (ggml_fp16_t *) dst->data;
  13533. for (int64_t i2 = 0; i2 < ne2; ++i2) {
  13534. for (int64_t i1 = 0; i1 < ne1; ++i1) {
  13535. const int64_t pos = (w - i1 - 1) + i2;
  13536. for (int64_t i0 = 0; i0 < ne0; ++i0) {
  13537. dst_data[i2*ne1*ne0 + i1*ne0 + i0] = src0_data[pos*ne00 + i0];
  13538. }
  13539. }
  13540. }
  13541. }
  13542. static void ggml_compute_forward_get_rel_pos(
  13543. const struct ggml_compute_params * params,
  13544. struct ggml_tensor * dst) {
  13545. const struct ggml_tensor * src0 = dst->src[0];
  13546. switch (src0->type) {
  13547. case GGML_TYPE_F16:
  13548. case GGML_TYPE_BF16:
  13549. {
  13550. ggml_compute_forward_get_rel_pos_f16(params, dst);
  13551. } break;
  13552. default:
  13553. {
  13554. GGML_ABORT("fatal error");
  13555. }
  13556. }
  13557. }
  13558. // ggml_compute_forward_add_rel_pos
  13559. static void ggml_compute_forward_add_rel_pos_f32(
  13560. const struct ggml_compute_params * params,
  13561. struct ggml_tensor * dst) {
  13562. const struct ggml_tensor * src0 = dst->src[0];
  13563. const struct ggml_tensor * src1 = dst->src[1];
  13564. const struct ggml_tensor * src2 = dst->src[2];
  13565. const bool inplace = (bool) ((int32_t *) dst->op_params)[0];
  13566. if (!inplace) {
  13567. if (params->ith == 0) {
  13568. memcpy((char *) dst->data, (char *) src0->data, ggml_nbytes(dst));
  13569. }
  13570. ggml_barrier(params->threadpool);
  13571. }
  13572. // ref: https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/modeling/image_encoder.py#L357-L359
  13573. float * src1_data = (float *) src1->data;
  13574. float * src2_data = (float *) src2->data;
  13575. float * dst_data = (float *) dst->data;
  13576. const int64_t ne10 = src1->ne[0];
  13577. const int64_t ne11 = src1->ne[1];
  13578. const int64_t ne12 = src1->ne[2];
  13579. const int64_t ne13 = src1->ne[3];
  13580. const int ith = params->ith;
  13581. const int nth = params->nth;
  13582. // total patches in dst
  13583. const int np = ne13;
  13584. // patches per thread
  13585. const int dp = (np + nth - 1)/nth;
  13586. // patch range for this thread
  13587. const int ip0 = dp*ith;
  13588. const int ip1 = MIN(ip0 + dp, np);
  13589. for (int64_t i13 = ip0; i13 < ip1; ++i13) {
  13590. for (int64_t i12 = 0; i12 < ne12; ++i12) {
  13591. for (int64_t i11 = 0; i11 < ne11; ++i11) {
  13592. const int64_t jp1 = i13*ne12*ne11*ne10 + i12*ne11*ne10 + i11*ne10;
  13593. for (int64_t i10 = 0; i10 < ne10; ++i10) {
  13594. const int64_t jp0 = jp1 + i10;
  13595. const float src1_e = src1_data[jp0];
  13596. const float src2_e = src2_data[jp0];
  13597. const int64_t jdh = jp0 * ne10;
  13598. const int64_t jdw = jdh - (ne10 - 1) * i10;
  13599. for (int64_t j = 0; j < ne10; ++j) {
  13600. dst_data[jdh + j ] += src2_e;
  13601. dst_data[jdw + j*ne10] += src1_e;
  13602. }
  13603. }
  13604. }
  13605. }
  13606. }
  13607. }
  13608. static void ggml_compute_forward_add_rel_pos(
  13609. const struct ggml_compute_params * params,
  13610. struct ggml_tensor * dst) {
  13611. const struct ggml_tensor * src0 = dst->src[0];
  13612. switch (src0->type) {
  13613. case GGML_TYPE_F32:
  13614. {
  13615. ggml_compute_forward_add_rel_pos_f32(params, dst);
  13616. } break;
  13617. default:
  13618. {
  13619. GGML_ABORT("fatal error");
  13620. }
  13621. }
  13622. }
  13623. // ggml_compute_forward_rwkv_wkv
  13624. static void ggml_compute_forward_rwkv_wkv_f32(
  13625. const struct ggml_compute_params * params,
  13626. struct ggml_tensor * dst) {
  13627. const size_t T = dst->src[1]->ne[3];
  13628. const size_t C = dst->ne[0];
  13629. const size_t H = dst->src[1]->ne[2];
  13630. const size_t n_seqs = dst->src[5]->ne[1];
  13631. float * dst_data = (float *) dst->data;
  13632. float * state = ((float *) dst->data) + C * T;
  13633. if (params->ith != 0) {
  13634. return;
  13635. }
  13636. memset(dst_data, 0, T * C * sizeof(float));
  13637. float * k = (float *) dst->src[0]->data;
  13638. float * v = (float *) dst->src[1]->data;
  13639. float * r = (float *) dst->src[2]->data;
  13640. float * time_faaaa = (float *) dst->src[3]->data;
  13641. float * time_decay = (float *) dst->src[4]->data;
  13642. size_t t_stride = H * (C / H);
  13643. size_t h_stride = C / H;
  13644. size_t h_stride_2d = (C / H) * (C / H);
  13645. // basically fused operations:
  13646. // dst = r @ (time_faaaa * (k @ v) + state),
  13647. // state = time_decay * state + (k @ v),
  13648. // recursive through each token
  13649. for (size_t t = 0; t < T; t++) {
  13650. size_t t_offset = t * t_stride;
  13651. size_t state_offset = (C / H) * C * (t / (T / n_seqs));
  13652. float * state_cur = state + state_offset;
  13653. float * state_prev = t % (T / n_seqs) ? state_cur : (float*)dst->src[5]->data + state_offset;
  13654. for (size_t h = 0; h < H; h++) {
  13655. size_t h_offset = h * h_stride;
  13656. size_t t_h_offset = t_offset + h_offset;
  13657. size_t h_2d_offset = h * h_stride_2d;
  13658. for (size_t i = 0; i < C / H; i++) {
  13659. size_t t_h_i_offset = t_h_offset + i;
  13660. size_t h_i_offset = h_offset + i;
  13661. size_t h_2d_i_offset = h_2d_offset + i * h_stride;
  13662. float k_val = k[t_h_i_offset];
  13663. float r_val = r[t_h_i_offset];
  13664. float time_faaaa_val = time_faaaa[h_i_offset];
  13665. // RWKV v6: different time_decay for each token.
  13666. float time_decay_val = time_decay[t_h_i_offset];
  13667. for (size_t j = 0; j < C / H; j ++) {
  13668. size_t t_h_j_offset = t_h_offset + j;
  13669. size_t h_2d_i_j_offset = h_2d_i_offset + j;
  13670. float v_val = v[t_h_j_offset];
  13671. float kv_val = v_val * k_val;
  13672. float prev_state_val = state_prev[h_2d_i_j_offset];
  13673. float temp_val = kv_val * time_faaaa_val + prev_state_val;
  13674. dst_data[t_h_j_offset] += temp_val * r_val;
  13675. state_cur[h_2d_i_j_offset] = prev_state_val * time_decay_val + kv_val;
  13676. }
  13677. }
  13678. }
  13679. }
  13680. }
  13681. static void ggml_compute_forward_rwkv_wkv(
  13682. const struct ggml_compute_params * params,
  13683. struct ggml_tensor * dst) {
  13684. const struct ggml_tensor * src0 = dst->src[0];
  13685. switch (src0->type) {
  13686. case GGML_TYPE_F32:
  13687. {
  13688. ggml_compute_forward_rwkv_wkv_f32(params, dst);
  13689. } break;
  13690. default:
  13691. {
  13692. GGML_ABORT("fatal error");
  13693. }
  13694. }
  13695. }
  13696. // ggml_compute_forward_map_unary
  13697. static void ggml_compute_forward_map_unary_f32(
  13698. const struct ggml_compute_params * params,
  13699. struct ggml_tensor * dst,
  13700. const ggml_unary_op_f32_t fun) {
  13701. const struct ggml_tensor * src0 = dst->src[0];
  13702. if (params->ith != 0) {
  13703. return;
  13704. }
  13705. assert(ggml_is_contiguous_1(src0));
  13706. assert(ggml_is_contiguous_1(dst));
  13707. assert(ggml_are_same_shape(src0, dst));
  13708. const int n = ggml_nrows(src0);
  13709. const int nc = src0->ne[0];
  13710. for (int i = 0; i < n; i++) {
  13711. fun(nc,
  13712. (float *) ((char *) dst->data + i*( dst->nb[1])),
  13713. (float *) ((char *) src0->data + i*(src0->nb[1])));
  13714. }
  13715. }
  13716. static void ggml_compute_forward_map_unary(
  13717. const struct ggml_compute_params * params,
  13718. struct ggml_tensor * dst,
  13719. const ggml_unary_op_f32_t fun) {
  13720. const struct ggml_tensor * src0 = dst->src[0];
  13721. switch (src0->type) {
  13722. case GGML_TYPE_F32:
  13723. {
  13724. ggml_compute_forward_map_unary_f32(params, dst, fun);
  13725. } break;
  13726. default:
  13727. {
  13728. GGML_ABORT("fatal error");
  13729. }
  13730. }
  13731. }
  13732. // ggml_compute_forward_map_binary
  13733. static void ggml_compute_forward_map_binary_f32(
  13734. const struct ggml_compute_params * params,
  13735. struct ggml_tensor * dst,
  13736. const ggml_binary_op_f32_t fun) {
  13737. const struct ggml_tensor * src0 = dst->src[0];
  13738. const struct ggml_tensor * src1 = dst->src[1];
  13739. if (params->ith != 0) {
  13740. return;
  13741. }
  13742. assert(ggml_is_contiguous_1(src0));
  13743. assert(ggml_is_contiguous_1(src1));
  13744. assert(ggml_is_contiguous_1(dst));
  13745. assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  13746. const int n = ggml_nrows(src0);
  13747. const int nc = src0->ne[0];
  13748. for (int i = 0; i < n; i++) {
  13749. fun(nc,
  13750. (float *) ((char *) dst->data + i*( dst->nb[1])),
  13751. (float *) ((char *) src0->data + i*(src0->nb[1])),
  13752. (float *) ((char *) src1->data + i*(src1->nb[1])));
  13753. }
  13754. }
  13755. static void ggml_compute_forward_map_binary(
  13756. const struct ggml_compute_params * params,
  13757. struct ggml_tensor * dst,
  13758. const ggml_binary_op_f32_t fun) {
  13759. const struct ggml_tensor * src0 = dst->src[0];
  13760. switch (src0->type) {
  13761. case GGML_TYPE_F32:
  13762. {
  13763. ggml_compute_forward_map_binary_f32(params, dst, fun);
  13764. } break;
  13765. default:
  13766. {
  13767. GGML_ABORT("fatal error");
  13768. }
  13769. }
  13770. }
  13771. // ggml_compute_forward_map_custom1
  13772. static void ggml_compute_forward_map_custom1_f32(
  13773. const struct ggml_compute_params * params,
  13774. struct ggml_tensor * dst,
  13775. const ggml_custom1_op_f32_t fun) {
  13776. const struct ggml_tensor * a = dst->src[0];
  13777. if (params->ith != 0) {
  13778. return;
  13779. }
  13780. fun(dst, a);
  13781. }
  13782. // ggml_compute_forward_map_custom2
  13783. static void ggml_compute_forward_map_custom2_f32(
  13784. const struct ggml_compute_params * params,
  13785. struct ggml_tensor * dst,
  13786. const ggml_custom2_op_f32_t fun) {
  13787. const struct ggml_tensor * a = dst->src[0];
  13788. const struct ggml_tensor * b = dst->src[1];
  13789. if (params->ith != 0) {
  13790. return;
  13791. }
  13792. fun(dst, a, b);
  13793. }
  13794. // ggml_compute_forward_map_custom3
  13795. static void ggml_compute_forward_map_custom3_f32(
  13796. const struct ggml_compute_params * params,
  13797. struct ggml_tensor * dst,
  13798. const ggml_custom3_op_f32_t fun) {
  13799. const struct ggml_tensor * a = dst->src[0];
  13800. const struct ggml_tensor * b = dst->src[1];
  13801. const struct ggml_tensor * c = dst->src[1];
  13802. if (params->ith != 0) {
  13803. return;
  13804. }
  13805. fun(dst, a, b, c);
  13806. }
  13807. // ggml_compute_forward_map_custom1
  13808. static void ggml_compute_forward_map_custom1(
  13809. const struct ggml_compute_params * params,
  13810. struct ggml_tensor * dst) {
  13811. const struct ggml_tensor * a = dst->src[0];
  13812. struct ggml_map_custom1_op_params p;
  13813. memcpy(&p, dst->op_params, sizeof(p));
  13814. p.fun(dst, a, params->ith, params->nth, p.userdata);
  13815. }
  13816. // ggml_compute_forward_map_custom2
  13817. static void ggml_compute_forward_map_custom2(
  13818. const struct ggml_compute_params * params,
  13819. struct ggml_tensor * dst) {
  13820. const struct ggml_tensor * a = dst->src[0];
  13821. const struct ggml_tensor * b = dst->src[1];
  13822. struct ggml_map_custom2_op_params p;
  13823. memcpy(&p, dst->op_params, sizeof(p));
  13824. p.fun(dst, a, b, params->ith, params->nth, p.userdata);
  13825. }
  13826. // ggml_compute_forward_map_custom3
  13827. static void ggml_compute_forward_map_custom3(
  13828. const struct ggml_compute_params * params,
  13829. struct ggml_tensor * dst) {
  13830. const struct ggml_tensor * a = dst->src[0];
  13831. const struct ggml_tensor * b = dst->src[1];
  13832. const struct ggml_tensor * c = dst->src[2];
  13833. struct ggml_map_custom3_op_params p;
  13834. memcpy(&p, dst->op_params, sizeof(p));
  13835. p.fun(dst, a, b, c, params->ith, params->nth, p.userdata);
  13836. }
  13837. // ggml_compute_forward_cross_entropy_loss
  13838. static void ggml_compute_forward_cross_entropy_loss_f32(
  13839. const struct ggml_compute_params * params,
  13840. struct ggml_tensor * dst) {
  13841. const struct ggml_tensor * src0 = dst->src[0];
  13842. const struct ggml_tensor * src1 = dst->src[1];
  13843. GGML_ASSERT(ggml_is_contiguous(src0));
  13844. GGML_ASSERT(ggml_is_contiguous(src1));
  13845. GGML_ASSERT(ggml_is_scalar(dst));
  13846. GGML_ASSERT(ggml_are_same_shape(src0, src1));
  13847. const int ith = params->ith;
  13848. const int nth = params->nth;
  13849. float * sums = (float *) params->wdata;
  13850. // TODO: handle transposed/permuted matrices
  13851. const int nc = src0->ne[0];
  13852. const int nr = ggml_nrows(src0);
  13853. GGML_ASSERT(params->wsize >= sizeof(float) * (nth + nth * nc));
  13854. if (ith == 0) {
  13855. memset(sums, 0, sizeof(float) * (nth + nth * nc));
  13856. }
  13857. ggml_barrier(params->threadpool);
  13858. // rows per thread
  13859. const int dr = (nr + nth - 1)/nth;
  13860. // row range for this thread
  13861. const int ir0 = dr*ith;
  13862. const int ir1 = MIN(ir0 + dr, nr);
  13863. for (int i1 = ir0; i1 < ir1; i1++) {
  13864. float * s0 = (float *)((char *) src0->data + i1*src0->nb[1]);
  13865. float * s1 = (float *)((char *) src1->data + i1*src1->nb[1]);
  13866. float * st = ((float *) params->wdata) + nth + ith*nc;
  13867. #ifndef NDEBUG
  13868. for (int i = 0; i < nc; ++i) {
  13869. //printf("p[%d] = %f\n", i, p[i]);
  13870. assert(!isnan(s0[i]));
  13871. assert(!isnan(s1[i]));
  13872. }
  13873. #endif
  13874. float max = -INFINITY;
  13875. ggml_vec_max_f32(nc, &max, s0);
  13876. ggml_float sum = ggml_vec_log_soft_max_f32(nc, st, s0, max);
  13877. assert(sum >= 0.0);
  13878. ggml_vec_add1_f32(nc, st, st, -sum);
  13879. ggml_vec_mul_f32(nc, st, st, s1);
  13880. float st_sum = 0.0f;
  13881. ggml_vec_sum_f32(nc, &st_sum, st);
  13882. sums[ith] += st_sum;
  13883. #ifndef NDEBUG
  13884. for (int i = 0; i < nc; ++i) {
  13885. assert(!isnan(st[i]));
  13886. assert(!isinf(st[i]));
  13887. }
  13888. #endif
  13889. }
  13890. ggml_barrier(params->threadpool);
  13891. if (ith == 0) {
  13892. float * dp = (float *) dst->data;
  13893. ggml_vec_sum_f32(nth, dp, sums);
  13894. dp[0] *= -1.0f / (float) nr;
  13895. }
  13896. }
  13897. static void ggml_compute_forward_cross_entropy_loss(
  13898. const struct ggml_compute_params * params,
  13899. struct ggml_tensor * dst) {
  13900. const struct ggml_tensor * src0 = dst->src[0];
  13901. switch (src0->type) {
  13902. case GGML_TYPE_F32:
  13903. {
  13904. ggml_compute_forward_cross_entropy_loss_f32(params, dst);
  13905. } break;
  13906. default:
  13907. {
  13908. GGML_ABORT("fatal error");
  13909. }
  13910. }
  13911. }
  13912. // ggml_compute_forward_cross_entropy_loss_back
  13913. static void ggml_compute_forward_cross_entropy_loss_back_f32(
  13914. const struct ggml_compute_params * params,
  13915. struct ggml_tensor * dst) {
  13916. const struct ggml_tensor * src0 = dst->src[0];
  13917. const struct ggml_tensor * src1 = dst->src[1];
  13918. const struct ggml_tensor * opt0 = dst->src[2];
  13919. GGML_ASSERT(ggml_is_contiguous(dst));
  13920. GGML_ASSERT(ggml_is_contiguous(src0));
  13921. GGML_ASSERT(ggml_is_contiguous(src1));
  13922. GGML_ASSERT(ggml_is_contiguous(opt0));
  13923. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  13924. const int64_t ith = params->ith;
  13925. const int64_t nth = params->nth;
  13926. // TODO: handle transposed/permuted matrices
  13927. const int64_t nc = src0->ne[0];
  13928. const int64_t nr = ggml_nrows(src0);
  13929. // rows per thread
  13930. const int64_t dr = (nr + nth - 1)/nth;
  13931. // row range for this thread
  13932. const int64_t ir0 = dr*ith;
  13933. const int64_t ir1 = MIN(ir0 + dr, nr);
  13934. const float d_by_nr = ((const float *) opt0->data)[0] / (float) nr;
  13935. for (int64_t i1 = ir0; i1 < ir1; i1++) {
  13936. float * ds0 = (float *)((char *) dst->data + i1*dst->nb[1]);
  13937. float * s0 = (float *)((char *) src0->data + i1*src0->nb[1]);
  13938. float * s1 = (float *)((char *) src1->data + i1*src1->nb[1]);
  13939. #ifndef NDEBUG
  13940. for (int i = 0; i < nc; ++i) {
  13941. //printf("p[%d] = %f\n", i, p[i]);
  13942. assert(!isnan(s0[i]));
  13943. assert(!isnan(s1[i]));
  13944. }
  13945. #endif
  13946. // soft_max
  13947. float max = -INFINITY;
  13948. ggml_vec_max_f32(nc, &max, s0);
  13949. ggml_float sum = ggml_vec_soft_max_f32(nc, ds0, s0, max);
  13950. assert(sum > 0.0);
  13951. ggml_vec_scale_f32(nc, ds0, 1.0/sum);
  13952. // grad(src0) = (softmax(src0) - src1) * grad(cross_entropy_loss(src0, src1)) / nr
  13953. ggml_vec_sub_f32(nc, ds0, ds0, s1);
  13954. ggml_vec_scale_f32(nc, ds0, d_by_nr);
  13955. #ifndef NDEBUG
  13956. for (int i = 0; i < nc; ++i) {
  13957. assert(!isnan(ds0[i]));
  13958. assert(!isinf(ds0[i]));
  13959. }
  13960. #endif
  13961. }
  13962. }
  13963. static void ggml_compute_forward_cross_entropy_loss_back(
  13964. const struct ggml_compute_params * params,
  13965. struct ggml_tensor * dst) {
  13966. const struct ggml_tensor * src0 = dst->src[0];
  13967. switch (src0->type) {
  13968. case GGML_TYPE_F32:
  13969. {
  13970. ggml_compute_forward_cross_entropy_loss_back_f32(params, dst);
  13971. } break;
  13972. default:
  13973. {
  13974. GGML_ABORT("fatal error");
  13975. }
  13976. }
  13977. }
  13978. static void ggml_compute_forward_opt_step_adamw_f32(
  13979. const struct ggml_compute_params * params,
  13980. struct ggml_tensor * dst) {
  13981. const struct ggml_tensor * src0 = dst->src[0];
  13982. const struct ggml_tensor * src0_grad = dst->src[1];
  13983. const struct ggml_tensor * src0_grad_m = dst->src[2];
  13984. const struct ggml_tensor * src0_grad_v = dst->src[3];
  13985. GGML_ASSERT(ggml_are_same_shape(src0, src0_grad));
  13986. const int ith = params->ith;
  13987. const int nth = params->nth;
  13988. const int nr = ggml_nrows(src0);
  13989. GGML_TENSOR_UNARY_OP_LOCALS
  13990. GGML_ASSERT(nb00 == sizeof(float));
  13991. // rows per thread
  13992. const int dr = (nr + nth - 1)/nth;
  13993. // row range for this thread
  13994. const int ir0 = dr*ith;
  13995. const int ir1 = MIN(ir0 + dr, nr);
  13996. /* const float gnorm = 1.0f; */
  13997. int64_t iter; memcpy(&iter, &dst->op_params[0], sizeof(int64_t));
  13998. const float alpha = ggml_get_op_params_f32(dst, 2);
  13999. const float beta1 = ggml_get_op_params_f32(dst, 3);
  14000. const float beta2 = ggml_get_op_params_f32(dst, 4);
  14001. const float eps = ggml_get_op_params_f32(dst, 5);
  14002. const float wd = ggml_get_op_params_f32(dst, 6);
  14003. const float beta1h = alpha/(1.0f - powf(beta1, iter));
  14004. const float beta2h = 1.0f/(1.0f - powf(beta2, iter));
  14005. for (int ir = ir0; ir < ir1; ++ir) {
  14006. const int64_t i03 = ir/(ne02*ne01);
  14007. const int64_t i02 = (ir - i03*ne02*ne01)/ne01;
  14008. const int64_t i01 = (ir - i03*ne02*ne01 - i02*ne01);
  14009. const size_t offset = i03*nb03 + i02*nb02 + i01*nb01;
  14010. float * w = (float *) ((char *) src0->data + offset); // weight
  14011. const float * g = (const float *) ((const char *) src0_grad->data + offset); // grad
  14012. float * m = (float *) ((char *) src0_grad_m->data + offset);
  14013. float * v = (float *) ((char *) src0_grad_v->data + offset);
  14014. for (int i00 = 0; i00 < ne00; ++i00) {
  14015. m[i00] = m[i00]*beta1 + g[i00]*(1.0f - beta1);
  14016. v[i00] = v[i00]*beta2 + g[i00]*g[i00]*(1.0f - beta2);
  14017. const float mh = m[i00]*beta1h;
  14018. const float vh = sqrtf(v[i00]*beta2h) + eps;
  14019. // The weight decay is applied independently of the Adam momenta m and v.
  14020. // This is NOT equivalent to l2 regularization that adds w[i00]*w[i00] to the loss.
  14021. // See: https://arxiv.org/pdf/1711.05101v3.pdf
  14022. w[i00] = w[i00]*(1.0f - alpha*wd) - mh/vh;
  14023. }
  14024. }
  14025. ggml_barrier(params->threadpool);
  14026. if (ith != 0) {
  14027. return;
  14028. }
  14029. iter++;
  14030. memcpy(&dst->op_params[0], &iter, sizeof(int64_t));
  14031. }
  14032. static void ggml_compute_forward_opt_step_adamw(
  14033. const struct ggml_compute_params * params,
  14034. struct ggml_tensor * dst) {
  14035. const struct ggml_tensor * src0 = dst->src[0];
  14036. switch (src0->type) {
  14037. case GGML_TYPE_F32:
  14038. {
  14039. ggml_compute_forward_opt_step_adamw_f32(params, dst);
  14040. } break;
  14041. default:
  14042. {
  14043. GGML_ABORT("fatal error");
  14044. }
  14045. }
  14046. }
  14047. /////////////////////////////////
  14048. static void ggml_compute_forward(struct ggml_compute_params * params, struct ggml_tensor * tensor) {
  14049. GGML_ASSERT(params);
  14050. if (tensor->op == GGML_OP_NONE || ggml_is_empty(tensor)) {
  14051. return;
  14052. }
  14053. switch (tensor->op) {
  14054. case GGML_OP_DUP:
  14055. {
  14056. ggml_compute_forward_dup(params, tensor);
  14057. } break;
  14058. case GGML_OP_ADD:
  14059. {
  14060. ggml_compute_forward_add(params, tensor);
  14061. } break;
  14062. case GGML_OP_ADD1:
  14063. {
  14064. ggml_compute_forward_add1(params, tensor);
  14065. } break;
  14066. case GGML_OP_ACC:
  14067. {
  14068. ggml_compute_forward_acc(params, tensor);
  14069. } break;
  14070. case GGML_OP_SUB:
  14071. {
  14072. ggml_compute_forward_sub(params, tensor);
  14073. } break;
  14074. case GGML_OP_MUL:
  14075. {
  14076. ggml_compute_forward_mul(params, tensor);
  14077. } break;
  14078. case GGML_OP_DIV:
  14079. {
  14080. ggml_compute_forward_div(params, tensor);
  14081. } break;
  14082. case GGML_OP_SQR:
  14083. {
  14084. ggml_compute_forward_sqr(params, tensor);
  14085. } break;
  14086. case GGML_OP_SQRT:
  14087. {
  14088. ggml_compute_forward_sqrt(params, tensor);
  14089. } break;
  14090. case GGML_OP_LOG:
  14091. {
  14092. ggml_compute_forward_log(params, tensor);
  14093. } break;
  14094. case GGML_OP_SIN:
  14095. {
  14096. ggml_compute_forward_sin(params, tensor);
  14097. } break;
  14098. case GGML_OP_COS:
  14099. {
  14100. ggml_compute_forward_cos(params, tensor);
  14101. } break;
  14102. case GGML_OP_SUM:
  14103. {
  14104. ggml_compute_forward_sum(params, tensor);
  14105. } break;
  14106. case GGML_OP_SUM_ROWS:
  14107. {
  14108. ggml_compute_forward_sum_rows(params, tensor);
  14109. } break;
  14110. case GGML_OP_MEAN:
  14111. {
  14112. ggml_compute_forward_mean(params, tensor);
  14113. } break;
  14114. case GGML_OP_ARGMAX:
  14115. {
  14116. ggml_compute_forward_argmax(params, tensor);
  14117. } break;
  14118. case GGML_OP_REPEAT:
  14119. {
  14120. ggml_compute_forward_repeat(params, tensor);
  14121. } break;
  14122. case GGML_OP_REPEAT_BACK:
  14123. {
  14124. ggml_compute_forward_repeat_back(params, tensor);
  14125. } break;
  14126. case GGML_OP_CONCAT:
  14127. {
  14128. ggml_compute_forward_concat(params, tensor);
  14129. } break;
  14130. case GGML_OP_SILU_BACK:
  14131. {
  14132. ggml_compute_forward_silu_back(params, tensor);
  14133. } break;
  14134. case GGML_OP_NORM:
  14135. {
  14136. ggml_compute_forward_norm(params, tensor);
  14137. } break;
  14138. case GGML_OP_RMS_NORM:
  14139. {
  14140. ggml_compute_forward_rms_norm(params, tensor);
  14141. } break;
  14142. case GGML_OP_RMS_NORM_BACK:
  14143. {
  14144. ggml_compute_forward_rms_norm_back(params, tensor);
  14145. } break;
  14146. case GGML_OP_GROUP_NORM:
  14147. {
  14148. ggml_compute_forward_group_norm(params, tensor);
  14149. } break;
  14150. case GGML_OP_MUL_MAT:
  14151. {
  14152. ggml_compute_forward_mul_mat(params, tensor);
  14153. } break;
  14154. case GGML_OP_MUL_MAT_ID:
  14155. {
  14156. ggml_compute_forward_mul_mat_id(params, tensor);
  14157. } break;
  14158. case GGML_OP_OUT_PROD:
  14159. {
  14160. ggml_compute_forward_out_prod(params, tensor);
  14161. } break;
  14162. case GGML_OP_SCALE:
  14163. {
  14164. ggml_compute_forward_scale(params, tensor);
  14165. } break;
  14166. case GGML_OP_SET:
  14167. {
  14168. ggml_compute_forward_set(params, tensor);
  14169. } break;
  14170. case GGML_OP_CPY:
  14171. {
  14172. ggml_compute_forward_cpy(params, tensor);
  14173. } break;
  14174. case GGML_OP_CONT:
  14175. {
  14176. ggml_compute_forward_cont(params, tensor);
  14177. } break;
  14178. case GGML_OP_RESHAPE:
  14179. {
  14180. ggml_compute_forward_reshape(params, tensor);
  14181. } break;
  14182. case GGML_OP_VIEW:
  14183. {
  14184. ggml_compute_forward_view(params, tensor);
  14185. } break;
  14186. case GGML_OP_PERMUTE:
  14187. {
  14188. ggml_compute_forward_permute(params, tensor);
  14189. } break;
  14190. case GGML_OP_TRANSPOSE:
  14191. {
  14192. ggml_compute_forward_transpose(params, tensor);
  14193. } break;
  14194. case GGML_OP_GET_ROWS:
  14195. {
  14196. ggml_compute_forward_get_rows(params, tensor);
  14197. } break;
  14198. case GGML_OP_GET_ROWS_BACK:
  14199. {
  14200. ggml_compute_forward_get_rows_back(params, tensor);
  14201. } break;
  14202. case GGML_OP_DIAG:
  14203. {
  14204. ggml_compute_forward_diag(params, tensor);
  14205. } break;
  14206. case GGML_OP_DIAG_MASK_INF:
  14207. {
  14208. ggml_compute_forward_diag_mask_inf(params, tensor);
  14209. } break;
  14210. case GGML_OP_DIAG_MASK_ZERO:
  14211. {
  14212. ggml_compute_forward_diag_mask_zero(params, tensor);
  14213. } break;
  14214. case GGML_OP_SOFT_MAX:
  14215. {
  14216. ggml_compute_forward_soft_max(params, tensor);
  14217. } break;
  14218. case GGML_OP_SOFT_MAX_BACK:
  14219. {
  14220. ggml_compute_forward_soft_max_back(params, tensor);
  14221. } break;
  14222. case GGML_OP_ROPE:
  14223. {
  14224. ggml_compute_forward_rope(params, tensor);
  14225. } break;
  14226. case GGML_OP_ROPE_BACK:
  14227. {
  14228. ggml_compute_forward_rope_back(params, tensor);
  14229. } break;
  14230. case GGML_OP_CLAMP:
  14231. {
  14232. ggml_compute_forward_clamp(params, tensor);
  14233. } break;
  14234. case GGML_OP_CONV_TRANSPOSE_1D:
  14235. {
  14236. ggml_compute_forward_conv_transpose_1d(params, tensor);
  14237. } break;
  14238. case GGML_OP_IM2COL:
  14239. {
  14240. ggml_compute_forward_im2col(params, tensor);
  14241. } break;
  14242. case GGML_OP_IM2COL_BACK:
  14243. {
  14244. ggml_compute_forward_im2col_back_f32(params, tensor);
  14245. } break;
  14246. case GGML_OP_CONV_TRANSPOSE_2D:
  14247. {
  14248. ggml_compute_forward_conv_transpose_2d(params, tensor);
  14249. } break;
  14250. case GGML_OP_POOL_1D:
  14251. {
  14252. ggml_compute_forward_pool_1d(params, tensor);
  14253. } break;
  14254. case GGML_OP_POOL_2D:
  14255. {
  14256. ggml_compute_forward_pool_2d(params, tensor);
  14257. } break;
  14258. case GGML_OP_POOL_2D_BACK:
  14259. {
  14260. ggml_compute_forward_pool_2d_back(params, tensor);
  14261. } break;
  14262. case GGML_OP_UPSCALE:
  14263. {
  14264. ggml_compute_forward_upscale(params, tensor);
  14265. } break;
  14266. case GGML_OP_PAD:
  14267. {
  14268. ggml_compute_forward_pad(params, tensor);
  14269. } break;
  14270. case GGML_OP_UNPAD:
  14271. {
  14272. ggml_compute_forward_unpad(params, tensor);
  14273. } break;
  14274. case GGML_OP_ARANGE:
  14275. {
  14276. ggml_compute_forward_arange(params, tensor);
  14277. } break;
  14278. case GGML_OP_TIMESTEP_EMBEDDING:
  14279. {
  14280. ggml_compute_forward_timestep_embedding(params, tensor);
  14281. } break;
  14282. case GGML_OP_ARGSORT:
  14283. {
  14284. ggml_compute_forward_argsort(params, tensor);
  14285. } break;
  14286. case GGML_OP_LEAKY_RELU:
  14287. {
  14288. ggml_compute_forward_leaky_relu(params, tensor);
  14289. } break;
  14290. case GGML_OP_FLASH_ATTN_EXT:
  14291. {
  14292. ggml_compute_forward_flash_attn_ext(params, tensor->src[0], tensor->src[1], tensor->src[2], tensor->src[3], tensor);
  14293. } break;
  14294. case GGML_OP_FLASH_ATTN_BACK:
  14295. {
  14296. int32_t t = ggml_get_op_params_i32(tensor, 0);
  14297. GGML_ASSERT(t == 0 || t == 1);
  14298. bool masked = t != 0;
  14299. ggml_compute_forward_flash_attn_back(params, masked, tensor);
  14300. } break;
  14301. case GGML_OP_SSM_CONV:
  14302. {
  14303. ggml_compute_forward_ssm_conv(params, tensor);
  14304. } break;
  14305. case GGML_OP_SSM_SCAN:
  14306. {
  14307. ggml_compute_forward_ssm_scan(params, tensor);
  14308. } break;
  14309. case GGML_OP_WIN_PART:
  14310. {
  14311. ggml_compute_forward_win_part(params, tensor);
  14312. } break;
  14313. case GGML_OP_WIN_UNPART:
  14314. {
  14315. ggml_compute_forward_win_unpart(params, tensor);
  14316. } break;
  14317. case GGML_OP_UNARY:
  14318. {
  14319. ggml_compute_forward_unary(params, tensor);
  14320. } break;
  14321. case GGML_OP_GET_REL_POS:
  14322. {
  14323. ggml_compute_forward_get_rel_pos(params, tensor);
  14324. } break;
  14325. case GGML_OP_ADD_REL_POS:
  14326. {
  14327. ggml_compute_forward_add_rel_pos(params, tensor);
  14328. } break;
  14329. case GGML_OP_RWKV_WKV:
  14330. {
  14331. ggml_compute_forward_rwkv_wkv(params, tensor);
  14332. } break;
  14333. case GGML_OP_MAP_UNARY:
  14334. {
  14335. ggml_unary_op_f32_t fun;
  14336. memcpy(&fun, tensor->op_params, sizeof(fun));
  14337. ggml_compute_forward_map_unary(params, tensor, fun);
  14338. }
  14339. break;
  14340. case GGML_OP_MAP_BINARY:
  14341. {
  14342. ggml_binary_op_f32_t fun;
  14343. memcpy(&fun, tensor->op_params, sizeof(fun));
  14344. ggml_compute_forward_map_binary(params, tensor, fun);
  14345. }
  14346. break;
  14347. case GGML_OP_MAP_CUSTOM1_F32:
  14348. {
  14349. ggml_custom1_op_f32_t fun;
  14350. memcpy(&fun, tensor->op_params, sizeof(fun));
  14351. ggml_compute_forward_map_custom1_f32(params, tensor, fun);
  14352. }
  14353. break;
  14354. case GGML_OP_MAP_CUSTOM2_F32:
  14355. {
  14356. ggml_custom2_op_f32_t fun;
  14357. memcpy(&fun, tensor->op_params, sizeof(fun));
  14358. ggml_compute_forward_map_custom2_f32(params, tensor, fun);
  14359. }
  14360. break;
  14361. case GGML_OP_MAP_CUSTOM3_F32:
  14362. {
  14363. ggml_custom3_op_f32_t fun;
  14364. memcpy(&fun, tensor->op_params, sizeof(fun));
  14365. ggml_compute_forward_map_custom3_f32(params, tensor, fun);
  14366. }
  14367. break;
  14368. case GGML_OP_MAP_CUSTOM1:
  14369. {
  14370. ggml_compute_forward_map_custom1(params, tensor);
  14371. }
  14372. break;
  14373. case GGML_OP_MAP_CUSTOM2:
  14374. {
  14375. ggml_compute_forward_map_custom2(params, tensor);
  14376. }
  14377. break;
  14378. case GGML_OP_MAP_CUSTOM3:
  14379. {
  14380. ggml_compute_forward_map_custom3(params, tensor);
  14381. }
  14382. break;
  14383. case GGML_OP_CROSS_ENTROPY_LOSS:
  14384. {
  14385. ggml_compute_forward_cross_entropy_loss(params, tensor);
  14386. }
  14387. break;
  14388. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  14389. {
  14390. ggml_compute_forward_cross_entropy_loss_back(params, tensor);
  14391. }
  14392. break;
  14393. case GGML_OP_OPT_STEP_ADAMW:
  14394. {
  14395. ggml_compute_forward_opt_step_adamw(params, tensor);
  14396. }
  14397. break;
  14398. case GGML_OP_NONE:
  14399. {
  14400. // nop
  14401. } break;
  14402. case GGML_OP_COUNT:
  14403. {
  14404. GGML_ABORT("fatal error");
  14405. }
  14406. }
  14407. }
  14408. ////////////////////////////////////////////////////////////////////////////////
  14409. struct ggml_hash_set ggml_hash_set_new(size_t size) {
  14410. size = ggml_hash_size(size);
  14411. struct ggml_hash_set result;
  14412. result.size = size;
  14413. result.keys = GGML_MALLOC(sizeof(struct ggml_tensor *) * size);
  14414. result.used = GGML_CALLOC(ggml_bitset_size(size), sizeof(ggml_bitset_t));
  14415. return result;
  14416. }
  14417. void ggml_hash_set_reset(struct ggml_hash_set * hash_set) {
  14418. memset(hash_set->used, 0, sizeof(ggml_bitset_t) * ggml_bitset_size(hash_set->size));
  14419. }
  14420. void ggml_hash_set_free(struct ggml_hash_set * hash_set) {
  14421. GGML_FREE(hash_set->used);
  14422. GGML_FREE(hash_set->keys);
  14423. }
  14424. size_t ggml_hash_size(size_t min_sz) {
  14425. // next primes after powers of two
  14426. static const size_t primes[] = {
  14427. 2, 3, 5, 11, 17, 37, 67, 131, 257, 521, 1031,
  14428. 2053, 4099, 8209, 16411, 32771, 65537, 131101,
  14429. 262147, 524309, 1048583, 2097169, 4194319, 8388617,
  14430. 16777259, 33554467, 67108879, 134217757, 268435459,
  14431. 536870923, 1073741827, 2147483659
  14432. };
  14433. static const size_t n_primes = sizeof(primes)/sizeof(primes[0]);
  14434. // find the smallest prime that is larger or equal than min_sz
  14435. size_t l = 0;
  14436. size_t r = n_primes;
  14437. while (l < r) {
  14438. size_t m = (l + r)/2;
  14439. if (primes[m] < min_sz) {
  14440. l = m + 1;
  14441. } else {
  14442. r = m;
  14443. }
  14444. }
  14445. size_t sz = l < n_primes ? primes[l] : min_sz | 1;
  14446. return sz;
  14447. }
  14448. struct hash_map {
  14449. struct ggml_hash_set set;
  14450. struct ggml_tensor ** vals;
  14451. };
  14452. static struct hash_map * ggml_new_hash_map(size_t size) {
  14453. struct hash_map * result = GGML_MALLOC(sizeof(struct hash_map));
  14454. result->set = ggml_hash_set_new(size);
  14455. result->vals = GGML_CALLOC(result->set.size, sizeof(struct ggml_tensor *));
  14456. return result;
  14457. }
  14458. static void ggml_hash_map_free(struct hash_map * map) {
  14459. ggml_hash_set_free(&map->set);
  14460. GGML_FREE(map->vals);
  14461. GGML_FREE(map);
  14462. }
  14463. // gradient checkpointing
  14464. static struct ggml_tensor * ggml_recompute_graph_node(
  14465. struct ggml_context * ctx,
  14466. struct ggml_cgraph * graph,
  14467. struct hash_map * replacements,
  14468. struct ggml_tensor * node) {
  14469. if (node == NULL) {
  14470. return NULL;
  14471. }
  14472. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  14473. return node;
  14474. }
  14475. if (!ggml_hash_contains(&graph->visited_hash_set, node)) {
  14476. return node;
  14477. }
  14478. int count_children = 0;
  14479. for (int k = 0; k < GGML_MAX_SRC; ++k) {
  14480. if (node->src[k]) {
  14481. ++count_children;
  14482. }
  14483. }
  14484. if (count_children == 0) {
  14485. return node;
  14486. }
  14487. size_t i = ggml_hash_find(&replacements->set, node);
  14488. GGML_ASSERT(i != GGML_HASHSET_FULL); // assert that not full
  14489. if (replacements->set.keys[i] == node) {
  14490. return replacements->vals[i];
  14491. }
  14492. struct ggml_tensor * clone = ggml_new_tensor(ctx, node->type, GGML_MAX_DIMS, node->ne);
  14493. // insert clone into replacements
  14494. GGML_ASSERT(replacements->set.keys[i] == NULL); // assert that we don't overwrite
  14495. replacements->set.keys[i] = node;
  14496. replacements->vals[i] = clone;
  14497. clone->op = node->op;
  14498. clone->grad = node->grad;
  14499. clone->flags = node->flags;
  14500. clone->extra = node->extra;
  14501. for (int k = 0; k < GGML_MAX_DIMS; ++k) {
  14502. clone->nb[k] = node->nb[k];
  14503. }
  14504. for (int k = 0; k < GGML_MAX_SRC; ++k) {
  14505. clone->src[k] = ggml_recompute_graph_node(ctx, graph, replacements, node->src[k]);
  14506. }
  14507. if (node->view_src != NULL) {
  14508. clone->data = (node->view_src->data == NULL)
  14509. ? NULL // view_src not yet allocated
  14510. : (char *) node->view_src->data // view_src already allocated
  14511. + node->view_offs;
  14512. clone->view_src = node->view_src;
  14513. clone->view_offs = node->view_offs;
  14514. }
  14515. GGML_ASSERT(sizeof(node->op_params) == sizeof(int32_t) * (GGML_MAX_OP_PARAMS / sizeof(int32_t)));
  14516. GGML_ASSERT(sizeof(node->name) == GGML_MAX_NAME);
  14517. memcpy(clone->op_params, node->op_params, sizeof(node->op_params));
  14518. ggml_format_name(clone, "%s (clone)", ggml_get_name(node));
  14519. return clone;
  14520. }
  14521. void ggml_build_backward_gradient_checkpointing(
  14522. struct ggml_context * ctx,
  14523. struct ggml_cgraph * gf,
  14524. struct ggml_cgraph * gb,
  14525. struct ggml_cgraph * gb_tmp,
  14526. struct ggml_tensor * * checkpoints,
  14527. int n_checkpoints) {
  14528. ggml_graph_cpy(gf, gb_tmp);
  14529. ggml_build_backward_expand(ctx, gf, gb_tmp, false);
  14530. if (n_checkpoints <= 0) {
  14531. ggml_graph_cpy(gb_tmp, gb);
  14532. return;
  14533. }
  14534. struct hash_map * replacements = ggml_new_hash_map(gf->n_nodes + gf->n_leafs + n_checkpoints);
  14535. // insert checkpoints in replacements
  14536. for (int i = 0; i < n_checkpoints; ++i) {
  14537. size_t k = ggml_hash_find(&replacements->set, checkpoints[i]);
  14538. GGML_ASSERT(k != GGML_HASHSET_FULL); // assert that not full
  14539. GGML_ASSERT(replacements->set.keys[k] == NULL); // assert that we don't overwrite
  14540. replacements->set.keys[k] = checkpoints[i];
  14541. replacements->vals[k] = checkpoints[i];
  14542. }
  14543. ggml_graph_cpy(gf, gb);
  14544. // rewrite gb_tmp->nodes[gf->n_nodes:gb_tmp->n_nodes],
  14545. // replacing references to gb_tmp->nodes[0:gf->n_nodes] ( == gf->nodes[0:gf->n_nodes]),
  14546. // by recomputing them from checkpoints
  14547. for (int i = gf->n_nodes; i<gb_tmp->n_nodes; ++i) {
  14548. struct ggml_tensor * node = gb_tmp->nodes[i];
  14549. for (int k = 0; k < GGML_MAX_SRC; ++k) {
  14550. // insert new tensors recomputing src, reusing already made replacements,
  14551. // remember replacements: remember new tensors with mapping from corresponding gf nodes
  14552. // recurse for input tensors,
  14553. // unless (i.e. terminating when) input tensors are replacements (like checkpoints)
  14554. node->src[k] = ggml_recompute_graph_node(ctx, gf, replacements, node->src[k]);
  14555. }
  14556. // insert rewritten backward node with replacements made into resulting backward graph gb
  14557. ggml_build_forward_expand(gb, node);
  14558. }
  14559. ggml_hash_map_free(replacements);
  14560. }
  14561. // utility functions to change gradients
  14562. // if a is in acc_table, modify gradients in-place and mark result as gradient accumulator
  14563. // else if a is in zero_table, replace a
  14564. // else, just add/subtract/etc. the gradients
  14565. static struct ggml_tensor * ggml_add_or_set(
  14566. struct ggml_context * ctx,
  14567. struct ggml_tensor * a,
  14568. struct ggml_tensor * b,
  14569. struct ggml_hash_set * zero_table,
  14570. struct ggml_hash_set * acc_table) {
  14571. if (ggml_hash_contains(acc_table, a)) {
  14572. struct ggml_tensor * ret = ggml_add_impl(ctx, a, b, true);
  14573. const size_t insert_result = ggml_hash_insert(acc_table, ret);
  14574. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  14575. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  14576. return ret;
  14577. }
  14578. if (ggml_hash_contains(zero_table, a)) {
  14579. return b;
  14580. }
  14581. return ggml_add_impl(ctx, a, b, false);
  14582. }
  14583. static struct ggml_tensor * ggml_acc_or_set(
  14584. struct ggml_context * ctx,
  14585. struct ggml_tensor * a,
  14586. struct ggml_tensor * b,
  14587. const size_t nb1,
  14588. const size_t nb2,
  14589. const size_t nb3,
  14590. const size_t offset,
  14591. struct ggml_hash_set * zero_table,
  14592. struct ggml_hash_set * acc_table) {
  14593. if (ggml_hash_contains(acc_table, a)) {
  14594. struct ggml_tensor * ret = ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  14595. const size_t insert_result = ggml_hash_insert(acc_table, ret);
  14596. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  14597. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  14598. return ret;
  14599. }
  14600. if (ggml_hash_contains(zero_table, a)) {
  14601. struct ggml_tensor * a_zero = ggml_scale(ctx, a, 0.0f); // FIXME this is going to produce NaN if a contains inf/NaN
  14602. return ggml_acc_impl(ctx, a_zero, b, nb1, nb2, nb3, offset, false);
  14603. }
  14604. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  14605. }
  14606. static struct ggml_tensor * ggml_add1_or_set(
  14607. struct ggml_context * ctx,
  14608. struct ggml_tensor * a,
  14609. struct ggml_tensor * b,
  14610. struct ggml_hash_set * zero_table,
  14611. struct ggml_hash_set * acc_table) {
  14612. if (ggml_hash_contains(acc_table, a)) {
  14613. struct ggml_tensor * ret = ggml_add1_impl(ctx, a, b, true);
  14614. const size_t insert_result = ggml_hash_insert(acc_table, ret);
  14615. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  14616. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  14617. return ret;
  14618. }
  14619. if (ggml_hash_contains(zero_table, a)) {
  14620. return ggml_repeat(ctx, b, a);
  14621. }
  14622. return ggml_add1_impl(ctx, a, b, false);
  14623. }
  14624. static struct ggml_tensor * ggml_sub_or_set(
  14625. struct ggml_context * ctx,
  14626. struct ggml_tensor * a,
  14627. struct ggml_tensor * b,
  14628. struct ggml_hash_set * zero_table,
  14629. struct ggml_hash_set * acc_table) {
  14630. if (ggml_hash_contains(acc_table, a)) {
  14631. struct ggml_tensor * ret = ggml_sub_impl(ctx, a, b, true);
  14632. const size_t insert_result = ggml_hash_insert(acc_table, ret);
  14633. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  14634. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  14635. return ret;
  14636. }
  14637. if (ggml_hash_contains(zero_table, a)) {
  14638. return ggml_neg(ctx, b);
  14639. }
  14640. return ggml_sub_impl(ctx, a, b, false);
  14641. }
  14642. 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) {
  14643. struct ggml_tensor * src0 = tensor->src[0];
  14644. struct ggml_tensor * src1 = tensor->src[1];
  14645. struct ggml_tensor * src2 = tensor->src[2];
  14646. switch (tensor->op) {
  14647. case GGML_OP_DUP:
  14648. {
  14649. if (src0->grad) {
  14650. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14651. }
  14652. } break;
  14653. case GGML_OP_ADD:
  14654. {
  14655. if (src0->grad) {
  14656. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14657. }
  14658. if (src1->grad) {
  14659. if (ggml_are_same_shape(src0, src1)) {
  14660. src1->grad = ggml_add_or_set(ctx, src1->grad, tensor->grad, zero_table, acc_table);
  14661. } else {
  14662. src1->grad = ggml_add_or_set(ctx, src1->grad, ggml_repeat_back(ctx, tensor->grad, src1), zero_table, acc_table);
  14663. }
  14664. }
  14665. } break;
  14666. case GGML_OP_ADD1:
  14667. {
  14668. if (src0->grad) {
  14669. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14670. }
  14671. if (src1->grad) {
  14672. src1->grad = ggml_add_or_set(ctx,
  14673. src1->grad,
  14674. ggml_mean(ctx, tensor->grad), // TODO: should probably be sum instead of mean
  14675. zero_table, acc_table);
  14676. }
  14677. } break;
  14678. case GGML_OP_ACC:
  14679. {
  14680. if (src0->grad) {
  14681. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14682. }
  14683. if (src1->grad) {
  14684. const size_t nb1 = ((int32_t *) tensor->op_params)[0];
  14685. const size_t nb2 = ((int32_t *) tensor->op_params)[1];
  14686. const size_t nb3 = ((int32_t *) tensor->op_params)[2];
  14687. const size_t offset = ((int32_t *) tensor->op_params)[3];
  14688. struct ggml_tensor * tensor_grad_view = ggml_view_4d(ctx,
  14689. tensor->grad,
  14690. src1->grad->ne[0],
  14691. src1->grad->ne[1],
  14692. src1->grad->ne[2],
  14693. src1->grad->ne[3],
  14694. nb1, nb2, nb3, offset);
  14695. src1->grad =
  14696. ggml_add_or_set(ctx,
  14697. src1->grad,
  14698. ggml_reshape(ctx,
  14699. ggml_cont(ctx, tensor_grad_view),
  14700. src1->grad),
  14701. zero_table, acc_table);
  14702. }
  14703. } break;
  14704. case GGML_OP_SUB:
  14705. {
  14706. if (src0->grad) {
  14707. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  14708. }
  14709. if (src1->grad) {
  14710. src1->grad = ggml_sub_or_set(ctx, src1->grad, tensor->grad, zero_table, acc_table);
  14711. }
  14712. } break;
  14713. case GGML_OP_MUL:
  14714. {
  14715. if (src0->grad) {
  14716. src0->grad =
  14717. ggml_add_or_set(ctx,
  14718. src0->grad,
  14719. ggml_mul(ctx, src1, tensor->grad),
  14720. zero_table, acc_table);
  14721. }
  14722. if (src1->grad) {
  14723. src1->grad =
  14724. ggml_add_or_set(ctx,
  14725. src1->grad,
  14726. ggml_mul(ctx, src0, tensor->grad),
  14727. zero_table, acc_table);
  14728. }
  14729. } break;
  14730. case GGML_OP_DIV:
  14731. {
  14732. if (src0->grad) {
  14733. src0->grad =
  14734. ggml_add_or_set(ctx,
  14735. src0->grad,
  14736. ggml_div(ctx, tensor->grad, src1),
  14737. zero_table, acc_table);
  14738. }
  14739. if (src1->grad) {
  14740. src1->grad =
  14741. ggml_sub_or_set(ctx,
  14742. src1->grad,
  14743. ggml_mul(ctx,
  14744. tensor->grad,
  14745. ggml_div(ctx, tensor, src1)),
  14746. zero_table, acc_table);
  14747. }
  14748. } break;
  14749. case GGML_OP_SQR:
  14750. {
  14751. if (src0->grad) {
  14752. src0->grad =
  14753. ggml_add_or_set(ctx,
  14754. src0->grad,
  14755. ggml_scale(ctx,
  14756. ggml_mul(ctx, src0, tensor->grad),
  14757. 2.0f),
  14758. zero_table, acc_table);
  14759. }
  14760. } break;
  14761. case GGML_OP_SQRT:
  14762. {
  14763. if (src0->grad) {
  14764. src0->grad =
  14765. ggml_add_or_set(ctx,
  14766. src0->grad,
  14767. ggml_scale(ctx,
  14768. ggml_div(ctx,
  14769. tensor->grad,
  14770. tensor),
  14771. 0.5f),
  14772. zero_table, acc_table);
  14773. }
  14774. } break;
  14775. case GGML_OP_LOG:
  14776. {
  14777. if (src0->grad) {
  14778. src0->grad =
  14779. ggml_add_or_set(ctx,
  14780. src0->grad,
  14781. ggml_div(ctx,
  14782. tensor->grad,
  14783. src0),
  14784. zero_table, acc_table);
  14785. }
  14786. } break;
  14787. case GGML_OP_SIN:
  14788. {
  14789. if (src0->grad) {
  14790. src0->grad =
  14791. ggml_add_or_set(ctx,
  14792. src0->grad,
  14793. ggml_mul(ctx,
  14794. tensor->grad,
  14795. ggml_cos(ctx, src0)),
  14796. zero_table, acc_table);
  14797. }
  14798. } break;
  14799. case GGML_OP_COS:
  14800. {
  14801. if (src0->grad) {
  14802. src0->grad =
  14803. ggml_sub_or_set(ctx,
  14804. src0->grad,
  14805. ggml_mul(ctx,
  14806. tensor->grad,
  14807. ggml_sin(ctx, src0)),
  14808. zero_table, acc_table);
  14809. }
  14810. } break;
  14811. case GGML_OP_SUM:
  14812. {
  14813. if (src0->grad) {
  14814. src0->grad =
  14815. ggml_add1_or_set(ctx,
  14816. src0->grad,
  14817. tensor->grad,
  14818. zero_table, acc_table);
  14819. }
  14820. } break;
  14821. case GGML_OP_SUM_ROWS:
  14822. {
  14823. if (src0->grad) {
  14824. src0->grad =
  14825. ggml_add_or_set(ctx,
  14826. src0->grad,
  14827. ggml_repeat(ctx,
  14828. tensor->grad,
  14829. src0->grad),
  14830. zero_table, acc_table);
  14831. }
  14832. } break;
  14833. case GGML_OP_MEAN:
  14834. case GGML_OP_ARGMAX:
  14835. {
  14836. GGML_ABORT("fatal error"); // TODO: implement
  14837. }
  14838. case GGML_OP_REPEAT:
  14839. {
  14840. // necessary for llama
  14841. if (src0->grad) {
  14842. src0->grad = ggml_add_or_set(ctx,
  14843. src0->grad,
  14844. ggml_repeat_back(ctx, tensor->grad, src0->grad),
  14845. zero_table, acc_table);
  14846. }
  14847. } break;
  14848. case GGML_OP_REPEAT_BACK:
  14849. {
  14850. if (src0->grad) {
  14851. // TODO: test this
  14852. src0->grad = ggml_add_or_set(ctx,
  14853. src0->grad,
  14854. ggml_repeat(ctx, tensor->grad, src0->grad),
  14855. zero_table, acc_table);
  14856. }
  14857. } break;
  14858. case GGML_OP_CONCAT:
  14859. {
  14860. GGML_ABORT("fatal error"); // TODO: implement
  14861. }
  14862. case GGML_OP_SILU_BACK:
  14863. {
  14864. GGML_ABORT("fatal error"); // TODO: not implemented
  14865. }
  14866. case GGML_OP_NORM:
  14867. {
  14868. GGML_ABORT("fatal error"); // TODO: not implemented
  14869. }
  14870. case GGML_OP_RMS_NORM:
  14871. {
  14872. // necessary for llama
  14873. if (src0->grad) {
  14874. float eps;
  14875. memcpy(&eps, tensor->op_params, sizeof(float));
  14876. src0->grad = ggml_add_or_set(ctx,
  14877. src0->grad,
  14878. ggml_rms_norm_back(ctx, src0, tensor->grad, eps),
  14879. zero_table, acc_table);
  14880. }
  14881. } break;
  14882. case GGML_OP_RMS_NORM_BACK:
  14883. {
  14884. GGML_ABORT("fatal error"); // TODO: not implemented
  14885. }
  14886. case GGML_OP_GROUP_NORM:
  14887. {
  14888. GGML_ABORT("fatal error"); // TODO: not implemented
  14889. }
  14890. case GGML_OP_MUL_MAT:
  14891. {
  14892. // https://cs231n.github.io/optimization-2/#staged
  14893. // # forward pass
  14894. // s0 = np.random.randn(5, 10)
  14895. // s1 = np.random.randn(10, 3)
  14896. // t = s0.dot(s1)
  14897. // # now suppose we had the gradient on t from above in the circuit
  14898. // dt = np.random.randn(*t.shape) # same shape as t
  14899. // ds0 = dt.dot(s1.T) #.T gives the transpose of the matrix
  14900. // ds1 = t.T.dot(dt)
  14901. // tensor.shape [m,p,qq,rr]
  14902. // src0.shape [n,m,q1,r1]
  14903. // src1.shape [n,p,qq,rr]
  14904. // necessary for llama
  14905. if (src0->grad) {
  14906. struct ggml_tensor * s1_tg =
  14907. ggml_out_prod(ctx, // [n,m,qq,rr]
  14908. src1, // [n,p,qq,rr]
  14909. tensor->grad); // [m,p,qq,rr]
  14910. const int64_t qq = s1_tg->ne[2];
  14911. const int64_t rr = s1_tg->ne[3];
  14912. const int64_t q1 = src0->ne[2];
  14913. const int64_t r1 = src0->ne[3];
  14914. const bool ne2_broadcasted = qq > q1;
  14915. const bool ne3_broadcasted = rr > r1;
  14916. if (ne2_broadcasted || ne3_broadcasted) {
  14917. // sum broadcast repetitions of s1_tg into shape of src0
  14918. s1_tg = ggml_repeat_back(ctx, s1_tg, src0);
  14919. }
  14920. src0->grad =
  14921. ggml_add_or_set(ctx,
  14922. src0->grad, // [n,m,q1,r1]
  14923. s1_tg, // [n,m,q1,r1]
  14924. zero_table, acc_table);
  14925. }
  14926. if (src1->grad) {
  14927. src1->grad =
  14928. ggml_add_or_set(ctx,
  14929. src1->grad, // [n,p,qq,rr]
  14930. // ggml_mul_mat(ctx, // [n,p,qq,rr]
  14931. // ggml_cont(ctx, // [m,n,q1,r1]
  14932. // ggml_transpose(ctx, src0)), // [m,n,q1,r1]
  14933. // tensor->grad), // [m,p,qq,rr]
  14934. // // when src0 is bigger than tensor->grad (this is mostly the case in llama),
  14935. // // avoid transpose of src0, rather transpose smaller tensor->grad
  14936. // // and then use ggml_out_prod
  14937. ggml_out_prod(ctx, // [n,p,qq,rr]
  14938. src0, // [n,m,q1,r1]
  14939. ggml_transpose(ctx, // [p,m,qq,rr]
  14940. tensor->grad)), // [m,p,qq,rr]
  14941. zero_table, acc_table);
  14942. }
  14943. } break;
  14944. case GGML_OP_MUL_MAT_ID:
  14945. {
  14946. GGML_ABORT("fatal error"); // TODO: not implemented
  14947. }
  14948. case GGML_OP_OUT_PROD:
  14949. {
  14950. GGML_ABORT("fatal error"); // TODO: not implemented
  14951. }
  14952. case GGML_OP_SCALE:
  14953. {
  14954. // necessary for llama
  14955. if (src0->grad) {
  14956. float s;
  14957. memcpy(&s, tensor->op_params, sizeof(float));
  14958. src0->grad =
  14959. ggml_add_or_set(ctx,
  14960. src0->grad,
  14961. ggml_scale_impl(ctx, tensor->grad, s, false),
  14962. zero_table, acc_table);
  14963. }
  14964. } break;
  14965. case GGML_OP_SET:
  14966. {
  14967. const size_t nb1 = ((int32_t *) tensor->op_params)[0];
  14968. const size_t nb2 = ((int32_t *) tensor->op_params)[1];
  14969. const size_t nb3 = ((int32_t *) tensor->op_params)[2];
  14970. const size_t offset = ((int32_t *) tensor->op_params)[3];
  14971. struct ggml_tensor * tensor_grad_view = NULL;
  14972. if (src0->grad || src1->grad) {
  14973. GGML_ASSERT(src0->type == tensor->type);
  14974. GGML_ASSERT(tensor->grad->type == tensor->type);
  14975. GGML_ASSERT(!src1->grad || src1->grad->type == tensor->grad->type);
  14976. tensor_grad_view = ggml_view_4d(ctx,
  14977. tensor->grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
  14978. nb1, nb2, nb3, offset);
  14979. }
  14980. if (src0->grad) {
  14981. src0->grad = ggml_add_or_set(ctx,
  14982. src0->grad,
  14983. ggml_acc_impl(ctx,
  14984. tensor->grad,
  14985. ggml_neg(ctx, tensor_grad_view),
  14986. nb1, nb2, nb3, offset, false),
  14987. zero_table, acc_table);
  14988. }
  14989. if (src1->grad) {
  14990. src1->grad =
  14991. ggml_add_or_set(ctx,
  14992. src1->grad,
  14993. ggml_reshape(ctx,
  14994. ggml_cont(ctx, tensor_grad_view),
  14995. src1->grad),
  14996. zero_table, acc_table);
  14997. }
  14998. } break;
  14999. case GGML_OP_CPY:
  15000. {
  15001. // necessary for llama
  15002. // cpy overwrites value of src1 by src0 and returns view(src1)
  15003. // the overwriting is mathematically equivalent to:
  15004. // tensor = src0 * 1 + src1 * 0
  15005. if (src0->grad) {
  15006. // dsrc0 = dtensor * 1
  15007. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  15008. }
  15009. if (src1->grad) {
  15010. // dsrc1 = dtensor * 0 -> noop
  15011. }
  15012. } break;
  15013. case GGML_OP_CONT:
  15014. {
  15015. // same as cpy
  15016. if (src0->grad) {
  15017. GGML_ASSERT(ggml_is_contiguous(src0->grad));
  15018. GGML_ASSERT(ggml_is_contiguous(tensor->grad));
  15019. src0->grad = ggml_add_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  15020. }
  15021. } break;
  15022. case GGML_OP_RESHAPE:
  15023. {
  15024. // necessary for llama
  15025. if (src0->grad) {
  15026. src0->grad =
  15027. ggml_add_or_set(ctx, src0->grad,
  15028. ggml_reshape(ctx,
  15029. ggml_is_contiguous(tensor->grad)
  15030. ? tensor->grad
  15031. : ggml_cont(ctx, tensor->grad),
  15032. src0->grad),
  15033. zero_table, acc_table);
  15034. }
  15035. } break;
  15036. case GGML_OP_VIEW:
  15037. {
  15038. // necessary for llama
  15039. if (src0->grad) {
  15040. size_t offset;
  15041. memcpy(&offset, tensor->op_params, sizeof(offset));
  15042. size_t nb1 = tensor->nb[1];
  15043. size_t nb2 = tensor->nb[2];
  15044. size_t nb3 = tensor->nb[3];
  15045. if (src0->type != src0->grad->type) {
  15046. // gradient is typically F32, but src0 could be other type
  15047. size_t ng = ggml_element_size(src0->grad);
  15048. size_t n0 = ggml_element_size(src0);
  15049. GGML_ASSERT(offset % n0 == 0);
  15050. GGML_ASSERT(nb1 % n0 == 0);
  15051. GGML_ASSERT(nb2 % n0 == 0);
  15052. GGML_ASSERT(nb3 % n0 == 0);
  15053. offset = (offset / n0) * ng;
  15054. nb1 = (nb1 / n0) * ng;
  15055. nb2 = (nb2 / n0) * ng;
  15056. nb3 = (nb3 / n0) * ng;
  15057. }
  15058. src0->grad = ggml_acc_or_set(ctx, src0->grad, tensor->grad, nb1, nb2, nb3, offset, zero_table, acc_table);
  15059. }
  15060. } break;
  15061. case GGML_OP_PERMUTE:
  15062. {
  15063. // necessary for llama
  15064. if (src0->grad) {
  15065. int32_t * axes = (int32_t *) tensor->op_params;
  15066. int axis0 = axes[0] & 0x3;
  15067. int axis1 = axes[1] & 0x3;
  15068. int axis2 = axes[2] & 0x3;
  15069. int axis3 = axes[3] & 0x3;
  15070. int axes_backward[4] = {0,0,0,0};
  15071. axes_backward[axis0] = 0;
  15072. axes_backward[axis1] = 1;
  15073. axes_backward[axis2] = 2;
  15074. axes_backward[axis3] = 3;
  15075. src0->grad =
  15076. ggml_add_or_set(ctx, src0->grad,
  15077. ggml_permute(ctx,
  15078. tensor->grad,
  15079. axes_backward[0],
  15080. axes_backward[1],
  15081. axes_backward[2],
  15082. axes_backward[3]),
  15083. zero_table, acc_table);
  15084. }
  15085. } break;
  15086. case GGML_OP_TRANSPOSE:
  15087. {
  15088. // necessary for llama
  15089. if (src0->grad) {
  15090. src0->grad =
  15091. ggml_add_or_set(ctx, src0->grad,
  15092. ggml_transpose(ctx, tensor->grad),
  15093. zero_table, acc_table);
  15094. }
  15095. } break;
  15096. case GGML_OP_GET_ROWS:
  15097. {
  15098. // necessary for llama (only for tokenizer)
  15099. if (src0->grad) {
  15100. src0->grad =
  15101. ggml_add_or_set(ctx, src0->grad,
  15102. // last ggml_get_rows_back argument src0->grad is only
  15103. // necessary to setup correct output shape
  15104. ggml_get_rows_back(ctx, tensor->grad, src1, src0->grad),
  15105. zero_table, acc_table);
  15106. }
  15107. if (src1->grad) {
  15108. // noop
  15109. }
  15110. } break;
  15111. case GGML_OP_GET_ROWS_BACK:
  15112. {
  15113. GGML_ABORT("fatal error"); // TODO: not implemented
  15114. }
  15115. case GGML_OP_DIAG:
  15116. {
  15117. GGML_ABORT("fatal error"); // TODO: not implemented
  15118. }
  15119. case GGML_OP_DIAG_MASK_INF:
  15120. {
  15121. // necessary for llama
  15122. if (src0->grad) {
  15123. const int n_past = ((int32_t *) tensor->op_params)[0];
  15124. src0->grad =
  15125. ggml_add_or_set(ctx, src0->grad,
  15126. /* ggml_diag_mask_inf_impl() shouldn't be here */
  15127. /* ref: https://github.com/ggerganov/llama.cpp/pull/4203#discussion_r1412377992 */
  15128. ggml_diag_mask_zero_impl(ctx, tensor->grad, n_past, false),
  15129. zero_table, acc_table);
  15130. }
  15131. } break;
  15132. case GGML_OP_DIAG_MASK_ZERO:
  15133. {
  15134. // necessary for llama
  15135. if (src0->grad) {
  15136. const int n_past = ((int32_t *) tensor->op_params)[0];
  15137. src0->grad =
  15138. ggml_add_or_set(ctx, src0->grad,
  15139. ggml_diag_mask_zero_impl(ctx, tensor->grad, n_past, false),
  15140. zero_table, acc_table);
  15141. }
  15142. } break;
  15143. case GGML_OP_SOFT_MAX:
  15144. {
  15145. // necessary for llama
  15146. if (src0->grad) {
  15147. src0->grad =
  15148. ggml_add_or_set(ctx, src0->grad,
  15149. ggml_soft_max_back(ctx, tensor->grad, tensor),
  15150. zero_table, acc_table);
  15151. }
  15152. GGML_ASSERT((!src1 || !src1->grad) && "backward pass for softmax mask not implemented");
  15153. } break;
  15154. case GGML_OP_SOFT_MAX_BACK:
  15155. {
  15156. GGML_ABORT("fatal error"); // TODO: not implemented
  15157. }
  15158. case GGML_OP_ROPE:
  15159. {
  15160. // necessary for llama
  15161. if (src0->grad) {
  15162. //const int n_past = ((int32_t *) tensor->op_params)[0];
  15163. const int n_dims = ((int32_t *) tensor->op_params)[1];
  15164. const int mode = ((int32_t *) tensor->op_params)[2];
  15165. //const int n_ctx = ((int32_t *) tensor->op_params)[3];
  15166. const int n_ctx_orig = ((int32_t *) tensor->op_params)[4];
  15167. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  15168. memcpy(&freq_base, (int32_t *) tensor->op_params + 5, sizeof(float));
  15169. memcpy(&freq_scale, (int32_t *) tensor->op_params + 6, sizeof(float));
  15170. memcpy(&ext_factor, (int32_t *) tensor->op_params + 7, sizeof(float));
  15171. memcpy(&attn_factor, (int32_t *) tensor->op_params + 8, sizeof(float));
  15172. memcpy(&beta_fast, (int32_t *) tensor->op_params + 9, sizeof(float));
  15173. memcpy(&beta_slow, (int32_t *) tensor->op_params + 10, sizeof(float));
  15174. src0->grad = ggml_add_or_set(ctx,
  15175. src0->grad,
  15176. ggml_rope_back(ctx,
  15177. tensor->grad,
  15178. src1,
  15179. src2,
  15180. n_dims,
  15181. mode,
  15182. n_ctx_orig,
  15183. freq_base,
  15184. freq_scale,
  15185. ext_factor,
  15186. attn_factor,
  15187. beta_fast,
  15188. beta_slow),
  15189. zero_table, acc_table);
  15190. }
  15191. GGML_ASSERT((!src2 || !src2->grad) && "gradients for freq factors not implemented");
  15192. } break;
  15193. case GGML_OP_ROPE_BACK:
  15194. {
  15195. if (src0->grad) {
  15196. //const int n_past = ((int32_t *) tensor->op_params)[0];
  15197. const int n_dims = ((int32_t *) tensor->op_params)[1];
  15198. const int mode = ((int32_t *) tensor->op_params)[2];
  15199. //const int n_ctx = ((int32_t *) tensor->op_params)[3];
  15200. const int n_ctx_orig = ((int32_t *) tensor->op_params)[4];
  15201. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  15202. memcpy(&freq_base, (int32_t *) tensor->op_params + 5, sizeof(float));
  15203. memcpy(&freq_scale, (int32_t *) tensor->op_params + 6, sizeof(float));
  15204. memcpy(&ext_factor, (int32_t *) tensor->op_params + 7, sizeof(float));
  15205. memcpy(&attn_factor, (int32_t *) tensor->op_params + 8, sizeof(float));
  15206. memcpy(&beta_fast, (int32_t *) tensor->op_params + 9, sizeof(float));
  15207. memcpy(&beta_slow, (int32_t *) tensor->op_params + 10, sizeof(float));
  15208. src0->grad = ggml_add_or_set(ctx,
  15209. src0->grad,
  15210. ggml_rope_impl(ctx,
  15211. tensor->grad,
  15212. src1,
  15213. src2,
  15214. n_dims,
  15215. mode,
  15216. n_ctx_orig,
  15217. freq_base,
  15218. freq_scale,
  15219. ext_factor,
  15220. attn_factor,
  15221. beta_fast,
  15222. beta_slow,
  15223. false),
  15224. zero_table, acc_table);
  15225. }
  15226. } break;
  15227. case GGML_OP_CLAMP:
  15228. {
  15229. GGML_ABORT("fatal error"); // TODO: not implemented
  15230. }
  15231. case GGML_OP_CONV_TRANSPOSE_1D:
  15232. {
  15233. GGML_ABORT("fatal error"); // TODO: not implemented
  15234. }
  15235. case GGML_OP_IM2COL:
  15236. {
  15237. if (src1->grad) {
  15238. const int32_t s0 = ggml_get_op_params_i32(tensor, 0);
  15239. const int32_t s1 = ggml_get_op_params_i32(tensor, 1);
  15240. const int32_t p0 = ggml_get_op_params_i32(tensor, 2);
  15241. const int32_t p1 = ggml_get_op_params_i32(tensor, 3);
  15242. const int32_t d0 = ggml_get_op_params_i32(tensor, 4);
  15243. const int32_t d1 = ggml_get_op_params_i32(tensor, 5);
  15244. const bool is_2D = ggml_get_op_params_i32(tensor, 6) == 1;
  15245. src1->grad = ggml_add_or_set(ctx,
  15246. src1->grad,
  15247. ggml_im2col_back(ctx, src0, tensor->grad, src1->ne, s0, s1, p0, p1, d0, d1, is_2D),
  15248. zero_table, acc_table);
  15249. }
  15250. } break;
  15251. case GGML_OP_IM2COL_BACK:
  15252. {
  15253. GGML_ABORT("fatal error"); // TODO: not implemented
  15254. }
  15255. case GGML_OP_CONV_TRANSPOSE_2D:
  15256. {
  15257. GGML_ABORT("fatal error"); // TODO: not implemented
  15258. }
  15259. case GGML_OP_POOL_1D:
  15260. {
  15261. GGML_ABORT("fatal error"); // TODO: not implemented
  15262. }
  15263. case GGML_OP_POOL_2D:
  15264. {
  15265. if (src0->grad) {
  15266. const enum ggml_op_pool op = ggml_get_op_params_i32(tensor, 0);
  15267. const int32_t k0 = ggml_get_op_params_i32(tensor, 1);
  15268. const int32_t k1 = ggml_get_op_params_i32(tensor, 2);
  15269. const int32_t s0 = ggml_get_op_params_i32(tensor, 3);
  15270. const int32_t s1 = ggml_get_op_params_i32(tensor, 4);
  15271. const int32_t p0 = ggml_get_op_params_i32(tensor, 5);
  15272. const int32_t p1 = ggml_get_op_params_i32(tensor, 6);
  15273. src0->grad = ggml_add_or_set(ctx,
  15274. src0->grad,
  15275. ggml_pool_2d_back(ctx, tensor->grad, src0, op, k0, k1, s0, s1, p0, p1),
  15276. zero_table, acc_table);
  15277. }
  15278. } break;
  15279. case GGML_OP_POOL_2D_BACK:
  15280. {
  15281. GGML_ABORT("fatal error"); // TODO: not implemented
  15282. }
  15283. case GGML_OP_UPSCALE:
  15284. {
  15285. GGML_ABORT("fatal error"); // TODO: not implemented
  15286. }
  15287. case GGML_OP_PAD:
  15288. {
  15289. GGML_ABORT("fatal error"); // TODO: not implemented
  15290. }
  15291. case GGML_OP_UNPAD:
  15292. {
  15293. GGML_ABORT("fatal error"); // TODO: not implemented
  15294. }
  15295. case GGML_OP_ARANGE:
  15296. {
  15297. GGML_ABORT("fatal error"); // TODO: not implemented
  15298. }
  15299. case GGML_OP_TIMESTEP_EMBEDDING:
  15300. {
  15301. GGML_ABORT("fatal error"); // TODO: not implemented
  15302. }
  15303. case GGML_OP_ARGSORT:
  15304. {
  15305. GGML_ABORT("fatal error"); // TODO: not implemented
  15306. }
  15307. case GGML_OP_LEAKY_RELU:
  15308. {
  15309. GGML_ABORT("fatal error"); // TODO: not implemented
  15310. }
  15311. case GGML_OP_FLASH_ATTN_EXT:
  15312. {
  15313. GGML_ABORT("FA backward pass not adapted after rework");
  15314. struct ggml_tensor * flash_grad = NULL;
  15315. if (src0->grad || src1->grad || tensor->src[2]->grad) {
  15316. int32_t t = ggml_get_op_params_i32(tensor, 0);
  15317. GGML_ASSERT(t == 0 || t == 1);
  15318. bool masked = t != 0;
  15319. flash_grad =
  15320. ggml_flash_attn_back(ctx,
  15321. src0,
  15322. src1,
  15323. tensor->src[2],
  15324. tensor->grad,
  15325. masked);
  15326. }
  15327. const int64_t elem_q = ggml_nelements(src0);
  15328. const int64_t elem_k = ggml_nelements(src1);
  15329. const int64_t elem_v = ggml_nelements(src2);
  15330. enum ggml_type result_type = flash_grad->type;
  15331. GGML_ASSERT(ggml_blck_size(result_type) == 1);
  15332. const size_t tsize = ggml_type_size(result_type);
  15333. const size_t offs_q = 0;
  15334. const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
  15335. const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
  15336. if (src0->grad) {
  15337. struct ggml_tensor * view_q = ggml_view_1d(ctx, flash_grad, elem_q, offs_q);
  15338. struct ggml_tensor * grad_q = ggml_reshape(ctx, view_q, src0);
  15339. src0->grad = ggml_add_or_set(ctx,
  15340. src0->grad,
  15341. grad_q,
  15342. zero_table, acc_table);
  15343. }
  15344. if (src1->grad) {
  15345. struct ggml_tensor * view_k = ggml_view_1d(ctx, flash_grad, elem_k, offs_k);
  15346. struct ggml_tensor * grad_k = ggml_reshape(ctx, view_k, src1);
  15347. src1->grad = ggml_add_or_set(ctx,
  15348. src1->grad,
  15349. grad_k,
  15350. zero_table, acc_table);
  15351. }
  15352. if (src2->grad) {
  15353. struct ggml_tensor * view_v = ggml_view_1d(ctx, flash_grad, elem_v, offs_v);
  15354. struct ggml_tensor * grad_v = ggml_reshape(ctx, view_v, src2);
  15355. src2->grad = ggml_add_or_set(ctx,
  15356. src2->grad,
  15357. grad_v,
  15358. zero_table, acc_table);
  15359. }
  15360. } break;
  15361. case GGML_OP_FLASH_ATTN_BACK:
  15362. {
  15363. GGML_ABORT("fatal error"); // not supported
  15364. }
  15365. case GGML_OP_SSM_CONV:
  15366. case GGML_OP_SSM_SCAN:
  15367. {
  15368. GGML_ABORT("fatal error"); // TODO: not implemented
  15369. }
  15370. case GGML_OP_WIN_PART:
  15371. case GGML_OP_WIN_UNPART:
  15372. case GGML_OP_UNARY:
  15373. {
  15374. switch (ggml_get_unary_op(tensor)) {
  15375. case GGML_UNARY_OP_ABS:
  15376. {
  15377. if (src0->grad) {
  15378. src0->grad =
  15379. ggml_add_or_set(ctx,
  15380. src0->grad,
  15381. ggml_mul(ctx,
  15382. ggml_sgn(ctx, src0),
  15383. tensor->grad),
  15384. zero_table, acc_table);
  15385. }
  15386. } break;
  15387. case GGML_UNARY_OP_SGN:
  15388. {
  15389. if (src0->grad) {
  15390. // noop
  15391. }
  15392. } break;
  15393. case GGML_UNARY_OP_NEG:
  15394. {
  15395. if (src0->grad) {
  15396. src0->grad = ggml_sub_or_set(ctx, src0->grad, tensor->grad, zero_table, acc_table);
  15397. }
  15398. } break;
  15399. case GGML_UNARY_OP_STEP:
  15400. {
  15401. if (src0->grad) {
  15402. // noop
  15403. }
  15404. } break;
  15405. case GGML_UNARY_OP_TANH:
  15406. {
  15407. GGML_ABORT("fatal error"); // TODO: not implemented
  15408. }
  15409. case GGML_UNARY_OP_ELU:
  15410. {
  15411. GGML_ABORT("fatal error"); // TODO: not implemented
  15412. }
  15413. case GGML_UNARY_OP_RELU:
  15414. {
  15415. if (src0->grad) {
  15416. src0->grad = ggml_add_or_set(ctx,
  15417. src0->grad,
  15418. ggml_mul(ctx,
  15419. ggml_step(ctx, src0),
  15420. tensor->grad),
  15421. zero_table, acc_table);
  15422. }
  15423. } break;
  15424. case GGML_UNARY_OP_SIGMOID:
  15425. {
  15426. GGML_ABORT("fatal error"); // TODO: not implemented
  15427. }
  15428. case GGML_UNARY_OP_GELU:
  15429. {
  15430. GGML_ABORT("fatal error"); // TODO: not implemented
  15431. }
  15432. case GGML_UNARY_OP_GELU_QUICK:
  15433. {
  15434. GGML_ABORT("fatal error"); // TODO: not implemented
  15435. }
  15436. case GGML_UNARY_OP_SILU:
  15437. {
  15438. // necessary for llama
  15439. if (src0->grad) {
  15440. src0->grad = ggml_add_or_set(ctx,
  15441. src0->grad,
  15442. ggml_silu_back(ctx, src0, tensor->grad),
  15443. zero_table, acc_table);
  15444. }
  15445. } break;
  15446. case GGML_UNARY_OP_EXP:
  15447. {
  15448. if (src0->grad) {
  15449. src0->grad = ggml_add_or_set(ctx,
  15450. src0->grad,
  15451. ggml_mul(ctx, tensor, tensor->grad),
  15452. zero_table, acc_table);
  15453. }
  15454. } break;
  15455. default:
  15456. GGML_ABORT("fatal error");
  15457. }
  15458. } break;
  15459. case GGML_OP_GET_REL_POS:
  15460. case GGML_OP_ADD_REL_POS:
  15461. case GGML_OP_RWKV_WKV:
  15462. case GGML_OP_MAP_UNARY:
  15463. case GGML_OP_MAP_BINARY:
  15464. case GGML_OP_MAP_CUSTOM1_F32:
  15465. case GGML_OP_MAP_CUSTOM2_F32:
  15466. case GGML_OP_MAP_CUSTOM3_F32:
  15467. case GGML_OP_MAP_CUSTOM1:
  15468. case GGML_OP_MAP_CUSTOM2:
  15469. case GGML_OP_MAP_CUSTOM3:
  15470. {
  15471. GGML_ABORT("fatal error"); // not supported
  15472. }
  15473. case GGML_OP_CROSS_ENTROPY_LOSS:
  15474. {
  15475. if (src0->grad) {
  15476. src0->grad = ggml_add_or_set(ctx,
  15477. src0->grad,
  15478. ggml_cross_entropy_loss_back(ctx,
  15479. src0,
  15480. src1,
  15481. tensor->grad),
  15482. zero_table, acc_table);
  15483. }
  15484. GGML_ASSERT(!src1->grad && "backward pass for labels not implemented");
  15485. } break;
  15486. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  15487. {
  15488. GGML_ABORT("fatal error"); // not supported
  15489. }
  15490. case GGML_OP_OPT_STEP_ADAMW:
  15491. {
  15492. GGML_ABORT("fatal error"); // not supported
  15493. }
  15494. case GGML_OP_NONE:
  15495. {
  15496. // nop
  15497. } break;
  15498. case GGML_OP_COUNT:
  15499. {
  15500. GGML_ABORT("fatal error");
  15501. }
  15502. }
  15503. for (int i = 0; i < GGML_MAX_SRC; ++i) {
  15504. if (tensor->src[i] && tensor->src[i]->grad) {
  15505. GGML_ASSERT(ggml_are_same_shape(tensor->src[i], tensor->src[i]->grad));
  15506. }
  15507. }
  15508. }
  15509. static void ggml_visit_parents(struct ggml_cgraph * cgraph, struct ggml_tensor * node) {
  15510. if (node->grad == NULL) {
  15511. // this usually happens when we generate intermediate nodes from constants in the backward pass
  15512. // it can also happen during forward pass, if the user performs computations with constants
  15513. if (node->op != GGML_OP_NONE) {
  15514. //GGML_PRINT_DEBUG("%s: warning: node %p has no grad, but op %d\n", __func__, (void *) node, node->op);
  15515. }
  15516. }
  15517. // check if already visited
  15518. if (ggml_hash_insert(&cgraph->visited_hash_set, node) == GGML_HASHSET_ALREADY_EXISTS) {
  15519. return;
  15520. }
  15521. for (int i = 0; i < GGML_MAX_SRC; ++i) {
  15522. const int k =
  15523. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT) ? i :
  15524. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT) ? (GGML_MAX_SRC-1-i) :
  15525. /* unknown order, just fall back to using i*/ i;
  15526. if (node->src[k]) {
  15527. ggml_visit_parents(cgraph, node->src[k]);
  15528. }
  15529. }
  15530. if (node->op == GGML_OP_NONE && !(node->flags & GGML_TENSOR_FLAG_PARAM)) {
  15531. // reached a leaf node, not part of the gradient graph (e.g. a constant)
  15532. GGML_ASSERT(cgraph->n_leafs < cgraph->size);
  15533. if (strlen(node->name) == 0) {
  15534. ggml_format_name(node, "leaf_%d", cgraph->n_leafs);
  15535. }
  15536. cgraph->leafs[cgraph->n_leafs] = node;
  15537. cgraph->n_leafs++;
  15538. } else {
  15539. GGML_ASSERT(cgraph->n_nodes < cgraph->size);
  15540. if (strlen(node->name) == 0) {
  15541. ggml_format_name(node, "node_%d", cgraph->n_nodes);
  15542. }
  15543. cgraph->nodes[cgraph->n_nodes] = node;
  15544. cgraph->n_nodes++;
  15545. }
  15546. }
  15547. static void ggml_build_forward_impl(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor, bool expand) {
  15548. if (!expand) {
  15549. // TODO: this branch isn't accessible anymore, maybe move this to ggml_build_forward_expand
  15550. ggml_graph_clear(cgraph);
  15551. }
  15552. const int n0 = cgraph->n_nodes;
  15553. ggml_visit_parents(cgraph, tensor);
  15554. const int n_new = cgraph->n_nodes - n0;
  15555. GGML_PRINT_DEBUG("%s: visited %d new nodes\n", __func__, n_new);
  15556. if (n_new > 0) {
  15557. // the last added node should always be starting point
  15558. GGML_ASSERT(cgraph->nodes[cgraph->n_nodes - 1] == tensor);
  15559. }
  15560. }
  15561. void ggml_build_forward_expand(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  15562. ggml_build_forward_impl(cgraph, tensor, true);
  15563. }
  15564. void ggml_build_backward_expand(struct ggml_context * ctx, struct ggml_cgraph * gf, struct ggml_cgraph * gb, bool accumulate) {
  15565. GGML_ASSERT(gf->n_nodes > 0);
  15566. GGML_ASSERT(gf->grads);
  15567. for (int i = 0; i < gf->n_nodes; ++i) {
  15568. struct ggml_tensor * node = gf->nodes[i];
  15569. bool needs_grad = node->flags & GGML_TENSOR_FLAG_PARAM;
  15570. bool ignore_src[GGML_MAX_SRC] = {false};
  15571. switch (node->op) {
  15572. // gradients in node->src[0] for one reason or another have no effect on output gradients
  15573. case GGML_OP_IM2COL: // only used for its shape
  15574. case GGML_OP_IM2COL_BACK: // same as IM2COL
  15575. ignore_src[0] = true;
  15576. break;
  15577. case GGML_OP_UNARY: {
  15578. const enum ggml_unary_op uop = ggml_get_unary_op(node);
  15579. // SGN and STEP unary ops are piecewise constant
  15580. if (uop == GGML_UNARY_OP_SGN || uop == GGML_UNARY_OP_STEP) {
  15581. ignore_src[0] = true;
  15582. }
  15583. } break;
  15584. // gradients in node->src[1] for one reason or another have no effect on output gradients
  15585. case GGML_OP_CPY: // gradients in CPY target are irrelevant
  15586. case GGML_OP_GET_ROWS: // row indices not differentiable
  15587. case GGML_OP_GET_ROWS_BACK: // same as for GET_ROWS
  15588. case GGML_OP_ROPE: // positions not differentiable
  15589. ignore_src[1] = true;
  15590. break;
  15591. default:
  15592. break;
  15593. }
  15594. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  15595. if (!node->src[j] || !node->src[j]->grad || ignore_src[j]) {
  15596. continue;
  15597. }
  15598. GGML_ASSERT(node->src[j]->type == GGML_TYPE_F32 || node->src[j]->type == GGML_TYPE_F16);
  15599. needs_grad = true;
  15600. break;
  15601. }
  15602. if (!needs_grad) {
  15603. continue;
  15604. }
  15605. // inplace operations are currently not supported
  15606. GGML_ASSERT(!node->view_src || node->op == GGML_OP_CPY || node->op == GGML_OP_VIEW ||
  15607. node->op == GGML_OP_RESHAPE || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_TRANSPOSE);
  15608. // create a new tensor with the same type and shape as the node and set it as grad
  15609. node->grad = ggml_dup_tensor(ctx, node);
  15610. }
  15611. // keep tables of original gradients for replacement/accumulation logic
  15612. struct ggml_hash_set zero_table = ggml_hash_set_new(gf->size);
  15613. struct ggml_hash_set acc_table = ggml_hash_set_new(gf->size);
  15614. for (int i = 0; i < gf->n_nodes; i++) {
  15615. struct ggml_tensor * node = gf->nodes[i];
  15616. if (node->grad) {
  15617. {
  15618. const size_t insert_result = ggml_hash_insert(&zero_table, node->grad);
  15619. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  15620. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  15621. }
  15622. // only gradients of trainable parameters should be accumulated
  15623. if (accumulate && (node->flags & GGML_TENSOR_FLAG_PARAM)) {
  15624. const size_t insert_result = ggml_hash_insert(&acc_table, node->grad);
  15625. GGML_ASSERT(insert_result != GGML_HASHSET_FULL);
  15626. GGML_ASSERT(insert_result != GGML_HASHSET_ALREADY_EXISTS);
  15627. }
  15628. }
  15629. }
  15630. for (int i = gf->n_nodes - 1; i >= 0; i--) {
  15631. struct ggml_tensor * node = gf->nodes[i];
  15632. // inplace operations to add gradients are not created by ggml_compute_backward except for gradient accumulation
  15633. // use allocator to automatically make inplace operations
  15634. if (node->grad) {
  15635. ggml_compute_backward(ctx, node, &zero_table, &acc_table);
  15636. }
  15637. }
  15638. for (int i = 0; i < gf->n_nodes; i++) {
  15639. struct ggml_tensor * node = gf->nodes[i];
  15640. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  15641. GGML_PRINT_DEBUG("%s: found root node %p\n", __func__, (void *) node);
  15642. ggml_build_forward_expand(gb, node->grad);
  15643. }
  15644. }
  15645. ggml_hash_set_free(&zero_table);
  15646. ggml_hash_set_free(&acc_table);
  15647. }
  15648. void ggml_build_opt_adamw(
  15649. struct ggml_context * ctx,
  15650. struct ggml_cgraph * gf,
  15651. struct ggml_cgraph * gb,
  15652. float alpha,
  15653. float beta1,
  15654. float beta2,
  15655. float eps,
  15656. float wd) {
  15657. for (int i = 0; i < gf->n_nodes; i++) {
  15658. struct ggml_tensor * node = gf->nodes[i];
  15659. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  15660. GGML_PRINT_DEBUG("%s: found root node %p\n", __func__, (void *) node);
  15661. struct ggml_tensor * opt_step = ggml_opt_step_adamw(ctx, node, node->grad, alpha, beta1, beta2, eps, wd);
  15662. ggml_build_forward_expand(gb, opt_step);
  15663. }
  15664. }
  15665. }
  15666. static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
  15667. void * ptr = *p;
  15668. ptr = (void *) GGML_PAD((uintptr_t) ptr, align);
  15669. *p = (void *) ((char *) ptr + size);
  15670. return ptr;
  15671. }
  15672. static size_t ggml_graph_nbytes(size_t size, bool grads) {
  15673. size_t hash_size = ggml_hash_size(size * 2);
  15674. void * p = 0;
  15675. incr_ptr_aligned(&p, sizeof(struct ggml_cgraph), 1);
  15676. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // nodes
  15677. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // leafs
  15678. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // hash keys
  15679. if (grads) {
  15680. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grads
  15681. }
  15682. incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  15683. size_t nbytes = (size_t) p;
  15684. return nbytes;
  15685. }
  15686. size_t ggml_graph_overhead_custom(size_t size, bool grads) {
  15687. return GGML_OBJECT_SIZE + GGML_PAD(ggml_graph_nbytes(size, grads), GGML_MEM_ALIGN);
  15688. }
  15689. size_t ggml_graph_overhead(void) {
  15690. return ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, false);
  15691. }
  15692. struct ggml_cgraph * ggml_new_graph_custom(struct ggml_context * ctx, size_t size, bool grads) {
  15693. const size_t obj_size = ggml_graph_nbytes(size, grads);
  15694. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_GRAPH, obj_size);
  15695. struct ggml_cgraph * cgraph = (struct ggml_cgraph *) ((char *) ctx->mem_buffer + obj->offs);
  15696. // the size of the hash table is doubled since it needs to hold both nodes and leafs
  15697. size_t hash_size = ggml_hash_size(size * 2);
  15698. void * p = cgraph + 1;
  15699. struct ggml_tensor ** nodes_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  15700. struct ggml_tensor ** leafs_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  15701. struct ggml_tensor ** hash_keys_ptr = incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  15702. struct ggml_tensor ** grads_ptr = grads ? incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
  15703. ggml_bitset_t * hash_used = incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  15704. // check that we allocated the correct amount of memory
  15705. assert(obj_size == (size_t)((char *)p - (char *)cgraph));
  15706. *cgraph = (struct ggml_cgraph) {
  15707. /*.size =*/ size,
  15708. /*.n_nodes =*/ 0,
  15709. /*.n_leafs =*/ 0,
  15710. /*.nodes =*/ nodes_ptr,
  15711. /*.grads =*/ grads_ptr,
  15712. /*.leafs =*/ leafs_ptr,
  15713. /*.hash_table =*/ { hash_size, hash_used, hash_keys_ptr },
  15714. /*.order =*/ GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT,
  15715. };
  15716. ggml_hash_set_reset(&cgraph->visited_hash_set);
  15717. return cgraph;
  15718. }
  15719. struct ggml_cgraph * ggml_new_graph(struct ggml_context * ctx) {
  15720. return ggml_new_graph_custom(ctx, GGML_DEFAULT_GRAPH_SIZE, false);
  15721. }
  15722. struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph0, int i0, int i1) {
  15723. struct ggml_cgraph cgraph = {
  15724. /*.size =*/ 0,
  15725. /*.n_nodes =*/ i1 - i0,
  15726. /*.n_leafs =*/ 0,
  15727. /*.nodes =*/ cgraph0->nodes + i0,
  15728. /*.grads =*/ cgraph0->grads ? cgraph0->grads + i0 : NULL,
  15729. /*.leafs =*/ NULL,
  15730. /*.hash_table =*/ { 0, NULL, NULL },
  15731. /*.order =*/ cgraph0->order,
  15732. };
  15733. return cgraph;
  15734. }
  15735. void ggml_graph_cpy(struct ggml_cgraph * src, struct ggml_cgraph * dst) {
  15736. GGML_ASSERT(dst->size >= src->n_leafs);
  15737. GGML_ASSERT(dst->size >= src->n_nodes);
  15738. GGML_ASSERT(dst->visited_hash_set.size >= src->visited_hash_set.size);
  15739. dst->n_leafs = src->n_leafs;
  15740. dst->n_nodes = src->n_nodes;
  15741. dst->order = src->order;
  15742. for (int i = 0; i < src->n_leafs; ++i) {
  15743. dst->leafs[i] = src->leafs[i];
  15744. }
  15745. for (int i = 0; i < src->n_nodes; ++i) {
  15746. dst->nodes[i] = src->nodes[i];
  15747. }
  15748. if (src->grads) {
  15749. GGML_ASSERT(dst->grads != NULL);
  15750. for (int i = 0; i < src->n_nodes; ++i) {
  15751. dst->grads[i] = src->grads[i];
  15752. }
  15753. }
  15754. for (size_t i = 0; i < src->visited_hash_set.size; ++i) {
  15755. // copy all hashset keys (tensors) that are in use
  15756. if (ggml_bitset_get(src->visited_hash_set.used, i)) {
  15757. ggml_hash_insert(&dst->visited_hash_set, src->visited_hash_set.keys[i]);
  15758. }
  15759. }
  15760. }
  15761. struct ggml_cgraph * ggml_graph_dup(struct ggml_context * ctx, struct ggml_cgraph * cgraph) {
  15762. struct ggml_cgraph * result = ggml_new_graph_custom(ctx, cgraph->size, cgraph->grads != NULL);
  15763. ggml_graph_cpy(cgraph, result);
  15764. return result;
  15765. }
  15766. void ggml_graph_reset(struct ggml_cgraph * cgraph) {
  15767. GGML_ASSERT(cgraph->grads != NULL);
  15768. for (int i = 0; i < cgraph->n_nodes; i++) {
  15769. struct ggml_tensor * node = cgraph->nodes[i];
  15770. // initial gradients of loss should be 1, 0 otherwise
  15771. if (node->grad) {
  15772. if (node->flags & GGML_TENSOR_FLAG_LOSS) {
  15773. GGML_ASSERT(node->grad->buffer);
  15774. GGML_ASSERT(node->type == GGML_TYPE_F32);
  15775. GGML_ASSERT(ggml_is_scalar(node));
  15776. const float onef = 1.0f;
  15777. ggml_backend_tensor_set(node->grad, &onef, 0, ggml_nbytes(node->grad));
  15778. } else {
  15779. ggml_set_zero(node->grad);
  15780. }
  15781. }
  15782. GGML_ASSERT(node);
  15783. if (node->op == GGML_OP_OPT_STEP_ADAMW) {
  15784. // set iteration to 1 and clear momenta
  15785. ggml_set_op_params_i32(node, 0, 1);
  15786. ggml_set_zero(node->src[2]);
  15787. ggml_set_zero(node->src[3]);
  15788. }
  15789. }
  15790. }
  15791. void ggml_graph_clear(struct ggml_cgraph * cgraph) {
  15792. cgraph->n_leafs = 0;
  15793. cgraph->n_nodes = 0;
  15794. ggml_hash_set_reset(&cgraph->visited_hash_set);
  15795. }
  15796. int ggml_graph_size(struct ggml_cgraph * cgraph) {
  15797. return cgraph->size;
  15798. }
  15799. struct ggml_tensor * ggml_graph_node(struct ggml_cgraph * cgraph, int i) {
  15800. if (i < 0) {
  15801. GGML_ASSERT(cgraph->n_nodes + i >= 0);
  15802. return cgraph->nodes[cgraph->n_nodes + i];
  15803. }
  15804. GGML_ASSERT(i < cgraph->n_nodes);
  15805. return cgraph->nodes[i];
  15806. }
  15807. struct ggml_tensor ** ggml_graph_nodes(struct ggml_cgraph * cgraph) {
  15808. return cgraph->nodes;
  15809. }
  15810. int ggml_graph_n_nodes(struct ggml_cgraph * cgraph) {
  15811. return cgraph->n_nodes;
  15812. }
  15813. void ggml_graph_add_node(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  15814. GGML_ASSERT(cgraph->size > cgraph->n_nodes);
  15815. cgraph->nodes[cgraph->n_nodes] = tensor;
  15816. cgraph->n_nodes++;
  15817. }
  15818. // Android's libc implementation "bionic" does not support setting affinity
  15819. #if defined(__gnu_linux__)
  15820. static void set_numa_thread_affinity(int thread_n) {
  15821. if (!ggml_is_numa()) {
  15822. return;
  15823. }
  15824. int node_num;
  15825. int rv;
  15826. size_t setsize = CPU_ALLOC_SIZE(g_state.numa.total_cpus);
  15827. switch(g_state.numa.numa_strategy) {
  15828. case GGML_NUMA_STRATEGY_DISTRIBUTE:
  15829. // run thread on node_num thread_n / (threads per node)
  15830. node_num = thread_n % g_state.numa.n_nodes;
  15831. break;
  15832. case GGML_NUMA_STRATEGY_ISOLATE:
  15833. // run thread on current_node
  15834. node_num = g_state.numa.current_node;
  15835. break;
  15836. case GGML_NUMA_STRATEGY_NUMACTL:
  15837. // use the cpuset that numactl gave us
  15838. rv = pthread_setaffinity_np(pthread_self(), setsize, &g_state.numa.cpuset);
  15839. if (rv) {
  15840. fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n",strerror(rv));
  15841. }
  15842. return;
  15843. default:
  15844. return;
  15845. }
  15846. struct ggml_numa_node * node = &g_state.numa.nodes[node_num];
  15847. cpu_set_t * cpus = CPU_ALLOC(g_state.numa.total_cpus);
  15848. CPU_ZERO_S(setsize, cpus);
  15849. for (size_t i = 0; i < node->n_cpus; ++i) {
  15850. CPU_SET_S(node->cpus[i], setsize, cpus);
  15851. }
  15852. rv = pthread_setaffinity_np(pthread_self(), setsize, cpus);
  15853. if (rv) {
  15854. fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n", strerror(rv));
  15855. }
  15856. CPU_FREE(cpus);
  15857. }
  15858. static void clear_numa_thread_affinity(void) {
  15859. if (!ggml_is_numa()) {
  15860. return;
  15861. }
  15862. size_t setsize = CPU_ALLOC_SIZE(g_state.numa.total_cpus);
  15863. cpu_set_t * cpus = CPU_ALLOC(g_state.numa.total_cpus);
  15864. CPU_ZERO_S(setsize, cpus);
  15865. for (unsigned i = 0; i < g_state.numa.total_cpus; ++i) {
  15866. CPU_SET_S(i, setsize, cpus);
  15867. }
  15868. int rv = pthread_setaffinity_np(pthread_self(), setsize, cpus);
  15869. if (rv) {
  15870. fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n", strerror(rv));
  15871. }
  15872. CPU_FREE(cpus);
  15873. }
  15874. #else
  15875. // TODO: Windows etc.
  15876. // (the linux implementation may also work on BSD, someone should test)
  15877. static void set_numa_thread_affinity(int thread_n) { UNUSED(thread_n); }
  15878. static void clear_numa_thread_affinity(void) {}
  15879. #endif
  15880. static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) {
  15881. int n_tasks = 0;
  15882. if (ggml_is_empty(node)) {
  15883. // no need to multi-thread a no-op
  15884. n_tasks = 1;
  15885. return n_tasks;
  15886. }
  15887. switch (node->op) {
  15888. case GGML_OP_CPY:
  15889. case GGML_OP_DUP:
  15890. case GGML_OP_CONT:
  15891. case GGML_OP_ADD:
  15892. case GGML_OP_ADD1:
  15893. case GGML_OP_ACC:
  15894. {
  15895. n_tasks = n_threads;
  15896. } break;
  15897. case GGML_OP_SUB:
  15898. case GGML_OP_SQR:
  15899. case GGML_OP_SQRT:
  15900. case GGML_OP_LOG:
  15901. case GGML_OP_SIN:
  15902. case GGML_OP_COS:
  15903. case GGML_OP_SUM:
  15904. case GGML_OP_SUM_ROWS:
  15905. case GGML_OP_MEAN:
  15906. case GGML_OP_ARGMAX:
  15907. case GGML_OP_REPEAT:
  15908. case GGML_OP_REPEAT_BACK:
  15909. case GGML_OP_LEAKY_RELU:
  15910. {
  15911. n_tasks = 1;
  15912. } break;
  15913. case GGML_OP_UNARY:
  15914. switch (ggml_get_unary_op(node)) {
  15915. case GGML_UNARY_OP_ABS:
  15916. case GGML_UNARY_OP_SGN:
  15917. case GGML_UNARY_OP_NEG:
  15918. case GGML_UNARY_OP_STEP:
  15919. case GGML_UNARY_OP_TANH:
  15920. case GGML_UNARY_OP_ELU:
  15921. case GGML_UNARY_OP_RELU:
  15922. case GGML_UNARY_OP_SIGMOID:
  15923. case GGML_UNARY_OP_HARDSWISH:
  15924. case GGML_UNARY_OP_HARDSIGMOID:
  15925. case GGML_UNARY_OP_EXP:
  15926. {
  15927. n_tasks = 1;
  15928. } break;
  15929. case GGML_UNARY_OP_GELU:
  15930. case GGML_UNARY_OP_GELU_QUICK:
  15931. case GGML_UNARY_OP_SILU:
  15932. {
  15933. n_tasks = n_threads;
  15934. } break;
  15935. default:
  15936. GGML_ABORT("fatal error");
  15937. }
  15938. break;
  15939. case GGML_OP_SILU_BACK:
  15940. case GGML_OP_MUL:
  15941. case GGML_OP_DIV:
  15942. case GGML_OP_NORM:
  15943. case GGML_OP_RMS_NORM:
  15944. case GGML_OP_RMS_NORM_BACK:
  15945. case GGML_OP_GROUP_NORM:
  15946. case GGML_OP_CONCAT:
  15947. case GGML_OP_MUL_MAT:
  15948. case GGML_OP_MUL_MAT_ID:
  15949. case GGML_OP_OUT_PROD:
  15950. {
  15951. n_tasks = n_threads;
  15952. } break;
  15953. case GGML_OP_GET_ROWS:
  15954. {
  15955. // FIXME: get_rows can use additional threads, but the cost of launching additional threads
  15956. // decreases performance with GPU offloading
  15957. //n_tasks = n_threads;
  15958. n_tasks = 1;
  15959. } break;
  15960. case GGML_OP_SCALE:
  15961. case GGML_OP_SET:
  15962. case GGML_OP_RESHAPE:
  15963. case GGML_OP_VIEW:
  15964. case GGML_OP_PERMUTE:
  15965. case GGML_OP_TRANSPOSE:
  15966. case GGML_OP_GET_ROWS_BACK:
  15967. case GGML_OP_DIAG:
  15968. {
  15969. n_tasks = 1;
  15970. } break;
  15971. case GGML_OP_DIAG_MASK_ZERO:
  15972. case GGML_OP_DIAG_MASK_INF:
  15973. case GGML_OP_SOFT_MAX_BACK:
  15974. case GGML_OP_ROPE:
  15975. case GGML_OP_ROPE_BACK:
  15976. case GGML_OP_ADD_REL_POS:
  15977. {
  15978. n_tasks = n_threads;
  15979. } break;
  15980. case GGML_OP_CLAMP:
  15981. {
  15982. n_tasks = 1; //TODO
  15983. } break;
  15984. case GGML_OP_SOFT_MAX:
  15985. {
  15986. n_tasks = MIN(n_threads, ggml_nrows(node->src[0]));
  15987. } break;
  15988. case GGML_OP_IM2COL:
  15989. case GGML_OP_IM2COL_BACK:
  15990. case GGML_OP_CONV_TRANSPOSE_1D:
  15991. case GGML_OP_CONV_TRANSPOSE_2D:
  15992. {
  15993. n_tasks = n_threads;
  15994. } break;
  15995. case GGML_OP_POOL_1D:
  15996. case GGML_OP_POOL_2D:
  15997. case GGML_OP_POOL_2D_BACK:
  15998. {
  15999. n_tasks = 1;
  16000. } break;
  16001. case GGML_OP_UPSCALE:
  16002. case GGML_OP_PAD:
  16003. case GGML_OP_UNPAD:
  16004. case GGML_OP_ARANGE:
  16005. case GGML_OP_TIMESTEP_EMBEDDING:
  16006. case GGML_OP_ARGSORT:
  16007. case GGML_OP_FLASH_ATTN_EXT:
  16008. case GGML_OP_FLASH_ATTN_BACK:
  16009. case GGML_OP_SSM_CONV:
  16010. case GGML_OP_SSM_SCAN:
  16011. {
  16012. n_tasks = n_threads;
  16013. } break;
  16014. case GGML_OP_WIN_PART:
  16015. case GGML_OP_WIN_UNPART:
  16016. case GGML_OP_GET_REL_POS:
  16017. case GGML_OP_RWKV_WKV:
  16018. case GGML_OP_MAP_UNARY:
  16019. case GGML_OP_MAP_BINARY:
  16020. case GGML_OP_MAP_CUSTOM1_F32:
  16021. case GGML_OP_MAP_CUSTOM2_F32:
  16022. case GGML_OP_MAP_CUSTOM3_F32:
  16023. {
  16024. n_tasks = 1;
  16025. } break;
  16026. case GGML_OP_MAP_CUSTOM1:
  16027. {
  16028. struct ggml_map_custom1_op_params p;
  16029. memcpy(&p, node->op_params, sizeof(p));
  16030. if (p.n_tasks == GGML_N_TASKS_MAX) {
  16031. n_tasks = n_threads;
  16032. } else {
  16033. n_tasks = MIN(p.n_tasks, n_threads);
  16034. }
  16035. } break;
  16036. case GGML_OP_MAP_CUSTOM2:
  16037. {
  16038. struct ggml_map_custom2_op_params p;
  16039. memcpy(&p, node->op_params, sizeof(p));
  16040. if (p.n_tasks == GGML_N_TASKS_MAX) {
  16041. n_tasks = n_threads;
  16042. } else {
  16043. n_tasks = MIN(p.n_tasks, n_threads);
  16044. }
  16045. } break;
  16046. case GGML_OP_MAP_CUSTOM3:
  16047. {
  16048. struct ggml_map_custom3_op_params p;
  16049. memcpy(&p, node->op_params, sizeof(p));
  16050. if (p.n_tasks == GGML_N_TASKS_MAX) {
  16051. n_tasks = n_threads;
  16052. } else {
  16053. n_tasks = MIN(p.n_tasks, n_threads);
  16054. }
  16055. } break;
  16056. case GGML_OP_CROSS_ENTROPY_LOSS:
  16057. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  16058. case GGML_OP_OPT_STEP_ADAMW:
  16059. {
  16060. n_tasks = n_threads;
  16061. } break;
  16062. case GGML_OP_NONE:
  16063. {
  16064. n_tasks = 1;
  16065. } break;
  16066. case GGML_OP_COUNT:
  16067. {
  16068. GGML_ABORT("fatal error");
  16069. }
  16070. default:
  16071. {
  16072. fprintf(stderr, "%s: op not implemented: ", __func__);
  16073. if (node->op < GGML_OP_COUNT) {
  16074. fprintf(stderr, "%s\n", ggml_op_name(node->op));
  16075. } else {
  16076. fprintf(stderr, "%d\n", node->op);
  16077. }
  16078. GGML_ABORT("fatal error");
  16079. }
  16080. }
  16081. assert(n_tasks > 0);
  16082. return n_tasks;
  16083. }
  16084. static thread_ret_t ggml_graph_compute_secondary_thread(void* data);
  16085. #if defined(_WIN32)
  16086. #include "windows.h"
  16087. // TODO: support > 64 CPUs
  16088. bool ggml_thread_apply_affinity(bool * mask) {
  16089. HANDLE h = GetCurrentThread();
  16090. uint64_t bitmask = 0ULL;
  16091. assert(GGML_MAX_N_THREADS >= 64);
  16092. for (int32_t i = 0; i < 8; i++) {
  16093. int32_t idx = i * 8;
  16094. uint8_t val = 0;
  16095. val |= mask[idx + 0] << 0;
  16096. val |= mask[idx + 1] << 1;
  16097. val |= mask[idx + 2] << 2;
  16098. val |= mask[idx + 3] << 3;
  16099. val |= mask[idx + 4] << 4;
  16100. val |= mask[idx + 5] << 5;
  16101. val |= mask[idx + 6] << 6;
  16102. val |= mask[idx + 7] << 7;
  16103. bitmask |= (uint64_t)val << idx;
  16104. }
  16105. for (int32_t i = 64; i < GGML_MAX_N_THREADS; i++) {
  16106. if (mask[i]) {
  16107. fprintf(stderr, "warn: setting thread-affinity for > 64 CPUs isn't supported on windows!\n");
  16108. break;
  16109. }
  16110. }
  16111. DWORD_PTR m = (DWORD_PTR)bitmask;
  16112. m = SetThreadAffinityMask(h, m);
  16113. return m != 0;
  16114. }
  16115. static bool ggml_thread_apply_priority(int32_t prio) {
  16116. // Note that on Windows the Process Priority Class must be updated in order to set Thread priority.
  16117. // This is up to the applications.
  16118. DWORD p = THREAD_PRIORITY_NORMAL;
  16119. switch (prio) {
  16120. case GGML_SCHED_PRIO_NORMAL: p = THREAD_PRIORITY_NORMAL; break;
  16121. case GGML_SCHED_PRIO_MEDIUM: p = THREAD_PRIORITY_ABOVE_NORMAL; break;
  16122. case GGML_SCHED_PRIO_HIGH: p = THREAD_PRIORITY_HIGHEST; break;
  16123. case GGML_SCHED_PRIO_REALTIME: p = THREAD_PRIORITY_TIME_CRITICAL; break;
  16124. }
  16125. if (prio == GGML_SCHED_PRIO_NORMAL) {
  16126. // Keep inherited policy/priority
  16127. return true;
  16128. }
  16129. if (!SetThreadPriority(GetCurrentThread(), p)) {
  16130. fprintf(stderr, "warn: failed to set thread priority %d : (%d)\n", prio, (int) GetLastError());
  16131. return false;
  16132. }
  16133. return true;
  16134. }
  16135. #elif defined(__APPLE__)
  16136. #include <sys/types.h>
  16137. #include <sys/resource.h>
  16138. static bool ggml_thread_apply_affinity(const bool * mask) {
  16139. // Not supported on Apple platforms
  16140. UNUSED(mask);
  16141. return true;
  16142. }
  16143. static bool ggml_thread_apply_priority(int32_t prio) {
  16144. struct sched_param p;
  16145. int32_t policy = SCHED_OTHER;
  16146. switch (prio) {
  16147. case GGML_SCHED_PRIO_NORMAL: policy = SCHED_OTHER; p.sched_priority = 0; break;
  16148. case GGML_SCHED_PRIO_MEDIUM: policy = SCHED_FIFO; p.sched_priority = 40; break;
  16149. case GGML_SCHED_PRIO_HIGH: policy = SCHED_FIFO; p.sched_priority = 80; break;
  16150. case GGML_SCHED_PRIO_REALTIME: policy = SCHED_FIFO; p.sched_priority = 90; break;
  16151. }
  16152. if (prio == GGML_SCHED_PRIO_NORMAL) {
  16153. // Keep inherited policy/priority
  16154. return true;
  16155. }
  16156. int32_t err = pthread_setschedparam(pthread_self(), policy, &p);
  16157. if (err != 0) {
  16158. fprintf(stderr, "warn: failed to set thread priority %d : %s (%d)\n", prio, strerror(err), err);
  16159. return false;
  16160. }
  16161. return true;
  16162. }
  16163. #elif defined(__gnu_linux__)
  16164. // TODO: this may not work on BSD, to be verified
  16165. static bool ggml_thread_apply_affinity(const bool * mask) {
  16166. cpu_set_t cpuset;
  16167. int err;
  16168. CPU_ZERO(&cpuset);
  16169. for (uint32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
  16170. if (mask[i]) {
  16171. GGML_PRINT_DEBUG("Thread %lx: adding %d to cpuset\n", pthread_self(), i);
  16172. CPU_SET(i, &cpuset);
  16173. }
  16174. }
  16175. #ifdef __ANDROID__
  16176. err = sched_setaffinity(0, sizeof(cpuset), &cpuset);
  16177. if (err < 0) {
  16178. err = errno;
  16179. }
  16180. #else
  16181. err = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
  16182. #endif
  16183. if (err != 0) {
  16184. fprintf(stderr, "warn: failed to set affinity mask 0x%llx : %s (%d)\n", (unsigned long long)mask, strerror(err), err);
  16185. return false;
  16186. }
  16187. return true;
  16188. }
  16189. static bool ggml_thread_apply_priority(int32_t prio) {
  16190. struct sched_param p;
  16191. int32_t policy = SCHED_OTHER;
  16192. switch (prio) {
  16193. case GGML_SCHED_PRIO_NORMAL: policy = SCHED_OTHER; p.sched_priority = 0; break;
  16194. case GGML_SCHED_PRIO_MEDIUM: policy = SCHED_FIFO; p.sched_priority = 40; break;
  16195. case GGML_SCHED_PRIO_HIGH: policy = SCHED_FIFO; p.sched_priority = 80; break;
  16196. case GGML_SCHED_PRIO_REALTIME: policy = SCHED_FIFO; p.sched_priority = 90; break;
  16197. }
  16198. if (prio == GGML_SCHED_PRIO_NORMAL) {
  16199. // Keep inherited policy/priority
  16200. return true;
  16201. }
  16202. int32_t err = pthread_setschedparam(pthread_self(), policy, &p);
  16203. if (err != 0) {
  16204. fprintf(stderr, "warn: failed to set thread priority %d : %s (%d)\n", prio, strerror(err), err);
  16205. return false;
  16206. }
  16207. return true;
  16208. }
  16209. #else // unsupported platforms
  16210. static bool ggml_thread_apply_affinity(const bool * mask) {
  16211. UNUSED(mask);
  16212. return true;
  16213. }
  16214. static bool ggml_thread_apply_priority(int32_t prio) {
  16215. UNUSED(prio);
  16216. return true;
  16217. }
  16218. #endif
  16219. static bool ggml_thread_cpumask_is_valid(const bool * mask) {
  16220. for (int i = 0; i < GGML_MAX_N_THREADS; i++) {
  16221. if (mask[i]) { return true; }
  16222. }
  16223. return false;
  16224. }
  16225. static void ggml_thread_cpumask_next(const bool * global_mask, bool * local_mask, bool strict, int32_t* iter) {
  16226. if (!strict) {
  16227. memcpy(local_mask, global_mask, GGML_MAX_N_THREADS);
  16228. return;
  16229. } else {
  16230. memset(local_mask, 0, GGML_MAX_N_THREADS);
  16231. int32_t base_idx = *iter;
  16232. for (int32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
  16233. int32_t idx = base_idx + i;
  16234. if (idx >= GGML_MAX_N_THREADS) {
  16235. // Just a cheaper modulo
  16236. idx -= GGML_MAX_N_THREADS;
  16237. }
  16238. if (global_mask[idx]) {
  16239. local_mask[idx] = 1;
  16240. *iter = idx + 1;
  16241. return;
  16242. }
  16243. }
  16244. }
  16245. }
  16246. void ggml_threadpool_free(struct ggml_threadpool* threadpool) {
  16247. if (!threadpool) return;
  16248. #ifndef GGML_USE_OPENMP
  16249. struct ggml_compute_state* workers = threadpool->workers;
  16250. const int n_threads = threadpool->n_threads_max;
  16251. ggml_mutex_lock(&threadpool->mutex);
  16252. threadpool->stop = true;
  16253. threadpool->pause = false;
  16254. ggml_cond_broadcast(&threadpool->cond);
  16255. ggml_mutex_unlock(&threadpool->mutex);
  16256. for (int j = 1; j < n_threads; j++) {
  16257. int32_t rc = ggml_thread_join(workers[j].thrd, NULL);
  16258. GGML_ASSERT(rc == GGML_EXIT_SUCCESS || rc == GGML_EXIT_ABORTED);
  16259. UNUSED(rc);
  16260. }
  16261. ggml_mutex_destroy(&threadpool->mutex);
  16262. ggml_cond_destroy(&threadpool->cond);
  16263. #endif // GGML_USE_OPENMP
  16264. GGML_ALIGNED_FREE(threadpool->workers);
  16265. GGML_ALIGNED_FREE(threadpool);
  16266. }
  16267. #ifndef GGML_USE_OPENMP
  16268. // pause/resume must be called under mutex
  16269. static void ggml_threadpool_pause_locked(struct ggml_threadpool * threadpool) {
  16270. GGML_PRINT_DEBUG("Pausing threadpool\n");
  16271. threadpool->pause = true;
  16272. ggml_cond_broadcast(&threadpool->cond);
  16273. }
  16274. static void ggml_threadpool_resume_locked(struct ggml_threadpool * threadpool) {
  16275. GGML_PRINT_DEBUG("Resuming threadpool\n");
  16276. threadpool->pause = false;
  16277. ggml_cond_broadcast(&threadpool->cond);
  16278. }
  16279. #endif
  16280. void ggml_threadpool_pause(struct ggml_threadpool * threadpool) {
  16281. #ifndef GGML_USE_OPENMP
  16282. ggml_mutex_lock(&threadpool->mutex);
  16283. if (!threadpool->pause) {
  16284. ggml_threadpool_pause_locked(threadpool);
  16285. }
  16286. ggml_mutex_unlock(&threadpool->mutex);
  16287. #else
  16288. UNUSED(threadpool);
  16289. #endif
  16290. }
  16291. void ggml_threadpool_resume(struct ggml_threadpool * threadpool) {
  16292. #ifndef GGML_USE_OPENMP
  16293. ggml_mutex_lock(&threadpool->mutex);
  16294. if (threadpool->pause) {
  16295. ggml_threadpool_resume_locked(threadpool);
  16296. }
  16297. ggml_mutex_unlock(&threadpool->mutex);
  16298. #else
  16299. UNUSED(threadpool);
  16300. #endif
  16301. }
  16302. struct ggml_cplan ggml_graph_plan(
  16303. const struct ggml_cgraph * cgraph,
  16304. int n_threads,
  16305. struct ggml_threadpool * threadpool) {
  16306. if (threadpool == NULL) {
  16307. GGML_PRINT_DEBUG("Threadpool is not specified. Will create a disposable threadpool : n_threads %d\n", n_threads);
  16308. }
  16309. if (n_threads <= 0) {
  16310. n_threads = threadpool ? threadpool->n_threads_max : GGML_DEFAULT_N_THREADS;
  16311. }
  16312. size_t work_size = 0;
  16313. struct ggml_cplan cplan;
  16314. memset(&cplan, 0, sizeof(struct ggml_cplan));
  16315. int max_tasks = 1;
  16316. // thread scheduling for the different operations + work buffer size estimation
  16317. for (int i = 0; i < cgraph->n_nodes; i++) {
  16318. struct ggml_tensor * node = cgraph->nodes[i];
  16319. const int n_tasks = ggml_get_n_tasks(node, n_threads);
  16320. max_tasks = MAX(max_tasks, n_tasks);
  16321. size_t cur = 0;
  16322. switch (node->op) {
  16323. case GGML_OP_CPY:
  16324. case GGML_OP_DUP:
  16325. {
  16326. if (ggml_is_quantized(node->type) ||
  16327. // F16 -> BF16 and BF16 -> F16 copies go through intermediate F32
  16328. (node->src[0]->type == GGML_TYPE_F16 && node->src[1] && node->src[1]->type == GGML_TYPE_BF16) ||
  16329. (node->src[0]->type == GGML_TYPE_BF16 && node->src[1] && node->src[1]->type == GGML_TYPE_F16)) {
  16330. cur = ggml_type_size(GGML_TYPE_F32) * node->ne[0] * n_tasks;
  16331. }
  16332. } break;
  16333. case GGML_OP_ADD:
  16334. case GGML_OP_ADD1:
  16335. {
  16336. if (ggml_is_quantized(node->src[0]->type)) {
  16337. cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
  16338. }
  16339. } break;
  16340. case GGML_OP_ACC:
  16341. {
  16342. if (ggml_is_quantized(node->src[0]->type)) {
  16343. cur = ggml_type_size(GGML_TYPE_F32) * node->src[1]->ne[0] * n_tasks;
  16344. }
  16345. } break;
  16346. case GGML_OP_MUL_MAT:
  16347. {
  16348. const enum ggml_type vec_dot_type = type_traits[node->src[0]->type].vec_dot_type;
  16349. if (node->src[1]->type != vec_dot_type) {
  16350. cur = ggml_row_size(vec_dot_type, ggml_nelements(node->src[1]));
  16351. }
  16352. } break;
  16353. case GGML_OP_MUL_MAT_ID:
  16354. {
  16355. cur = 0;
  16356. const struct ggml_tensor * src0 = node->src[0];
  16357. const struct ggml_tensor * src1 = node->src[1];
  16358. const enum ggml_type vec_dot_type = type_traits[src0->type].vec_dot_type;
  16359. if (src1->type != vec_dot_type) {
  16360. cur += ggml_row_size(vec_dot_type, ggml_nelements(src1));
  16361. }
  16362. const int n_as = src0->ne[2];
  16363. cur += GGML_PAD(cur, sizeof(int64_t)); // align
  16364. cur += n_as * sizeof(int64_t); // matrix_row_counts
  16365. cur += n_as * src1->ne[2] * sizeof(int64_t); // matrix_rows
  16366. } break;
  16367. case GGML_OP_OUT_PROD:
  16368. {
  16369. if (ggml_is_quantized(node->src[0]->type)) {
  16370. cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
  16371. }
  16372. } break;
  16373. case GGML_OP_SOFT_MAX:
  16374. case GGML_OP_ROPE:
  16375. {
  16376. cur = ggml_type_size(GGML_TYPE_F32) * node->ne[0] * n_tasks;
  16377. } break;
  16378. case GGML_OP_CONV_TRANSPOSE_1D:
  16379. {
  16380. GGML_ASSERT(node->src[0]->ne[3] == 1);
  16381. GGML_ASSERT(node->src[1]->ne[2] == 1);
  16382. GGML_ASSERT(node->src[1]->ne[3] == 1);
  16383. const int64_t ne00 = node->src[0]->ne[0]; // K
  16384. const int64_t ne01 = node->src[0]->ne[1]; // Cout
  16385. const int64_t ne02 = node->src[0]->ne[2]; // Cin
  16386. const int64_t ne10 = node->src[1]->ne[0]; // L
  16387. const int64_t ne11 = node->src[1]->ne[1]; // Cin
  16388. if ((node->src[0]->type == GGML_TYPE_F16 ||
  16389. node->src[0]->type == GGML_TYPE_BF16) &&
  16390. node->src[1]->type == GGML_TYPE_F32) {
  16391. cur += sizeof(ggml_fp16_t)*ne00*ne01*ne02;
  16392. cur += sizeof(ggml_fp16_t)*ne10*ne11;
  16393. } else if (node->src[0]->type == GGML_TYPE_F32 &&
  16394. node->src[1]->type == GGML_TYPE_F32) {
  16395. cur += sizeof(float)*ne00*ne01*ne02;
  16396. cur += sizeof(float)*ne10*ne11;
  16397. } else {
  16398. GGML_ABORT("fatal error");
  16399. }
  16400. } break;
  16401. case GGML_OP_CONV_TRANSPOSE_2D:
  16402. {
  16403. const int64_t ne00 = node->src[0]->ne[0]; // W
  16404. const int64_t ne01 = node->src[0]->ne[1]; // H
  16405. const int64_t ne02 = node->src[0]->ne[2]; // Channels Out
  16406. const int64_t ne03 = node->src[0]->ne[3]; // Channels In
  16407. const int64_t ne10 = node->src[1]->ne[0]; // W
  16408. const int64_t ne11 = node->src[1]->ne[1]; // H
  16409. const int64_t ne12 = node->src[1]->ne[2]; // Channels In
  16410. cur += sizeof(ggml_fp16_t)*ne00*ne01*ne02*ne03;
  16411. cur += sizeof(ggml_fp16_t)*ne10*ne11*ne12;
  16412. } break;
  16413. case GGML_OP_FLASH_ATTN_EXT:
  16414. {
  16415. const int64_t ne00 = node->src[0]->ne[0]; // D
  16416. cur = 3*sizeof(float)*ne00*n_tasks; // 3x head size/thread
  16417. } break;
  16418. case GGML_OP_FLASH_ATTN_BACK:
  16419. {
  16420. const int64_t D = node->src[0]->ne[0];
  16421. const int64_t ne11 = ggml_up(node->src[1]->ne[1], GGML_SOFT_MAX_UNROLL);
  16422. const int64_t mxDn = MAX(D, ne11) * 2; // *2 because of S and SM in ggml_compute_forward_flash_attn_back
  16423. if (node->src[1]->type == GGML_TYPE_F32) {
  16424. cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1)
  16425. cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2
  16426. } else if (node->src[1]->type == GGML_TYPE_F16) {
  16427. cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1)
  16428. cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2
  16429. } else if (node->src[1]->type == GGML_TYPE_BF16) {
  16430. cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1)
  16431. cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2
  16432. }
  16433. } break;
  16434. case GGML_OP_CROSS_ENTROPY_LOSS:
  16435. {
  16436. cur = ggml_type_size(node->type)*(n_tasks + node->src[0]->ne[0]*n_tasks);
  16437. } break;
  16438. case GGML_OP_COUNT:
  16439. {
  16440. GGML_ABORT("fatal error");
  16441. }
  16442. default:
  16443. break;
  16444. }
  16445. work_size = MAX(work_size, cur);
  16446. }
  16447. if (work_size > 0) {
  16448. work_size += CACHE_LINE_SIZE*(n_threads);
  16449. }
  16450. cplan.threadpool = threadpool;
  16451. cplan.n_threads = MIN(max_tasks, n_threads);
  16452. cplan.work_size = work_size;
  16453. cplan.work_data = NULL;
  16454. return cplan;
  16455. }
  16456. static thread_ret_t ggml_graph_compute_thread(void * data) {
  16457. struct ggml_compute_state * state = (struct ggml_compute_state *) data;
  16458. struct ggml_threadpool * tp = state->threadpool;
  16459. const struct ggml_cgraph * cgraph = tp->cgraph;
  16460. const struct ggml_cplan * cplan = tp->cplan;
  16461. set_numa_thread_affinity(state->ith);
  16462. struct ggml_compute_params params = {
  16463. /*.ith =*/ state->ith,
  16464. /*.nth =*/ atomic_load_explicit(&tp->n_threads_cur, memory_order_relaxed),
  16465. /*.wsize =*/ cplan->work_size,
  16466. /*.wdata =*/ cplan->work_data,
  16467. /*.threadpool=*/ tp,
  16468. };
  16469. for (int node_n = 0; node_n < cgraph->n_nodes && !tp->abort; node_n++) {
  16470. struct ggml_tensor * node = cgraph->nodes[node_n];
  16471. ggml_compute_forward(&params, node);
  16472. if (state->ith == 0 && cplan->abort_callback &&
  16473. cplan->abort_callback(cplan->abort_callback_data)) {
  16474. tp->abort = true;
  16475. tp->ec = GGML_STATUS_ABORTED;
  16476. }
  16477. ggml_barrier(state->threadpool);
  16478. }
  16479. return 0;
  16480. }
  16481. #ifndef GGML_USE_OPENMP
  16482. // check if thread is active
  16483. static inline bool ggml_graph_compute_thread_active(struct ggml_compute_state * state) {
  16484. struct ggml_threadpool * threadpool = state->threadpool;
  16485. int n_threads = atomic_load_explicit(&threadpool->n_threads_cur, memory_order_relaxed);
  16486. return (state->ith < n_threads);
  16487. }
  16488. // check if thread is ready to proceed (exit from polling or sleeping)
  16489. static inline bool ggml_graph_compute_thread_ready(struct ggml_compute_state * state) {
  16490. struct ggml_threadpool * threadpool = state->threadpool;
  16491. if (state->pending || threadpool->stop || threadpool->pause) { return true; }
  16492. // check for new graph/work
  16493. int new_graph = atomic_load_explicit(&threadpool->n_graph, memory_order_relaxed);
  16494. if (new_graph != state->last_graph) {
  16495. state->pending = ggml_graph_compute_thread_active(state);
  16496. state->last_graph = new_graph;
  16497. }
  16498. return state->pending;
  16499. }
  16500. // sync thread state after polling
  16501. static inline void ggml_graph_compute_thread_sync(struct ggml_compute_state * state) {
  16502. // TSAN doesn't support standalone fence yet, we use a dummy read-modify-write instead
  16503. #ifdef GGML_TSAN_ENABLED
  16504. atomic_fetch_add_explicit(&state->threadpool->n_graph, 0, memory_order_seq_cst);
  16505. #else
  16506. atomic_thread_fence(memory_order_seq_cst);
  16507. #endif
  16508. UNUSED(state);
  16509. }
  16510. static inline bool ggml_graph_compute_poll_for_work(struct ggml_compute_state * state) {
  16511. struct ggml_threadpool * threadpool = state->threadpool;
  16512. // Skip polling for unused threads
  16513. if (!ggml_graph_compute_thread_active(state)) {
  16514. return state->pending;
  16515. }
  16516. // This seems to make 0 ... 100 a decent range for polling level across modern processors.
  16517. // Perhaps, we can adjust it dynamically based on load and things.
  16518. const uint64_t n_rounds = 1024UL * 128 * threadpool->poll;
  16519. for (uint64_t i=0; !ggml_graph_compute_thread_ready(state) && i < n_rounds; i++) {
  16520. // No new work. Keep polling.
  16521. ggml_thread_cpu_relax();
  16522. }
  16523. return state->pending;
  16524. }
  16525. static inline bool ggml_graph_compute_check_for_work(struct ggml_compute_state * state) {
  16526. struct ggml_threadpool * threadpool = state->threadpool;
  16527. if (ggml_graph_compute_poll_for_work(state)) {
  16528. ggml_graph_compute_thread_sync(state);
  16529. return state->pending;
  16530. }
  16531. ggml_mutex_lock_shared(&threadpool->mutex);
  16532. while (!ggml_graph_compute_thread_ready(state)) {
  16533. // No new work. Wait for the signal.
  16534. GGML_PRINT_DEBUG("thread #%d waiting for work (sleeping)\n", state->ith);
  16535. ggml_cond_wait(&threadpool->cond, &threadpool->mutex);
  16536. }
  16537. ggml_mutex_unlock_shared(&threadpool->mutex);
  16538. return state->pending;
  16539. }
  16540. static thread_ret_t ggml_graph_compute_secondary_thread(void* data) {
  16541. struct ggml_compute_state * state = (struct ggml_compute_state *) data;
  16542. struct ggml_threadpool * threadpool = state->threadpool;
  16543. ggml_thread_apply_priority(threadpool->prio);
  16544. if (ggml_thread_cpumask_is_valid(state->cpumask)) {
  16545. ggml_thread_apply_affinity(state->cpumask);
  16546. }
  16547. while (true) {
  16548. // Check if we need to sleep
  16549. while (threadpool->pause) {
  16550. GGML_PRINT_DEBUG("thread #%d inside pause loop\n", state->ith);
  16551. ggml_mutex_lock_shared(&threadpool->mutex);
  16552. if (threadpool->pause) {
  16553. ggml_cond_wait(&threadpool->cond, &threadpool->mutex);
  16554. }
  16555. GGML_PRINT_DEBUG("thread #%d resuming after wait\n", state->ith);
  16556. ggml_mutex_unlock_shared(&threadpool->mutex);
  16557. }
  16558. // This needs to be checked for after the cond_wait
  16559. if (threadpool->stop) break;
  16560. // Check if there is new work
  16561. // The main thread is the only one that can dispatch new work
  16562. ggml_graph_compute_check_for_work(state);
  16563. if (state->pending) {
  16564. state->pending = false;
  16565. ggml_graph_compute_thread(state);
  16566. }
  16567. }
  16568. return (thread_ret_t) 0;
  16569. }
  16570. // Start processing new graph
  16571. static void ggml_graph_compute_kickoff(struct ggml_threadpool * threadpool, int n_threads)
  16572. {
  16573. // Always take the mutex here because the worker threads are doing hybrid poll/wait
  16574. ggml_mutex_lock(&threadpool->mutex);
  16575. GGML_PRINT_DEBUG("threadpool: n_threads_cur %d n_threads %d\n", threadpool->n_threads_cur, n_threads);
  16576. // Update the number of active threads
  16577. atomic_store_explicit(&threadpool->n_threads_cur, n_threads, memory_order_relaxed);
  16578. // Indicate the graph is ready to be processed
  16579. // We need the full seq-cst fence here because of the polling threads (used in thread_sync)
  16580. atomic_fetch_add_explicit(&threadpool->n_graph, 1, memory_order_seq_cst);
  16581. if (threadpool->pause) {
  16582. // Update main thread prio and affinity to match the threadpool settings
  16583. ggml_thread_apply_priority(threadpool->prio);
  16584. if (ggml_thread_cpumask_is_valid(threadpool->workers[0].cpumask)) {
  16585. ggml_thread_apply_affinity(threadpool->workers[0].cpumask);
  16586. }
  16587. // resume does cond broadcast
  16588. ggml_threadpool_resume_locked(threadpool);
  16589. } else {
  16590. ggml_cond_broadcast(&threadpool->cond);
  16591. }
  16592. ggml_mutex_unlock(&threadpool->mutex);
  16593. }
  16594. #endif // GGML_USE_OPENMP
  16595. void ggml_threadpool_params_init(struct ggml_threadpool_params * p, int n_threads) {
  16596. p->n_threads = n_threads;
  16597. p->prio = 0; // default priority (usually means normal or inherited)
  16598. p->poll = 50; // hybrid-polling enabled
  16599. p->strict_cpu = false; // no strict placement (all threads share same cpumask)
  16600. p->paused = false; // threads are ready to go
  16601. memset(p->cpumask, 0, GGML_MAX_N_THREADS); // all-zero means use the default affinity (usually inherited)
  16602. }
  16603. struct ggml_threadpool_params ggml_threadpool_params_default(int n_threads) {
  16604. struct ggml_threadpool_params p;
  16605. ggml_threadpool_params_init(&p, n_threads);
  16606. return p;
  16607. }
  16608. bool ggml_threadpool_params_match(const struct ggml_threadpool_params * p0, const struct ggml_threadpool_params * p1) {
  16609. if (p0->n_threads != p1->n_threads ) return false;
  16610. if (p0->prio != p1->prio ) return false;
  16611. if (p0->poll != p1->poll ) return false;
  16612. if (p0->strict_cpu != p1->strict_cpu ) return false;
  16613. return memcmp(p0->cpumask, p1->cpumask, GGML_MAX_N_THREADS) == 0;
  16614. }
  16615. static struct ggml_threadpool * ggml_threadpool_new_impl(
  16616. struct ggml_threadpool_params * tpp,
  16617. struct ggml_cgraph * cgraph,
  16618. struct ggml_cplan * cplan) {
  16619. struct ggml_threadpool * threadpool =
  16620. GGML_ALIGNED_MALLOC(sizeof(struct ggml_threadpool));
  16621. {
  16622. threadpool->cgraph = cgraph;
  16623. threadpool->cplan = cplan;
  16624. threadpool->n_graph = 0;
  16625. threadpool->n_barrier = 0;
  16626. threadpool->n_barrier_passed = 0;
  16627. threadpool->current_chunk = 0;
  16628. threadpool->stop = false;
  16629. threadpool->pause = tpp->paused;
  16630. threadpool->abort = false;
  16631. threadpool->workers = NULL;
  16632. threadpool->n_threads_max = tpp->n_threads;
  16633. threadpool->n_threads_cur = tpp->n_threads;
  16634. threadpool->poll = tpp->poll;
  16635. threadpool->prio = tpp->prio;
  16636. threadpool->ec = GGML_STATUS_SUCCESS;
  16637. }
  16638. // Allocate and init workers state
  16639. const size_t workers_size = sizeof(struct ggml_compute_state) * tpp->n_threads;
  16640. struct ggml_compute_state * workers = GGML_ALIGNED_MALLOC(workers_size);
  16641. memset(workers, 0, workers_size);
  16642. for (int j = 0; j < tpp->n_threads; j++) {
  16643. workers[j].threadpool = threadpool;
  16644. workers[j].ith = j;
  16645. }
  16646. threadpool->workers = workers;
  16647. #ifndef GGML_USE_OPENMP
  16648. ggml_mutex_init(&threadpool->mutex);
  16649. ggml_cond_init(&threadpool->cond);
  16650. // Spin the threads for all workers, and update CPU placements.
  16651. // Place the main thread last (towards the higher numbered CPU cores).
  16652. int32_t cpumask_iter = 0;
  16653. for (int j = 1; j < tpp->n_threads; j++) {
  16654. ggml_thread_cpumask_next(tpp->cpumask, workers[j].cpumask, tpp->strict_cpu, &cpumask_iter);
  16655. int32_t rc = ggml_thread_create(&workers[j].thrd, NULL, ggml_graph_compute_secondary_thread, &workers[j]);
  16656. GGML_ASSERT(rc == 0);
  16657. }
  16658. ggml_thread_cpumask_next(tpp->cpumask, workers[0].cpumask, tpp->strict_cpu, &cpumask_iter);
  16659. if (!threadpool->pause) {
  16660. // Update main thread prio and affinity at the start, otherwise we'll do it in resume
  16661. ggml_thread_apply_priority(threadpool->prio);
  16662. if (ggml_thread_cpumask_is_valid(threadpool->workers[0].cpumask)) {
  16663. ggml_thread_apply_affinity(threadpool->workers[0].cpumask);
  16664. }
  16665. }
  16666. #endif // GGML_USE_OPENMP
  16667. return threadpool;
  16668. }
  16669. struct ggml_threadpool * ggml_threadpool_new(struct ggml_threadpool_params * tpp) {
  16670. return ggml_threadpool_new_impl(tpp, NULL, NULL);
  16671. }
  16672. enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cplan * cplan) {
  16673. GGML_ASSERT(cplan);
  16674. GGML_ASSERT(cplan->n_threads > 0);
  16675. GGML_ASSERT(cplan->work_size == 0 || cplan->work_data != NULL);
  16676. int n_threads = cplan->n_threads;
  16677. struct ggml_threadpool * threadpool = cplan->threadpool;
  16678. bool disposable_threadpool = false;
  16679. if (threadpool == NULL) {
  16680. GGML_PRINT_DEBUG("Threadpool is not specified. Will create a disposable threadpool : n_threads %d\n", n_threads);
  16681. disposable_threadpool = true;
  16682. struct ggml_threadpool_params ttp = ggml_threadpool_params_default(n_threads);
  16683. threadpool = ggml_threadpool_new_impl(&ttp, cgraph, cplan);
  16684. } else {
  16685. // Reset some of the parameters that need resetting
  16686. // No worker threads should be accessing the parameters below at this stage
  16687. threadpool->cgraph = cgraph;
  16688. threadpool->cplan = cplan;
  16689. threadpool->current_chunk = 0;
  16690. threadpool->abort = false;
  16691. threadpool->ec = GGML_STATUS_SUCCESS;
  16692. }
  16693. #ifdef GGML_USE_OPENMP
  16694. if (n_threads > 1) {
  16695. #pragma omp parallel num_threads(n_threads)
  16696. {
  16697. #pragma omp single
  16698. {
  16699. // update the number of threads from the actual number of threads that we got from OpenMP
  16700. n_threads = omp_get_num_threads();
  16701. atomic_store_explicit(&threadpool->n_threads_cur, n_threads, memory_order_relaxed);
  16702. }
  16703. ggml_graph_compute_thread(&threadpool->workers[omp_get_thread_num()]);
  16704. }
  16705. } else {
  16706. atomic_store_explicit(&threadpool->n_threads_cur, 1, memory_order_relaxed);
  16707. ggml_graph_compute_thread(&threadpool->workers[0]);
  16708. }
  16709. #else
  16710. if (n_threads > threadpool->n_threads_max) {
  16711. GGML_PRINT("WARNING: cplan requested more threads (%d) than available (%d)\n", n_threads, threadpool->n_threads_max);
  16712. n_threads = threadpool->n_threads_max;
  16713. }
  16714. // Kick all threads to start the new graph
  16715. ggml_graph_compute_kickoff(threadpool, n_threads);
  16716. // This is a work thread too
  16717. ggml_graph_compute_thread(&threadpool->workers[0]);
  16718. #endif
  16719. // don't leave affinity set on the main thread
  16720. clear_numa_thread_affinity();
  16721. enum ggml_status ret = threadpool->ec;
  16722. if (disposable_threadpool) {
  16723. ggml_threadpool_free(threadpool);
  16724. }
  16725. return ret;
  16726. }
  16727. enum ggml_status ggml_graph_compute_with_ctx(struct ggml_context * ctx, struct ggml_cgraph * cgraph, int n_threads) {
  16728. struct ggml_cplan cplan = ggml_graph_plan(cgraph, n_threads, NULL);
  16729. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, cplan.work_size);
  16730. cplan.work_data = (uint8_t *)ctx->mem_buffer + obj->offs;
  16731. return ggml_graph_compute(cgraph, &cplan);
  16732. }
  16733. struct ggml_tensor * ggml_graph_get_tensor(struct ggml_cgraph * cgraph, const char * name) {
  16734. for (int i = 0; i < cgraph->n_leafs; i++) {
  16735. struct ggml_tensor * leaf = cgraph->leafs[i];
  16736. if (strcmp(leaf->name, name) == 0) {
  16737. return leaf;
  16738. }
  16739. }
  16740. for (int i = 0; i < cgraph->n_nodes; i++) {
  16741. struct ggml_tensor * node = cgraph->nodes[i];
  16742. if (strcmp(node->name, name) == 0) {
  16743. return node;
  16744. }
  16745. }
  16746. return NULL;
  16747. }
  16748. static void ggml_graph_export_leaf(const struct ggml_tensor * tensor, FILE * fout) {
  16749. const int64_t * ne = tensor->ne;
  16750. const size_t * nb = tensor->nb;
  16751. fprintf(fout, "%-6s %-12s %8d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %16zu %16zu %16zu %16zu %16p %32s\n",
  16752. ggml_type_name(tensor->type),
  16753. ggml_op_name (tensor->op),
  16754. ggml_n_dims(tensor),
  16755. ne[0], ne[1], ne[2], ne[3],
  16756. nb[0], nb[1], nb[2], nb[3],
  16757. tensor->data,
  16758. tensor->name);
  16759. }
  16760. static void ggml_graph_export_node(const struct ggml_tensor * tensor, const char * arg, FILE * fout) {
  16761. const int64_t * ne = tensor->ne;
  16762. const size_t * nb = tensor->nb;
  16763. fprintf(fout, "%-6s %-6s %-12s %8d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %16zu %16zu %16zu %16zu %16p %32s\n",
  16764. arg,
  16765. ggml_type_name(tensor->type),
  16766. ggml_op_name (tensor->op),
  16767. ggml_n_dims(tensor),
  16768. ne[0], ne[1], ne[2], ne[3],
  16769. nb[0], nb[1], nb[2], nb[3],
  16770. tensor->data,
  16771. tensor->name);
  16772. }
  16773. void ggml_graph_export(const struct ggml_cgraph * cgraph, const char * fname) {
  16774. uint64_t size_eval = 0;
  16775. // compute size of intermediate results
  16776. // TODO: does not take into account scratch buffers !!!!
  16777. for (int i = 0; i < cgraph->n_nodes; ++i) {
  16778. size_eval += ggml_nbytes_pad(cgraph->nodes[i]);
  16779. }
  16780. // print
  16781. {
  16782. FILE * fout = stdout;
  16783. fprintf(fout, "\n");
  16784. fprintf(fout, "%-16s %8x\n", "magic", GGML_FILE_MAGIC);
  16785. fprintf(fout, "%-16s %8d\n", "version", GGML_FILE_VERSION);
  16786. fprintf(fout, "%-16s %8d\n", "leafs", cgraph->n_leafs);
  16787. fprintf(fout, "%-16s %8d\n", "nodes", cgraph->n_nodes);
  16788. fprintf(fout, "%-16s %" PRIu64 "\n", "eval", size_eval);
  16789. // header
  16790. fprintf(fout, "\n");
  16791. fprintf(fout, "%-6s %-12s %8s %8s %8s %8s %8s %16s %16s %16s %16s %16s %16s\n",
  16792. "TYPE", "OP", "NDIMS", "NE0", "NE1", "NE2", "NE3", "NB0", "NB1", "NB2", "NB3", "DATA", "NAME");
  16793. for (int i = 0; i < cgraph->n_leafs; ++i) {
  16794. ggml_graph_export_leaf(cgraph->leafs[i], fout);
  16795. GGML_ASSERT(cgraph->leafs[i]->op == GGML_OP_NONE);
  16796. GGML_ASSERT(cgraph->leafs[i]->src[0] == NULL);
  16797. GGML_ASSERT(cgraph->leafs[i]->src[1] == NULL);
  16798. }
  16799. // header
  16800. fprintf(fout, "\n");
  16801. fprintf(fout, "%-6s %-6s %-12s %8s %8s %8s %8s %8s %16s %16s %16s %16s %8s %16s %16s\n",
  16802. "ARG", "TYPE", "OP", "NDIMS", "NE0", "NE1", "NE2", "NE3", "NB0", "NB1", "NB2", "NB3", "NTASKS", "DATA", "NAME");
  16803. for (int i = 0; i < cgraph->n_nodes; ++i) {
  16804. ggml_graph_export_node(cgraph->nodes[i], "DST", fout);
  16805. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  16806. if (cgraph->nodes[i]->src[j]) {
  16807. ggml_graph_export_node(cgraph->nodes[i]->src[j], "SRC", fout);
  16808. }
  16809. }
  16810. fprintf(fout, "\n");
  16811. }
  16812. fprintf(fout, "\n");
  16813. }
  16814. // write binary data
  16815. {
  16816. FILE * fout = ggml_fopen(fname, "wb");
  16817. if (!fout) {
  16818. fprintf(stderr, "%s: failed to open %s: %s\n", __func__, fname, strerror(errno));
  16819. return;
  16820. }
  16821. // header
  16822. {
  16823. const uint32_t magic = GGML_FILE_MAGIC;
  16824. const uint32_t version = GGML_FILE_VERSION;
  16825. const uint32_t n_leafs = cgraph->n_leafs;
  16826. const uint32_t n_nodes = cgraph->n_nodes;
  16827. fwrite(&magic, sizeof(uint32_t), 1, fout);
  16828. fwrite(&version, sizeof(uint32_t), 1, fout);
  16829. fwrite(&n_leafs, sizeof(uint32_t), 1, fout);
  16830. fwrite(&n_nodes, sizeof(uint32_t), 1, fout);
  16831. fwrite(&size_eval, sizeof(uint64_t), 1, fout);
  16832. }
  16833. // leafs
  16834. {
  16835. for (int i = 0; i < cgraph->n_leafs; ++i) {
  16836. const struct ggml_tensor * tensor = cgraph->leafs[i];
  16837. const uint32_t type = tensor->type;
  16838. const uint32_t op = tensor->op;
  16839. const int32_t flags = tensor->flags;
  16840. fwrite(&type, sizeof(uint32_t), 1, fout);
  16841. fwrite(&op, sizeof(uint32_t), 1, fout);
  16842. fwrite(&flags, sizeof(int32_t), 1, fout);
  16843. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  16844. const uint64_t ne = tensor->ne[j];
  16845. const uint64_t nb = tensor->nb[j];
  16846. fwrite(&ne, sizeof(uint64_t), 1, fout);
  16847. fwrite(&nb, sizeof(uint64_t), 1, fout);
  16848. }
  16849. fwrite(tensor->name, sizeof(char), GGML_MAX_NAME, fout);
  16850. fwrite(tensor->op_params, sizeof(char), GGML_MAX_OP_PARAMS, fout);
  16851. // dump the data
  16852. // TODO: pad this to 32 byte boundary
  16853. {
  16854. const size_t size = ggml_nbytes(tensor);
  16855. fwrite(tensor->data, sizeof(char), size, fout);
  16856. }
  16857. }
  16858. }
  16859. // nodes
  16860. {
  16861. for (int i = 0; i < cgraph->n_nodes; ++i) {
  16862. const struct ggml_tensor * tensor = cgraph->nodes[i];
  16863. const uint32_t type = tensor->type;
  16864. const uint32_t op = tensor->op;
  16865. const int32_t flags = tensor->flags;
  16866. fwrite(&type, sizeof(uint32_t), 1, fout);
  16867. fwrite(&op, sizeof(uint32_t), 1, fout);
  16868. fwrite(&flags, sizeof(int32_t), 1, fout);
  16869. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  16870. const uint64_t ne = tensor->ne[j];
  16871. const uint64_t nb = tensor->nb[j];
  16872. fwrite(&ne, sizeof(uint64_t), 1, fout);
  16873. fwrite(&nb, sizeof(uint64_t), 1, fout);
  16874. }
  16875. fwrite(tensor->name, sizeof(char), GGML_MAX_NAME, fout);
  16876. fwrite(tensor->op_params, sizeof(char), GGML_MAX_OP_PARAMS, fout);
  16877. // output the op arguments
  16878. {
  16879. struct ggml_tensor * args[GGML_MAX_SRC] = { NULL };
  16880. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  16881. args[j] = tensor->src[j];
  16882. }
  16883. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  16884. if (args[j]) {
  16885. int32_t idx = -1;
  16886. // check if leaf
  16887. {
  16888. for (int k = 0; k < cgraph->n_leafs; ++k) {
  16889. if (args[j] == cgraph->leafs[k]) {
  16890. idx = k;
  16891. break;
  16892. }
  16893. }
  16894. }
  16895. // check if node
  16896. if (idx == -1) {
  16897. for (int k = 0; k < cgraph->n_nodes; ++k) {
  16898. if (args[j] == cgraph->nodes[k]) {
  16899. idx = cgraph->n_leafs + k;
  16900. break;
  16901. }
  16902. }
  16903. }
  16904. if (idx == -1) {
  16905. fprintf(stderr, "%s: failed to find tensor, arg = %d, node = %d\n", __func__, j, i);
  16906. fclose(fout);
  16907. return;
  16908. }
  16909. fwrite(&idx, sizeof(int32_t), 1, fout);
  16910. } else {
  16911. const int32_t nul = -1;
  16912. fwrite(&nul, sizeof(int32_t), 1, fout);
  16913. }
  16914. }
  16915. }
  16916. // dump the data
  16917. // TODO: pad this to 32 byte boundary
  16918. if ((flags & GGML_TENSOR_FLAG_PARAM)) {
  16919. const size_t size = ggml_nbytes(tensor);
  16920. fwrite(tensor->data, sizeof(char), size, fout);
  16921. }
  16922. }
  16923. }
  16924. fclose(fout);
  16925. }
  16926. }
  16927. struct ggml_cgraph * ggml_graph_import(const char * fname, struct ggml_context ** ctx_data, struct ggml_context ** ctx_eval) {
  16928. assert(*ctx_data == NULL);
  16929. assert(*ctx_eval == NULL);
  16930. struct ggml_cgraph * result = NULL;
  16931. struct ggml_tensor * data = NULL;
  16932. // read file into data
  16933. {
  16934. FILE * fin = ggml_fopen(fname, "rb");
  16935. if (!fin) {
  16936. fprintf(stderr, "%s: failed to open %s: %s\n", __func__, fname, strerror(errno));
  16937. return result;
  16938. }
  16939. size_t fsize = 0;
  16940. fseek(fin, 0, SEEK_END);
  16941. fsize = ftell(fin);
  16942. fseek(fin, 0, SEEK_SET);
  16943. // create the data context
  16944. {
  16945. const size_t overhead = 1*ggml_tensor_overhead();
  16946. struct ggml_init_params params = {
  16947. .mem_size = fsize + overhead,
  16948. .mem_buffer = NULL,
  16949. .no_alloc = false,
  16950. };
  16951. *ctx_data = ggml_init(params);
  16952. if (!*ctx_data) {
  16953. fprintf(stderr, "%s: failed to create ggml context\n", __func__);
  16954. fclose(fin);
  16955. return result;
  16956. }
  16957. }
  16958. data = ggml_new_tensor_1d(*ctx_data, GGML_TYPE_I8, fsize);
  16959. {
  16960. const size_t ret = fread(data->data, sizeof(char), fsize, fin);
  16961. if (ret != fsize) {
  16962. fprintf(stderr, "%s: failed to read %s\n", __func__, fname);
  16963. fclose(fin);
  16964. return result;
  16965. }
  16966. }
  16967. fclose(fin);
  16968. }
  16969. // populate result
  16970. {
  16971. char * ptr = (char *) data->data;
  16972. const uint32_t magic = *(const uint32_t *) ptr; ptr += sizeof(magic);
  16973. if (magic != GGML_FILE_MAGIC) {
  16974. fprintf(stderr, "%s: invalid magic number, got %08x\n", __func__, magic);
  16975. return result;
  16976. }
  16977. const uint32_t version = *(const uint32_t *) ptr; ptr += sizeof(version);
  16978. if (version != GGML_FILE_VERSION) {
  16979. fprintf(stderr, "%s: invalid version number\n", __func__);
  16980. return result;
  16981. }
  16982. const uint32_t n_leafs = *(const uint32_t *) ptr; ptr += sizeof(n_leafs);
  16983. const uint32_t n_nodes = *(const uint32_t *) ptr; ptr += sizeof(n_nodes);
  16984. const uint64_t size_eval = *(const uint64_t *) ptr; ptr += sizeof(size_eval);
  16985. const int graph_size = MAX(n_leafs, n_nodes);
  16986. // create the data context
  16987. {
  16988. const size_t overhead = (n_leafs + n_nodes)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false);
  16989. struct ggml_init_params params = {
  16990. .mem_size = size_eval + overhead,
  16991. .mem_buffer = NULL,
  16992. .no_alloc = true,
  16993. };
  16994. *ctx_eval = ggml_init(params);
  16995. if (!*ctx_eval) {
  16996. fprintf(stderr, "%s: failed to create ggml context\n", __func__);
  16997. return result;
  16998. }
  16999. }
  17000. result = ggml_new_graph_custom(*ctx_eval, graph_size, false);
  17001. result->n_leafs = n_leafs;
  17002. result->n_nodes = n_nodes;
  17003. // leafs
  17004. {
  17005. uint32_t type;
  17006. uint32_t op;
  17007. int32_t flags;
  17008. for (uint32_t i = 0; i < n_leafs; ++i) {
  17009. type = *(const uint32_t *) ptr; ptr += sizeof(type);
  17010. op = *(const uint32_t *) ptr; ptr += sizeof(op);
  17011. flags = *(const int32_t *) ptr; ptr += sizeof(flags);
  17012. int64_t ne[GGML_MAX_DIMS];
  17013. size_t nb[GGML_MAX_DIMS];
  17014. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  17015. uint64_t ne_cur;
  17016. uint64_t nb_cur;
  17017. ne_cur = *(const uint64_t *) ptr; ptr += sizeof(ne_cur);
  17018. nb_cur = *(const uint64_t *) ptr; ptr += sizeof(nb_cur);
  17019. ne[j] = ne_cur;
  17020. nb[j] = nb_cur;
  17021. }
  17022. struct ggml_tensor * tensor = ggml_new_tensor(*ctx_eval, (enum ggml_type) type, GGML_MAX_DIMS, ne);
  17023. tensor->op = (enum ggml_op) op;
  17024. tensor->flags = flags;
  17025. memcpy(tensor->name, ptr, GGML_MAX_NAME); ptr += GGML_MAX_NAME;
  17026. memcpy(tensor->op_params, ptr, GGML_MAX_OP_PARAMS); ptr += GGML_MAX_OP_PARAMS;
  17027. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  17028. tensor->nb[j] = nb[j];
  17029. }
  17030. tensor->data = (void *) ptr; ptr += ggml_nbytes(tensor);
  17031. result->leafs[i] = tensor;
  17032. fprintf(stderr, "%s: loaded leaf %u: '%16s', %9zu bytes\n", __func__, i, tensor->name, ggml_nbytes(tensor));
  17033. }
  17034. }
  17035. ggml_set_no_alloc(*ctx_eval, false);
  17036. // nodes
  17037. {
  17038. uint32_t type;
  17039. uint32_t op;
  17040. int32_t flags;
  17041. for (uint32_t i = 0; i < n_nodes; ++i) {
  17042. type = *(const uint32_t *) ptr; ptr += sizeof(type);
  17043. op = *(const uint32_t *) ptr; ptr += sizeof(op);
  17044. flags = *(const int32_t *) ptr; ptr += sizeof(flags);
  17045. enum ggml_op eop = (enum ggml_op) op;
  17046. int64_t ne[GGML_MAX_DIMS];
  17047. size_t nb[GGML_MAX_DIMS];
  17048. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  17049. uint64_t ne_cur;
  17050. uint64_t nb_cur;
  17051. ne_cur = *(const uint64_t *) ptr; ptr += sizeof(ne_cur);
  17052. nb_cur = *(const uint64_t *) ptr; ptr += sizeof(nb_cur);
  17053. ne[j] = ne_cur;
  17054. nb[j] = nb_cur;
  17055. }
  17056. const char * ptr_name = ptr; ptr += GGML_MAX_NAME;
  17057. const char * ptr_op_params = ptr; ptr += GGML_MAX_OP_PARAMS;
  17058. const int32_t * ptr_arg_idx = (const int32_t *) ptr; ptr += GGML_MAX_SRC*sizeof(int32_t);
  17059. struct ggml_tensor * args[GGML_MAX_SRC] = { NULL };
  17060. // parse args
  17061. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  17062. const int32_t arg_idx = ptr_arg_idx[j];
  17063. if (arg_idx == -1) {
  17064. continue;
  17065. }
  17066. if (arg_idx < result->n_leafs) {
  17067. args[j] = result->leafs[arg_idx];
  17068. } else {
  17069. args[j] = result->nodes[arg_idx - result->n_leafs];
  17070. }
  17071. }
  17072. // create the tensor
  17073. // "view" operations are handled differently
  17074. // TODO: handle inplace ops - currently a copy is always made
  17075. struct ggml_tensor * tensor = NULL;
  17076. switch (eop) {
  17077. // TODO: implement other view ops
  17078. case GGML_OP_RESHAPE:
  17079. {
  17080. tensor = ggml_reshape_4d(*ctx_eval, args[0], ne[0], ne[1], ne[2], ne[3]);
  17081. } break;
  17082. case GGML_OP_VIEW:
  17083. {
  17084. tensor = ggml_view_4d(*ctx_eval, args[0], ne[0], ne[1], ne[2], ne[3], 0, 0, 0, 0);
  17085. size_t offs;
  17086. memcpy(&offs, ptr_op_params, sizeof(offs));
  17087. tensor->data = ((char *) tensor->data) + offs;
  17088. } break;
  17089. case GGML_OP_TRANSPOSE:
  17090. {
  17091. tensor = ggml_transpose(*ctx_eval, args[0]);
  17092. } break;
  17093. case GGML_OP_PERMUTE:
  17094. {
  17095. tensor = ggml_view_4d(*ctx_eval, args[0], ne[0], ne[1], ne[2], ne[3], 0, 0, 0, 0);
  17096. } break;
  17097. default:
  17098. {
  17099. tensor = ggml_new_tensor(*ctx_eval, (enum ggml_type) type, GGML_MAX_DIMS, ne);
  17100. tensor->op = eop;
  17101. } break;
  17102. }
  17103. memcpy(tensor->name, ptr_name, GGML_MAX_NAME);
  17104. memcpy(tensor->op_params, ptr_op_params, GGML_MAX_OP_PARAMS);
  17105. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  17106. tensor->nb[j] = nb[j];
  17107. }
  17108. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  17109. tensor->src[j] = args[j];
  17110. }
  17111. result->nodes[i] = tensor;
  17112. // TODO tensor data is be duplicated due to ggml_new_tensor call above
  17113. if (flags & GGML_TENSOR_FLAG_PARAM) {
  17114. tensor->data = (void *) ptr; ptr += ggml_nbytes(tensor);
  17115. }
  17116. fprintf(stderr, "%s: loaded node %u: '%16s', %9zu bytes\n", __func__, i, tensor->name, ggml_nbytes(tensor));
  17117. }
  17118. }
  17119. }
  17120. return result;
  17121. }
  17122. void ggml_graph_print(const struct ggml_cgraph * cgraph) {
  17123. GGML_PRINT("=== GRAPH ===\n");
  17124. GGML_PRINT("n_nodes = %d\n", cgraph->n_nodes);
  17125. for (int i = 0; i < cgraph->n_nodes; i++) {
  17126. struct ggml_tensor * node = cgraph->nodes[i];
  17127. GGML_PRINT(" - %3d: [ %5" PRId64 ", %5" PRId64 ", %5" PRId64 "] %16s %s\n",
  17128. i,
  17129. node->ne[0], node->ne[1], node->ne[2],
  17130. ggml_op_name(node->op), (node->flags & GGML_TENSOR_FLAG_PARAM) ? "x" : node->grad ? "g" : " ");
  17131. }
  17132. GGML_PRINT("n_leafs = %d\n", cgraph->n_leafs);
  17133. for (int i = 0; i < cgraph->n_leafs; i++) {
  17134. struct ggml_tensor * node = cgraph->leafs[i];
  17135. GGML_PRINT(" - %3d: [ %5" PRId64 ", %5" PRId64 "] %8s %16s\n",
  17136. i,
  17137. node->ne[0], node->ne[1],
  17138. ggml_op_name(node->op),
  17139. ggml_get_name(node));
  17140. }
  17141. GGML_PRINT("========================================\n");
  17142. }
  17143. // check if node is part of the graph
  17144. static bool ggml_graph_find(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  17145. if (cgraph == NULL) {
  17146. return true;
  17147. }
  17148. for (int i = 0; i < cgraph->n_nodes; i++) {
  17149. if (cgraph->nodes[i] == node) {
  17150. return true;
  17151. }
  17152. }
  17153. return false;
  17154. }
  17155. static struct ggml_tensor * ggml_graph_get_parent(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  17156. for (int i = 0; i < cgraph->n_nodes; i++) {
  17157. struct ggml_tensor * parent = cgraph->nodes[i];
  17158. if (parent->grad == node) {
  17159. return parent;
  17160. }
  17161. }
  17162. return NULL;
  17163. }
  17164. 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) {
  17165. struct ggml_tensor * gparent = ggml_graph_get_parent(gb, node);
  17166. struct ggml_tensor * gparent0 = ggml_graph_get_parent(gb, parent);
  17167. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ arrowhead = %s; style = %s; label = \"%s\"; ]\n",
  17168. gparent0 ? (void *) gparent0 : (void *) parent,
  17169. gparent0 ? "g" : "x",
  17170. gparent ? (void *) gparent : (void *) node,
  17171. gparent ? "g" : "x",
  17172. gparent ? "empty" : "vee",
  17173. gparent ? "dashed" : "solid",
  17174. label);
  17175. }
  17176. static void ggml_graph_dump_dot_leaf_edge(FILE * fp, struct ggml_tensor * node, struct ggml_tensor * parent, const char * label) {
  17177. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ label = \"%s\"; ]\n",
  17178. (void *) parent, "x",
  17179. (void *) node, "x",
  17180. label);
  17181. }
  17182. void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * gf, const char * filename) {
  17183. char color[16];
  17184. FILE * fp = ggml_fopen(filename, "w");
  17185. GGML_ASSERT(fp);
  17186. fprintf(fp, "digraph G {\n");
  17187. fprintf(fp, " newrank = true;\n");
  17188. fprintf(fp, " rankdir = TB;\n");
  17189. for (int i = 0; i < gb->n_nodes; i++) {
  17190. struct ggml_tensor * node = gb->nodes[i];
  17191. if (ggml_graph_get_parent(gb, node) != NULL) {
  17192. continue;
  17193. }
  17194. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  17195. snprintf(color, sizeof(color), "yellow");
  17196. } else if (node->grad) {
  17197. if (ggml_graph_find(gf, node)) {
  17198. snprintf(color, sizeof(color), "green");
  17199. } else {
  17200. snprintf(color, sizeof(color), "lightblue");
  17201. }
  17202. } else {
  17203. snprintf(color, sizeof(color), "white");
  17204. }
  17205. fprintf(fp, " \"%p\" [ "
  17206. "style = filled; fillcolor = %s; shape = record; "
  17207. "label=\"",
  17208. (void *) node, color);
  17209. if (strlen(node->name) > 0) {
  17210. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  17211. } else {
  17212. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  17213. }
  17214. if (ggml_is_matrix(node)) {
  17215. fprintf(fp, "%d [%" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], ggml_op_symbol(node->op));
  17216. } else {
  17217. fprintf(fp, "%d [%" PRId64 ", %" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], node->ne[2], ggml_op_symbol(node->op));
  17218. }
  17219. if (node->grad) {
  17220. fprintf(fp, " | <g>%s\"; ]\n", ggml_op_symbol(node->grad->op));
  17221. } else {
  17222. fprintf(fp, "\"; ]\n");
  17223. }
  17224. }
  17225. for (int i = 0; i < gb->n_leafs; i++) {
  17226. struct ggml_tensor * node = gb->leafs[i];
  17227. snprintf(color, sizeof(color), "pink");
  17228. fprintf(fp, " \"%p\" [ "
  17229. "style = filled; fillcolor = %s; shape = record; "
  17230. "label=\"<x>",
  17231. (void *) node, color);
  17232. if (strlen(node->name) > 0) {
  17233. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  17234. } else {
  17235. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  17236. }
  17237. fprintf(fp, "CONST %d [%" PRId64 ", %" PRId64 "]", i, node->ne[0], node->ne[1]);
  17238. if (ggml_nelements(node) < 5 && node->data != NULL) {
  17239. fprintf(fp, " | (");
  17240. for (int j = 0; j < ggml_nelements(node); j++) {
  17241. if (node->type == GGML_TYPE_I8 || node->type == GGML_TYPE_I16 || node->type == GGML_TYPE_I32) {
  17242. fprintf(fp, "%d", ggml_get_i32_1d(node, j));
  17243. }
  17244. else if (node->type == GGML_TYPE_F32 ||
  17245. node->type == GGML_TYPE_F16 ||
  17246. node->type == GGML_TYPE_BF16) {
  17247. fprintf(fp, "%.1e", (double)ggml_get_f32_1d(node, j));
  17248. }
  17249. else {
  17250. fprintf(fp, "#");
  17251. }
  17252. if (j < ggml_nelements(node) - 1) {
  17253. fprintf(fp, ", ");
  17254. }
  17255. }
  17256. fprintf(fp, ")");
  17257. }
  17258. fprintf(fp, "\"; ]\n");
  17259. }
  17260. for (int i = 0; i < gb->n_nodes; i++) {
  17261. struct ggml_tensor * node = gb->nodes[i];
  17262. for (int j = 0; j < GGML_MAX_SRC; j++) {
  17263. if (node->src[j]) {
  17264. char label[16];
  17265. snprintf(label, sizeof(label), "src %d", j);
  17266. ggml_graph_dump_dot_node_edge(fp, gb, node, node->src[j], label);
  17267. }
  17268. }
  17269. }
  17270. for (int i = 0; i < gb->n_leafs; i++) {
  17271. struct ggml_tensor * node = gb->leafs[i];
  17272. for (int j = 0; j < GGML_MAX_SRC; j++) {
  17273. if (node->src[j]) {
  17274. char label[16];
  17275. snprintf(label, sizeof(label), "src %d", j);
  17276. ggml_graph_dump_dot_leaf_edge(fp, node, node->src[j], label);
  17277. }
  17278. }
  17279. }
  17280. fprintf(fp, "}\n");
  17281. fclose(fp);
  17282. GGML_PRINT("%s: dot -Tpng %s -o %s.png && open %s.png\n", __func__, filename, filename, filename);
  17283. }
  17284. ////////////////////////////////////////////////////////////////////////////////
  17285. static void ggml_opt_set_params(int np, struct ggml_tensor * const ps[], const float * x) {
  17286. int i = 0;
  17287. for (int p = 0; p < np; ++p) {
  17288. const int64_t ne = ggml_nelements(ps[p]) ;
  17289. // TODO: add function to set tensor from array
  17290. for (int64_t j = 0; j < ne; ++j) {
  17291. ggml_set_f32_1d(ps[p], j, x[i++]);
  17292. }
  17293. }
  17294. }
  17295. static void ggml_opt_get_params(int np, struct ggml_tensor * const ps[], float * x) {
  17296. int i = 0;
  17297. for (int p = 0; p < np; ++p) {
  17298. const int64_t ne = ggml_nelements(ps[p]) ;
  17299. // TODO: add function to get all elements at once
  17300. for (int64_t j = 0; j < ne; ++j) {
  17301. x[i++] = ggml_get_f32_1d(ps[p], j);
  17302. }
  17303. }
  17304. }
  17305. static void ggml_opt_get_grad(int np, struct ggml_tensor * const ps[], float * g) {
  17306. int64_t i = 0;
  17307. for (int p = 0; p < np; ++p) {
  17308. const int64_t ne = ggml_nelements(ps[p]) ;
  17309. // TODO: add function to get all elements at once
  17310. for (int64_t j = 0; j < ne; ++j) {
  17311. g[i++] = ggml_get_f32_1d(ps[p]->grad, j);
  17312. }
  17313. }
  17314. }
  17315. static void ggml_opt_acc_grad(int np, struct ggml_tensor * const ps[], float * g, float scale) {
  17316. int64_t i = 0;
  17317. for (int p = 0; p < np; ++p) {
  17318. const int64_t ne = ggml_nelements(ps[p]) ;
  17319. // TODO: add function to get all elements at once
  17320. for (int64_t j = 0; j < ne; ++j) {
  17321. g[i++] += ggml_get_f32_1d(ps[p]->grad, j) * scale;
  17322. }
  17323. }
  17324. }
  17325. //
  17326. // Using AdamW - ref: https://arxiv.org/pdf/1711.05101v3.pdf
  17327. //
  17328. // (Original Adam - ref: https://arxiv.org/pdf/1412.6980.pdf)
  17329. //
  17330. static enum ggml_opt_result ggml_opt_adam(
  17331. struct ggml_context * ctx,
  17332. struct ggml_opt_context * opt,
  17333. struct ggml_opt_params params,
  17334. struct ggml_tensor * f,
  17335. struct ggml_cgraph * gf,
  17336. struct ggml_cgraph * gb,
  17337. ggml_opt_callback callback,
  17338. void * callback_data) {
  17339. GGML_ASSERT(ggml_is_scalar(f));
  17340. GGML_ASSERT(f->type == GGML_TYPE_F32);
  17341. // these will store the parameters we want to optimize
  17342. struct ggml_tensor * ps[GGML_MAX_PARAMS];
  17343. int np = 0;
  17344. int64_t nx = 0;
  17345. for (int i = 0; i < gf->n_nodes; ++i) {
  17346. if (gf->nodes[i]->flags & GGML_TENSOR_FLAG_PARAM) {
  17347. GGML_PRINT_DEBUG("found param %d: grad->op = %d\n", np, gf->nodes[i]->grad->op);
  17348. GGML_ASSERT(np < GGML_MAX_PARAMS);
  17349. ps[np++] = gf->nodes[i];
  17350. nx += ggml_nelements(gf->nodes[i]);
  17351. }
  17352. }
  17353. if ((opt->params.type != params.type) || (opt->nx != nx) || (opt->params.past != params.past)) {
  17354. int iter = opt->iter;
  17355. ggml_opt_init(opt->ctx, opt, params, nx);
  17356. opt->iter = iter;
  17357. }
  17358. // constants
  17359. float sched = params.adam.sched;
  17360. const float alpha = params.adam.alpha;
  17361. const float decay = params.adam.decay * alpha;
  17362. const float beta1 = params.adam.beta1;
  17363. const float beta2 = params.adam.beta2;
  17364. const float eps = params.adam.eps;
  17365. const float gclip = params.adam.gclip;
  17366. const int decay_min_ndim = params.adam.decay_min_ndim;
  17367. const int n_accum = MAX(1, params.n_gradient_accumulation);
  17368. const float accum_norm = 1.0f / (float) n_accum;
  17369. float * g = opt->adam.g->data; // gradients
  17370. float * m = opt->adam.m->data; // first moment
  17371. float * v = opt->adam.v->data; // second moment
  17372. float * pf = params.past > 0 ? opt->adam.pf->data : NULL; // past function values
  17373. struct ggml_cplan cplan = ggml_graph_plan(gb, params.n_threads, NULL);
  17374. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, cplan.work_size);
  17375. cplan.work_data = (uint8_t *)ctx->mem_buffer + obj->offs;
  17376. bool cancel = false;
  17377. // compute the function value
  17378. float fx = 0;
  17379. ggml_set_zero(opt->adam.g);
  17380. for (int accum_step = 0; accum_step < n_accum; ++accum_step) {
  17381. if (callback) {
  17382. callback(callback_data, accum_step, &sched, &cancel);
  17383. if (cancel) {
  17384. return GGML_OPT_RESULT_CANCEL;
  17385. }
  17386. }
  17387. // ggml_graph_reset (gf);
  17388. ggml_set_f32 (f->grad, 1.0f);
  17389. ggml_graph_compute(gb, &cplan);
  17390. ggml_opt_acc_grad(np, ps, g, accum_norm);
  17391. fx += ggml_get_f32_1d(f, 0);
  17392. }
  17393. fx *= accum_norm;
  17394. opt->adam.fx_prev = fx;
  17395. opt->adam.fx_best = opt->adam.fx_prev;
  17396. if (pf) {
  17397. pf[opt->iter % params.past] = opt->adam.fx_prev;
  17398. }
  17399. opt->loss_before = opt->adam.fx_prev;
  17400. opt->loss_after = opt->adam.fx_prev;
  17401. // initialize
  17402. if (opt->just_initialized) {
  17403. opt->adam.n_no_improvement = 0;
  17404. opt->just_initialized = false;
  17405. }
  17406. float * fx_best = &opt->adam.fx_best;
  17407. float * fx_prev = &opt->adam.fx_prev;
  17408. int * n_no_improvement = &opt->adam.n_no_improvement;
  17409. int iter0 = opt->iter;
  17410. // run the optimizer
  17411. for (int t = 0; t < params.adam.n_iter; ++t) {
  17412. opt->iter = iter0 + t + 1;
  17413. GGML_PRINT_DEBUG ("=== iter %d ===\n", t);
  17414. GGML_PRINT_DEBUG ("f = %10.6f\n", ggml_get_f32_1d(f, 0));
  17415. GGML_PRINT_DEBUG_5("df/dx0 = %10.6f\n", ggml_get_f32_1d(ps[0]->grad, 0));
  17416. GGML_PRINT_DEBUG_5("df/dx1 = %10.6f\n", ggml_get_f32_1d(ps[1]->grad, 0));
  17417. for (int i = 0; i < np; ++i) {
  17418. GGML_PRINT_DEBUG("param %d: %10.6f, g = %10.6f\n", i,
  17419. ggml_get_f32_1d(ps[i], 0), ggml_get_f32_1d(ps[i]->grad, 0));
  17420. }
  17421. const int64_t t_start_wall = ggml_time_us();
  17422. const int64_t t_start_cpu = ggml_cycles();
  17423. UNUSED(t_start_wall);
  17424. UNUSED(t_start_cpu);
  17425. {
  17426. float gnorm = 1.0f;
  17427. if (gclip > 0.0f) {
  17428. // gradient clipping
  17429. ggml_float sum = 0.0;
  17430. for (int64_t i = 0; i < nx; ++i) {
  17431. sum += (ggml_float)(g[i]*g[i]);
  17432. }
  17433. ggml_float norm = sqrt(sum);
  17434. if (norm > (ggml_float) gclip) {
  17435. gnorm = (float) ((ggml_float) gclip / norm);
  17436. }
  17437. }
  17438. const float beta1h = alpha*sched/(1.0f - powf(beta1, opt->iter));
  17439. const float beta2h = 1.0f/(1.0f - powf(beta2, opt->iter));
  17440. int64_t i = 0;
  17441. for (int p = 0; p < np; ++p) {
  17442. const int64_t ne = ggml_nelements(ps[p]);
  17443. const float p_decay = ((ggml_n_dims(ps[p]) >= decay_min_ndim) ? decay : 0.0f) * sched;
  17444. for (int64_t j = 0; j < ne; ++j) {
  17445. float x = ggml_get_f32_1d(ps[p], j);
  17446. float g_ = g[i]*gnorm;
  17447. m[i] = m[i]*beta1 + g_*(1.0f - beta1);
  17448. v[i] = v[i]*beta2 + g_*g_*(1.0f - beta2);
  17449. float mh = m[i]*beta1h;
  17450. float vh = v[i]*beta2h;
  17451. vh = sqrtf(vh) + eps;
  17452. x = x*(1.0f - p_decay) - mh/vh;
  17453. ggml_set_f32_1d(ps[p], j, x);
  17454. ++i;
  17455. }
  17456. }
  17457. }
  17458. fx = 0;
  17459. ggml_set_zero(opt->adam.g);
  17460. for (int accum_step = 0; accum_step < n_accum; ++accum_step) {
  17461. if (callback) {
  17462. callback(callback_data, accum_step, &sched, &cancel);
  17463. if (cancel) {
  17464. return GGML_OPT_RESULT_CANCEL;;
  17465. }
  17466. }
  17467. // ggml_graph_reset (gf);
  17468. ggml_set_f32 (f->grad, 1.0f);
  17469. ggml_graph_compute(gb, &cplan);
  17470. ggml_opt_acc_grad(np, ps, g, accum_norm);
  17471. fx += ggml_get_f32_1d(f, 0);
  17472. }
  17473. fx *= accum_norm;
  17474. opt->loss_after = fx;
  17475. // check convergence
  17476. if (fabsf(fx - fx_prev[0])/fx < params.adam.eps_f) {
  17477. GGML_PRINT_DEBUG("converged\n");
  17478. return GGML_OPT_RESULT_OK;
  17479. }
  17480. // delta-based convergence test
  17481. if (pf != NULL) {
  17482. // need at least params.past iterations to start checking for convergence
  17483. if (params.past <= iter0 + t) {
  17484. const float rate = (pf[(iter0 + t)%params.past] - fx)/fx;
  17485. if (fabsf(rate) < params.delta) {
  17486. return GGML_OPT_RESULT_OK;
  17487. }
  17488. }
  17489. pf[(iter0 + t)%params.past] = fx;
  17490. }
  17491. // check for improvement
  17492. if (params.max_no_improvement > 0) {
  17493. if (fx_best[0] > fx) {
  17494. fx_best[0] = fx;
  17495. n_no_improvement[0] = 0;
  17496. } else {
  17497. ++n_no_improvement[0];
  17498. if (n_no_improvement[0] >= params.max_no_improvement) {
  17499. return GGML_OPT_RESULT_OK;
  17500. }
  17501. }
  17502. }
  17503. fx_prev[0] = fx;
  17504. {
  17505. const int64_t t_end_cpu = ggml_cycles();
  17506. GGML_PRINT_DEBUG("time iter: %5.3f s\n", ((float)(t_end_cpu - t_start_cpu))/CLOCKS_PER_SEC);
  17507. UNUSED(t_end_cpu);
  17508. const int64_t t_end_wall = ggml_time_us();
  17509. GGML_PRINT_DEBUG("wall time iter: %5.3f s\n", (t_end_wall - t_start_wall)/1e6);
  17510. UNUSED(t_end_wall);
  17511. }
  17512. }
  17513. return GGML_OPT_RESULT_DID_NOT_CONVERGE;
  17514. }
  17515. //
  17516. // L-BFGS
  17517. //
  17518. // the L-BFGS implementation below is based on the following implementation:
  17519. //
  17520. // https://github.com/chokkan/liblbfgs
  17521. //
  17522. struct ggml_lbfgs_iteration_data {
  17523. float alpha;
  17524. float ys;
  17525. float * s;
  17526. float * y;
  17527. };
  17528. static enum ggml_opt_result linesearch_backtracking(
  17529. const struct ggml_opt_params * params,
  17530. int nx,
  17531. float * x,
  17532. float * fx,
  17533. float * g,
  17534. float * d,
  17535. float * step,
  17536. const float * xp,
  17537. struct ggml_tensor * f,
  17538. struct ggml_cgraph * gb,
  17539. struct ggml_cplan * cplan,
  17540. const int np,
  17541. struct ggml_tensor * ps[],
  17542. bool * cancel,
  17543. ggml_opt_callback callback,
  17544. void * callback_data) {
  17545. int count = 0;
  17546. float width = 0.0f;
  17547. float dg = 0.0f;
  17548. float finit = 0.0f;
  17549. float dginit = 0.0f;
  17550. float dgtest = 0.0f;
  17551. const float dec = 0.5f;
  17552. const float inc = 2.1f;
  17553. const int n_accum = MAX(1, params->n_gradient_accumulation);
  17554. const float accum_norm = 1.0f / (float) n_accum;
  17555. if (*step <= 0.f) {
  17556. return GGML_LINESEARCH_INVALID_PARAMETERS;
  17557. }
  17558. // compute the initial gradient in the search direction
  17559. ggml_vec_dot_f32(nx, &dginit, 0, g, 0, d, 0, 1);
  17560. // make sure that d points to a descent direction
  17561. if (0 < dginit) {
  17562. return GGML_LINESEARCH_FAIL;
  17563. }
  17564. // initialize local variables
  17565. finit = *fx;
  17566. dgtest = params->lbfgs.ftol*dginit;
  17567. while (true) {
  17568. ggml_vec_cpy_f32(nx, x, xp);
  17569. ggml_vec_mad_f32(nx, x, d, *step);
  17570. // evaluate the function and gradient values
  17571. {
  17572. ggml_opt_set_params(np, ps, x);
  17573. *fx = 0;
  17574. memset(g, 0, sizeof(float)*nx);
  17575. for (int accum_step = 0; accum_step < n_accum; ++accum_step) {
  17576. if (callback) {
  17577. // LBFG-S does not support learning rate -> ignore learning schedule
  17578. float sched = 0;
  17579. callback(callback_data, accum_step, &sched, cancel);
  17580. if (*cancel) {
  17581. return GGML_OPT_RESULT_CANCEL;
  17582. }
  17583. }
  17584. // ggml_graph_reset (gf);
  17585. ggml_set_f32 (f->grad, 1.0f);
  17586. ggml_graph_compute(gb, cplan);
  17587. ggml_opt_acc_grad(np, ps, g, accum_norm);
  17588. *fx += ggml_get_f32_1d(f, 0);
  17589. }
  17590. *fx *= accum_norm;
  17591. }
  17592. ++count;
  17593. if (*fx > finit + (*step)*dgtest) {
  17594. width = dec;
  17595. } else {
  17596. // Armijo condition is satisfied
  17597. if (params->lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_ARMIJO) {
  17598. return count;
  17599. }
  17600. ggml_vec_dot_f32(nx, &dg, 0, g, 0, d, 0, 1);
  17601. // check the Wolfe condition
  17602. if (dg < params->lbfgs.wolfe * dginit) {
  17603. width = inc;
  17604. } else {
  17605. if(params->lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_WOLFE) {
  17606. // regular Wolfe conditions
  17607. return count;
  17608. }
  17609. if(dg > -params->lbfgs.wolfe*dginit) {
  17610. width = dec;
  17611. } else {
  17612. // strong Wolfe condition (GGML_LINESEARCH_BACKTRACKING_STRONG_WOLFE)
  17613. return count;
  17614. }
  17615. }
  17616. }
  17617. if (*step < params->lbfgs.min_step) {
  17618. return GGML_LINESEARCH_MINIMUM_STEP;
  17619. }
  17620. if (*step > params->lbfgs.max_step) {
  17621. return GGML_LINESEARCH_MAXIMUM_STEP;
  17622. }
  17623. if (params->lbfgs.max_linesearch <= count) {
  17624. return GGML_LINESEARCH_MAXIMUM_ITERATIONS;
  17625. }
  17626. (*step) *= width;
  17627. }
  17628. GGML_ABORT("line search failed");
  17629. //return GGML_LINESEARCH_FAIL;
  17630. }
  17631. static enum ggml_opt_result ggml_opt_lbfgs(
  17632. struct ggml_context * ctx,
  17633. struct ggml_opt_context * opt,
  17634. struct ggml_opt_params params,
  17635. struct ggml_tensor * f,
  17636. struct ggml_cgraph * gf,
  17637. struct ggml_cgraph * gb,
  17638. ggml_opt_callback callback,
  17639. void * callback_data) {
  17640. if (params.lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_WOLFE ||
  17641. params.lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_STRONG_WOLFE) {
  17642. if (params.lbfgs.wolfe <= params.lbfgs.ftol || 1.f <= params.lbfgs.wolfe) {
  17643. return GGML_OPT_RESULT_INVALID_WOLFE;
  17644. }
  17645. }
  17646. const int m = params.lbfgs.m;
  17647. // these will store the parameters we want to optimize
  17648. struct ggml_tensor * ps[GGML_MAX_PARAMS];
  17649. int np = 0;
  17650. int nx = 0;
  17651. for (int i = 0; i < gf->n_nodes; ++i) {
  17652. if (gf->nodes[i]->flags & GGML_TENSOR_FLAG_PARAM) {
  17653. GGML_PRINT_DEBUG("found param %d: grad->op = %d\n", np, gf->nodes[i]->grad->op);
  17654. GGML_ASSERT(np < GGML_MAX_PARAMS);
  17655. ps[np++] = gf->nodes[i];
  17656. nx += ggml_nelements(gf->nodes[i]);
  17657. }
  17658. }
  17659. if ((opt->params.type != params.type) || (opt->nx != nx) || (opt->params.past != params.past) || (opt->params.lbfgs.m != params.lbfgs.m)) {
  17660. int iter = opt->iter;
  17661. ggml_opt_init(ctx, opt, params, nx);
  17662. opt->iter = iter;
  17663. }
  17664. struct ggml_cplan cplan = ggml_graph_plan(gb, params.n_threads, NULL);
  17665. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, cplan.work_size);
  17666. cplan.work_data = (uint8_t *)ctx->mem_buffer + obj->offs;
  17667. float * x = opt->lbfgs.x->data; // current parameters
  17668. float * xp = opt->lbfgs.xp->data; // previous parameters
  17669. float * g = opt->lbfgs.g->data; // current gradient
  17670. float * gp = opt->lbfgs.gp->data; // previous gradient
  17671. float * d = opt->lbfgs.d->data; // search direction
  17672. float * pf = params.past > 0 ? opt->lbfgs.pf->data : NULL; // past function values
  17673. const int n_accum = MAX(1, params.n_gradient_accumulation);
  17674. const float accum_norm = 1.0f / (float) n_accum;
  17675. float fx = 0.0f; // cost function value
  17676. float xnorm = 0.0f; // ||x||
  17677. float gnorm = 0.0f; // ||g||
  17678. // initialize x from the graph nodes
  17679. ggml_opt_get_params(np, ps, x);
  17680. // the L-BFGS memory
  17681. float * lm_alpha = opt->lbfgs.lmal->data;
  17682. float * lm_ys = opt->lbfgs.lmys->data;
  17683. float * lm_s = opt->lbfgs.lms->data;
  17684. float * lm_y = opt->lbfgs.lmy->data;
  17685. bool cancel = false;
  17686. // evaluate the function value and its gradient
  17687. {
  17688. ggml_opt_set_params(np, ps, x);
  17689. fx = 0;
  17690. memset(g, 0, sizeof(float)*nx);
  17691. for (int accum_step = 0; accum_step < n_accum; ++accum_step) {
  17692. if (callback) {
  17693. // LBFG-S does not support learning rate -> ignore learning schedule
  17694. float sched = 0;
  17695. callback(callback_data, accum_step, &sched, &cancel);
  17696. if (cancel) {
  17697. return GGML_OPT_RESULT_CANCEL;
  17698. }
  17699. }
  17700. // ggml_graph_reset (gf);
  17701. ggml_set_f32 (f->grad, 1.0f);
  17702. ggml_graph_compute(gb, &cplan);
  17703. ggml_opt_acc_grad(np, ps, g, accum_norm);
  17704. fx += ggml_get_f32_1d(f, 0);
  17705. }
  17706. fx *= accum_norm;
  17707. opt->loss_before = fx;
  17708. opt->loss_after = fx;
  17709. }
  17710. // search direction = -gradient
  17711. ggml_vec_neg_f32(nx, d, g);
  17712. // ||x||, ||g||
  17713. ggml_vec_norm_f32(nx, &xnorm, x);
  17714. ggml_vec_norm_f32(nx, &gnorm, g);
  17715. if (xnorm < 1.0f) {
  17716. xnorm = 1.0f;
  17717. }
  17718. // already optimized
  17719. if (gnorm/xnorm <= params.lbfgs.eps) {
  17720. return GGML_OPT_RESULT_OK;
  17721. }
  17722. if (opt->just_initialized) {
  17723. if (pf) {
  17724. pf[0] = fx;
  17725. }
  17726. opt->lbfgs.fx_best = fx;
  17727. // initial step
  17728. ggml_vec_norm_inv_f32(nx, &opt->lbfgs.step, d);
  17729. opt->lbfgs.j = 0;
  17730. opt->lbfgs.k = 1;
  17731. opt->lbfgs.end = 0;
  17732. opt->lbfgs.n_no_improvement = 0;
  17733. opt->just_initialized = false;
  17734. }
  17735. float * fx_best = &opt->lbfgs.fx_best;
  17736. float * step = &opt->lbfgs.step;
  17737. int * j = &opt->lbfgs.j;
  17738. int * k = &opt->lbfgs.k;
  17739. int * end = &opt->lbfgs.end;
  17740. int * n_no_improvement = &opt->lbfgs.n_no_improvement;
  17741. int ls = 0;
  17742. int bound = 0;
  17743. float ys = 0.0f;
  17744. float yy = 0.0f;
  17745. float beta = 0.0f;
  17746. int it = 0;
  17747. while (true) {
  17748. // store the current position and gradient vectors
  17749. ggml_vec_cpy_f32(nx, xp, x);
  17750. ggml_vec_cpy_f32(nx, gp, g);
  17751. // TODO: instead of passing &cancel here, use the return code of the linesearch
  17752. // to determine if the optimization should be cancelled
  17753. // this is a simple change, but not doing this atm, since I don't have a nice
  17754. // way to test and don't want to break something with so many changes lined up
  17755. ls = linesearch_backtracking(&params, nx, x, &fx, g, d, step, xp, f, gb, &cplan, np, ps, &cancel, callback, callback_data);
  17756. if (cancel) {
  17757. return GGML_OPT_RESULT_CANCEL;
  17758. }
  17759. if (ls < 0) {
  17760. // linesearch failed - go back to the previous point and return
  17761. ggml_vec_cpy_f32(nx, x, xp);
  17762. ggml_vec_cpy_f32(nx, g, gp);
  17763. return ls;
  17764. }
  17765. opt->loss_after = fx;
  17766. ggml_vec_norm_f32(nx, &xnorm, x);
  17767. ggml_vec_norm_f32(nx, &gnorm, g);
  17768. GGML_PRINT_DEBUG("f = %10.6f\n", ggml_get_f32_1d(f, 0));
  17769. if (xnorm < 1.0f) {
  17770. xnorm = 1.0f;
  17771. }
  17772. if (gnorm/xnorm <= params.lbfgs.eps) {
  17773. // converged
  17774. return GGML_OPT_RESULT_OK;
  17775. }
  17776. // delta-based convergence test
  17777. if (pf != NULL) {
  17778. // need at least params.past iterations to start checking for convergence
  17779. if (params.past <= k[0]) {
  17780. const float rate = (pf[k[0]%params.past] - fx)/fx;
  17781. if (fabsf(rate) < params.delta) {
  17782. return GGML_OPT_RESULT_OK;
  17783. }
  17784. }
  17785. pf[k[0]%params.past] = fx;
  17786. }
  17787. // check for improvement
  17788. if (params.max_no_improvement > 0) {
  17789. if (fx < fx_best[0]) {
  17790. fx_best[0] = fx;
  17791. n_no_improvement[0] = 0;
  17792. } else {
  17793. n_no_improvement[0]++;
  17794. if (n_no_improvement[0] >= params.max_no_improvement) {
  17795. return GGML_OPT_RESULT_OK;
  17796. }
  17797. }
  17798. }
  17799. if (params.lbfgs.n_iter != 0 && params.lbfgs.n_iter < it + 1) {
  17800. // reached the maximum number of iterations
  17801. return GGML_OPT_RESULT_DID_NOT_CONVERGE;
  17802. }
  17803. // update vectors s and y:
  17804. // s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}.
  17805. // y_{k+1} = g_{k+1} - g_{k}.
  17806. //
  17807. ggml_vec_sub_f32(nx, &lm_s[end[0]*nx], x, xp);
  17808. ggml_vec_sub_f32(nx, &lm_y[end[0]*nx], g, gp);
  17809. // compute scalars ys and yy:
  17810. // ys = y^t \cdot s -> 1 / \rho.
  17811. // yy = y^t \cdot y.
  17812. //
  17813. ggml_vec_dot_f32(nx, &ys, 0, &lm_y[end[0]*nx], 0, &lm_s[end[0]*nx], 0, 1);
  17814. ggml_vec_dot_f32(nx, &yy, 0, &lm_y[end[0]*nx], 0, &lm_y[end[0]*nx], 0, 1);
  17815. lm_ys[end[0]] = ys;
  17816. // find new search direction
  17817. // ref: https://en.wikipedia.org/wiki/Limited-memory_BFGS
  17818. bound = (m <= k[0]) ? m : k[0];
  17819. k[0]++;
  17820. it++;
  17821. end[0] = (end[0] + 1)%m;
  17822. // initialize search direction with -g
  17823. ggml_vec_neg_f32(nx, d, g);
  17824. j[0] = end[0];
  17825. for (int i = 0; i < bound; ++i) {
  17826. j[0] = (j[0] + m - 1) % m;
  17827. // \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}
  17828. ggml_vec_dot_f32(nx, &lm_alpha[j[0]], 0, &lm_s[j[0]*nx], 0, d, 0, 1);
  17829. lm_alpha[j[0]] /= lm_ys[j[0]];
  17830. // q_{i} = q_{i+1} - \alpha_{i} y_{i}
  17831. ggml_vec_mad_f32(nx, d, &lm_y[j[0]*nx], -lm_alpha[j[0]]);
  17832. }
  17833. ggml_vec_scale_f32(nx, d, ys/yy);
  17834. for (int i = 0; i < bound; ++i) {
  17835. // \beta_{j} = \rho_{j} y^t_{j} \cdot \gamma_{i}
  17836. ggml_vec_dot_f32(nx, &beta, 0, &lm_y[j[0]*nx], 0, d, 0, 1);
  17837. beta /= lm_ys[j[0]];
  17838. // \gamma_{i+1} = \gamma_{i} + (\alpha_{j} - \beta_{j}) s_{j}
  17839. ggml_vec_mad_f32(nx, d, &lm_s[j[0]*nx], lm_alpha[j[0]] - beta);
  17840. j[0] = (j[0] + 1)%m;
  17841. }
  17842. step[0] = 1.0;
  17843. }
  17844. GGML_ABORT("lbfgs failed");
  17845. //return GGML_OPT_RESULT_DID_NOT_CONVERGE;
  17846. }
  17847. struct ggml_opt_params ggml_opt_default_params(enum ggml_opt_type type) {
  17848. struct ggml_opt_params result;
  17849. switch (type) {
  17850. case GGML_OPT_TYPE_ADAM:
  17851. {
  17852. result = (struct ggml_opt_params) {
  17853. .type = GGML_OPT_TYPE_ADAM,
  17854. .graph_size = GGML_DEFAULT_GRAPH_SIZE,
  17855. .n_threads = 1, // FIXME: GGML_DEFAULT_N_THREADS ?
  17856. .past = 0,
  17857. .delta = 1e-5f,
  17858. .max_no_improvement = 100,
  17859. .print_forward_graph = true,
  17860. .print_backward_graph = true,
  17861. .n_gradient_accumulation = 1,
  17862. .adam = {
  17863. .n_iter = 10000,
  17864. .sched = 1.000f,
  17865. .decay = 0.0f,
  17866. .decay_min_ndim = 2,
  17867. .alpha = 0.001f,
  17868. .beta1 = 0.9f,
  17869. .beta2 = 0.999f,
  17870. .eps = 1e-8f,
  17871. .eps_f = 1e-5f,
  17872. .eps_g = 1e-3f,
  17873. .gclip = 0.0f,
  17874. },
  17875. };
  17876. } break;
  17877. case GGML_OPT_TYPE_LBFGS:
  17878. {
  17879. result = (struct ggml_opt_params) {
  17880. .type = GGML_OPT_TYPE_LBFGS,
  17881. .graph_size = GGML_DEFAULT_GRAPH_SIZE,
  17882. .n_threads = 1,
  17883. .past = 0,
  17884. .delta = 1e-5f,
  17885. .max_no_improvement = 0,
  17886. .print_forward_graph = true,
  17887. .print_backward_graph = true,
  17888. .n_gradient_accumulation = 1,
  17889. .lbfgs = {
  17890. .m = 6,
  17891. .n_iter = 100,
  17892. .max_linesearch = 20,
  17893. .eps = 1e-5f,
  17894. .ftol = 1e-4f,
  17895. .wolfe = 0.9f,
  17896. .min_step = 1e-20f,
  17897. .max_step = 1e+20f,
  17898. .linesearch = GGML_LINESEARCH_DEFAULT,
  17899. },
  17900. };
  17901. } break;
  17902. }
  17903. return result;
  17904. }
  17905. GGML_API void ggml_opt_init(
  17906. struct ggml_context * ctx,
  17907. struct ggml_opt_context * opt,
  17908. struct ggml_opt_params params,
  17909. int64_t nx) {
  17910. opt->ctx = ctx;
  17911. opt->params = params;
  17912. opt->iter = 0;
  17913. opt->nx = nx;
  17914. opt->just_initialized = true;
  17915. if (opt->ctx == NULL) {
  17916. struct ggml_init_params ctx_opt_params;
  17917. if (opt->params.type == GGML_OPT_TYPE_ADAM) {
  17918. ctx_opt_params.mem_size = GGML_MEM_ALIGN*3 + ggml_tensor_overhead()*3 + ggml_type_size(GGML_TYPE_F32)*nx*3;
  17919. if (opt->params.past > 0) {
  17920. ctx_opt_params.mem_size += GGML_MEM_ALIGN + ggml_tensor_overhead() + ggml_type_size(GGML_TYPE_F32)*opt->params.past;
  17921. }
  17922. } else if (opt->params.type == GGML_OPT_TYPE_LBFGS) {
  17923. 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);
  17924. if (opt->params.past > 0) {
  17925. ctx_opt_params.mem_size += GGML_MEM_ALIGN + ggml_tensor_overhead() + ggml_type_size(GGML_TYPE_F32)*opt->params.past;
  17926. }
  17927. }
  17928. ctx_opt_params.mem_buffer = NULL;
  17929. ctx_opt_params.no_alloc = false;
  17930. opt->ctx = ggml_init(ctx_opt_params);
  17931. }
  17932. switch (opt->params.type) {
  17933. case GGML_OPT_TYPE_ADAM:
  17934. {
  17935. opt->adam.g = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17936. opt->adam.m = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17937. opt->adam.v = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17938. opt->adam.pf = params.past > 0
  17939. ? ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, params.past)
  17940. : NULL;
  17941. ggml_set_zero(opt->adam.m);
  17942. ggml_set_zero(opt->adam.v);
  17943. if (opt->adam.pf) {
  17944. ggml_set_zero(opt->adam.pf);
  17945. }
  17946. } break;
  17947. case GGML_OPT_TYPE_LBFGS:
  17948. {
  17949. opt->lbfgs.x = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17950. opt->lbfgs.xp = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17951. opt->lbfgs.g = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17952. opt->lbfgs.gp = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17953. opt->lbfgs.d = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, nx);
  17954. opt->lbfgs.pf = params.past > 0
  17955. ? ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, params.past)
  17956. : NULL;
  17957. opt->lbfgs.lmal = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, params.lbfgs.m);
  17958. opt->lbfgs.lmys = ggml_new_tensor_1d(opt->ctx, GGML_TYPE_F32, params.lbfgs.m);
  17959. opt->lbfgs.lms = ggml_new_tensor_2d(opt->ctx, GGML_TYPE_F32, nx, params.lbfgs.m);
  17960. opt->lbfgs.lmy = ggml_new_tensor_2d(opt->ctx, GGML_TYPE_F32, nx, params.lbfgs.m);
  17961. ggml_set_zero(opt->lbfgs.x);
  17962. ggml_set_zero(opt->lbfgs.xp);
  17963. ggml_set_zero(opt->lbfgs.g);
  17964. ggml_set_zero(opt->lbfgs.gp);
  17965. ggml_set_zero(opt->lbfgs.d);
  17966. if (opt->lbfgs.pf) {
  17967. ggml_set_zero(opt->lbfgs.pf);
  17968. }
  17969. ggml_set_zero(opt->lbfgs.lmal);
  17970. ggml_set_zero(opt->lbfgs.lmys);
  17971. ggml_set_zero(opt->lbfgs.lms);
  17972. ggml_set_zero(opt->lbfgs.lmy);
  17973. } break;
  17974. }
  17975. }
  17976. enum ggml_opt_result ggml_opt(
  17977. struct ggml_context * ctx,
  17978. struct ggml_opt_params params,
  17979. struct ggml_tensor * f) {
  17980. bool free_ctx = false;
  17981. if (ctx == NULL) {
  17982. struct ggml_init_params params_ctx = {
  17983. .mem_size = 16*1024*1024,
  17984. .mem_buffer = NULL,
  17985. .no_alloc = false,
  17986. };
  17987. ctx = ggml_init(params_ctx);
  17988. if (ctx == NULL) {
  17989. return GGML_OPT_RESULT_NO_CONTEXT;
  17990. }
  17991. free_ctx = true;
  17992. }
  17993. enum ggml_opt_result result = GGML_OPT_RESULT_OK;
  17994. struct ggml_opt_context * opt = (struct ggml_opt_context *) alloca(sizeof(struct ggml_opt_context));
  17995. ggml_opt_init(ctx, opt, params, 0);
  17996. result = ggml_opt_resume(ctx, opt, f);
  17997. if (free_ctx) {
  17998. ggml_free(ctx);
  17999. }
  18000. return result;
  18001. }
  18002. enum ggml_opt_result ggml_opt_resume(
  18003. struct ggml_context * ctx,
  18004. struct ggml_opt_context * opt,
  18005. struct ggml_tensor * f) {
  18006. // build forward + backward compute graphs
  18007. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx, opt->params.graph_size, true);
  18008. ggml_build_forward_expand(gf, f);
  18009. struct ggml_cgraph * gb = ggml_graph_dup(ctx, gf);
  18010. ggml_build_backward_expand(ctx, gf, gb, false);
  18011. return ggml_opt_resume_g(ctx, opt, f, gf, gb, NULL, NULL);
  18012. }
  18013. enum ggml_opt_result ggml_opt_resume_g(
  18014. struct ggml_context * ctx,
  18015. struct ggml_opt_context * opt,
  18016. struct ggml_tensor * f,
  18017. struct ggml_cgraph * gf,
  18018. struct ggml_cgraph * gb,
  18019. ggml_opt_callback callback,
  18020. void * callback_data) {
  18021. GGML_ASSERT(f->grad && "ggml_set_param must be called for at least one ancestor");
  18022. // build forward + backward compute graphs
  18023. enum ggml_opt_result result = GGML_OPT_RESULT_OK;
  18024. switch (opt->params.type) {
  18025. case GGML_OPT_TYPE_ADAM:
  18026. {
  18027. result = ggml_opt_adam(ctx, opt, opt->params, f, gf, gb, callback, callback_data);
  18028. } break;
  18029. case GGML_OPT_TYPE_LBFGS:
  18030. {
  18031. result = ggml_opt_lbfgs(ctx, opt, opt->params, f, gf, gb, callback, callback_data);
  18032. } break;
  18033. }
  18034. if (opt->params.print_forward_graph) {
  18035. ggml_graph_print (gf);
  18036. ggml_graph_dump_dot(gf, NULL, "opt-forward.dot");
  18037. }
  18038. if (opt->params.print_backward_graph) {
  18039. ggml_graph_print (gb);
  18040. ggml_graph_dump_dot(gb, gf, "opt-backward.dot");
  18041. }
  18042. return result;
  18043. }
  18044. ////////////////////////////////////////////////////////////////////////////////
  18045. void ggml_set_input(struct ggml_tensor * tensor) {
  18046. tensor->flags |= GGML_TENSOR_FLAG_INPUT;
  18047. }
  18048. void ggml_set_output(struct ggml_tensor * tensor) {
  18049. tensor->flags |= GGML_TENSOR_FLAG_OUTPUT;
  18050. }
  18051. void ggml_set_param(struct ggml_context * ctx, struct ggml_tensor * tensor) {
  18052. GGML_UNUSED(ctx); // TODO: remove this parameter
  18053. tensor->flags |= GGML_TENSOR_FLAG_PARAM;
  18054. }
  18055. void ggml_set_loss(struct ggml_tensor * tensor) {
  18056. GGML_ASSERT(ggml_is_scalar(tensor));
  18057. GGML_ASSERT(tensor->type == GGML_TYPE_F32);
  18058. tensor->flags |= GGML_TENSOR_FLAG_LOSS;
  18059. }
  18060. ////////////////////////////////////////////////////////////////////////////////
  18061. void ggml_quantize_init(enum ggml_type type) {
  18062. ggml_critical_section_start();
  18063. switch (type) {
  18064. case GGML_TYPE_IQ2_XXS:
  18065. case GGML_TYPE_IQ2_XS:
  18066. case GGML_TYPE_IQ2_S:
  18067. case GGML_TYPE_IQ1_S:
  18068. case GGML_TYPE_IQ1_M: iq2xs_init_impl(type); break;
  18069. case GGML_TYPE_IQ3_XXS: iq3xs_init_impl(256); break;
  18070. case GGML_TYPE_IQ3_S: iq3xs_init_impl(512); break;
  18071. default: // nothing
  18072. break;
  18073. }
  18074. ggml_critical_section_end();
  18075. }
  18076. void ggml_quantize_free(void) {
  18077. ggml_critical_section_start();
  18078. iq2xs_free_impl(GGML_TYPE_IQ2_XXS);
  18079. iq2xs_free_impl(GGML_TYPE_IQ2_XS);
  18080. iq2xs_free_impl(GGML_TYPE_IQ1_S);
  18081. iq3xs_free_impl(256);
  18082. ggml_critical_section_end();
  18083. }
  18084. bool ggml_quantize_requires_imatrix(enum ggml_type type) {
  18085. return
  18086. type == GGML_TYPE_IQ2_XXS ||
  18087. type == GGML_TYPE_IQ2_XS ||
  18088. type == GGML_TYPE_IQ1_S;// ||
  18089. //type == GGML_TYPE_IQ1_M;
  18090. }
  18091. size_t ggml_quantize_chunk(
  18092. enum ggml_type type,
  18093. const float * src,
  18094. void * dst,
  18095. int64_t start,
  18096. int64_t nrows,
  18097. int64_t n_per_row,
  18098. const float * imatrix) {
  18099. const int64_t n = (int64_t) nrows * n_per_row;
  18100. if (ggml_quantize_requires_imatrix(type)) {
  18101. GGML_ASSERT(imatrix != NULL);
  18102. }
  18103. GGML_ASSERT(start % type_traits[type].blck_size == 0);
  18104. GGML_ASSERT(start % n_per_row == 0);
  18105. ggml_quantize_init(type); // this is noop if already initialized
  18106. const size_t start_row = start / n_per_row;
  18107. const size_t row_size = ggml_row_size(type, n_per_row);
  18108. size_t result = 0;
  18109. switch (type) {
  18110. case GGML_TYPE_Q4_0: result = quantize_q4_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18111. case GGML_TYPE_Q4_1: result = quantize_q4_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18112. case GGML_TYPE_Q5_0: result = quantize_q5_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18113. case GGML_TYPE_Q5_1: result = quantize_q5_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18114. case GGML_TYPE_Q8_0: result = quantize_q8_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18115. case GGML_TYPE_Q2_K: result = quantize_q2_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18116. case GGML_TYPE_Q3_K: result = quantize_q3_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18117. case GGML_TYPE_Q4_K: result = quantize_q4_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18118. case GGML_TYPE_Q5_K: result = quantize_q5_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18119. case GGML_TYPE_Q6_K: result = quantize_q6_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18120. case GGML_TYPE_TQ1_0: result = quantize_tq1_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18121. case GGML_TYPE_TQ2_0: result = quantize_tq2_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18122. case GGML_TYPE_IQ2_XXS: result = quantize_iq2_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18123. case GGML_TYPE_IQ2_XS: result = quantize_iq2_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18124. case GGML_TYPE_IQ3_XXS: result = quantize_iq3_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18125. case GGML_TYPE_IQ3_S: result = quantize_iq3_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18126. case GGML_TYPE_IQ2_S: result = quantize_iq2_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18127. case GGML_TYPE_IQ1_S: result = quantize_iq1_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18128. case GGML_TYPE_IQ1_M: result = quantize_iq1_m (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18129. case GGML_TYPE_IQ4_NL: result = quantize_iq4_nl (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18130. case GGML_TYPE_IQ4_XS: result = quantize_iq4_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  18131. 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;
  18132. 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;
  18133. 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;
  18134. case GGML_TYPE_F16:
  18135. {
  18136. size_t elemsize = sizeof(ggml_fp16_t);
  18137. ggml_fp32_to_fp16_row(src + start, (ggml_fp16_t *)dst + start, n);
  18138. result = n * elemsize;
  18139. } break;
  18140. case GGML_TYPE_BF16:
  18141. {
  18142. size_t elemsize = sizeof(ggml_bf16_t);
  18143. ggml_fp32_to_bf16_row_ref(src + start, (ggml_bf16_t *)dst + start, n);
  18144. result = n * elemsize;
  18145. } break;
  18146. case GGML_TYPE_F32:
  18147. {
  18148. size_t elemsize = sizeof(float);
  18149. result = n * elemsize;
  18150. memcpy((uint8_t *)dst + start * elemsize, src + start, result);
  18151. } break;
  18152. default:
  18153. assert(false);
  18154. }
  18155. GGML_ASSERT(result == nrows * row_size);
  18156. return result;
  18157. }
  18158. ////////////////////////////////////////////////////////////////////////////////
  18159. struct gguf_str {
  18160. uint64_t n; // GGUFv2
  18161. char * data;
  18162. };
  18163. static const size_t GGUF_TYPE_SIZE[GGUF_TYPE_COUNT] = {
  18164. [GGUF_TYPE_UINT8] = sizeof(uint8_t),
  18165. [GGUF_TYPE_INT8] = sizeof(int8_t),
  18166. [GGUF_TYPE_UINT16] = sizeof(uint16_t),
  18167. [GGUF_TYPE_INT16] = sizeof(int16_t),
  18168. [GGUF_TYPE_UINT32] = sizeof(uint32_t),
  18169. [GGUF_TYPE_INT32] = sizeof(int32_t),
  18170. [GGUF_TYPE_FLOAT32] = sizeof(float),
  18171. [GGUF_TYPE_BOOL] = sizeof(bool),
  18172. [GGUF_TYPE_STRING] = sizeof(struct gguf_str),
  18173. [GGUF_TYPE_UINT64] = sizeof(uint64_t),
  18174. [GGUF_TYPE_INT64] = sizeof(int64_t),
  18175. [GGUF_TYPE_FLOAT64] = sizeof(double),
  18176. [GGUF_TYPE_ARRAY] = 0, // undefined
  18177. };
  18178. static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
  18179. static const char * GGUF_TYPE_NAME[GGUF_TYPE_COUNT] = {
  18180. [GGUF_TYPE_UINT8] = "u8",
  18181. [GGUF_TYPE_INT8] = "i8",
  18182. [GGUF_TYPE_UINT16] = "u16",
  18183. [GGUF_TYPE_INT16] = "i16",
  18184. [GGUF_TYPE_UINT32] = "u32",
  18185. [GGUF_TYPE_INT32] = "i32",
  18186. [GGUF_TYPE_FLOAT32] = "f32",
  18187. [GGUF_TYPE_BOOL] = "bool",
  18188. [GGUF_TYPE_STRING] = "str",
  18189. [GGUF_TYPE_ARRAY] = "arr",
  18190. [GGUF_TYPE_UINT64] = "u64",
  18191. [GGUF_TYPE_INT64] = "i64",
  18192. [GGUF_TYPE_FLOAT64] = "f64",
  18193. };
  18194. static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
  18195. union gguf_value {
  18196. uint8_t uint8;
  18197. int8_t int8;
  18198. uint16_t uint16;
  18199. int16_t int16;
  18200. uint32_t uint32;
  18201. int32_t int32;
  18202. float float32;
  18203. uint64_t uint64;
  18204. int64_t int64;
  18205. double float64;
  18206. bool bool_;
  18207. struct gguf_str str;
  18208. struct {
  18209. enum gguf_type type;
  18210. uint64_t n; // GGUFv2
  18211. void * data;
  18212. } arr;
  18213. };
  18214. struct gguf_kv {
  18215. struct gguf_str key;
  18216. enum gguf_type type;
  18217. union gguf_value value;
  18218. };
  18219. struct gguf_header {
  18220. char magic[4];
  18221. uint32_t version;
  18222. uint64_t n_tensors; // GGUFv2
  18223. uint64_t n_kv; // GGUFv2
  18224. };
  18225. struct gguf_tensor_info {
  18226. struct gguf_str name;
  18227. uint32_t n_dims;
  18228. uint64_t ne[GGML_MAX_DIMS];
  18229. enum ggml_type type;
  18230. uint64_t offset; // offset from start of `data`, must be a multiple of `ALIGNMENT`
  18231. // for writing API
  18232. const void * data;
  18233. size_t size;
  18234. };
  18235. struct gguf_context {
  18236. struct gguf_header header;
  18237. struct gguf_kv * kv;
  18238. struct gguf_tensor_info * infos;
  18239. size_t alignment;
  18240. size_t offset; // offset of `data` from beginning of file
  18241. size_t size; // size of `data` in bytes
  18242. //uint8_t * padding;
  18243. void * data;
  18244. };
  18245. static size_t gguf_type_size(enum gguf_type type) {
  18246. GGML_ASSERT(0 <= type && type < GGUF_TYPE_COUNT);
  18247. return GGUF_TYPE_SIZE[type];
  18248. }
  18249. static void gguf_tensor_info_sanitize(struct gguf_tensor_info * info) {
  18250. GGML_ASSERT(info->n_dims <= GGML_MAX_DIMS);
  18251. GGML_ASSERT(0 <= info->type && info->type < GGML_TYPE_COUNT);
  18252. for (uint32_t i = 0; i < info->n_dims; ++i) {
  18253. GGML_ASSERT(info->ne[i] > 0);
  18254. }
  18255. // prevent overflow for total number of elements
  18256. GGML_ASSERT(INT64_MAX/info->ne[1] > info->ne[0]);
  18257. GGML_ASSERT(INT64_MAX/info->ne[2] > info->ne[0]*info->ne[1]);
  18258. GGML_ASSERT(INT64_MAX/info->ne[3] > info->ne[0]*info->ne[1]*info->ne[2]);
  18259. }
  18260. static bool gguf_fread_el(FILE * file, void * dst, size_t size, size_t * offset) {
  18261. const size_t n = fread(dst, 1, size, file);
  18262. *offset += n;
  18263. return n == size;
  18264. }
  18265. static bool gguf_fread_str(FILE * file, struct gguf_str * p, size_t * offset) {
  18266. p->n = 0;
  18267. p->data = NULL;
  18268. bool ok = true;
  18269. ok = ok && gguf_fread_el(file, &p->n, sizeof(p->n), offset);
  18270. // early exit if string length is invalid, prevents from integer overflow
  18271. if (p->n == SIZE_MAX) {
  18272. fprintf(stderr, "%s: invalid string length (%" PRIu64 ")\n", __func__, p->n);
  18273. return false;
  18274. }
  18275. p->data = GGML_CALLOC(p->n + 1, 1);
  18276. ok = ok && gguf_fread_el(file, p->data, p->n, offset);
  18277. return ok;
  18278. }
  18279. static void gguf_free_kv(struct gguf_kv * kv) {
  18280. if (kv->key.data) {
  18281. GGML_FREE(kv->key.data);
  18282. }
  18283. if (kv->type == GGUF_TYPE_STRING) {
  18284. if (kv->value.str.data) {
  18285. GGML_FREE(kv->value.str.data);
  18286. }
  18287. }
  18288. if (kv->type == GGUF_TYPE_ARRAY) {
  18289. if (kv->value.arr.data) {
  18290. if (kv->value.arr.type == GGUF_TYPE_STRING) {
  18291. for (uint64_t j = 0; j < kv->value.arr.n; ++j) {
  18292. struct gguf_str * str = &((struct gguf_str *) kv->value.arr.data)[j];
  18293. if (str->data) {
  18294. GGML_FREE(str->data);
  18295. }
  18296. }
  18297. }
  18298. GGML_FREE(kv->value.arr.data);
  18299. }
  18300. }
  18301. }
  18302. struct gguf_context * gguf_init_empty(void) {
  18303. struct gguf_context * ctx = GGML_CALLOC(1, sizeof(struct gguf_context));
  18304. memcpy(ctx->header.magic, GGUF_MAGIC, sizeof(ctx->header.magic));
  18305. ctx->header.version = GGUF_VERSION;
  18306. ctx->header.n_tensors = 0;
  18307. ctx->header.n_kv = 0;
  18308. ctx->kv = NULL;
  18309. ctx->infos = NULL;
  18310. ctx->alignment = GGUF_DEFAULT_ALIGNMENT;
  18311. ctx->offset = 0;
  18312. ctx->size = 0;
  18313. ctx->data = NULL;
  18314. return ctx;
  18315. }
  18316. struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params) {
  18317. FILE * file = ggml_fopen(fname, "rb");
  18318. if (!file) {
  18319. fprintf(stderr, "%s: failed to open '%s': '%s'\n", __func__, fname, strerror(errno));
  18320. return NULL;
  18321. }
  18322. // offset from start of file
  18323. size_t offset = 0;
  18324. char magic[4];
  18325. // check the magic before making allocations
  18326. {
  18327. gguf_fread_el(file, &magic, sizeof(magic), &offset);
  18328. for (uint32_t i = 0; i < sizeof(magic); i++) {
  18329. if (magic[i] != GGUF_MAGIC[i]) {
  18330. fprintf(stderr, "%s: invalid magic characters '%c%c%c%c'\n", __func__, magic[0], magic[1], magic[2], magic[3]);
  18331. fclose(file);
  18332. return NULL;
  18333. }
  18334. }
  18335. }
  18336. bool ok = true;
  18337. struct gguf_context * ctx = GGML_CALLOC(1, sizeof(struct gguf_context));
  18338. // read the header
  18339. {
  18340. strncpy(ctx->header.magic, magic, 4);
  18341. ctx->kv = NULL;
  18342. ctx->infos = NULL;
  18343. ctx->data = NULL;
  18344. ok = ok && gguf_fread_el(file, &ctx->header.version, sizeof(ctx->header.version), &offset);
  18345. ok = ok && gguf_fread_el(file, &ctx->header.n_tensors, sizeof(ctx->header.n_tensors), &offset);
  18346. ok = ok && gguf_fread_el(file, &ctx->header.n_kv, sizeof(ctx->header.n_kv), &offset);
  18347. if (ctx->header.version == 1) {
  18348. fprintf(stderr, "%s: GGUFv1 is no longer supported. please use a more up-to-date version\n", __func__);
  18349. fclose(file);
  18350. gguf_free(ctx);
  18351. return NULL;
  18352. }
  18353. // sanity-checks to prevent from integer/buffer overflows
  18354. ok = ok && (ctx->header.n_tensors < (SIZE_MAX/2)/sizeof(struct gguf_tensor_info));
  18355. ok = ok && (ctx->header.n_tensors < (SIZE_MAX/2)/ggml_tensor_overhead());
  18356. ok = ok && (ctx->header.n_kv < (SIZE_MAX/2)/sizeof(struct gguf_kv));
  18357. if (!ok) {
  18358. fprintf(stderr, "%s: failed to read header\n", __func__);
  18359. fclose(file);
  18360. gguf_free(ctx);
  18361. return NULL;
  18362. }
  18363. }
  18364. // read the kv pairs
  18365. {
  18366. const uint64_t n_kv = ctx->header.n_kv;
  18367. // header.n_kv will hold the actual value of pairs that were successfully read in the loop below
  18368. ctx->header.n_kv = 0;
  18369. ctx->kv = GGML_CALLOC(n_kv, sizeof(struct gguf_kv));
  18370. for (uint64_t i = 0; i < n_kv; ++i) {
  18371. struct gguf_kv * kv = &ctx->kv[i];
  18372. //fprintf(stderr, "%s: reading kv %d\n", __func__, i);
  18373. ok = ok && gguf_fread_str(file, &kv->key, &offset);
  18374. ok = ok && gguf_fread_el (file, &kv->type, sizeof(kv->type), &offset);
  18375. //fprintf(stderr, "%s: reading kv with key %s\n", __func__, kv->key.data);
  18376. switch (kv->type) {
  18377. case GGUF_TYPE_UINT8: ok = ok && gguf_fread_el (file, &kv->value.uint8, sizeof(kv->value.uint8), &offset); break;
  18378. case GGUF_TYPE_INT8: ok = ok && gguf_fread_el (file, &kv->value.int8, sizeof(kv->value.int8), &offset); break;
  18379. case GGUF_TYPE_UINT16: ok = ok && gguf_fread_el (file, &kv->value.uint16, sizeof(kv->value.uint16), &offset); break;
  18380. case GGUF_TYPE_INT16: ok = ok && gguf_fread_el (file, &kv->value.int16, sizeof(kv->value.int16), &offset); break;
  18381. case GGUF_TYPE_UINT32: ok = ok && gguf_fread_el (file, &kv->value.uint32, sizeof(kv->value.uint32), &offset); break;
  18382. case GGUF_TYPE_INT32: ok = ok && gguf_fread_el (file, &kv->value.int32, sizeof(kv->value.int32), &offset); break;
  18383. case GGUF_TYPE_FLOAT32: ok = ok && gguf_fread_el (file, &kv->value.float32, sizeof(kv->value.float32), &offset); break;
  18384. case GGUF_TYPE_UINT64: ok = ok && gguf_fread_el (file, &kv->value.uint64, sizeof(kv->value.uint64), &offset); break;
  18385. case GGUF_TYPE_INT64: ok = ok && gguf_fread_el (file, &kv->value.int64, sizeof(kv->value.int64), &offset); break;
  18386. case GGUF_TYPE_FLOAT64: ok = ok && gguf_fread_el (file, &kv->value.float64, sizeof(kv->value.float64), &offset); break;
  18387. case GGUF_TYPE_BOOL: ok = ok && gguf_fread_el (file, &kv->value.bool_, sizeof(kv->value.bool_), &offset); break;
  18388. case GGUF_TYPE_STRING: ok = ok && gguf_fread_str(file, &kv->value.str, &offset); break;
  18389. case GGUF_TYPE_ARRAY:
  18390. {
  18391. ok = ok && gguf_fread_el(file, &kv->value.arr.type, sizeof(kv->value.arr.type), &offset);
  18392. ok = ok && gguf_fread_el(file, &kv->value.arr.n, sizeof(kv->value.arr.n), &offset);
  18393. switch (kv->value.arr.type) {
  18394. case GGUF_TYPE_UINT8:
  18395. case GGUF_TYPE_INT8:
  18396. case GGUF_TYPE_UINT16:
  18397. case GGUF_TYPE_INT16:
  18398. case GGUF_TYPE_UINT32:
  18399. case GGUF_TYPE_INT32:
  18400. case GGUF_TYPE_FLOAT32:
  18401. case GGUF_TYPE_UINT64:
  18402. case GGUF_TYPE_INT64:
  18403. case GGUF_TYPE_FLOAT64:
  18404. case GGUF_TYPE_BOOL:
  18405. {
  18406. // prevent from integer overflow in the malloc below
  18407. if (kv->value.arr.n >= SIZE_MAX/gguf_type_size(kv->value.arr.type)) {
  18408. fprintf(stderr, "%s: array size is too large (%" PRIu64 ")\n", __func__, kv->value.arr.n);
  18409. fclose(file);
  18410. gguf_free(ctx);
  18411. return NULL;
  18412. }
  18413. kv->value.arr.data = GGML_CALLOC(kv->value.arr.n, gguf_type_size(kv->value.arr.type));
  18414. ok = ok && gguf_fread_el(file, kv->value.arr.data, kv->value.arr.n * gguf_type_size(kv->value.arr.type), &offset);
  18415. } break;
  18416. case GGUF_TYPE_STRING:
  18417. {
  18418. // prevent from integer overflow in the malloc below
  18419. if (kv->value.arr.n >= SIZE_MAX/sizeof(struct gguf_str)) {
  18420. fprintf(stderr, "%s: array size is too large (%" PRIu64 ")\n", __func__, kv->value.arr.n);
  18421. fclose(file);
  18422. gguf_free(ctx);
  18423. return NULL;
  18424. }
  18425. kv->value.arr.data = GGML_CALLOC(kv->value.arr.n, sizeof(struct gguf_str));
  18426. for (uint64_t j = 0; j < kv->value.arr.n; ++j) {
  18427. ok = ok && gguf_fread_str(file, &((struct gguf_str *) kv->value.arr.data)[j], &offset);
  18428. }
  18429. } break;
  18430. case GGUF_TYPE_ARRAY:
  18431. default: GGML_ABORT("invalid type");
  18432. }
  18433. } break;
  18434. default: GGML_ABORT("invalid type");
  18435. }
  18436. if (!ok) {
  18437. break;
  18438. }
  18439. ctx->header.n_kv++;
  18440. }
  18441. if (!ok) {
  18442. fprintf(stderr, "%s: failed to read key-value pairs\n", __func__);
  18443. fclose(file);
  18444. gguf_free(ctx);
  18445. return NULL;
  18446. }
  18447. }
  18448. // read the tensor infos
  18449. if (ctx->header.n_tensors > 0) {
  18450. ctx->infos = GGML_CALLOC(ctx->header.n_tensors, sizeof(struct gguf_tensor_info));
  18451. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  18452. struct gguf_tensor_info * info = &ctx->infos[i];
  18453. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  18454. info->ne[j] = 1;
  18455. }
  18456. ok = ok && gguf_fread_str(file, &info->name, &offset);
  18457. ok = ok && gguf_fread_el (file, &info->n_dims, sizeof(info->n_dims), &offset);
  18458. ok = ok && (info->n_dims <= GGML_MAX_DIMS);
  18459. for (uint32_t j = 0; j < info->n_dims; ++j) {
  18460. ok = ok && gguf_fread_el(file, &info->ne[j], sizeof(info->ne[j]), &offset);
  18461. }
  18462. ok = ok && gguf_fread_el (file, &info->type, sizeof(info->type), &offset);
  18463. ok = ok && gguf_fread_el (file, &info->offset, sizeof(info->offset), &offset);
  18464. // TODO: return an error instead of crashing with GGML_ASSERT
  18465. gguf_tensor_info_sanitize(info);
  18466. // make sure there is no duplicated tensor names
  18467. for (uint64_t j = 0; j < i && ok; ++j) {
  18468. if (strcmp(info->name.data, ctx->infos[j].name.data) == 0) {
  18469. fprintf(stderr, "%s: duplicated tensor name %s\n", __func__, info->name.data);
  18470. ok = false;
  18471. }
  18472. }
  18473. if (!ok) {
  18474. fprintf(stderr, "%s: failed to read tensor info\n", __func__);
  18475. fclose(file);
  18476. gguf_free(ctx);
  18477. return NULL;
  18478. }
  18479. }
  18480. }
  18481. ctx->alignment = GGUF_DEFAULT_ALIGNMENT;
  18482. int alignment_idx = gguf_find_key(ctx, "general.alignment");
  18483. if (alignment_idx != -1) {
  18484. ctx->alignment = gguf_get_val_u32(ctx, alignment_idx);
  18485. }
  18486. // we require the data section to be aligned, so take into account any padding
  18487. {
  18488. const size_t offset_pad = offset % ctx->alignment;
  18489. if (offset_pad != 0) {
  18490. offset += ctx->alignment - offset_pad;
  18491. fseek(file, offset, SEEK_SET);
  18492. }
  18493. }
  18494. // store the current file offset - this is where the data section starts
  18495. ctx->offset = offset;
  18496. // compute the total size of the data section, taking into account the alignment
  18497. {
  18498. ctx->size = 0;
  18499. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  18500. struct gguf_tensor_info * info = &ctx->infos[i];
  18501. const int64_t ne =
  18502. (int64_t) info->ne[0] *
  18503. (int64_t) info->ne[1] *
  18504. (int64_t) info->ne[2] *
  18505. (int64_t) info->ne[3];
  18506. if (ggml_blck_size(info->type) == 0 || ne % ggml_blck_size(info->type) != 0) {
  18507. fprintf(stderr, "%s: tensor '%s' of type %d (%s) number of elements (%" PRId64 ") is not a multiple of block size (%" PRId64 ")\n",
  18508. __func__, info->name.data, (int) info->type, ggml_type_name(info->type), ne, ggml_blck_size(info->type));
  18509. fclose(file);
  18510. gguf_free(ctx);
  18511. return NULL;
  18512. }
  18513. const size_t size_cur = ggml_row_size(info->type, ne);
  18514. ctx->size += GGML_PAD(size_cur, ctx->alignment);
  18515. }
  18516. }
  18517. // load the tensor data only if requested
  18518. if (params.ctx != NULL) {
  18519. // if the provided gguf_context is no_alloc, then we create "empty" tensors and do not read the binary blob
  18520. // otherwise, we load the binary blob into the created ggml_context as well, and point the "data" members of
  18521. // the ggml_tensor structs to the appropriate locations in the binary blob
  18522. // compute the exact size needed for the new ggml_context
  18523. const size_t mem_size =
  18524. params.no_alloc ?
  18525. (ctx->header.n_tensors )*ggml_tensor_overhead() :
  18526. (ctx->header.n_tensors + 1)*ggml_tensor_overhead() + ctx->size;
  18527. struct ggml_init_params pdata = {
  18528. .mem_size = mem_size,
  18529. .mem_buffer = NULL,
  18530. .no_alloc = params.no_alloc,
  18531. };
  18532. *params.ctx = ggml_init(pdata);
  18533. if (*params.ctx == NULL) {
  18534. fprintf(stderr, "%s: failed to initialize context\n", __func__);
  18535. fclose(file);
  18536. gguf_free(ctx);
  18537. return NULL;
  18538. }
  18539. struct ggml_context * ctx_data = *params.ctx;
  18540. struct ggml_tensor * data = NULL;
  18541. if (!params.no_alloc) {
  18542. data = ggml_new_tensor_1d(ctx_data, GGML_TYPE_I8, ctx->size);
  18543. ok = ok && data != NULL;
  18544. // read the binary blob with the tensor data
  18545. ok = ok && gguf_fread_el(file, data->data, ctx->size, &offset);
  18546. if (!ok) {
  18547. fprintf(stderr, "%s: failed to read tensor data\n", __func__);
  18548. fclose(file);
  18549. ggml_free(ctx_data);
  18550. gguf_free(ctx);
  18551. return NULL;
  18552. }
  18553. ctx->data = data->data;
  18554. }
  18555. ggml_set_no_alloc(ctx_data, true);
  18556. // create the tensors
  18557. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  18558. const int64_t ne[GGML_MAX_DIMS] = {
  18559. ctx->infos[i].ne[0],
  18560. ctx->infos[i].ne[1],
  18561. ctx->infos[i].ne[2],
  18562. ctx->infos[i].ne[3],
  18563. };
  18564. struct ggml_tensor * cur = ggml_new_tensor(ctx_data, ctx->infos[i].type, ctx->infos[i].n_dims, ne);
  18565. ok = ok && cur != NULL;
  18566. if (!ok) {
  18567. break;
  18568. }
  18569. ggml_set_name(cur, ctx->infos[i].name.data);
  18570. // point the data member to the appropriate location in the binary blob using the tensor infos
  18571. if (!params.no_alloc) {
  18572. //cur->data = (char *) data->data + ctx->infos[i].offset - ctx->offset; // offset from start of file
  18573. cur->data = (char *) data->data + ctx->infos[i].offset; // offset from data
  18574. }
  18575. }
  18576. if (!ok) {
  18577. fprintf(stderr, "%s: failed to read the tensor data\n", __func__);
  18578. fclose(file);
  18579. ggml_free(ctx_data);
  18580. gguf_free(ctx);
  18581. return NULL;
  18582. }
  18583. ggml_set_no_alloc(ctx_data, params.no_alloc);
  18584. }
  18585. fclose(file);
  18586. return ctx;
  18587. }
  18588. void gguf_free(struct gguf_context * ctx) {
  18589. if (ctx == NULL) {
  18590. return;
  18591. }
  18592. if (ctx->kv) {
  18593. // free string memory - not great..
  18594. for (uint64_t i = 0; i < ctx->header.n_kv; ++i) {
  18595. gguf_free_kv(&ctx->kv[i]);
  18596. }
  18597. GGML_FREE(ctx->kv);
  18598. }
  18599. if (ctx->infos) {
  18600. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  18601. struct gguf_tensor_info * info = &ctx->infos[i];
  18602. if (info->name.data) {
  18603. GGML_FREE(info->name.data);
  18604. }
  18605. }
  18606. GGML_FREE(ctx->infos);
  18607. }
  18608. GGML_FREE(ctx);
  18609. }
  18610. const char * gguf_type_name(enum gguf_type type) {
  18611. return GGUF_TYPE_NAME[type];
  18612. }
  18613. int gguf_get_version(const struct gguf_context * ctx) {
  18614. return ctx->header.version;
  18615. }
  18616. size_t gguf_get_alignment(const struct gguf_context * ctx) {
  18617. return ctx->alignment;
  18618. }
  18619. size_t gguf_get_data_offset(const struct gguf_context * ctx) {
  18620. return ctx->offset;
  18621. }
  18622. void * gguf_get_data(const struct gguf_context * ctx) {
  18623. return ctx->data;
  18624. }
  18625. int gguf_get_n_kv(const struct gguf_context * ctx) {
  18626. return ctx->header.n_kv;
  18627. }
  18628. int gguf_find_key(const struct gguf_context * ctx, const char * key) {
  18629. // return -1 if key not found
  18630. int keyfound = -1;
  18631. const int n_kv = gguf_get_n_kv(ctx);
  18632. for (int i = 0; i < n_kv; ++i) {
  18633. if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
  18634. keyfound = i;
  18635. break;
  18636. }
  18637. }
  18638. return keyfound;
  18639. }
  18640. const char * gguf_get_key(const struct gguf_context * ctx, int key_id) {
  18641. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18642. return ctx->kv[key_id].key.data;
  18643. }
  18644. enum gguf_type gguf_get_kv_type(const struct gguf_context * ctx, int key_id) {
  18645. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18646. return ctx->kv[key_id].type;
  18647. }
  18648. enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int key_id) {
  18649. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18650. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  18651. return ctx->kv[key_id].value.arr.type;
  18652. }
  18653. const void * gguf_get_arr_data(const struct gguf_context * ctx, int key_id) {
  18654. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18655. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  18656. return ctx->kv[key_id].value.arr.data;
  18657. }
  18658. const char * gguf_get_arr_str(const struct gguf_context * ctx, int key_id, int i) {
  18659. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18660. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  18661. struct gguf_kv * kv = &ctx->kv[key_id];
  18662. struct gguf_str * str = &((struct gguf_str *) kv->value.arr.data)[i];
  18663. return str->data;
  18664. }
  18665. int gguf_get_arr_n(const struct gguf_context * ctx, int key_id) {
  18666. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18667. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  18668. return ctx->kv[key_id].value.arr.n;
  18669. }
  18670. uint8_t gguf_get_val_u8(const struct gguf_context * ctx, int key_id) {
  18671. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18672. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT8);
  18673. return ctx->kv[key_id].value.uint8;
  18674. }
  18675. int8_t gguf_get_val_i8(const struct gguf_context * ctx, int key_id) {
  18676. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18677. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT8);
  18678. return ctx->kv[key_id].value.int8;
  18679. }
  18680. uint16_t gguf_get_val_u16(const struct gguf_context * ctx, int key_id) {
  18681. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18682. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT16);
  18683. return ctx->kv[key_id].value.uint16;
  18684. }
  18685. int16_t gguf_get_val_i16(const struct gguf_context * ctx, int key_id) {
  18686. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18687. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT16);
  18688. return ctx->kv[key_id].value.int16;
  18689. }
  18690. uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int key_id) {
  18691. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18692. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT32);
  18693. return ctx->kv[key_id].value.uint32;
  18694. }
  18695. int32_t gguf_get_val_i32(const struct gguf_context * ctx, int key_id) {
  18696. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18697. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT32);
  18698. return ctx->kv[key_id].value.int32;
  18699. }
  18700. float gguf_get_val_f32(const struct gguf_context * ctx, int key_id) {
  18701. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18702. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_FLOAT32);
  18703. return ctx->kv[key_id].value.float32;
  18704. }
  18705. uint64_t gguf_get_val_u64(const struct gguf_context * ctx, int key_id) {
  18706. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18707. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT64);
  18708. return ctx->kv[key_id].value.uint64;
  18709. }
  18710. int64_t gguf_get_val_i64(const struct gguf_context * ctx, int key_id) {
  18711. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18712. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT64);
  18713. return ctx->kv[key_id].value.int64;
  18714. }
  18715. double gguf_get_val_f64(const struct gguf_context * ctx, int key_id) {
  18716. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18717. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_FLOAT64);
  18718. return ctx->kv[key_id].value.float64;
  18719. }
  18720. bool gguf_get_val_bool(const struct gguf_context * ctx, int key_id) {
  18721. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18722. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_BOOL);
  18723. return ctx->kv[key_id].value.bool_;
  18724. }
  18725. const char * gguf_get_val_str(const struct gguf_context * ctx, int key_id) {
  18726. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18727. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_STRING);
  18728. return ctx->kv[key_id].value.str.data;
  18729. }
  18730. const void * gguf_get_val_data(const struct gguf_context * ctx, int key_id) {
  18731. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  18732. GGML_ASSERT(ctx->kv[key_id].type != GGUF_TYPE_ARRAY);
  18733. GGML_ASSERT(ctx->kv[key_id].type != GGUF_TYPE_STRING);
  18734. return &ctx->kv[key_id].value;
  18735. }
  18736. int gguf_get_n_tensors(const struct gguf_context * ctx) {
  18737. return ctx->header.n_tensors;
  18738. }
  18739. int gguf_find_tensor(const struct gguf_context * ctx, const char * name) {
  18740. // return -1 if tensor not found
  18741. int tensorfound = -1;
  18742. const int n_tensors = gguf_get_n_tensors(ctx);
  18743. for (int i = 0; i < n_tensors; ++i) {
  18744. if (strcmp(name, gguf_get_tensor_name(ctx, i)) == 0) {
  18745. tensorfound = i;
  18746. break;
  18747. }
  18748. }
  18749. return tensorfound;
  18750. }
  18751. size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int i) {
  18752. return ctx->infos[i].offset;
  18753. }
  18754. char * gguf_get_tensor_name(const struct gguf_context * ctx, int i) {
  18755. return ctx->infos[i].name.data;
  18756. }
  18757. enum ggml_type gguf_get_tensor_type(const struct gguf_context * ctx, int i) {
  18758. return ctx->infos[i].type;
  18759. }
  18760. // returns the index
  18761. static int gguf_get_or_add_key(struct gguf_context * ctx, const char * key) {
  18762. const int idx = gguf_find_key(ctx, key);
  18763. if (idx >= 0) {
  18764. return idx;
  18765. }
  18766. const int n_kv = gguf_get_n_kv(ctx);
  18767. ctx->kv = realloc(ctx->kv, (n_kv + 1) * sizeof(struct gguf_kv));
  18768. ctx->kv[n_kv].key.n = strlen(key);
  18769. ctx->kv[n_kv].key.data = strdup(key);
  18770. ctx->header.n_kv++;
  18771. return n_kv;
  18772. }
  18773. void gguf_remove_key(struct gguf_context * ctx, const char * key) {
  18774. const int idx = gguf_find_key(ctx, key);
  18775. if (idx >= 0) {
  18776. const int n_kv = gguf_get_n_kv(ctx);
  18777. gguf_free_kv(&ctx->kv[idx]);
  18778. for (int i = idx; i < n_kv-1; ++i) {
  18779. ctx->kv[i] = ctx->kv[i+1];
  18780. }
  18781. ctx->kv = realloc(ctx->kv, (n_kv - 1) * sizeof(struct gguf_kv));
  18782. ctx->header.n_kv--;
  18783. }
  18784. }
  18785. void gguf_set_val_u8(struct gguf_context * ctx, const char * key, uint8_t val) {
  18786. const int idx = gguf_get_or_add_key(ctx, key);
  18787. ctx->kv[idx].type = GGUF_TYPE_UINT8;
  18788. ctx->kv[idx].value.uint8 = val;
  18789. }
  18790. void gguf_set_val_i8(struct gguf_context * ctx, const char * key, int8_t val) {
  18791. const int idx = gguf_get_or_add_key(ctx, key);
  18792. ctx->kv[idx].type = GGUF_TYPE_INT8;
  18793. ctx->kv[idx].value.int8 = val;
  18794. }
  18795. void gguf_set_val_u16(struct gguf_context * ctx, const char * key, uint16_t val) {
  18796. const int idx = gguf_get_or_add_key(ctx, key);
  18797. ctx->kv[idx].type = GGUF_TYPE_UINT16;
  18798. ctx->kv[idx].value.uint16 = val;
  18799. }
  18800. void gguf_set_val_i16(struct gguf_context * ctx, const char * key, int16_t val) {
  18801. const int idx = gguf_get_or_add_key(ctx, key);
  18802. ctx->kv[idx].type = GGUF_TYPE_INT16;
  18803. ctx->kv[idx].value.int16 = val;
  18804. }
  18805. void gguf_set_val_u32(struct gguf_context * ctx, const char * key, uint32_t val) {
  18806. const int idx = gguf_get_or_add_key(ctx, key);
  18807. ctx->kv[idx].type = GGUF_TYPE_UINT32;
  18808. ctx->kv[idx].value.uint32 = val;
  18809. }
  18810. void gguf_set_val_i32(struct gguf_context * ctx, const char * key, int32_t val) {
  18811. const int idx = gguf_get_or_add_key(ctx, key);
  18812. ctx->kv[idx].type = GGUF_TYPE_INT32;
  18813. ctx->kv[idx].value.int32 = val;
  18814. }
  18815. void gguf_set_val_f32(struct gguf_context * ctx, const char * key, float val) {
  18816. const int idx = gguf_get_or_add_key(ctx, key);
  18817. ctx->kv[idx].type = GGUF_TYPE_FLOAT32;
  18818. ctx->kv[idx].value.float32 = val;
  18819. }
  18820. void gguf_set_val_u64(struct gguf_context * ctx, const char * key, uint64_t val) {
  18821. const int idx = gguf_get_or_add_key(ctx, key);
  18822. ctx->kv[idx].type = GGUF_TYPE_UINT64;
  18823. ctx->kv[idx].value.uint64 = val;
  18824. }
  18825. void gguf_set_val_i64(struct gguf_context * ctx, const char * key, int64_t val) {
  18826. const int idx = gguf_get_or_add_key(ctx, key);
  18827. ctx->kv[idx].type = GGUF_TYPE_INT64;
  18828. ctx->kv[idx].value.int64 = val;
  18829. }
  18830. void gguf_set_val_f64(struct gguf_context * ctx, const char * key, double val) {
  18831. const int idx = gguf_get_or_add_key(ctx, key);
  18832. ctx->kv[idx].type = GGUF_TYPE_FLOAT64;
  18833. ctx->kv[idx].value.float64 = val;
  18834. }
  18835. void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val) {
  18836. const int idx = gguf_get_or_add_key(ctx, key);
  18837. ctx->kv[idx].type = GGUF_TYPE_BOOL;
  18838. ctx->kv[idx].value.bool_ = val;
  18839. }
  18840. void gguf_set_val_str(struct gguf_context * ctx, const char * key, const char * val) {
  18841. const int idx = gguf_get_or_add_key(ctx, key);
  18842. ctx->kv[idx].type = GGUF_TYPE_STRING;
  18843. ctx->kv[idx].value.str.n = strlen(val);
  18844. ctx->kv[idx].value.str.data = strdup(val);
  18845. }
  18846. void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, int n) {
  18847. const int idx = gguf_get_or_add_key(ctx, key);
  18848. ctx->kv[idx].type = GGUF_TYPE_ARRAY;
  18849. ctx->kv[idx].value.arr.type = type;
  18850. ctx->kv[idx].value.arr.n = n;
  18851. ctx->kv[idx].value.arr.data = GGML_CALLOC(n, gguf_type_size(type));
  18852. memcpy(ctx->kv[idx].value.arr.data, data, n*gguf_type_size(type));
  18853. }
  18854. void gguf_set_arr_str(struct gguf_context * ctx, const char * key, const char ** data, int n) {
  18855. const int idx = gguf_get_or_add_key(ctx, key);
  18856. ctx->kv[idx].type = GGUF_TYPE_ARRAY;
  18857. ctx->kv[idx].value.arr.type = GGUF_TYPE_STRING;
  18858. ctx->kv[idx].value.arr.n = n;
  18859. ctx->kv[idx].value.arr.data = GGML_CALLOC(n, sizeof(struct gguf_str));
  18860. for (int i = 0; i < n; i++) {
  18861. struct gguf_str * str = &((struct gguf_str *)ctx->kv[idx].value.arr.data)[i];
  18862. str->n = strlen(data[i]);
  18863. str->data = strdup(data[i]);
  18864. }
  18865. }
  18866. // set or add KV pairs from another context
  18867. void gguf_set_kv(struct gguf_context * ctx, struct gguf_context * src) {
  18868. for (uint32_t i = 0; i < src->header.n_kv; i++) {
  18869. switch (src->kv[i].type) {
  18870. case GGUF_TYPE_UINT8: gguf_set_val_u8 (ctx, src->kv[i].key.data, src->kv[i].value.uint8); break;
  18871. case GGUF_TYPE_INT8: gguf_set_val_i8 (ctx, src->kv[i].key.data, src->kv[i].value.int8); break;
  18872. case GGUF_TYPE_UINT16: gguf_set_val_u16 (ctx, src->kv[i].key.data, src->kv[i].value.uint16); break;
  18873. case GGUF_TYPE_INT16: gguf_set_val_i16 (ctx, src->kv[i].key.data, src->kv[i].value.int16); break;
  18874. case GGUF_TYPE_UINT32: gguf_set_val_u32 (ctx, src->kv[i].key.data, src->kv[i].value.uint32); break;
  18875. case GGUF_TYPE_INT32: gguf_set_val_i32 (ctx, src->kv[i].key.data, src->kv[i].value.int32); break;
  18876. case GGUF_TYPE_FLOAT32: gguf_set_val_f32 (ctx, src->kv[i].key.data, src->kv[i].value.float32); break;
  18877. case GGUF_TYPE_UINT64: gguf_set_val_u64 (ctx, src->kv[i].key.data, src->kv[i].value.uint64); break;
  18878. case GGUF_TYPE_INT64: gguf_set_val_i64 (ctx, src->kv[i].key.data, src->kv[i].value.int64); break;
  18879. case GGUF_TYPE_FLOAT64: gguf_set_val_f64 (ctx, src->kv[i].key.data, src->kv[i].value.float64); break;
  18880. case GGUF_TYPE_BOOL: gguf_set_val_bool(ctx, src->kv[i].key.data, src->kv[i].value.bool_); break;
  18881. case GGUF_TYPE_STRING: gguf_set_val_str (ctx, src->kv[i].key.data, src->kv[i].value.str.data); break;
  18882. case GGUF_TYPE_ARRAY:
  18883. {
  18884. if (src->kv[i].value.arr.type == GGUF_TYPE_STRING) {
  18885. const char ** data = GGML_CALLOC(src->kv[i].value.arr.n, sizeof(char *));
  18886. for (uint32_t j = 0; j < src->kv[i].value.arr.n; j++) {
  18887. data[j] = ((struct gguf_str *)src->kv[i].value.arr.data)[j].data;
  18888. }
  18889. gguf_set_arr_str(ctx, src->kv[i].key.data, data, src->kv[i].value.arr.n);
  18890. GGML_FREE((void *)data);
  18891. } else if (src->kv[i].value.arr.type == GGUF_TYPE_ARRAY) {
  18892. GGML_ABORT("nested arrays not supported");
  18893. } else {
  18894. 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);
  18895. }
  18896. } break;
  18897. default: GGML_ABORT("invalid type");
  18898. }
  18899. }
  18900. }
  18901. void gguf_add_tensor(
  18902. struct gguf_context * ctx,
  18903. const struct ggml_tensor * tensor) {
  18904. GGML_ASSERT(tensor);
  18905. if (gguf_find_tensor(ctx, tensor->name) != -1) {
  18906. GGML_ABORT("duplicated tensor name");
  18907. }
  18908. const int idx = ctx->header.n_tensors;
  18909. ctx->infos = realloc(ctx->infos, (idx + 1)*sizeof(struct gguf_tensor_info));
  18910. ctx->infos[idx].name.n = strlen(tensor->name);
  18911. ctx->infos[idx].name.data = strdup(tensor->name);
  18912. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  18913. ctx->infos[idx].ne[i] = 1;
  18914. }
  18915. ctx->infos[idx].n_dims = ggml_n_dims(tensor);
  18916. for (uint32_t i = 0; i < ctx->infos[idx].n_dims; i++) {
  18917. ctx->infos[idx].ne[i] = tensor->ne[i];
  18918. }
  18919. ctx->infos[idx].type = tensor->type;
  18920. ctx->infos[idx].offset = 0;
  18921. ctx->infos[idx].data = tensor->data;
  18922. ctx->infos[idx].size = ggml_nbytes(tensor);
  18923. if (ctx->header.n_tensors > 0) {
  18924. ctx->infos[idx].offset = ctx->infos[idx - 1].offset + GGML_PAD(ctx->infos[idx - 1].size, ctx->alignment);
  18925. }
  18926. ctx->header.n_tensors++;
  18927. }
  18928. void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
  18929. const int idx = gguf_find_tensor(ctx, name);
  18930. if (idx < 0) {
  18931. GGML_ABORT("tensor not found");
  18932. }
  18933. ctx->infos[idx].type = type;
  18934. }
  18935. void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data, size_t size) {
  18936. const int idx = gguf_find_tensor(ctx, name);
  18937. if (idx < 0) {
  18938. GGML_ABORT("tensor not found");
  18939. }
  18940. ctx->infos[idx].data = data;
  18941. ctx->infos[idx].size = size;
  18942. // update offsets
  18943. for (uint32_t i = idx + 1; i < ctx->header.n_tensors; ++i) {
  18944. ctx->infos[i].offset = ctx->infos[i - 1].offset + GGML_PAD(ctx->infos[i - 1].size, ctx->alignment);
  18945. }
  18946. }
  18947. //static void gguf_fwrite_str(FILE * file, const struct gguf_str * val) {
  18948. // fwrite(&val->n, sizeof(val->n), 1, file);
  18949. // fwrite(val->data, sizeof(char), val->n, file);
  18950. //}
  18951. //
  18952. //static void gguf_fwrite_el(FILE * file, const void * val, size_t size) {
  18953. // fwrite(val, sizeof(char), size, file);
  18954. //}
  18955. struct gguf_buf {
  18956. void * data;
  18957. size_t size;
  18958. size_t offset;
  18959. };
  18960. static struct gguf_buf gguf_buf_init(size_t size) {
  18961. struct gguf_buf buf = {
  18962. /*buf.data =*/ size == 0 ? NULL : GGML_CALLOC(1, size),
  18963. /*buf.size =*/ size,
  18964. /*buf.offset =*/ 0,
  18965. };
  18966. return buf;
  18967. }
  18968. static void gguf_buf_free(struct gguf_buf buf) {
  18969. if (buf.data) {
  18970. GGML_FREE(buf.data);
  18971. }
  18972. }
  18973. static void gguf_buf_grow(struct gguf_buf * buf, size_t size) {
  18974. if (buf->offset + size > buf->size) {
  18975. buf->size = 1.5*(buf->offset + size);
  18976. if (buf->data) {
  18977. buf->data = realloc(buf->data, buf->size);
  18978. }
  18979. }
  18980. }
  18981. static void gguf_bwrite_str(struct gguf_buf * buf, const struct gguf_str * val) {
  18982. gguf_buf_grow(buf, sizeof(val->n) + val->n);
  18983. if (buf->data) {
  18984. memcpy((char *) buf->data + buf->offset, &val->n, sizeof(val->n));
  18985. }
  18986. buf->offset += sizeof(val->n);
  18987. if (buf->data) {
  18988. memcpy((char *) buf->data + buf->offset, val->data, val->n);
  18989. }
  18990. buf->offset += val->n;
  18991. }
  18992. static void gguf_bwrite_el(struct gguf_buf * buf, const void * val, size_t el_size) {
  18993. gguf_buf_grow(buf, el_size);
  18994. if (buf->data) {
  18995. memcpy((char *) buf->data + buf->offset, val, el_size);
  18996. }
  18997. buf->offset += el_size;
  18998. }
  18999. static void gguf_write_to_buf(const struct gguf_context * ctx, struct gguf_buf * buf, bool only_meta) {
  19000. // write header
  19001. gguf_bwrite_el(buf, &ctx->header.magic, sizeof(ctx->header.magic));
  19002. gguf_bwrite_el(buf, &ctx->header.version, sizeof(ctx->header.version));
  19003. gguf_bwrite_el(buf, &ctx->header.n_tensors, sizeof(ctx->header.n_tensors));
  19004. gguf_bwrite_el(buf, &ctx->header.n_kv, sizeof(ctx->header.n_kv));
  19005. // write key-value pairs
  19006. for (uint32_t i = 0; i < ctx->header.n_kv; ++i) {
  19007. struct gguf_kv * kv = &ctx->kv[i];
  19008. gguf_bwrite_str(buf, &kv->key);
  19009. gguf_bwrite_el (buf, &kv->type, sizeof(kv->type));
  19010. switch (kv->type) {
  19011. case GGUF_TYPE_UINT8: gguf_bwrite_el( buf, &kv->value.uint8, sizeof(kv->value.uint8) ); break;
  19012. case GGUF_TYPE_INT8: gguf_bwrite_el (buf, &kv->value.int8, sizeof(kv->value.int8) ); break;
  19013. case GGUF_TYPE_UINT16: gguf_bwrite_el (buf, &kv->value.uint16, sizeof(kv->value.uint16) ); break;
  19014. case GGUF_TYPE_INT16: gguf_bwrite_el (buf, &kv->value.int16, sizeof(kv->value.int16) ); break;
  19015. case GGUF_TYPE_UINT32: gguf_bwrite_el (buf, &kv->value.uint32, sizeof(kv->value.uint32) ); break;
  19016. case GGUF_TYPE_INT32: gguf_bwrite_el (buf, &kv->value.int32, sizeof(kv->value.int32) ); break;
  19017. case GGUF_TYPE_FLOAT32: gguf_bwrite_el (buf, &kv->value.float32, sizeof(kv->value.float32)); break;
  19018. case GGUF_TYPE_UINT64: gguf_bwrite_el (buf, &kv->value.uint64, sizeof(kv->value.uint64) ); break;
  19019. case GGUF_TYPE_INT64: gguf_bwrite_el (buf, &kv->value.int64, sizeof(kv->value.int64) ); break;
  19020. case GGUF_TYPE_FLOAT64: gguf_bwrite_el (buf, &kv->value.float64, sizeof(kv->value.float64)); break;
  19021. case GGUF_TYPE_BOOL: gguf_bwrite_el (buf, &kv->value.bool_, sizeof(kv->value.bool_) ); break;
  19022. case GGUF_TYPE_STRING: gguf_bwrite_str(buf, &kv->value.str ); break;
  19023. case GGUF_TYPE_ARRAY:
  19024. {
  19025. gguf_bwrite_el(buf, &kv->value.arr.type, sizeof(kv->value.arr.type));
  19026. gguf_bwrite_el(buf, &kv->value.arr.n, sizeof(kv->value.arr.n) );
  19027. switch (kv->value.arr.type) {
  19028. case GGUF_TYPE_UINT8:
  19029. case GGUF_TYPE_INT8:
  19030. case GGUF_TYPE_UINT16:
  19031. case GGUF_TYPE_INT16:
  19032. case GGUF_TYPE_UINT32:
  19033. case GGUF_TYPE_INT32:
  19034. case GGUF_TYPE_FLOAT32:
  19035. case GGUF_TYPE_UINT64:
  19036. case GGUF_TYPE_INT64:
  19037. case GGUF_TYPE_FLOAT64:
  19038. case GGUF_TYPE_BOOL:
  19039. {
  19040. gguf_bwrite_el(buf, kv->value.arr.data, kv->value.arr.n * gguf_type_size(kv->value.arr.type));
  19041. } break;
  19042. case GGUF_TYPE_STRING:
  19043. {
  19044. for (uint32_t j = 0; j < kv->value.arr.n; ++j) {
  19045. gguf_bwrite_str(buf, &((struct gguf_str *) kv->value.arr.data)[j]);
  19046. }
  19047. } break;
  19048. case GGUF_TYPE_ARRAY:
  19049. default: GGML_ABORT("invalid type");
  19050. }
  19051. } break;
  19052. default: GGML_ABORT("invalid type");
  19053. }
  19054. }
  19055. // write tensor infos
  19056. for (uint32_t i = 0; i < ctx->header.n_tensors; ++i) {
  19057. struct gguf_tensor_info * info = &ctx->infos[i];
  19058. gguf_bwrite_str(buf, &info->name);
  19059. gguf_bwrite_el (buf, &info->n_dims, sizeof(info->n_dims));
  19060. for (uint32_t j = 0; j < info->n_dims; ++j) {
  19061. gguf_bwrite_el(buf, &info->ne[j], sizeof(info->ne[j]));
  19062. }
  19063. gguf_bwrite_el(buf, &info->type, sizeof(info->type));
  19064. gguf_bwrite_el(buf, &info->offset, sizeof(info->offset));
  19065. }
  19066. // we require the data section to be aligned, so take into account any padding
  19067. {
  19068. const size_t offset = buf->offset;
  19069. const size_t offset_pad = GGML_PAD(offset, ctx->alignment);
  19070. if (offset_pad != offset) {
  19071. uint8_t pad = 0;
  19072. for (size_t i = 0; i < offset_pad - offset; ++i) {
  19073. gguf_bwrite_el(buf, &pad, sizeof(pad));
  19074. }
  19075. }
  19076. }
  19077. if (only_meta) {
  19078. return;
  19079. }
  19080. size_t offset = 0;
  19081. // write tensor data
  19082. for (uint32_t i = 0; i < ctx->header.n_tensors; ++i) {
  19083. struct gguf_tensor_info * info = &ctx->infos[i];
  19084. const size_t size = info->size;
  19085. const size_t size_pad = GGML_PAD(size, ctx->alignment);
  19086. gguf_bwrite_el(buf, info->data, size);
  19087. if (size_pad != size) {
  19088. uint8_t pad = 0;
  19089. for (size_t j = 0; j < size_pad - size; ++j) {
  19090. gguf_bwrite_el(buf, &pad, sizeof(pad));
  19091. }
  19092. }
  19093. GGML_ASSERT(offset == info->offset);
  19094. offset += size_pad;
  19095. }
  19096. }
  19097. void gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta) {
  19098. FILE * file = ggml_fopen(fname, "wb");
  19099. if (!file) {
  19100. GGML_ABORT("failed to open file for writing");
  19101. }
  19102. struct gguf_buf buf = gguf_buf_init(16*1024);
  19103. gguf_write_to_buf(ctx, &buf, only_meta);
  19104. fwrite(buf.data, 1, buf.offset, file);
  19105. gguf_buf_free(buf);
  19106. fclose(file);
  19107. }
  19108. size_t gguf_get_meta_size(const struct gguf_context * ctx) {
  19109. // no allocs - only compute size
  19110. struct gguf_buf buf = gguf_buf_init(0);
  19111. gguf_write_to_buf(ctx, &buf, true);
  19112. return buf.offset;
  19113. }
  19114. void gguf_get_meta_data(const struct gguf_context * ctx, void * data) {
  19115. struct gguf_buf buf = gguf_buf_init(16*1024);
  19116. gguf_write_to_buf(ctx, &buf, true);
  19117. memcpy(data, buf.data, buf.offset);
  19118. gguf_buf_free(buf);
  19119. }
  19120. ////////////////////////////////////////////////////////////////////////////////
  19121. int ggml_cpu_has_avx(void) {
  19122. #if defined(__AVX__)
  19123. return 1;
  19124. #else
  19125. return 0;
  19126. #endif
  19127. }
  19128. int ggml_cpu_has_avx_vnni(void) {
  19129. #if defined(__AVXVNNI__)
  19130. return 1;
  19131. #else
  19132. return 0;
  19133. #endif
  19134. }
  19135. int ggml_cpu_has_avx2(void) {
  19136. #if defined(__AVX2__)
  19137. return 1;
  19138. #else
  19139. return 0;
  19140. #endif
  19141. }
  19142. int ggml_cpu_has_avx512(void) {
  19143. #if defined(__AVX512F__)
  19144. return 1;
  19145. #else
  19146. return 0;
  19147. #endif
  19148. }
  19149. int ggml_cpu_has_avx512_vbmi(void) {
  19150. #if defined(__AVX512VBMI__)
  19151. return 1;
  19152. #else
  19153. return 0;
  19154. #endif
  19155. }
  19156. int ggml_cpu_has_avx512_vnni(void) {
  19157. #if defined(__AVX512VNNI__)
  19158. return 1;
  19159. #else
  19160. return 0;
  19161. #endif
  19162. }
  19163. int ggml_cpu_has_avx512_bf16(void) {
  19164. #if defined(__AVX512BF16__)
  19165. return 1;
  19166. #else
  19167. return 0;
  19168. #endif
  19169. }
  19170. int ggml_cpu_has_fma(void) {
  19171. #if defined(__FMA__)
  19172. return 1;
  19173. #else
  19174. return 0;
  19175. #endif
  19176. }
  19177. int ggml_cpu_has_neon(void) {
  19178. #if defined(__ARM_ARCH)
  19179. return ggml_arm_arch_features.has_neon;
  19180. #else
  19181. return 0;
  19182. #endif
  19183. }
  19184. int ggml_cpu_has_sve(void) {
  19185. #if defined(__ARM_ARCH)
  19186. return ggml_arm_arch_features.has_sve;
  19187. #else
  19188. return 0;
  19189. #endif
  19190. }
  19191. int ggml_cpu_has_arm_fma(void) {
  19192. #if defined(__ARM_FEATURE_FMA)
  19193. return 1;
  19194. #else
  19195. return 0;
  19196. #endif
  19197. }
  19198. int ggml_cpu_has_riscv_v(void) {
  19199. #if defined(__riscv_v_intrinsic)
  19200. return 1;
  19201. #else
  19202. return 0;
  19203. #endif
  19204. }
  19205. int ggml_cpu_has_metal(void) {
  19206. #if defined(GGML_USE_METAL)
  19207. return 1;
  19208. #else
  19209. return 0;
  19210. #endif
  19211. }
  19212. int ggml_cpu_has_f16c(void) {
  19213. #if defined(__F16C__)
  19214. return 1;
  19215. #else
  19216. return 0;
  19217. #endif
  19218. }
  19219. int ggml_cpu_has_fp16_va(void) {
  19220. #if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
  19221. return 1;
  19222. #else
  19223. return 0;
  19224. #endif
  19225. }
  19226. int ggml_cpu_has_wasm_simd(void) {
  19227. #if defined(__wasm_simd128__)
  19228. return 1;
  19229. #else
  19230. return 0;
  19231. #endif
  19232. }
  19233. int ggml_cpu_has_blas(void) {
  19234. #if defined(GGML_USE_BLAS) || defined(GGML_USE_CUDA) || defined(GGML_USE_VULKAN) || defined(GGML_USE_SYCL)
  19235. return 1;
  19236. #else
  19237. return 0;
  19238. #endif
  19239. }
  19240. int ggml_cpu_has_cuda(void) {
  19241. #if defined(GGML_USE_CUDA)
  19242. return 1;
  19243. #else
  19244. return 0;
  19245. #endif
  19246. }
  19247. int ggml_cpu_has_vulkan(void) {
  19248. #if defined(GGML_USE_VULKAN)
  19249. return 1;
  19250. #else
  19251. return 0;
  19252. #endif
  19253. }
  19254. int ggml_cpu_has_kompute(void) {
  19255. #if defined(GGML_USE_KOMPUTE)
  19256. return 1;
  19257. #else
  19258. return 0;
  19259. #endif
  19260. }
  19261. int ggml_cpu_has_sycl(void) {
  19262. #if defined(GGML_USE_SYCL)
  19263. return 1;
  19264. #else
  19265. return 0;
  19266. #endif
  19267. }
  19268. int ggml_cpu_has_rpc(void) {
  19269. #if defined(GGML_USE_RPC)
  19270. return 1;
  19271. #else
  19272. return 0;
  19273. #endif
  19274. }
  19275. int ggml_cpu_has_cann(void) {
  19276. #if defined(GGML_USE_CANN)
  19277. return 1;
  19278. #else
  19279. return 0;
  19280. #endif
  19281. }
  19282. int ggml_cpu_has_llamafile(void) {
  19283. #if defined(GGML_USE_LLAMAFILE)
  19284. return 1;
  19285. #else
  19286. return 0;
  19287. #endif
  19288. }
  19289. int ggml_cpu_has_gpublas(void) {
  19290. return ggml_cpu_has_cuda() || ggml_cpu_has_vulkan() || ggml_cpu_has_kompute() || ggml_cpu_has_sycl();
  19291. }
  19292. int ggml_cpu_has_sse3(void) {
  19293. #if defined(__SSE3__)
  19294. return 1;
  19295. #else
  19296. return 0;
  19297. #endif
  19298. }
  19299. int ggml_cpu_has_ssse3(void) {
  19300. #if defined(__SSSE3__)
  19301. return 1;
  19302. #else
  19303. return 0;
  19304. #endif
  19305. }
  19306. int ggml_cpu_has_vsx(void) {
  19307. #if defined(__POWER9_VECTOR__)
  19308. return 1;
  19309. #else
  19310. return 0;
  19311. #endif
  19312. }
  19313. int ggml_cpu_has_matmul_int8(void) {
  19314. #if defined(__ARM_ARCH)
  19315. return ggml_arm_arch_features.has_i8mm;
  19316. #else
  19317. return 0;
  19318. #endif
  19319. }
  19320. int ggml_cpu_get_sve_cnt(void) {
  19321. #if defined(__ARM_ARCH)
  19322. return ggml_arm_arch_features.sve_cnt;
  19323. #else
  19324. return 0;
  19325. #endif
  19326. }
  19327. ////////////////////////////////////////////////////////////////////////////////