ggml.c 321 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643
  1. #include "ggml.h"
  2. #if defined(_MSC_VER) || defined(__MINGW32__)
  3. #include <malloc.h> // using malloc.h with MSC/MINGW
  4. #elif !defined(__FreeBSD__) && !defined(__NetBSD__)
  5. #include <alloca.h>
  6. #endif
  7. #include <assert.h>
  8. #include <time.h>
  9. #include <math.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <stdint.h>
  13. #include <stdio.h>
  14. #include <float.h>
  15. // if C99 - static_assert is noop
  16. // ref: https://stackoverflow.com/a/53923785/4039976
  17. #ifndef static_assert
  18. #define static_assert(cond, msg) struct global_scope_noop_trick
  19. #endif
  20. #if defined _MSC_VER || defined(__MINGW32__)
  21. #if !defined(__MINGW32__)
  22. #include <Windows.h>
  23. #else
  24. // ref: https://github.com/ggerganov/whisper.cpp/issues/168
  25. #include <windows.h>
  26. #include <errno.h>
  27. #endif
  28. typedef volatile LONG atomic_int;
  29. typedef atomic_int atomic_bool;
  30. static void atomic_store(atomic_int* ptr, LONG val) {
  31. InterlockedExchange(ptr, val);
  32. }
  33. static LONG atomic_load(atomic_int* ptr) {
  34. return InterlockedCompareExchange(ptr, 0, 0);
  35. }
  36. static LONG atomic_fetch_add(atomic_int* ptr, LONG inc) {
  37. return InterlockedExchangeAdd(ptr, inc);
  38. }
  39. static LONG atomic_fetch_sub(atomic_int* ptr, LONG dec) {
  40. return atomic_fetch_add(ptr, -(dec));
  41. }
  42. typedef HANDLE pthread_t;
  43. typedef DWORD thread_ret_t;
  44. static int pthread_create(pthread_t* out, void* unused, thread_ret_t(*func)(void*), void* arg) {
  45. HANDLE handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) func, arg, 0, NULL);
  46. if (handle == NULL)
  47. {
  48. return EAGAIN;
  49. }
  50. *out = handle;
  51. return 0;
  52. }
  53. static int pthread_join(pthread_t thread, void* unused) {
  54. return (int) WaitForSingleObject(thread, INFINITE);
  55. }
  56. static int sched_yield (void) {
  57. Sleep (0);
  58. return 0;
  59. }
  60. #else
  61. #include <pthread.h>
  62. #include <stdatomic.h>
  63. typedef void* thread_ret_t;
  64. #endif
  65. #ifdef __HAIKU__
  66. #define static_assert(cond, msg) _Static_assert(cond, msg)
  67. #endif
  68. /*#define GGML_PERF*/
  69. #define GGML_DEBUG 0
  70. #define GGML_GELU_FP16
  71. #define GGML_SILU_FP16
  72. #define GGML_SOFT_MAX_UNROLL 4
  73. #define GGML_VEC_DOT_UNROLL 2
  74. #ifdef GGML_USE_ACCELERATE
  75. // uncomment to use vDSP for soft max computation
  76. // note: not sure if it is actually faster
  77. //#define GGML_SOFT_MAX_ACCELERATE
  78. #endif
  79. #if UINTPTR_MAX == 0xFFFFFFFF
  80. #define GGML_MEM_ALIGN 4
  81. #else
  82. #define GGML_MEM_ALIGN 16
  83. #endif
  84. #define UNUSED(x) (void)(x)
  85. #define SWAP(x, y, T) do { T SWAP = x; x = y; y = SWAP; } while (0)
  86. #define GGML_ASSERT(x) \
  87. do { \
  88. if (!(x)) { \
  89. fprintf(stderr, "GGML_ASSERT: %s:%d: %s\n", __FILE__, __LINE__, #x); \
  90. abort(); \
  91. } \
  92. } while (0)
  93. #ifdef GGML_USE_ACCELERATE
  94. #include <Accelerate/Accelerate.h>
  95. #elif GGML_USE_OPENBLAS
  96. #include <cblas.h>
  97. #endif
  98. #undef MIN
  99. #undef MAX
  100. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  101. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  102. // floating point type used to accumulate sums
  103. typedef double ggml_float;
  104. // 16-bit float
  105. // on Arm, we use __fp16
  106. // on x86, we use uint16_t
  107. #ifdef __ARM_NEON
  108. // if YCM cannot find <arm_neon.h>, make a symbolic link to it, for example:
  109. //
  110. // $ ln -sfn /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include/arm_neon.h ./src/
  111. //
  112. #include <arm_neon.h>
  113. #define GGML_COMPUTE_FP16_TO_FP32(x) (x)
  114. #define GGML_COMPUTE_FP32_TO_FP16(x) (x)
  115. #define GGML_FP16_TO_FP32(x) (x)
  116. #define GGML_FP32_TO_FP16(x) (x)
  117. #else
  118. #ifdef __wasm_simd128__
  119. #include <wasm_simd128.h>
  120. #else
  121. #ifdef __POWER9_VECTOR__
  122. #include <altivec.h>
  123. #undef bool
  124. #define bool _Bool
  125. #else
  126. #include <immintrin.h>
  127. #endif
  128. #endif
  129. #ifdef __F16C__
  130. #define GGML_COMPUTE_FP16_TO_FP32(x) _cvtsh_ss(x)
  131. #define GGML_COMPUTE_FP32_TO_FP16(x) _cvtss_sh(x, 0)
  132. #else
  133. // FP16 <-> FP32
  134. // ref: https://github.com/Maratyszcza/FP16
  135. static inline float fp32_from_bits(uint32_t w) {
  136. union {
  137. uint32_t as_bits;
  138. float as_value;
  139. } fp32;
  140. fp32.as_bits = w;
  141. return fp32.as_value;
  142. }
  143. static inline uint32_t fp32_to_bits(float f) {
  144. union {
  145. float as_value;
  146. uint32_t as_bits;
  147. } fp32;
  148. fp32.as_value = f;
  149. return fp32.as_bits;
  150. }
  151. static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
  152. const uint32_t w = (uint32_t) h << 16;
  153. const uint32_t sign = w & UINT32_C(0x80000000);
  154. const uint32_t two_w = w + w;
  155. const uint32_t exp_offset = UINT32_C(0xE0) << 23;
  156. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)
  157. const float exp_scale = 0x1.0p-112f;
  158. #else
  159. const float exp_scale = fp32_from_bits(UINT32_C(0x7800000));
  160. #endif
  161. const float normalized_value = fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale;
  162. const uint32_t magic_mask = UINT32_C(126) << 23;
  163. const float magic_bias = 0.5f;
  164. const float denormalized_value = fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias;
  165. const uint32_t denormalized_cutoff = UINT32_C(1) << 27;
  166. const uint32_t result = sign |
  167. (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) : fp32_to_bits(normalized_value));
  168. return fp32_from_bits(result);
  169. }
  170. static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
  171. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)
  172. const float scale_to_inf = 0x1.0p+112f;
  173. const float scale_to_zero = 0x1.0p-110f;
  174. #else
  175. const float scale_to_inf = fp32_from_bits(UINT32_C(0x77800000));
  176. const float scale_to_zero = fp32_from_bits(UINT32_C(0x08800000));
  177. #endif
  178. float base = (fabsf(f) * scale_to_inf) * scale_to_zero;
  179. const uint32_t w = fp32_to_bits(f);
  180. const uint32_t shl1_w = w + w;
  181. const uint32_t sign = w & UINT32_C(0x80000000);
  182. uint32_t bias = shl1_w & UINT32_C(0xFF000000);
  183. if (bias < UINT32_C(0x71000000)) {
  184. bias = UINT32_C(0x71000000);
  185. }
  186. base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base;
  187. const uint32_t bits = fp32_to_bits(base);
  188. const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00);
  189. const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF);
  190. const uint32_t nonsign = exp_bits + mantissa_bits;
  191. return (sign >> 16) | (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign);
  192. }
  193. #define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
  194. #define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x)
  195. #endif // __F16C__
  196. #endif // __ARM_NEON
  197. //
  198. // global data
  199. //
  200. // precomputed gelu table for f16 (128 KB)
  201. static ggml_fp16_t table_gelu_f16[1 << 16];
  202. // precomputed silu table for f16 (128 KB)
  203. static ggml_fp16_t table_silu_f16[1 << 16];
  204. // precomputed exp table for f16 (128 KB)
  205. static ggml_fp16_t table_exp_f16[1 << 16];
  206. // precomputed f32 table for f16 (256 KB)
  207. static float table_f32_f16[1 << 16];
  208. // On ARM NEON, it's quicker to directly convert x -> x instead of calling into ggml_lookup_fp16_to_fp32,
  209. // so we define GGML_FP16_TO_FP32 and GGML_FP32_TO_FP16 elsewhere for NEON.
  210. #if !defined(GGML_FP16_TO_FP32) || !defined(GGML_FP32_TO_FP16)
  211. inline static float ggml_lookup_fp16_to_fp32(ggml_fp16_t f) {
  212. uint16_t s;
  213. memcpy(&s, &f, sizeof(uint16_t));
  214. return table_f32_f16[s];
  215. }
  216. #define GGML_FP16_TO_FP32(x) ggml_lookup_fp16_to_fp32(x)
  217. #define GGML_FP32_TO_FP16(x) GGML_COMPUTE_FP32_TO_FP16(x)
  218. #endif
  219. // note: do not use these inside ggml.c
  220. // these are meant to be used via the ggml.h API
  221. float ggml_fp16_to_fp32(ggml_fp16_t x) {
  222. return GGML_FP16_TO_FP32(x);
  223. }
  224. ggml_fp16_t ggml_fp32_to_fp16(float x) {
  225. return GGML_FP32_TO_FP16(x);
  226. }
  227. //
  228. // timing
  229. //
  230. #if defined(_MSC_VER) || defined(__MINGW32__)
  231. static int64_t timer_freq;
  232. void ggml_time_init(void) {
  233. LARGE_INTEGER frequency;
  234. QueryPerformanceFrequency(&frequency);
  235. timer_freq = frequency.QuadPart;
  236. }
  237. int64_t ggml_time_ms(void) {
  238. LARGE_INTEGER t;
  239. QueryPerformanceCounter(&t);
  240. return (t.QuadPart * 1000) / timer_freq;
  241. }
  242. int64_t ggml_time_us(void) {
  243. LARGE_INTEGER t;
  244. QueryPerformanceCounter(&t);
  245. return (t.QuadPart * 1000000) / timer_freq;
  246. }
  247. #else
  248. void ggml_time_init(void) {}
  249. int64_t ggml_time_ms(void) {
  250. struct timespec ts;
  251. clock_gettime(CLOCK_MONOTONIC, &ts);
  252. return (int64_t)ts.tv_sec*1000 + (int64_t)ts.tv_nsec/1000000;
  253. }
  254. int64_t ggml_time_us(void) {
  255. struct timespec ts;
  256. clock_gettime(CLOCK_MONOTONIC, &ts);
  257. return (int64_t)ts.tv_sec*1000000 + (int64_t)ts.tv_nsec/1000;
  258. }
  259. #endif
  260. int64_t ggml_cycles(void) {
  261. return clock();
  262. }
  263. int64_t ggml_cycles_per_ms(void) {
  264. return CLOCKS_PER_SEC/1000;
  265. }
  266. #ifdef GGML_PERF
  267. #define ggml_perf_time_ms() ggml_time_ms()
  268. #define ggml_perf_time_us() ggml_time_us()
  269. #define ggml_perf_cycles() ggml_cycles()
  270. #define ggml_perf_cycles_per_ms() ggml_cycles_per_ms()
  271. #else
  272. #define ggml_perf_time_ms() 0
  273. #define ggml_perf_time_us() 0
  274. #define ggml_perf_cycles() 0
  275. #define ggml_perf_cycles_per_ms() 0
  276. #endif
  277. //
  278. // cache line
  279. //
  280. #if defined(__cpp_lib_hardware_interference_size)
  281. #define CACHE_LINE_SIZE hardware_destructive_interference_size
  282. #else
  283. #if defined(__POWER9_VECTOR__)
  284. #define CACHE_LINE_SIZE 128
  285. #else
  286. #define CACHE_LINE_SIZE 64
  287. #endif
  288. #endif
  289. static const size_t CACHE_LINE_SIZE_F32 = CACHE_LINE_SIZE/sizeof(float);
  290. //
  291. // quantization
  292. //
  293. #define QK 32
  294. // AVX routines provided by GH user Const-me
  295. // ref: https://github.com/ggerganov/ggml/pull/27#issuecomment-1464934600
  296. #if __AVX2__
  297. // Unpack 32 4-bit fields into 32 bytes
  298. // The output vector contains 32 bytes, each one in [ 0 .. 15 ] interval
  299. static inline __m256i bytesFromNibbles( const uint8_t* rsi )
  300. {
  301. // Load 16 bytes from memory
  302. __m128i tmp = _mm_loadu_si128( ( const __m128i* )rsi );
  303. // Expand bytes into uint16_t values
  304. __m256i bytes = _mm256_cvtepu8_epi16( tmp );
  305. // Unpack values into individual bytes
  306. const __m256i lowMask = _mm256_set1_epi8( 0xF );
  307. __m256i high = _mm256_andnot_si256( lowMask, bytes );
  308. __m256i low = _mm256_and_si256( lowMask, bytes );
  309. high = _mm256_slli_epi16( high, 4 );
  310. bytes = _mm256_or_si256( low, high );
  311. return bytes;
  312. }
  313. static inline __m128i packNibbles( __m256i bytes )
  314. {
  315. // Move bits within 16-bit lanes from 0000_abcd_0000_efgh into 0000_0000_abcd_efgh
  316. const __m256i lowByte = _mm256_set1_epi16( 0xFF );
  317. __m256i high = _mm256_andnot_si256( lowByte, bytes );
  318. __m256i low = _mm256_and_si256( lowByte, bytes );
  319. high = _mm256_srli_epi16( high, 4 );
  320. bytes = _mm256_or_si256( low, high );
  321. // Compress uint16_t lanes into bytes
  322. __m128i r0 = _mm256_castsi256_si128( bytes );
  323. __m128i r1 = _mm256_extracti128_si256( bytes, 1 );
  324. return _mm_packus_epi16( r0, r1 );
  325. }
  326. #endif
  327. // method 5
  328. // blocks of QK elements
  329. // represented with a single float (delta) and QK/2 8-bit ints (i.e QK 4-bit signed integer factors)
  330. void quantize_row_q4_0(const float * restrict x, void * restrict y, int k) {
  331. assert(k % QK == 0);
  332. const int nb = k / QK;
  333. const size_t bs = sizeof(float) + QK/2;
  334. uint8_t * restrict pd = ((uint8_t *)y + 0*bs);
  335. uint8_t * restrict pb = ((uint8_t *)y + 0*bs + sizeof(float));
  336. uint8_t pp[QK/2];
  337. #if __ARM_NEON
  338. #if QK == 32
  339. for (int i = 0; i < nb; i++) {
  340. float amax = 0.0f; // absolute max
  341. float32x4_t srcv [8];
  342. float32x4_t asrcv[8];
  343. float32x4_t amaxv[8];
  344. for (int l = 0; l < 8; l++) srcv[l] = vld1q_f32(x + i*32 + 4*l);
  345. for (int l = 0; l < 8; l++) asrcv[l] = vabsq_f32(srcv[l]);
  346. for (int l = 0; l < 4; l++) amaxv[2*l] = vmaxq_f32(asrcv[2*l], asrcv[2*l+1]);
  347. for (int l = 0; l < 2; l++) amaxv[4*l] = vmaxq_f32(amaxv[4*l], amaxv[4*l+2]);
  348. for (int l = 0; l < 1; l++) amaxv[8*l] = vmaxq_f32(amaxv[8*l], amaxv[8*l+4]);
  349. amax = MAX(
  350. MAX(vgetq_lane_f32(amaxv[0], 0), vgetq_lane_f32(amaxv[0], 1)),
  351. MAX(vgetq_lane_f32(amaxv[0], 2), vgetq_lane_f32(amaxv[0], 3)));
  352. const float d = amax / ((1 << 3) - 1);
  353. const float id = d ? 1.0/d : 0.0;
  354. *(float *)pd = d;
  355. pd += bs;
  356. for (int l = 0; l < 8; l++) {
  357. const float32x4_t v = vmulq_n_f32(srcv[l], id);
  358. const float32x4_t vf = vaddq_f32(v, vdupq_n_f32(8.5f));
  359. const int32x4_t vi = vcvtq_s32_f32(vf);
  360. pp[2*l + 0] = vgetq_lane_s32(vi, 0) | (vgetq_lane_s32(vi, 1) << 4);
  361. pp[2*l + 1] = vgetq_lane_s32(vi, 2) | (vgetq_lane_s32(vi, 3) << 4);
  362. }
  363. memcpy(pb, pp, sizeof(pp));
  364. pb += bs;
  365. }
  366. #else
  367. #error "not implemented for QK"
  368. #endif
  369. #elif defined(__AVX2__)
  370. #if QK == 32
  371. for (int i = 0; i < nb; i++) {
  372. // Load elements into 4 AVX vectors
  373. __m256 v0 = _mm256_loadu_ps( x );
  374. __m256 v1 = _mm256_loadu_ps( x + 8 );
  375. __m256 v2 = _mm256_loadu_ps( x + 16 );
  376. __m256 v3 = _mm256_loadu_ps( x + 24 );
  377. x += 32;
  378. // Compute max(abs(e)) for the block
  379. const __m256 signBit = _mm256_set1_ps( -0.0f );
  380. __m256 maxAbs = _mm256_andnot_ps( signBit, v0 );
  381. maxAbs = _mm256_max_ps( maxAbs, _mm256_andnot_ps( signBit, v1 ) );
  382. maxAbs = _mm256_max_ps( maxAbs, _mm256_andnot_ps( signBit, v2 ) );
  383. maxAbs = _mm256_max_ps( maxAbs, _mm256_andnot_ps( signBit, v3 ) );
  384. __m128 max4 = _mm_max_ps( _mm256_extractf128_ps( maxAbs, 1 ), _mm256_castps256_ps128( maxAbs ) );
  385. max4 = _mm_max_ps( max4, _mm_movehl_ps( max4, max4 ) );
  386. max4 = _mm_max_ss( max4, _mm_movehdup_ps( max4 ) );
  387. const float maxScalar = _mm_cvtss_f32( max4 );
  388. // Quantize these floats
  389. const float d = maxScalar / 7.0f;
  390. *(float *)pd = d;
  391. pd += bs;
  392. const float id = ( maxScalar != 0.0f ) ? 7.0f / maxScalar : 0.0f;
  393. const __m256 mul = _mm256_set1_ps( id );
  394. // Apply the multiplier
  395. v0 = _mm256_mul_ps( v0, mul );
  396. v1 = _mm256_mul_ps( v1, mul );
  397. v2 = _mm256_mul_ps( v2, mul );
  398. v3 = _mm256_mul_ps( v3, mul );
  399. // Round to nearest integer
  400. v0 = _mm256_round_ps( v0, _MM_ROUND_NEAREST );
  401. v1 = _mm256_round_ps( v1, _MM_ROUND_NEAREST );
  402. v2 = _mm256_round_ps( v2, _MM_ROUND_NEAREST );
  403. v3 = _mm256_round_ps( v3, _MM_ROUND_NEAREST );
  404. // Convert floats to integers
  405. __m256i i0 = _mm256_cvtps_epi32( v0 );
  406. __m256i i1 = _mm256_cvtps_epi32( v1 );
  407. __m256i i2 = _mm256_cvtps_epi32( v2 );
  408. __m256i i3 = _mm256_cvtps_epi32( v3 );
  409. // Convert int32 to int16
  410. i0 = _mm256_packs_epi32( i0, i1 ); // 0, 1, 2, 3, 8, 9, 10, 11, 4, 5, 6, 7, 12, 13, 14, 15
  411. i2 = _mm256_packs_epi32( i2, i3 ); // 16, 17, 18, 19, 24, 25, 26, 27, 20, 21, 22, 23, 28, 29, 30, 31
  412. // Convert int16 to int8
  413. i0 = _mm256_packs_epi16( i0, i2 ); // 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27, 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31
  414. // We got our precious signed bytes, but the order is now wrong
  415. // These AVX2 pack instructions process 16-byte pieces independently
  416. // The following instruction is fixing the order
  417. const __m256i perm = _mm256_setr_epi32( 0, 4, 1, 5, 2, 6, 3, 7 );
  418. i0 = _mm256_permutevar8x32_epi32( i0, perm );
  419. // Apply offset to translate the range from [ -7 .. +7 ] into [ +1 .. +15 ]
  420. const __m256i off = _mm256_set1_epi8( 8 );
  421. i0 = _mm256_add_epi8( i0, off );
  422. // Compress the vector into 4 bit/value, and store
  423. __m128i res = packNibbles( i0 );
  424. _mm_storeu_si128( ( __m128i* )pb, res );
  425. pb += bs;
  426. }
  427. #else
  428. #error "not implemented for QK"
  429. #endif
  430. #elif defined(__wasm_simd128__)
  431. #if QK == 32
  432. for (int i = 0; i < nb; i++) {
  433. float amax = 0.0f; // absolute max
  434. v128_t srcv [8];
  435. v128_t asrcv[8];
  436. v128_t amaxv[8];
  437. for (int l = 0; l < 8; l++) srcv[l] = wasm_v128_load(x + i*32 + 4*l);
  438. for (int l = 0; l < 8; l++) asrcv[l] = wasm_f32x4_abs(srcv[l]);
  439. for (int l = 0; l < 4; l++) amaxv[2*l] = wasm_f32x4_max(asrcv[2*l], asrcv[2*l+1]);
  440. for (int l = 0; l < 2; l++) amaxv[4*l] = wasm_f32x4_max(amaxv[4*l], amaxv[4*l+2]);
  441. for (int l = 0; l < 1; l++) amaxv[8*l] = wasm_f32x4_max(amaxv[8*l], amaxv[8*l+4]);
  442. amax = MAX(
  443. MAX(wasm_f32x4_extract_lane(amaxv[0], 0), wasm_f32x4_extract_lane(amaxv[0], 1)),
  444. MAX(wasm_f32x4_extract_lane(amaxv[0], 2), wasm_f32x4_extract_lane(amaxv[0], 3)));
  445. const float d = amax / ((1 << 3) - 1);
  446. const float id = d ? 1.0/d : 0.0;
  447. *(float *)pd = d;
  448. pd += bs;
  449. for (int l = 0; l < 8; l++) {
  450. const v128_t v = wasm_f32x4_mul(srcv[l], wasm_f32x4_splat(id));
  451. const v128_t vf = wasm_f32x4_add(v, wasm_f32x4_splat(8.5f));
  452. const v128_t vi = wasm_i32x4_trunc_sat_f32x4(vf);
  453. pp[2*l + 0] = wasm_i32x4_extract_lane(vi, 0) | (wasm_i32x4_extract_lane(vi, 1) << 4);
  454. pp[2*l + 1] = wasm_i32x4_extract_lane(vi, 2) | (wasm_i32x4_extract_lane(vi, 3) << 4);
  455. }
  456. memcpy(pb, pp, sizeof(pp));
  457. pb += bs;
  458. }
  459. #else
  460. #error "not implemented for QK"
  461. #endif
  462. #else
  463. // scalar
  464. for (int i = 0; i < nb; i++) {
  465. float amax = 0.0f; // absolute max
  466. for (int l = 0; l < QK; l++) {
  467. const float v = x[i*QK + l];
  468. amax = MAX(amax, fabsf(v));
  469. }
  470. const float d = amax / ((1 << 3) - 1);
  471. const float id = d ? 1.0f/d : 0.0f;
  472. *(float *)pd = d;
  473. pd += bs;
  474. for (int l = 0; l < QK; l += 2) {
  475. const float v0 = x[i*QK + l + 0]*id;
  476. const float v1 = x[i*QK + l + 1]*id;
  477. const uint8_t vi0 = ((int8_t) (round(v0))) + 8;
  478. const uint8_t vi1 = ((int8_t) (round(v1))) + 8;
  479. assert(vi0 >= 0 && vi0 < 16);
  480. assert(vi1 >= 0 && vi1 < 16);
  481. pp[l/2] = vi0 | (vi1 << 4);
  482. }
  483. memcpy(pb, pp, sizeof(pp));
  484. pb += bs;
  485. }
  486. #endif
  487. }
  488. // method 4
  489. // blocks of QK elements
  490. // represented with 2 floats (min + delta) and QK/2 8-bit ints (i.e QK 4-bit unsigned integer factors)
  491. void quantize_row_q4_1(const float * restrict x, void * restrict y, int k) {
  492. assert(k % QK == 0);
  493. const int nb = k / QK;
  494. float * restrict pm = (float *) (y);
  495. float * restrict pd = (float *) (pm + nb);
  496. uint8_t * restrict pb = (uint8_t *) (pd + nb);
  497. uint8_t pp[QK/2];
  498. for (int i = 0; i < nb; i++) {
  499. float min = FLT_MAX;
  500. float max = -FLT_MAX;
  501. for (int l = 0; l < QK; l++) {
  502. const float v = x[i*QK + l];
  503. if (v < min) min = v;
  504. if (v > max) max = v;
  505. }
  506. const float d = (max - min) / ((1 << 4) - 1);
  507. const float id = d ? 1.0f/d : 0.0f;
  508. pm[i] = min;
  509. pd[i] = d;
  510. for (int l = 0; l < QK; l += 2) {
  511. const float v0 = (x[i*QK + l + 0] - min)*id;
  512. const float v1 = (x[i*QK + l + 1] - min)*id;
  513. const uint8_t vi0 = round(v0);
  514. const uint8_t vi1 = round(v1);
  515. assert(vi0 >= 0 && vi0 < 16);
  516. assert(vi1 >= 0 && vi1 < 16);
  517. pp[l/2] = vi0 | (vi1 << 4);
  518. }
  519. memcpy(pb + i*QK/2, pp, sizeof(pp));
  520. }
  521. }
  522. // TODO: vectorize
  523. void dequantize_row_q4_0(const void * restrict x, float * restrict y, int k) {
  524. assert(k % QK == 0);
  525. const int nb = k / QK;
  526. const size_t bs = sizeof(float) + QK/2;
  527. const uint8_t * restrict pd = ((const uint8_t *)x + 0*bs);
  528. const uint8_t * restrict pb = ((const uint8_t *)x + 0*bs + sizeof(float));
  529. // scalar
  530. for (int i = 0; i < nb; i++) {
  531. const float d = *(const float *) (pd + i*bs);
  532. const uint8_t * restrict pp = pb + i*bs;
  533. for (int l = 0; l < QK; l += 2) {
  534. const uint8_t vi = pp[l/2];
  535. const int8_t vi0 = vi & 0xf;
  536. const int8_t vi1 = vi >> 4;
  537. const float v0 = (vi0 - 8)*d;
  538. const float v1 = (vi1 - 8)*d;
  539. //printf("d = %f, vi = %d, vi0 = %d, vi1 = %d, v0 = %f, v1 = %f\n", d, vi, vi0, vi1, v0, v1);
  540. y[i*QK + l + 0] = v0;
  541. y[i*QK + l + 1] = v1;
  542. assert(!isnan(y[i*QK + l + 0]));
  543. assert(!isnan(y[i*QK + l + 1]));
  544. }
  545. }
  546. }
  547. void dequantize_row_q4_1(const void * restrict x, float * restrict y, int k) {
  548. assert(k % QK == 0);
  549. const int nb = k / QK;
  550. const float * restrict pm = (const float *) (x);
  551. const float * restrict pd = (const float *) (pm + nb);
  552. const uint8_t * restrict pb = (const uint8_t *) (pd + nb);
  553. for (int i = 0; i < nb; i++) {
  554. const float m = pm[i];
  555. const float d = pd[i];
  556. const uint8_t * restrict pp = pb + i*QK/2;
  557. for (int l = 0; l < QK; l += 2) {
  558. const uint8_t vi = pp[l/2];
  559. const int8_t vi0 = vi & 0xf;
  560. const int8_t vi1 = vi >> 4;
  561. const float v0 = vi0*d + m;
  562. const float v1 = vi1*d + m;
  563. y[i*QK + l + 0] = v0;
  564. y[i*QK + l + 1] = v1;
  565. assert(!isnan(y[i*QK + l + 0]));
  566. assert(!isnan(y[i*QK + l + 1]));
  567. }
  568. }
  569. }
  570. //
  571. // simd mappings
  572. //
  573. // we define a common set of C macros which map to specific intrinsics based on the current architecture
  574. // we then implement the fundamental computation operations below using only these macros
  575. // adding support for new architectures requires to define the corresponding SIMD macros
  576. //
  577. // GGML_F32_STEP / GGML_F16_STEP
  578. // number of elements to process in a single step
  579. //
  580. // GGML_F32_EPR / GGML_F16_EPR
  581. // number of elements to fit in a single register
  582. //
  583. #if defined(__ARM_NEON) && defined(__ARM_FEATURE_FMA)
  584. #define GGML_SIMD
  585. // F32 NEON
  586. #define GGML_F32_STEP 16
  587. #define GGML_F32_EPR 4
  588. #define GGML_F32x4 float32x4_t
  589. #define GGML_F32x4_ZERO vdupq_n_f32(0.0f)
  590. #define GGML_F32x4_SET1(x) vdupq_n_f32(x)
  591. #define GGML_F32x4_LOAD vld1q_f32
  592. #define GGML_F32x4_STORE vst1q_f32
  593. #define GGML_F32x4_FMA(a, b, c) vfmaq_f32(a, b, c)
  594. #define GGML_F32x4_ADD vaddq_f32
  595. #define GGML_F32x4_MUL vmulq_f32
  596. #if defined(__ARM_FEATURE_QRDMX)
  597. #define GGML_F32x4_REDUCE_ONE(x) vaddvq_f32(x)
  598. #else
  599. #define GGML_F32x4_REDUCE_ONE(x) \
  600. (vgetq_lane_f32(x, 0) + \
  601. vgetq_lane_f32(x, 1) + \
  602. vgetq_lane_f32(x, 2) + \
  603. vgetq_lane_f32(x, 3))
  604. #endif
  605. #define GGML_F32x4_REDUCE(res, x) \
  606. { \
  607. for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
  608. x[2*i] = vaddq_f32(x[2*i], x[2*i+1]); \
  609. } \
  610. for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
  611. x[4*i] = vaddq_f32(x[4*i], x[4*i+2]); \
  612. } \
  613. for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
  614. x[8*i] = vaddq_f32(x[8*i], x[8*i+4]); \
  615. } \
  616. res = GGML_F32x4_REDUCE_ONE(x[0]); \
  617. }
  618. #define GGML_F32_VEC GGML_F32x4
  619. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  620. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  621. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  622. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  623. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  624. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  625. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  626. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  627. // F16 NEON
  628. #if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
  629. #define GGML_F16_STEP 32
  630. #define GGML_F16_EPR 8
  631. #define GGML_F16x8 float16x8_t
  632. #define GGML_F16x8_ZERO vdupq_n_f16(0.0f)
  633. #define GGML_F16x8_SET1(x) vdupq_n_f16(x)
  634. #define GGML_F16x8_LOAD vld1q_f16
  635. #define GGML_F16x8_STORE vst1q_f16
  636. #define GGML_F16x8_FMA(a, b, c) vfmaq_f16(a, b, c)
  637. #define GGML_F16x8_ADD vaddq_f16
  638. #define GGML_F16x8_MUL vmulq_f16
  639. #define GGML_F16x8_REDUCE(res, x) \
  640. { \
  641. for (int i = 0; i < GGML_F16_ARR/2; ++i) { \
  642. x[2*i] = vaddq_f16(x[2*i], x[2*i+1]); \
  643. } \
  644. for (int i = 0; i < GGML_F16_ARR/4; ++i) { \
  645. x[4*i] = vaddq_f16(x[4*i], x[4*i+2]); \
  646. } \
  647. for (int i = 0; i < GGML_F16_ARR/8; ++i) { \
  648. x[8*i] = vaddq_f16(x[8*i], x[8*i+4]); \
  649. } \
  650. const float32x4_t t0 = vcvt_f32_f16(vget_low_f16 (x[0])); \
  651. const float32x4_t t1 = vcvt_f32_f16(vget_high_f16(x[0])); \
  652. res = vaddvq_f32(vaddq_f32(t0, t1)); \
  653. }
  654. #define GGML_F16_VEC GGML_F16x8
  655. #define GGML_F16_VEC_ZERO GGML_F16x8_ZERO
  656. #define GGML_F16_VEC_SET1 GGML_F16x8_SET1
  657. #define GGML_F16_VEC_LOAD(p, i) GGML_F16x8_LOAD(p)
  658. #define GGML_F16_VEC_STORE(p, r, i) GGML_F16x8_STORE(p, r[i])
  659. #define GGML_F16_VEC_FMA GGML_F16x8_FMA
  660. #define GGML_F16_VEC_ADD GGML_F16x8_ADD
  661. #define GGML_F16_VEC_MUL GGML_F16x8_MUL
  662. #define GGML_F16_VEC_REDUCE GGML_F16x8_REDUCE
  663. #else
  664. // if FP16 vector arithmetic is not supported, we use FP32 instead
  665. // and take advantage of the vcvt_ functions to convert to/from FP16
  666. #define GGML_F16_STEP 16
  667. #define GGML_F16_EPR 4
  668. #define GGML_F32Cx4 float32x4_t
  669. #define GGML_F32Cx4_ZERO vdupq_n_f32(0.0f)
  670. #define GGML_F32Cx4_SET1(x) vdupq_n_f32(x)
  671. #define GGML_F32Cx4_LOAD(x) vcvt_f32_f16(vld1_f16(x))
  672. #define GGML_F32Cx4_STORE(x, y) vst1_f16(x, vcvt_f16_f32(y))
  673. #define GGML_F32Cx4_FMA(a, b, c) vfmaq_f32(a, b, c)
  674. #define GGML_F32Cx4_ADD vaddq_f32
  675. #define GGML_F32Cx4_MUL vmulq_f32
  676. #define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
  677. #define GGML_F16_VEC GGML_F32Cx4
  678. #define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
  679. #define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
  680. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
  681. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE(p, r[i])
  682. #define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
  683. #define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
  684. #define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
  685. #define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
  686. #endif
  687. #elif defined(__AVX__)
  688. #define GGML_SIMD
  689. // F32 AVX
  690. #define GGML_F32_STEP 32
  691. #define GGML_F32_EPR 8
  692. #define GGML_F32x8 __m256
  693. #define GGML_F32x8_ZERO _mm256_setzero_ps()
  694. #define GGML_F32x8_SET1(x) _mm256_set1_ps(x)
  695. #define GGML_F32x8_LOAD _mm256_loadu_ps
  696. #define GGML_F32x8_STORE _mm256_storeu_ps
  697. #if defined(__FMA__)
  698. #define GGML_F32x8_FMA(a, b, c) _mm256_fmadd_ps(b, c, a)
  699. #else
  700. #define GGML_F32x8_FMA(a, b, c) _mm256_add_ps(_mm256_mul_ps(b, c), a)
  701. #endif
  702. #define GGML_F32x8_ADD _mm256_add_ps
  703. #define GGML_F32x8_MUL _mm256_mul_ps
  704. #define GGML_F32x8_REDUCE(res, x) \
  705. { \
  706. for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
  707. x[2*i] = _mm256_add_ps(x[2*i], x[2*i+1]); \
  708. } \
  709. for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
  710. x[4*i] = _mm256_add_ps(x[4*i], x[4*i+2]); \
  711. } \
  712. for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
  713. x[8*i] = _mm256_add_ps(x[8*i], x[8*i+4]); \
  714. } \
  715. const __m128 t0 = _mm_add_ps(_mm256_castps256_ps128(x[0]), \
  716. _mm256_extractf128_ps(x[0], 1)); \
  717. const __m128 t1 = _mm_hadd_ps(t0, t0); \
  718. res = _mm_cvtss_f32(_mm_hadd_ps(t1, t1)); \
  719. }
  720. // TODO: is this optimal ?
  721. #define GGML_F32_VEC GGML_F32x8
  722. #define GGML_F32_VEC_ZERO GGML_F32x8_ZERO
  723. #define GGML_F32_VEC_SET1 GGML_F32x8_SET1
  724. #define GGML_F32_VEC_LOAD GGML_F32x8_LOAD
  725. #define GGML_F32_VEC_STORE GGML_F32x8_STORE
  726. #define GGML_F32_VEC_FMA GGML_F32x8_FMA
  727. #define GGML_F32_VEC_ADD GGML_F32x8_ADD
  728. #define GGML_F32_VEC_MUL GGML_F32x8_MUL
  729. #define GGML_F32_VEC_REDUCE GGML_F32x8_REDUCE
  730. // F16 AVX
  731. #define GGML_F16_STEP 32
  732. #define GGML_F16_EPR 8
  733. // F16 arithmetic is not supported by AVX, so we use F32 instead
  734. // we take advantage of the _mm256_cvt intrinsics to convert F16 <-> F32
  735. #define GGML_F32Cx8 __m256
  736. #define GGML_F32Cx8_ZERO _mm256_setzero_ps()
  737. #define GGML_F32Cx8_SET1(x) _mm256_set1_ps(x)
  738. #define GGML_F32Cx8_LOAD(x) _mm256_cvtph_ps(_mm_loadu_si128((__m128i *)(x)))
  739. #define GGML_F32Cx8_STORE(x, y) _mm_storeu_si128((__m128i *)(x), _mm256_cvtps_ph(y, 0))
  740. #define GGML_F32Cx8_FMA GGML_F32x8_FMA
  741. #define GGML_F32Cx8_ADD _mm256_add_ps
  742. #define GGML_F32Cx8_MUL _mm256_mul_ps
  743. #define GGML_F32Cx8_REDUCE GGML_F32x8_REDUCE
  744. #define GGML_F16_VEC GGML_F32Cx8
  745. #define GGML_F16_VEC_ZERO GGML_F32Cx8_ZERO
  746. #define GGML_F16_VEC_SET1 GGML_F32Cx8_SET1
  747. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx8_LOAD(p)
  748. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx8_STORE(p, r[i])
  749. #define GGML_F16_VEC_FMA GGML_F32Cx8_FMA
  750. #define GGML_F16_VEC_ADD GGML_F32Cx8_ADD
  751. #define GGML_F16_VEC_MUL GGML_F32Cx8_MUL
  752. #define GGML_F16_VEC_REDUCE GGML_F32Cx8_REDUCE
  753. #elif defined(__POWER9_VECTOR__)
  754. #define GGML_SIMD
  755. // F32 POWER9
  756. #define GGML_F32_STEP 32
  757. #define GGML_F32_EPR 4
  758. #define GGML_F32x4 vector float
  759. #define GGML_F32x4_ZERO 0.0f
  760. #define GGML_F32x4_SET1 vec_splats
  761. #define GGML_F32x4_LOAD(p) vec_xl(0, p)
  762. #define GGML_F32x4_STORE(p, r) vec_xst(r, 0, p)
  763. #define GGML_F32x4_FMA(a, b, c) vec_madd(b, c, a)
  764. #define GGML_F32x4_ADD vec_add
  765. #define GGML_F32x4_MUL vec_mul
  766. #define GGML_F32x4_REDUCE(res, x) \
  767. { \
  768. for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
  769. x[2*i] = vec_add(x[2*i], x[2*i+1]); \
  770. } \
  771. for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
  772. x[4*i] = vec_add(x[4*i], x[4*i+2]); \
  773. } \
  774. for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
  775. x[8*i] = vec_add(x[8*i], x[8*i+4]); \
  776. } \
  777. res = vec_extract(x[0], 0) + \
  778. vec_extract(x[0], 1) + \
  779. vec_extract(x[0], 2) + \
  780. vec_extract(x[0], 3); \
  781. }
  782. #define GGML_F32_VEC GGML_F32x4
  783. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  784. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  785. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  786. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  787. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  788. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  789. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  790. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  791. // F16 POWER9
  792. #define GGML_F16_STEP GGML_F32_STEP
  793. #define GGML_F16_EPR GGML_F32_EPR
  794. #define GGML_F16_VEC GGML_F32x4
  795. #define GGML_F16_VEC_ZERO GGML_F32x4_ZERO
  796. #define GGML_F16_VEC_SET1 GGML_F32x4_SET1
  797. #define GGML_F16_VEC_FMA GGML_F32x4_FMA
  798. #define GGML_F16_VEC_REDUCE GGML_F32x4_REDUCE
  799. // Use vec_xl, not vec_ld, in case the load address is not aligned.
  800. #define GGML_F16_VEC_LOAD(p, i) (i & 0x1) ? \
  801. vec_extract_fp32_from_shorth(vec_xl(0, p - GGML_F16_EPR)) : \
  802. vec_extract_fp32_from_shortl(vec_xl(0, p))
  803. #define GGML_ENDIAN_BYTE(i) ((unsigned char *)&(uint16_t){1})[i]
  804. #define GGML_F16_VEC_STORE(p, r, i) \
  805. if (i & 0x1) \
  806. vec_xst(vec_pack_to_short_fp32(r[i - GGML_ENDIAN_BYTE(1)], \
  807. r[i - GGML_ENDIAN_BYTE(0)]), \
  808. 0, p - GGML_F16_EPR)
  809. #elif defined(__wasm_simd128__)
  810. #define GGML_SIMD
  811. // F32 WASM
  812. #define GGML_F32_STEP 16
  813. #define GGML_F32_EPR 4
  814. #define GGML_F32x4 v128_t
  815. #define GGML_F32x4_ZERO wasm_f32x4_splat(0.0f)
  816. #define GGML_F32x4_SET1(x) wasm_f32x4_splat(x)
  817. #define GGML_F32x4_LOAD wasm_v128_load
  818. #define GGML_F32x4_STORE wasm_v128_store
  819. #define GGML_F32x4_FMA(a, b, c) wasm_f32x4_add(wasm_f32x4_mul(b, c), a)
  820. #define GGML_F32x4_ADD wasm_f32x4_add
  821. #define GGML_F32x4_MUL wasm_f32x4_mul
  822. #define GGML_F32x4_REDUCE(res, x) \
  823. { \
  824. for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
  825. x[2*i] = wasm_f32x4_add(x[2*i], x[2*i+1]); \
  826. } \
  827. for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
  828. x[4*i] = wasm_f32x4_add(x[4*i], x[4*i+2]); \
  829. } \
  830. for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
  831. x[8*i] = wasm_f32x4_add(x[8*i], x[8*i+4]); \
  832. } \
  833. res = wasm_f32x4_extract_lane(x[0], 0) + \
  834. wasm_f32x4_extract_lane(x[0], 1) + \
  835. wasm_f32x4_extract_lane(x[0], 2) + \
  836. wasm_f32x4_extract_lane(x[0], 3); \
  837. }
  838. #define GGML_F32_VEC GGML_F32x4
  839. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  840. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  841. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  842. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  843. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  844. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  845. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  846. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  847. // F16 WASM
  848. #define GGML_F16_STEP 16
  849. #define GGML_F16_EPR 4
  850. inline static v128_t __wasm_f16x4_load(const ggml_fp16_t * p) {
  851. float tmp[4];
  852. tmp[0] = GGML_FP16_TO_FP32(p[0]);
  853. tmp[1] = GGML_FP16_TO_FP32(p[1]);
  854. tmp[2] = GGML_FP16_TO_FP32(p[2]);
  855. tmp[3] = GGML_FP16_TO_FP32(p[3]);
  856. return wasm_v128_load(tmp);
  857. }
  858. inline static void __wasm_f16x4_store(ggml_fp16_t * p, v128_t x) {
  859. float tmp[4];
  860. wasm_v128_store(tmp, x);
  861. p[0] = GGML_FP32_TO_FP16(tmp[0]);
  862. p[1] = GGML_FP32_TO_FP16(tmp[1]);
  863. p[2] = GGML_FP32_TO_FP16(tmp[2]);
  864. p[3] = GGML_FP32_TO_FP16(tmp[3]);
  865. }
  866. #define GGML_F16x4 v128_t
  867. #define GGML_F16x4_ZERO wasm_f32x4_splat(0.0f)
  868. #define GGML_F16x4_SET1(x) wasm_f32x4_splat(x)
  869. #define GGML_F16x4_LOAD(x) __wasm_f16x4_load(x)
  870. #define GGML_F16x4_STORE(x, y) __wasm_f16x4_store(x, y)
  871. #define GGML_F16x4_FMA GGML_F32x4_FMA
  872. #define GGML_F16x4_ADD wasm_f32x4_add
  873. #define GGML_F16x4_MUL wasm_f32x4_mul
  874. #define GGML_F16x4_REDUCE(res, x) \
  875. { \
  876. for (int i = 0; i < GGML_F16_ARR/2; ++i) { \
  877. x[2*i] = wasm_f32x4_add(x[2*i], x[2*i+1]); \
  878. } \
  879. for (int i = 0; i < GGML_F16_ARR/4; ++i) { \
  880. x[4*i] = wasm_f32x4_add(x[4*i], x[4*i+2]); \
  881. } \
  882. for (int i = 0; i < GGML_F16_ARR/8; ++i) { \
  883. x[8*i] = wasm_f32x4_add(x[8*i], x[8*i+4]); \
  884. } \
  885. res = wasm_f32x4_extract_lane(x[0], 0) + \
  886. wasm_f32x4_extract_lane(x[0], 1) + \
  887. wasm_f32x4_extract_lane(x[0], 2) + \
  888. wasm_f32x4_extract_lane(x[0], 3); \
  889. }
  890. #define GGML_F16_VEC GGML_F16x4
  891. #define GGML_F16_VEC_ZERO GGML_F16x4_ZERO
  892. #define GGML_F16_VEC_SET1 GGML_F16x4_SET1
  893. #define GGML_F16_VEC_LOAD(p, i) GGML_F16x4_LOAD(p)
  894. #define GGML_F16_VEC_STORE(p, r, i) GGML_F16x4_STORE(p, r[i])
  895. #define GGML_F16_VEC_FMA GGML_F16x4_FMA
  896. #define GGML_F16_VEC_ADD GGML_F16x4_ADD
  897. #define GGML_F16_VEC_MUL GGML_F16x4_MUL
  898. #define GGML_F16_VEC_REDUCE GGML_F16x4_REDUCE
  899. #elif defined(__SSE3__)
  900. #define GGML_SIMD
  901. // F32 SSE
  902. #define GGML_F32_STEP 32
  903. #define GGML_F32_EPR 4
  904. #define GGML_F32x4 __m128
  905. #define GGML_F32x4_ZERO _mm_setzero_ps()
  906. #define GGML_F32x4_SET1(x) _mm_set1_ps(x)
  907. #define GGML_F32x4_LOAD _mm_loadu_ps
  908. #define GGML_F32x4_STORE _mm_storeu_ps
  909. #if defined(__FMA__)
  910. // TODO: Does this work?
  911. #define GGML_F32x4_FMA(a, b, c) _mm_fmadd_ps(b, c, a)
  912. #else
  913. #define GGML_F32x4_FMA(a, b, c) _mm_add_ps(_mm_mul_ps(b, c), a)
  914. #endif
  915. #define GGML_F32x4_ADD _mm_add_ps
  916. #define GGML_F32x4_MUL _mm_mul_ps
  917. #define GGML_F32x4_REDUCE(res, x) \
  918. { \
  919. for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
  920. x[2*i] = _mm_add_ps(x[2*i], x[2*i+1]); \
  921. } \
  922. for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
  923. x[4*i] = _mm_add_ps(x[4*i], x[4*i+2]); \
  924. } \
  925. for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
  926. x[8*i] = _mm_add_ps(x[8*i], x[8*i+4]); \
  927. } \
  928. const __m128 t0 = _mm_hadd_ps(x[0], x[0]); \
  929. res = _mm_cvtss_f32(_mm_hadd_ps(t0, t0)); \
  930. }
  931. // TODO: is this optimal ?
  932. #define GGML_F32_VEC GGML_F32x4
  933. #define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
  934. #define GGML_F32_VEC_SET1 GGML_F32x4_SET1
  935. #define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
  936. #define GGML_F32_VEC_STORE GGML_F32x4_STORE
  937. #define GGML_F32_VEC_FMA GGML_F32x4_FMA
  938. #define GGML_F32_VEC_ADD GGML_F32x4_ADD
  939. #define GGML_F32_VEC_MUL GGML_F32x4_MUL
  940. #define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
  941. // F16 SSE
  942. #define GGML_F16_STEP 32
  943. #define GGML_F16_EPR 4
  944. static inline __m128 __sse_f16x4_load(ggml_fp16_t *x) {
  945. float tmp[4];
  946. tmp[0] = GGML_FP16_TO_FP32(x[0]);
  947. tmp[1] = GGML_FP16_TO_FP32(x[1]);
  948. tmp[2] = GGML_FP16_TO_FP32(x[2]);
  949. tmp[3] = GGML_FP16_TO_FP32(x[3]);
  950. return _mm_loadu_ps(tmp);
  951. }
  952. static inline void __sse_f16x4_store(ggml_fp16_t *x, __m128 y) {
  953. float arr[4];
  954. _mm_storeu_ps(arr, y);
  955. x[0] = GGML_FP32_TO_FP16(arr[0]);
  956. x[1] = GGML_FP32_TO_FP16(arr[1]);
  957. x[2] = GGML_FP32_TO_FP16(arr[2]);
  958. x[3] = GGML_FP32_TO_FP16(arr[3]);
  959. }
  960. #define GGML_F32Cx4 __m128
  961. #define GGML_F32Cx4_ZERO _mm_setzero_ps()
  962. #define GGML_F32Cx4_SET1(x) _mm_set1_ps(x)
  963. #define GGML_F32Cx4_LOAD(x) __sse_f16x4_load(x)
  964. #define GGML_F32Cx4_STORE(x, y) __sse_f16x4_store(x, y)
  965. #define GGML_F32Cx4_FMA GGML_F32x4_FMA
  966. #define GGML_F32Cx4_ADD _mm_add_ps
  967. #define GGML_F32Cx4_MUL _mm_mul_ps
  968. #define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
  969. #define GGML_F16_VEC GGML_F32Cx4
  970. #define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
  971. #define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
  972. #define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
  973. #define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE(p, r[i])
  974. #define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
  975. #define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
  976. #define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
  977. #define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
  978. #endif
  979. // GGML_F32_ARR / GGML_F16_ARR
  980. // number of registers to use per step
  981. #ifdef GGML_SIMD
  982. #define GGML_F32_ARR (GGML_F32_STEP/GGML_F32_EPR)
  983. #define GGML_F16_ARR (GGML_F16_STEP/GGML_F16_EPR)
  984. #endif
  985. //
  986. // fundamental operations
  987. //
  988. 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; }
  989. 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; }
  990. 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; }
  991. 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; }
  992. 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]; }
  993. 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]; }
  994. 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; }
  995. 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]; }
  996. 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; }
  997. 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]; }
  998. 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]; }
  999. 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]; }
  1000. 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]; }
  1001. inline static void ggml_vec_dot_f32(const int n, float * restrict s, const float * restrict x, const float * restrict y) {
  1002. ggml_float sumf = 0.0;
  1003. #ifdef GGML_SIMD
  1004. const int np = (n & ~(GGML_F32_STEP - 1));
  1005. GGML_F32_VEC sum[GGML_F32_ARR] = { GGML_F32_VEC_ZERO };
  1006. GGML_F32_VEC ax[GGML_F32_ARR];
  1007. GGML_F32_VEC ay[GGML_F32_ARR];
  1008. for (int i = 0; i < np; i += GGML_F32_STEP) {
  1009. for (int j = 0; j < GGML_F32_ARR; j++) {
  1010. ax[j] = GGML_F32_VEC_LOAD(x + i + j*GGML_F32_EPR);
  1011. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  1012. sum[j] = GGML_F32_VEC_FMA(sum[j], ax[j], ay[j]);
  1013. }
  1014. }
  1015. // reduce sum0..sum3 to sum0
  1016. GGML_F32_VEC_REDUCE(sumf, sum);
  1017. // leftovers
  1018. for (int i = np; i < n; ++i) {
  1019. sumf += x[i]*y[i];
  1020. }
  1021. #else
  1022. // scalar
  1023. for (int i = 0; i < n; ++i) {
  1024. sumf += x[i]*y[i];
  1025. }
  1026. #endif
  1027. *s = sumf;
  1028. }
  1029. inline static void ggml_vec_dot_f16(const int n, float * restrict s, ggml_fp16_t * restrict x, ggml_fp16_t * restrict y) {
  1030. ggml_float sumf = 0.0;
  1031. #if defined(GGML_SIMD)
  1032. const int np = (n & ~(GGML_F16_STEP - 1));
  1033. GGML_F16_VEC sum[GGML_F16_ARR] = { GGML_F16_VEC_ZERO };
  1034. GGML_F16_VEC ax[GGML_F16_ARR];
  1035. GGML_F16_VEC ay[GGML_F16_ARR];
  1036. for (int i = 0; i < np; i += GGML_F16_STEP) {
  1037. for (int j = 0; j < GGML_F16_ARR; j++) {
  1038. ax[j] = GGML_F16_VEC_LOAD(x + i + j*GGML_F16_EPR, j);
  1039. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  1040. sum[j] = GGML_F16_VEC_FMA(sum[j], ax[j], ay[j]);
  1041. }
  1042. }
  1043. // reduce sum0..sum3 to sum0
  1044. GGML_F16_VEC_REDUCE(sumf, sum);
  1045. // leftovers
  1046. for (int i = np; i < n; ++i) {
  1047. sumf += GGML_FP16_TO_FP32(x[i])*GGML_FP16_TO_FP32(y[i]);
  1048. }
  1049. #else
  1050. for (int i = 0; i < n; ++i) {
  1051. sumf += GGML_FP16_TO_FP32(x[i])*GGML_FP16_TO_FP32(y[i]);
  1052. }
  1053. #endif
  1054. *s = sumf;
  1055. }
  1056. inline static void ggml_vec_dot_q4_0(const int n, float * restrict s, const void * restrict x, const void * restrict y) {
  1057. const int nb = n / QK;
  1058. assert(n % QK == 0);
  1059. assert(nb % 2 == 0);
  1060. const size_t bs = sizeof(float) + QK/2;
  1061. const uint8_t * restrict pd0 = ((const uint8_t *)x + 0*bs);
  1062. const uint8_t * restrict pd1 = ((const uint8_t *)y + 0*bs);
  1063. const uint8_t * restrict pb0 = ((const uint8_t *)x + 0*bs + sizeof(float));
  1064. const uint8_t * restrict pb1 = ((const uint8_t *)y + 0*bs + sizeof(float));
  1065. float sumf = 0.0;
  1066. #ifdef __ARM_NEON
  1067. #if QK == 32
  1068. float sum0 = 0.0f;
  1069. float sum1 = 0.0f;
  1070. for (int i = 0; i < nb; i += 2) {
  1071. const float d0_0 = *(const float *) (pd0 + i*bs);
  1072. const float d1_0 = *(const float *) (pd1 + i*bs);
  1073. const float d0_1 = *(const float *) (pd0 + (i + 1)*bs);
  1074. const float d1_1 = *(const float *) (pd1 + (i + 1)*bs);
  1075. //printf("d0_0: %f, d1_0: %f, d0_1: %f, d1_1: %f\n", d0_0, d1_0, d0_1, d1_1);
  1076. const uint8_t * restrict p0 = pb0 + i*bs;
  1077. const uint8_t * restrict p1 = pb1 + i*bs;
  1078. const uint8x16_t m4b = vdupq_n_u8(0xf);
  1079. const int8x16_t s8b = vdupq_n_s8(0x8);
  1080. const uint8x16_t v0_0 = vld1q_u8(p0);
  1081. const uint8x16_t v1_0 = vld1q_u8(p1);
  1082. const uint8x16_t v0_1 = vld1q_u8(p0 + bs);
  1083. const uint8x16_t v1_1 = vld1q_u8(p1 + bs);
  1084. // 4-bit -> 8-bit
  1085. const int8x16_t v0_0l = vreinterpretq_s8_u8(vandq_u8(v0_0, m4b));
  1086. const int8x16_t v1_0l = vreinterpretq_s8_u8(vandq_u8(v1_0, m4b));
  1087. const int8x16_t v0_0h = vreinterpretq_s8_u8(vshrq_n_u8(v0_0, 4));
  1088. const int8x16_t v1_0h = vreinterpretq_s8_u8(vshrq_n_u8(v1_0, 4));
  1089. const int8x16_t v0_1l = vreinterpretq_s8_u8(vandq_u8(v0_1, m4b));
  1090. const int8x16_t v1_1l = vreinterpretq_s8_u8(vandq_u8(v1_1, m4b));
  1091. const int8x16_t v0_1h = vreinterpretq_s8_u8(vshrq_n_u8(v0_1, 4));
  1092. const int8x16_t v1_1h = vreinterpretq_s8_u8(vshrq_n_u8(v1_1, 4));
  1093. // sub 8
  1094. const int8x16_t v0_0ls = vsubq_s8(v0_0l, s8b);
  1095. const int8x16_t v1_0ls = vsubq_s8(v1_0l, s8b);
  1096. const int8x16_t v0_0hs = vsubq_s8(v0_0h, s8b);
  1097. const int8x16_t v1_0hs = vsubq_s8(v1_0h, s8b);
  1098. const int8x16_t v0_1ls = vsubq_s8(v0_1l, s8b);
  1099. const int8x16_t v1_1ls = vsubq_s8(v1_1l, s8b);
  1100. const int8x16_t v0_1hs = vsubq_s8(v0_1h, s8b);
  1101. const int8x16_t v1_1hs = vsubq_s8(v1_1h, s8b);
  1102. #if defined(__ARM_FEATURE_DOTPROD)
  1103. // dot product into int16x8_t
  1104. int32x4_t p_0 = vdotq_s32(vdupq_n_s32(0), v0_0ls, v1_0ls);
  1105. int32x4_t p_1 = vdotq_s32(vdupq_n_s32(0), v0_1ls, v1_1ls);
  1106. p_0 = vdotq_s32(p_0, v0_0hs, v1_0hs);
  1107. p_1 = vdotq_s32(p_1, v0_1hs, v1_1hs);
  1108. // scalar
  1109. #if defined(__ARM_FEATURE_QRDMX)
  1110. sum0 += d0_0*d1_0*vaddvq_s32(p_0);
  1111. sum1 += d0_1*d1_1*vaddvq_s32(p_1);
  1112. #else
  1113. sum0 += d0_0*d1_0*(vgetq_lane_s32(p_0, 0) + vgetq_lane_s32(p_0, 1) + vgetq_lane_s32(p_0, 2) + vgetq_lane_s32(p_0, 3));
  1114. sum1 += d0_1*d1_1*(vgetq_lane_s32(p_1, 0) + vgetq_lane_s32(p_1, 1) + vgetq_lane_s32(p_1, 2) + vgetq_lane_s32(p_1, 3));
  1115. #endif
  1116. #else
  1117. const int16x8_t pl0l = vmull_s8(vget_low_s8 (v0_0ls), vget_low_s8 (v1_0ls));
  1118. const int16x8_t pl0h = vmull_s8(vget_high_s8(v0_0ls), vget_high_s8(v1_0ls));
  1119. const int16x8_t ph0l = vmull_s8(vget_low_s8 (v0_0hs), vget_low_s8 (v1_0hs));
  1120. const int16x8_t ph0h = vmull_s8(vget_high_s8(v0_0hs), vget_high_s8(v1_0hs));
  1121. const int16x8_t pl1l = vmull_s8(vget_low_s8 (v0_1ls), vget_low_s8 (v1_1ls));
  1122. const int16x8_t pl1h = vmull_s8(vget_high_s8(v0_1ls), vget_high_s8(v1_1ls));
  1123. const int16x8_t ph1l = vmull_s8(vget_low_s8 (v0_1hs), vget_low_s8 (v1_1hs));
  1124. const int16x8_t ph1h = vmull_s8(vget_high_s8(v0_1hs), vget_high_s8(v1_1hs));
  1125. const int16x8_t pl_0 = vaddq_s16(pl0l, pl0h);
  1126. const int16x8_t ph_0 = vaddq_s16(ph0l, ph0h);
  1127. const int16x8_t pl_1 = vaddq_s16(pl1l, pl1h);
  1128. const int16x8_t ph_1 = vaddq_s16(ph1l, ph1h);
  1129. const int16x8_t p_0 = vaddq_s16(pl_0, ph_0);
  1130. const int16x8_t p_1 = vaddq_s16(pl_1, ph_1);
  1131. // scalar
  1132. #if defined(__ARM_FEATURE_QRDMX)
  1133. sum0 += d0_0*d1_0*vaddvq_s16(p_0);
  1134. sum1 += d0_1*d1_1*vaddvq_s16(p_1);
  1135. #else
  1136. sum0 += d0_0*d1_0*(vgetq_lane_s16(p_0, 0) + vgetq_lane_s16(p_0, 1) + vgetq_lane_s16(p_0, 2) + vgetq_lane_s16(p_0, 3) + vgetq_lane_s16(p_0, 4) + vgetq_lane_s16(p_0, 5) + vgetq_lane_s16(p_0, 6) + vgetq_lane_s16(p_0, 7));
  1137. sum1 += d0_1*d1_1*(vgetq_lane_s16(p_1, 0) + vgetq_lane_s16(p_1, 1) + vgetq_lane_s16(p_1, 2) + vgetq_lane_s16(p_1, 3) + vgetq_lane_s16(p_1, 4) + vgetq_lane_s16(p_1, 5) + vgetq_lane_s16(p_1, 6) + vgetq_lane_s16(p_1, 7));
  1138. #endif
  1139. #endif
  1140. }
  1141. sumf = sum0 + sum1;
  1142. #else
  1143. #error "not implemented for QK"
  1144. #endif
  1145. #elif defined(__AVX2__)
  1146. #if QK == 32
  1147. const size_t countBlocks = nb;
  1148. // Initialize accumulator with zeros
  1149. __m256 acc = _mm256_setzero_ps();
  1150. // Main loop
  1151. for (int i = 0; i < nb; ++i) {
  1152. const float * d0_0 = (const float *) (pd0 + i*bs);
  1153. const float * d1_0 = (const float *) (pd1 + i*bs);
  1154. const uint8_t * restrict p0 = pb0 + i*bs;
  1155. const uint8_t * restrict p1 = pb1 + i*bs;
  1156. // Compute combined scale for the block
  1157. const __m256 scale = _mm256_mul_ps( _mm256_broadcast_ss( d0_0 ), _mm256_broadcast_ss( d1_0 ) );
  1158. // Load 16 bytes, and unpack 4 bit fields into bytes, making 32 bytes
  1159. __m256i bx = bytesFromNibbles( p0 );
  1160. __m256i by = bytesFromNibbles( p1 );
  1161. // Now we have a vector with bytes in [ 0 .. 15 ] interval. Offset them into [ -8 .. +7 ] interval.
  1162. const __m256i off = _mm256_set1_epi8( 8 );
  1163. bx = _mm256_sub_epi8( bx, off );
  1164. by = _mm256_sub_epi8( by, off );
  1165. // Sign-extend first 16 signed bytes into int16_t
  1166. __m256i x16 = _mm256_cvtepi8_epi16( _mm256_castsi256_si128( bx ) );
  1167. __m256i y16 = _mm256_cvtepi8_epi16( _mm256_castsi256_si128( by ) );
  1168. // Compute products of int16_t integers, add pairwise
  1169. __m256i i32 = _mm256_madd_epi16( x16, y16 );
  1170. // Sign-extend last 16 signed bytes into int16_t vectors
  1171. x16 = _mm256_cvtepi8_epi16( _mm256_extracti128_si256( bx, 1 ) );
  1172. y16 = _mm256_cvtepi8_epi16( _mm256_extracti128_si256( by, 1 ) );
  1173. // Accumulate products of int16_t integers
  1174. i32 = _mm256_add_epi32( i32, _mm256_madd_epi16( x16, y16 ) );
  1175. // Convert int32_t to float
  1176. __m256 p = _mm256_cvtepi32_ps( i32 );
  1177. // Apply the scale, and accumulate
  1178. acc = _mm256_fmadd_ps( scale, p, acc );
  1179. }
  1180. // Return horizontal sum of the acc vector
  1181. __m128 res = _mm256_extractf128_ps( acc, 1 );
  1182. res = _mm_add_ps( res, _mm256_castps256_ps128( acc ) );
  1183. res = _mm_add_ps( res, _mm_movehl_ps( res, res ) );
  1184. res = _mm_add_ss( res, _mm_movehdup_ps( res ) );
  1185. sumf = _mm_cvtss_f32( res );
  1186. #else
  1187. #error "not implemented for QK"
  1188. #endif
  1189. #elif defined(__wasm_simd128__)
  1190. #if QK == 32
  1191. // wasm simd
  1192. float sum0 = 0.0f;
  1193. float sum1 = 0.0f;
  1194. for (int i = 0; i < nb; i += 2) {
  1195. const float d0_0 = *(const float *) (pd0 + i*bs);
  1196. const float d1_0 = *(const float *) (pd1 + i*bs);
  1197. const float d0_1 = *(const float *) (pd0 + (i + 1)*bs);
  1198. const float d1_1 = *(const float *) (pd1 + (i + 1)*bs);
  1199. const uint8_t * restrict p0 = pb0 + i*bs;
  1200. const uint8_t * restrict p1 = pb1 + i*bs;
  1201. const v128_t m4b = wasm_u8x16_splat(0xf);
  1202. const v128_t s8b = wasm_i8x16_splat(0x8);
  1203. const v128_t v0_0 = wasm_v128_load(p0);
  1204. const v128_t v0_1 = wasm_v128_load(p0 + bs);
  1205. const v128_t v1_0 = wasm_v128_load(p1);
  1206. const v128_t v1_1 = wasm_v128_load(p1 + bs);
  1207. // 4-bit -> 8-bit
  1208. const v128_t v0_0l = wasm_v128_and(v0_0, m4b);
  1209. const v128_t v1_0l = wasm_v128_and(v1_0, m4b);
  1210. const v128_t v0_0h = wasm_u8x16_shr(v0_0, 4);
  1211. const v128_t v1_0h = wasm_u8x16_shr(v1_0, 4);
  1212. const v128_t v0_1l = wasm_v128_and(v0_1, m4b);
  1213. const v128_t v1_1l = wasm_v128_and(v1_1, m4b);
  1214. const v128_t v0_1h = wasm_u8x16_shr(v0_1, 4);
  1215. const v128_t v1_1h = wasm_u8x16_shr(v1_1, 4);
  1216. // sub 8
  1217. const v128_t v0_0ls = wasm_i8x16_sub(v0_0l, s8b);
  1218. const v128_t v1_0ls = wasm_i8x16_sub(v1_0l, s8b);
  1219. const v128_t v0_0hs = wasm_i8x16_sub(v0_0h, s8b);
  1220. const v128_t v1_0hs = wasm_i8x16_sub(v1_0h, s8b);
  1221. const v128_t v0_1ls = wasm_i8x16_sub(v0_1l, s8b);
  1222. const v128_t v1_1ls = wasm_i8x16_sub(v1_1l, s8b);
  1223. const v128_t v0_1hs = wasm_i8x16_sub(v0_1h, s8b);
  1224. const v128_t v1_1hs = wasm_i8x16_sub(v1_1h, s8b);
  1225. // dot product into int16x8_t
  1226. const v128_t pl0l = wasm_i16x8_mul(wasm_i16x8_extend_low_i8x16(v0_0ls), wasm_i16x8_extend_low_i8x16(v1_0ls));
  1227. const v128_t pl0h = wasm_i16x8_mul(wasm_i16x8_extend_high_i8x16(v0_0ls), wasm_i16x8_extend_high_i8x16(v1_0ls));
  1228. const v128_t ph0l = wasm_i16x8_mul(wasm_i16x8_extend_low_i8x16(v0_0hs), wasm_i16x8_extend_low_i8x16(v1_0hs));
  1229. const v128_t ph0h = wasm_i16x8_mul(wasm_i16x8_extend_high_i8x16(v0_0hs), wasm_i16x8_extend_high_i8x16(v1_0hs));
  1230. const v128_t pl1l = wasm_i16x8_mul(wasm_i16x8_extend_low_i8x16(v0_1ls), wasm_i16x8_extend_low_i8x16(v1_1ls));
  1231. const v128_t pl1h = wasm_i16x8_mul(wasm_i16x8_extend_high_i8x16(v0_1ls), wasm_i16x8_extend_high_i8x16(v1_1ls));
  1232. const v128_t ph1l = wasm_i16x8_mul(wasm_i16x8_extend_low_i8x16(v0_1hs), wasm_i16x8_extend_low_i8x16(v1_1hs));
  1233. const v128_t ph1h = wasm_i16x8_mul(wasm_i16x8_extend_high_i8x16(v0_1hs), wasm_i16x8_extend_high_i8x16(v1_1hs));
  1234. const v128_t pl_0 = wasm_i16x8_add(pl0l, pl0h);
  1235. const v128_t ph_0 = wasm_i16x8_add(ph0l, ph0h);
  1236. const v128_t pl_1 = wasm_i16x8_add(pl1l, pl1h);
  1237. const v128_t ph_1 = wasm_i16x8_add(ph1l, ph1h);
  1238. const v128_t p_0 = wasm_i16x8_add(pl_0, ph_0);
  1239. const v128_t p_1 = wasm_i16x8_add(pl_1, ph_1);
  1240. sum0 += d0_0*d1_0*(
  1241. wasm_i16x8_extract_lane(p_0, 0) + wasm_i16x8_extract_lane(p_0, 1) +
  1242. wasm_i16x8_extract_lane(p_0, 2) + wasm_i16x8_extract_lane(p_0, 3) +
  1243. wasm_i16x8_extract_lane(p_0, 4) + wasm_i16x8_extract_lane(p_0, 5) +
  1244. wasm_i16x8_extract_lane(p_0, 6) + wasm_i16x8_extract_lane(p_0, 7));
  1245. sum1 += d0_1*d1_1*(
  1246. wasm_i16x8_extract_lane(p_1, 0) + wasm_i16x8_extract_lane(p_1, 1) +
  1247. wasm_i16x8_extract_lane(p_1, 2) + wasm_i16x8_extract_lane(p_1, 3) +
  1248. wasm_i16x8_extract_lane(p_1, 4) + wasm_i16x8_extract_lane(p_1, 5) +
  1249. wasm_i16x8_extract_lane(p_1, 6) + wasm_i16x8_extract_lane(p_1, 7));
  1250. }
  1251. sumf = sum0 + sum1;
  1252. #else
  1253. #error "not implemented for QK"
  1254. #endif
  1255. #else
  1256. // scalar
  1257. for (int i = 0; i < nb; i++) {
  1258. const float d0 = *(const float *) (pd0 + i*bs);
  1259. const float d1 = *(const float *) (pd1 + i*bs);
  1260. const uint8_t * restrict p0 = pb0 + i*bs;
  1261. const uint8_t * restrict p1 = pb1 + i*bs;
  1262. for (int j = 0; j < QK/2; j++) {
  1263. const uint8_t v0 = p0[j];
  1264. const uint8_t v1 = p1[j];
  1265. const float f0 = d0*((int8_t) (v0 & 0xf) - 8);
  1266. const float f1 = d0*((int8_t) (v0 >> 4) - 8);
  1267. const float f2 = d1*((int8_t) (v1 & 0xf) - 8);
  1268. const float f3 = d1*((int8_t) (v1 >> 4) - 8);
  1269. sumf += f0*f2 + f1*f3;
  1270. }
  1271. }
  1272. #endif
  1273. *s = sumf;
  1274. }
  1275. inline static void ggml_vec_dot_q4_1(const int n, float * restrict s, const void * restrict x, const void * restrict y) {
  1276. const int nb = n / QK;
  1277. const float * restrict pm0 = (const float *) x;
  1278. const float * restrict pm1 = (const float *) y;
  1279. const float * restrict pd0 = (const float *) (pm0 + nb);
  1280. const float * restrict pd1 = (const float *) (pm1 + nb);
  1281. const uint8_t * restrict pb0 = (const uint8_t *) (pd0 + nb);
  1282. const uint8_t * restrict pb1 = (const uint8_t *) (pd1 + nb);
  1283. float sumf = 0.0;
  1284. #if 1
  1285. // scalar
  1286. for (int i = 0; i < nb; i++) {
  1287. const float m0 = pm0[i];
  1288. const float m1 = pm1[i];
  1289. const float d0 = pd0[i];
  1290. const float d1 = pd1[i];
  1291. const uint8_t * restrict p0 = pb0 + i*QK/2;
  1292. const uint8_t * restrict p1 = pb1 + i*QK/2;
  1293. for (int j = 0; j < QK/2; j++) {
  1294. const uint8_t v0 = p0[j];
  1295. const uint8_t v1 = p1[j];
  1296. const float f0 = d0*(v0 & 0xf) + m0;
  1297. const float f1 = d0*(v0 >> 4) + m0;
  1298. const float f2 = d1*(v1 & 0xf) + m1;
  1299. const float f3 = d1*(v1 >> 4) + m1;
  1300. sumf += f0*f2 + f1*f3;
  1301. }
  1302. }
  1303. #endif
  1304. *s = sumf;
  1305. }
  1306. // compute GGML_VEC_DOT_UNROLL dot products at once
  1307. // xs - x row stride in bytes
  1308. 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) {
  1309. ggml_float sumf[GGML_VEC_DOT_UNROLL] = { 0.0 };
  1310. ggml_fp16_t * restrict x[GGML_VEC_DOT_UNROLL];
  1311. for (int i = 0; i < GGML_VEC_DOT_UNROLL; ++i) {
  1312. x[i] = (ggml_fp16_t *) ((char *) xv + i*xs);
  1313. }
  1314. #if defined(GGML_SIMD)
  1315. const int np = (n & ~(GGML_F16_STEP - 1));
  1316. GGML_F16_VEC sum[GGML_VEC_DOT_UNROLL][GGML_F16_ARR] = { { GGML_F16_VEC_ZERO } };
  1317. GGML_F16_VEC ax[GGML_F16_ARR];
  1318. GGML_F16_VEC ay[GGML_F16_ARR];
  1319. for (int i = 0; i < np; i += GGML_F16_STEP) {
  1320. for (int j = 0; j < GGML_F16_ARR; j++) {
  1321. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  1322. for (int k = 0; k < GGML_VEC_DOT_UNROLL; ++k) {
  1323. ax[j] = GGML_F16_VEC_LOAD(x[k] + i + j*GGML_F16_EPR, j);
  1324. sum[k][j] = GGML_F16_VEC_FMA(sum[k][j], ax[j], ay[j]);
  1325. }
  1326. }
  1327. }
  1328. // reduce sum0..sum3 to sum0
  1329. for (int k = 0; k < GGML_VEC_DOT_UNROLL; ++k) {
  1330. GGML_F16_VEC_REDUCE(sumf[k], sum[k]);
  1331. }
  1332. // leftovers
  1333. for (int i = np; i < n; ++i) {
  1334. for (int j = 0; j < GGML_VEC_DOT_UNROLL; ++j) {
  1335. sumf[j] += GGML_FP16_TO_FP32(x[j][i])*GGML_FP16_TO_FP32(y[i]);
  1336. }
  1337. }
  1338. #else
  1339. for (int i = 0; i < n; ++i) {
  1340. for (int j = 0; j < GGML_VEC_DOT_UNROLL; ++j) {
  1341. sumf[j] += GGML_FP16_TO_FP32(x[j][i])*GGML_FP16_TO_FP32(y[i]);
  1342. }
  1343. }
  1344. #endif
  1345. for (int i = 0; i < GGML_VEC_DOT_UNROLL; ++i) {
  1346. s[i] = sumf[i];
  1347. }
  1348. }
  1349. inline static void ggml_vec_mad_f32(const int n, float * restrict y, const float * restrict x, const float v) {
  1350. #if defined(GGML_SIMD)
  1351. const int np = (n & ~(GGML_F32_STEP - 1));
  1352. GGML_F32_VEC vx = GGML_F32_VEC_SET1(v);
  1353. GGML_F32_VEC ax[GGML_F32_ARR];
  1354. GGML_F32_VEC ay[GGML_F32_ARR];
  1355. for (int i = 0; i < np; i += GGML_F32_STEP) {
  1356. for (int j = 0; j < GGML_F32_ARR; j++) {
  1357. ax[j] = GGML_F32_VEC_LOAD(x + i + j*GGML_F32_EPR);
  1358. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  1359. ay[j] = GGML_F32_VEC_FMA(ay[j], ax[j], vx);
  1360. GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
  1361. }
  1362. }
  1363. // leftovers
  1364. for (int i = np; i < n; ++i) {
  1365. y[i] += x[i]*v;
  1366. }
  1367. #else
  1368. // scalar
  1369. for (int i = 0; i < n; ++i) {
  1370. y[i] += x[i]*v;
  1371. }
  1372. #endif
  1373. }
  1374. inline static void ggml_vec_mad_f16(const int n, ggml_fp16_t * restrict y, ggml_fp16_t * restrict x, const float v) {
  1375. #if defined(GGML_SIMD)
  1376. const int np = (n & ~(GGML_F16_STEP - 1));
  1377. GGML_F16_VEC vx = GGML_F16_VEC_SET1(v);
  1378. GGML_F16_VEC ax[GGML_F16_ARR];
  1379. GGML_F16_VEC ay[GGML_F16_ARR];
  1380. for (int i = 0; i < np; i += GGML_F16_STEP) {
  1381. for (int j = 0; j < GGML_F16_ARR; j++) {
  1382. ax[j] = GGML_F16_VEC_LOAD(x + i + j*GGML_F16_EPR, j);
  1383. ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
  1384. ay[j] = GGML_F16_VEC_FMA(ay[j], ax[j], vx);
  1385. GGML_F16_VEC_STORE(y + i + j*GGML_F16_EPR, ay, j);
  1386. }
  1387. }
  1388. // leftovers
  1389. for (int i = np; i < n; ++i) {
  1390. GGML_ASSERT(false);
  1391. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i]) + GGML_FP16_TO_FP32(x[i])*v);
  1392. }
  1393. #else
  1394. for (int i = 0; i < n; ++i) {
  1395. y[i] = GGML_FP32_TO_FP16(GGML_FP16_TO_FP32(y[i]) + GGML_FP16_TO_FP32(x[i])*v);
  1396. }
  1397. #endif
  1398. }
  1399. inline static void ggml_vec_mad_q4_0(const int n, float * restrict y, void * restrict x, const float v) {
  1400. assert(n % QK == 0);
  1401. const int nb = n / QK;
  1402. const size_t bs = sizeof(float) + QK/2;
  1403. const uint8_t * restrict pd = ((const uint8_t *)x + 0*bs);
  1404. const uint8_t * restrict pb = ((const uint8_t *)x + 0*bs + sizeof(float));
  1405. #if __ARM_NEON
  1406. #if QK == 32
  1407. for (int i = 0; i < nb; ++i) {
  1408. const float d0 = v*(*(const float *) (pd + i*bs));
  1409. const uint8_t * restrict pp = pb + i*bs;
  1410. const uint8x8_t m4b = vdup_n_u8(0xf);
  1411. const int8x8_t s8b = vdup_n_s8(0x8);
  1412. const float32x4_t vd = vdupq_n_f32(d0);
  1413. for (int j = 0; j < 2; j++) {
  1414. const uint8x8_t vx = vld1_u8(pp + j*8);
  1415. const int8x8_t vxl = vreinterpret_s8_u8(vand_u8(vx, m4b));
  1416. const int8x8_t vxh = vreinterpret_s8_u8(vshr_n_u8(vx, 4));
  1417. // sub 8
  1418. const int8x8_t vxls = vsub_s8(vxl, s8b);
  1419. const int8x8_t vxhs = vsub_s8(vxh, s8b);
  1420. //const int8x8_t vxlt = vzip_s8(vxls, vxhs)[0];
  1421. //const int8x8_t vxht = vzip_s8(vxls, vxhs)[1];
  1422. const int8x8_t vxlt = vzip1_s8(vxls, vxhs);
  1423. const int8x8_t vxht = vzip2_s8(vxls, vxhs);
  1424. const int8x16_t vxq = vcombine_s8(vxlt, vxht);
  1425. // convert to 2x int16x8_t
  1426. const int16x8_t vxq0 = vmovl_s8(vget_low_s8 (vxq));
  1427. const int16x8_t vxq1 = vmovl_s8(vget_high_s8(vxq));
  1428. // convert to 4x float32x4_t
  1429. const float32x4_t vx0 = vcvtq_f32_s32(vmovl_s16(vget_low_s16 (vxq0)));
  1430. const float32x4_t vx1 = vcvtq_f32_s32(vmovl_s16(vget_high_s16(vxq0)));
  1431. const float32x4_t vx2 = vcvtq_f32_s32(vmovl_s16(vget_low_s16 (vxq1)));
  1432. const float32x4_t vx3 = vcvtq_f32_s32(vmovl_s16(vget_high_s16(vxq1)));
  1433. const float32x4_t vy0 = vld1q_f32(y + i*32 + j*16 + 0);
  1434. const float32x4_t vy1 = vld1q_f32(y + i*32 + j*16 + 4);
  1435. const float32x4_t vy2 = vld1q_f32(y + i*32 + j*16 + 8);
  1436. const float32x4_t vy3 = vld1q_f32(y + i*32 + j*16 + 12);
  1437. const float32x4_t vr0 = vfmaq_f32(vy0, vx0, vd);
  1438. const float32x4_t vr1 = vfmaq_f32(vy1, vx1, vd);
  1439. const float32x4_t vr2 = vfmaq_f32(vy2, vx2, vd);
  1440. const float32x4_t vr3 = vfmaq_f32(vy3, vx3, vd);
  1441. vst1q_f32(y + i*32 + j*16 + 0, vr0);
  1442. vst1q_f32(y + i*32 + j*16 + 4, vr1);
  1443. vst1q_f32(y + i*32 + j*16 + 8, vr2);
  1444. vst1q_f32(y + i*32 + j*16 + 12, vr3);
  1445. }
  1446. }
  1447. #endif
  1448. #else
  1449. // scalar
  1450. for (int i = 0; i < nb; i++) {
  1451. const float d = *(const float *) (pd + i*bs);
  1452. const uint8_t * restrict pp = pb + i*bs;
  1453. for (int l = 0; l < QK; l += 2) {
  1454. const uint8_t vi = pp[l/2];
  1455. const int8_t vi0 = vi & 0xf;
  1456. const int8_t vi1 = vi >> 4;
  1457. const float v0 = (vi0 - 8)*d;
  1458. const float v1 = (vi1 - 8)*d;
  1459. y[i*QK + l + 0] += v0*v;
  1460. y[i*QK + l + 1] += v1*v;
  1461. assert(!isnan(y[i*QK + l + 0]));
  1462. assert(!isnan(y[i*QK + l + 1]));
  1463. assert(!isinf(y[i*QK + l + 0]));
  1464. assert(!isinf(y[i*QK + l + 1]));
  1465. }
  1466. }
  1467. #endif
  1468. }
  1469. inline static void ggml_vec_mad_q4_1(const int n, float * restrict y, void * restrict x, const float v) {
  1470. assert(n % QK == 0);
  1471. const int nb = n / QK;
  1472. const float * restrict pm = (const float *) (x);
  1473. const float * restrict pd = (const float *) (pm + nb);
  1474. const uint8_t * restrict pb = (const uint8_t *) (pd + nb);
  1475. for (int i = 0; i < nb; i++) {
  1476. const float m = pm[i];
  1477. const float d = pd[i];
  1478. const uint8_t * restrict pp = pb + i*QK/2;
  1479. for (int l = 0; l < QK; l += 2) {
  1480. const uint8_t vi = pp[l/2];
  1481. const uint8_t vi0 = vi & 0xf;
  1482. const uint8_t vi1 = vi >> 4;
  1483. const float v0 = d*vi0 + m;
  1484. const float v1 = d*vi1 + m;
  1485. y[i*QK + l + 0] += v0*v;
  1486. y[i*QK + l + 1] += v1*v;
  1487. assert(!isnan(y[i*QK + l + 0]));
  1488. assert(!isnan(y[i*QK + l + 1]));
  1489. assert(!isinf(y[i*QK + l + 0]));
  1490. assert(!isinf(y[i*QK + l + 1]));
  1491. //printf("mad: v0 %f v1 %f, i = %d, l = %d, d = %f, vi = %d, vi0 = %d, vi1 = %d\n", v0, v1, i, l, d, vi, vi0, vi1);
  1492. }
  1493. }
  1494. }
  1495. //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; }
  1496. inline static void ggml_vec_scale_f32(const int n, float * y, const float v) {
  1497. #if defined(GGML_SIMD)
  1498. const int np = (n & ~(GGML_F32_STEP - 1));
  1499. GGML_F32_VEC vx = GGML_F32_VEC_SET1(v);
  1500. GGML_F32_VEC ay[GGML_F32_ARR];
  1501. for (int i = 0; i < np; i += GGML_F32_STEP) {
  1502. for (int j = 0; j < GGML_F32_ARR; j++) {
  1503. ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
  1504. ay[j] = GGML_F32_VEC_MUL(ay[j], vx);
  1505. GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
  1506. }
  1507. }
  1508. // leftovers
  1509. for (int i = np; i < n; ++i) {
  1510. y[i] *= v;
  1511. }
  1512. #else
  1513. // scalar
  1514. for (int i = 0; i < n; ++i) {
  1515. y[i] *= v;
  1516. }
  1517. #endif
  1518. }
  1519. inline static void ggml_vec_norm_f32 (const int n, float * s, const float * x) { ggml_vec_dot_f32(n, s, x, x); *s = sqrt(*s); }
  1520. 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]; }
  1521. inline static void ggml_vec_sqrt_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = sqrt(x[i]); }
  1522. 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]); }
  1523. 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); }
  1524. 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; }
  1525. 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; }
  1526. static const ggml_float GELU_COEF_A = 0.044715;
  1527. static const ggml_float SQRT_2_OVER_PI = 0.79788456080286535587989211986876;
  1528. inline static float ggml_gelu_f32(float x) {
  1529. return 0.5*x*(1.0 + tanh(SQRT_2_OVER_PI*x*(1.0 + GELU_COEF_A*x*x)));
  1530. }
  1531. inline static void ggml_vec_gelu_f16(const int n, ggml_fp16_t * y, const ggml_fp16_t * x) {
  1532. const uint16_t * i16 = (const uint16_t *) x;
  1533. for (int i = 0; i < n; ++i) {
  1534. y[i] = table_gelu_f16[i16[i]];
  1535. }
  1536. }
  1537. #ifdef GGML_GELU_FP16
  1538. inline static void ggml_vec_gelu_f32(const int n, float * y, const float * x) {
  1539. uint16_t t;
  1540. for (int i = 0; i < n; ++i) {
  1541. ggml_fp16_t fp16 = GGML_FP32_TO_FP16(x[i]);
  1542. memcpy(&t, &fp16, sizeof(uint16_t));
  1543. y[i] = GGML_FP16_TO_FP32(table_gelu_f16[t]);
  1544. }
  1545. }
  1546. #else
  1547. inline static void ggml_vec_gelu_f32(const int n, float * y, const float * x) {
  1548. for (int i = 0; i < n; ++i) {
  1549. y[i] = ggml_gelu_f32(x[i]);
  1550. }
  1551. }
  1552. #endif
  1553. // Sigmoid Linear Unit (SiLU) function
  1554. inline static float ggml_silu_f32(float x) {
  1555. return x/(1.0 + exp(-x));
  1556. }
  1557. inline static void ggml_vec_silu_f16(const int n, ggml_fp16_t * y, const ggml_fp16_t * x) {
  1558. const uint16_t * i16 = (const uint16_t *) x;
  1559. for (int i = 0; i < n; ++i) {
  1560. y[i] = table_silu_f16[i16[i]];
  1561. }
  1562. }
  1563. #ifdef GGML_SILU_FP16
  1564. inline static void ggml_vec_silu_f32(const int n, float * y, const float * x) {
  1565. uint16_t t;
  1566. for (int i = 0; i < n; ++i) {
  1567. ggml_fp16_t fp16 = GGML_FP32_TO_FP16(x[i]);
  1568. memcpy(&t, &fp16, sizeof(uint16_t));
  1569. y[i] = GGML_FP16_TO_FP32(table_silu_f16[t]);
  1570. }
  1571. }
  1572. #else
  1573. inline static void ggml_vec_silu_f32(const int n, float * y, const float * x) {
  1574. for (int i = 0; i < n; ++i) {
  1575. y[i] = ggml_silu_f32(x[i]);
  1576. }
  1577. }
  1578. #endif
  1579. inline static void ggml_vec_sum_f32(const int n, float * s, const float * x) {
  1580. #ifndef GGML_USE_ACCELERATE
  1581. ggml_float sum = 0.0;
  1582. for (int i = 0; i < n; ++i) {
  1583. sum += x[i];
  1584. }
  1585. *s = sum;
  1586. #else
  1587. vDSP_sve(x, 1, s, n);
  1588. #endif
  1589. }
  1590. inline static void ggml_vec_max_f32(const int n, float * s, const float * x) {
  1591. #ifndef GGML_USE_ACCELERATE
  1592. ggml_float max = -INFINITY;
  1593. for (int i = 0; i < n; ++i) {
  1594. max = MAX(max, x[i]);
  1595. }
  1596. *s = max;
  1597. #else
  1598. vDSP_maxv(x, 1, s, n);
  1599. #endif
  1600. }
  1601. inline static void ggml_vec_norm_inv_f32(const int n, float * s, const float * x) { ggml_vec_norm_f32(n, s, x); *s = 1./(*s); }
  1602. //
  1603. // logging
  1604. //
  1605. #if (GGML_DEBUG >= 1)
  1606. #define GGML_PRINT_DEBUG(...) printf(__VA_ARGS__)
  1607. #else
  1608. #define GGML_PRINT_DEBUG(...)
  1609. #endif
  1610. #if (GGML_DEBUG >= 5)
  1611. #define GGML_PRINT_DEBUG_5(...) printf(__VA_ARGS__)
  1612. #else
  1613. #define GGML_PRINT_DEBUG_5(...)
  1614. #endif
  1615. #if (GGML_DEBUG >= 10)
  1616. #define GGML_PRINT_DEBUG_10(...) printf(__VA_ARGS__)
  1617. #else
  1618. #define GGML_PRINT_DEBUG_10(...)
  1619. #endif
  1620. #define GGML_PRINT(...) printf(__VA_ARGS__)
  1621. //
  1622. // data types
  1623. //
  1624. static const int GGML_BLCK_SIZE[GGML_TYPE_COUNT] = {
  1625. QK,
  1626. QK,
  1627. 1,
  1628. 1,
  1629. 1,
  1630. 1,
  1631. 1,
  1632. };
  1633. static_assert(GGML_TYPE_COUNT == 7, "GGML_TYPE_COUNT != 5");
  1634. static const size_t GGML_TYPE_SIZE[GGML_TYPE_COUNT] = {
  1635. sizeof(float ) + QK/2,
  1636. sizeof(float )*2 + QK/2,
  1637. sizeof(int8_t ),
  1638. sizeof(int16_t),
  1639. sizeof(int32_t),
  1640. sizeof(ggml_fp16_t),
  1641. sizeof(float ),
  1642. };
  1643. // don't forget to update the array above when adding new types
  1644. static_assert(GGML_TYPE_COUNT == 7, "GGML_TYPE_COUNT != 5");
  1645. static const char * GGML_OP_LABEL[GGML_OP_COUNT] = {
  1646. "NONE",
  1647. "DUP",
  1648. "ADD",
  1649. "SUB",
  1650. "MUL",
  1651. "DIV",
  1652. "SQR",
  1653. "SQRT",
  1654. "SUM",
  1655. "MEAN",
  1656. "REPEAT",
  1657. "ABS",
  1658. "SGN",
  1659. "NEG",
  1660. "STEP",
  1661. "RELU",
  1662. "GELU",
  1663. "SILU",
  1664. "NORM",
  1665. "RMS_NORM",
  1666. "MUL_MAT",
  1667. "SCALE",
  1668. "CPY",
  1669. "RESHAPE",
  1670. "VIEW",
  1671. "PERMUTE",
  1672. "TRANSPOSE",
  1673. "GET_ROWS",
  1674. "DIAG_MASK_INF",
  1675. "SOFT_MAX",
  1676. "ROPE",
  1677. "CONV_1D_1S",
  1678. "CONV_1D_2S",
  1679. "FLASH_ATTN",
  1680. "FLASH_FF",
  1681. };
  1682. static_assert(GGML_OP_COUNT == 35, "GGML_OP_COUNT != 35");
  1683. static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = {
  1684. "none",
  1685. "x",
  1686. "x+y",
  1687. "x-y",
  1688. "x*y",
  1689. "x/y",
  1690. "x^2",
  1691. "√x",
  1692. "Σx",
  1693. "Σx/n",
  1694. "repeat(x)",
  1695. "abs(x)",
  1696. "sgn(x)",
  1697. "-x",
  1698. "step(x)",
  1699. "relu(x)",
  1700. "gelu(x)",
  1701. "silu(x)",
  1702. "norm(x)",
  1703. "rms_norm(x)",
  1704. "X*Y",
  1705. "x*v",
  1706. "x-\\>y",
  1707. "reshape(x)",
  1708. "view(x)",
  1709. "permute(x)",
  1710. "transpose(x)",
  1711. "get_rows(x)",
  1712. "diag_mask_inf(x)",
  1713. "soft_max(x)",
  1714. "rope(x)",
  1715. "conv_1d_1s(x)",
  1716. "conv_1d_2s(x)",
  1717. "flash_attn(x)",
  1718. "flash_ff(x)",
  1719. };
  1720. static_assert(GGML_OP_COUNT == 35, "GGML_OP_COUNT != 35");
  1721. //
  1722. // ggml object
  1723. //
  1724. struct ggml_object {
  1725. size_t offs;
  1726. size_t size;
  1727. struct ggml_object * next;
  1728. char padding[8];
  1729. };
  1730. static const size_t GGML_OBJECT_SIZE = sizeof(struct ggml_object);
  1731. static_assert(sizeof(struct ggml_object)%GGML_MEM_ALIGN == 0, "ggml_object size must be a multiple of GGML_MEM_ALIGN");
  1732. static_assert(sizeof(struct ggml_tensor)%GGML_MEM_ALIGN == 0, "ggml_tensor size must be a multiple of GGML_MEM_ALIGN");
  1733. //
  1734. // ggml context
  1735. //
  1736. struct ggml_context {
  1737. size_t mem_size;
  1738. void * mem_buffer;
  1739. bool mem_buffer_owned;
  1740. int n_objects;
  1741. struct ggml_object * objects_begin;
  1742. struct ggml_object * objects_end;
  1743. struct ggml_scratch scratch;
  1744. struct ggml_scratch scratch_save;
  1745. };
  1746. struct ggml_context_container {
  1747. bool used;
  1748. struct ggml_context context;
  1749. };
  1750. //
  1751. // compute types
  1752. //
  1753. enum ggml_task_type {
  1754. GGML_TASK_INIT = 0,
  1755. GGML_TASK_COMPUTE,
  1756. GGML_TASK_FINALIZE,
  1757. };
  1758. struct ggml_compute_params {
  1759. enum ggml_task_type type;
  1760. int ith, nth;
  1761. // work buffer for all threads
  1762. size_t wsize;
  1763. void * wdata;
  1764. };
  1765. //
  1766. // ggml state
  1767. //
  1768. struct ggml_state {
  1769. struct ggml_context_container contexts[GGML_MAX_CONTEXTS];
  1770. };
  1771. // global state
  1772. static struct ggml_state g_state;
  1773. static atomic_int g_state_barrier = 0;
  1774. // barrier via spin lock
  1775. inline static void ggml_critical_section_start(void) {
  1776. int processing = atomic_fetch_add(&g_state_barrier, 1);
  1777. while (processing > 0) {
  1778. // wait for other threads to finish
  1779. atomic_fetch_sub(&g_state_barrier, 1);
  1780. sched_yield(); // TODO: reconsider this
  1781. processing = atomic_fetch_add(&g_state_barrier, 1);
  1782. }
  1783. }
  1784. // TODO: make this somehow automatically executed
  1785. // some sort of "sentry" mechanism
  1786. inline static void ggml_critical_section_end(void) {
  1787. atomic_fetch_sub(&g_state_barrier, 1);
  1788. }
  1789. ////////////////////////////////////////////////////////////////////////////////
  1790. void ggml_print_object(const struct ggml_object * obj) {
  1791. GGML_PRINT(" - ggml_object: offset = %zu, size = %zu, next = %p\n",
  1792. obj->offs, obj->size, (const void *) obj->next);
  1793. }
  1794. void ggml_print_objects(const struct ggml_context * ctx) {
  1795. struct ggml_object * obj = ctx->objects_begin;
  1796. GGML_PRINT("%s: objects in context %p:\n", __func__, (const void *) ctx);
  1797. while (obj != NULL) {
  1798. ggml_print_object(obj);
  1799. obj = obj->next;
  1800. }
  1801. GGML_PRINT("%s: --- end ---\n", __func__);
  1802. }
  1803. int ggml_nelements(const struct ggml_tensor * tensor) {
  1804. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1805. return tensor->ne[0]*tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
  1806. }
  1807. int ggml_nrows(const struct ggml_tensor * tensor) {
  1808. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1809. return tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
  1810. }
  1811. size_t ggml_nbytes(const struct ggml_tensor * tensor) {
  1812. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1813. return (ggml_nelements(tensor)*GGML_TYPE_SIZE[tensor->type])/GGML_BLCK_SIZE[tensor->type];
  1814. }
  1815. int ggml_blck_size(enum ggml_type type) {
  1816. return GGML_BLCK_SIZE[type];
  1817. }
  1818. size_t ggml_type_size(enum ggml_type type) {
  1819. return GGML_TYPE_SIZE[type];
  1820. }
  1821. float ggml_type_sizef(enum ggml_type type) {
  1822. return ((float)(GGML_TYPE_SIZE[type]))/GGML_BLCK_SIZE[type];
  1823. }
  1824. size_t ggml_element_size(const struct ggml_tensor * tensor) {
  1825. return GGML_TYPE_SIZE[tensor->type];
  1826. }
  1827. static inline bool ggml_is_scalar(const struct ggml_tensor * tensor) {
  1828. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1829. return tensor->ne[0] == 1 && tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  1830. }
  1831. static inline bool ggml_is_vector(const struct ggml_tensor * tensor) {
  1832. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1833. return tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  1834. }
  1835. static inline bool ggml_is_matrix(const struct ggml_tensor * tensor) {
  1836. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1837. return tensor->ne[2] == 1 && tensor->ne[3] == 1;
  1838. }
  1839. static inline bool ggml_can_mul_mat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1840. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1841. return
  1842. (t0->ne[0] == t1->ne[0]) &&
  1843. (t0->ne[2] == t1->ne[2]) &&
  1844. (t0->ne[3] == t1->ne[3]);
  1845. }
  1846. static inline bool ggml_is_contiguous(const struct ggml_tensor * tensor) {
  1847. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1848. return
  1849. tensor->nb[0] == GGML_TYPE_SIZE[tensor->type] &&
  1850. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/GGML_BLCK_SIZE[tensor->type] &&
  1851. tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
  1852. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  1853. }
  1854. static inline bool ggml_is_padded_1d(const struct ggml_tensor * tensor) {
  1855. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1856. return
  1857. tensor->nb[0] == GGML_TYPE_SIZE[tensor->type] &&
  1858. tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
  1859. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  1860. }
  1861. static inline bool ggml_are_same_shape(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1862. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1863. return
  1864. (t0->ne[0] == t1->ne[0] ) &&
  1865. (t0->ne[1] == t1->ne[1] ) &&
  1866. (t0->ne[2] == t1->ne[2] ) &&
  1867. (t0->ne[3] == t1->ne[3] );
  1868. }
  1869. // check if t1 can be represented as a repeatition of t0
  1870. static inline bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1871. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1872. return
  1873. (t1->ne[0]%t0->ne[0] == 0) &&
  1874. (t1->ne[1]%t0->ne[1] == 0) &&
  1875. (t1->ne[2]%t0->ne[2] == 0) &&
  1876. (t1->ne[3]%t0->ne[3] == 0);
  1877. }
  1878. static inline int ggml_up32(int n) {
  1879. return (n + 31) & ~31;
  1880. }
  1881. static inline int ggml_up64(int n) {
  1882. return (n + 63) & ~63;
  1883. }
  1884. static inline int ggml_up(int n, int m) {
  1885. // assert m is a power of 2
  1886. GGML_ASSERT((m & (m - 1)) == 0);
  1887. return (n + m - 1) & ~(m - 1);
  1888. }
  1889. // assert that pointer is aligned to GGML_MEM_ALIGN
  1890. #define ggml_assert_aligned(ptr) \
  1891. assert(((uintptr_t) (ptr))%GGML_MEM_ALIGN == 0)
  1892. ////////////////////////////////////////////////////////////////////////////////
  1893. struct ggml_context * ggml_init(struct ggml_init_params params) {
  1894. // make this function thread safe
  1895. ggml_critical_section_start();
  1896. static bool is_first_call = true;
  1897. if (is_first_call) {
  1898. // initialize GELU, SILU and EXP F32 tables
  1899. {
  1900. const uint64_t t_start = ggml_time_us(); UNUSED(t_start);
  1901. ggml_fp16_t ii;
  1902. for (int i = 0; i < (1 << 16); ++i) {
  1903. uint16_t ui = i;
  1904. memcpy(&ii, &ui, sizeof(ii));
  1905. const float f = table_f32_f16[i] = GGML_COMPUTE_FP16_TO_FP32(ii);
  1906. table_gelu_f16[i] = GGML_FP32_TO_FP16(ggml_gelu_f32(f));
  1907. table_silu_f16[i] = GGML_FP32_TO_FP16(ggml_silu_f32(f));
  1908. table_exp_f16[i] = GGML_FP32_TO_FP16(exp(f));
  1909. }
  1910. const uint64_t t_end = ggml_time_us(); UNUSED(t_end);
  1911. GGML_PRINT_DEBUG("%s: GELU, SILU and EXP tables initialized in %f ms\n", __func__, (t_end - t_start)/1000.0f);
  1912. }
  1913. // initialize g_state
  1914. {
  1915. const uint64_t t_start = ggml_time_us(); UNUSED(t_start);
  1916. g_state = (struct ggml_state) {
  1917. /*.contexts =*/ { { 0 } },
  1918. };
  1919. for (int i = 0; i < GGML_MAX_CONTEXTS; ++i) {
  1920. g_state.contexts[i].used = false;
  1921. }
  1922. const uint64_t t_end = ggml_time_us(); UNUSED(t_end);
  1923. GGML_PRINT_DEBUG("%s: g_state initialized in %f ms\n", __func__, (t_end - t_start)/1000.0f);
  1924. }
  1925. is_first_call = false;
  1926. }
  1927. // find non-used context in g_state
  1928. struct ggml_context * ctx = NULL;
  1929. for (int i = 0; i < GGML_MAX_CONTEXTS; i++) {
  1930. if (!g_state.contexts[i].used) {
  1931. g_state.contexts[i].used = true;
  1932. ctx = &g_state.contexts[i].context;
  1933. GGML_PRINT_DEBUG("%s: found unused context %d\n", __func__, i);
  1934. break;
  1935. }
  1936. }
  1937. if (ctx == NULL) {
  1938. GGML_PRINT_DEBUG("%s: no unused context found\n", __func__);
  1939. ggml_critical_section_end();
  1940. return NULL;
  1941. }
  1942. *ctx = (struct ggml_context) {
  1943. /*.mem_size =*/ params.mem_size,
  1944. /*.mem_buffer =*/ params.mem_buffer ? params.mem_buffer : malloc(params.mem_size),
  1945. /*.mem_buffer_owned =*/ params.mem_buffer ? false : true,
  1946. /*.n_objects =*/ 0,
  1947. /*.objects_begin =*/ NULL,
  1948. /*.objects_end =*/ NULL,
  1949. /*.scratch =*/ { 0, 0, NULL, },
  1950. /*.scratch_save =*/ { 0, 0, NULL, },
  1951. };
  1952. ggml_assert_aligned(ctx->mem_buffer);
  1953. GGML_PRINT_DEBUG("%s: context initialized\n", __func__);
  1954. ggml_critical_section_end();
  1955. return ctx;
  1956. }
  1957. void ggml_free(struct ggml_context * ctx) {
  1958. // make this function thread safe
  1959. ggml_critical_section_start();
  1960. bool found = false;
  1961. for (int i = 0; i < GGML_MAX_CONTEXTS; i++) {
  1962. if (&g_state.contexts[i].context == ctx) {
  1963. g_state.contexts[i].used = false;
  1964. GGML_PRINT_DEBUG("%s: context %d with %d objects has been freed. memory used = %zu\n",
  1965. __func__, i, ctx->n_objects, ctx->objects_end->offs + ctx->objects_end->size);
  1966. if (ctx->mem_buffer_owned) {
  1967. free(ctx->mem_buffer);
  1968. }
  1969. found = true;
  1970. break;
  1971. }
  1972. }
  1973. if (!found) {
  1974. GGML_PRINT_DEBUG("%s: context not found\n", __func__);
  1975. }
  1976. ggml_critical_section_end();
  1977. }
  1978. size_t ggml_used_mem(const struct ggml_context * ctx) {
  1979. return ctx->objects_end->offs + ctx->objects_end->size;
  1980. }
  1981. size_t ggml_set_scratch(struct ggml_context * ctx, struct ggml_scratch scratch) {
  1982. const size_t result = ctx->scratch.data ? ctx->scratch.offs : 0;
  1983. ctx->scratch = scratch;
  1984. return result;
  1985. }
  1986. ////////////////////////////////////////////////////////////////////////////////
  1987. struct ggml_tensor * ggml_new_tensor_impl(
  1988. struct ggml_context * ctx,
  1989. enum ggml_type type,
  1990. int n_dims,
  1991. const int* ne,
  1992. void* data) {
  1993. // always insert objects at the end of the context's memory pool
  1994. struct ggml_object * obj_cur = ctx->objects_end;
  1995. const size_t cur_offs = obj_cur == NULL ? 0 : obj_cur->offs;
  1996. const size_t cur_size = obj_cur == NULL ? 0 : obj_cur->size;
  1997. const size_t cur_end = cur_offs + cur_size;
  1998. size_t size_needed = 0;
  1999. if (data == NULL) {
  2000. size_needed += GGML_TYPE_SIZE[type]*(ne[0]/GGML_BLCK_SIZE[type]);
  2001. for (int i = 1; i < n_dims; i++) {
  2002. size_needed *= ne[i];
  2003. }
  2004. // align to GGML_MEM_ALIGN
  2005. size_needed = ((size_needed + GGML_MEM_ALIGN - 1)/GGML_MEM_ALIGN)*GGML_MEM_ALIGN;
  2006. }
  2007. char * const mem_buffer = ctx->mem_buffer;
  2008. struct ggml_object * const obj_new = (struct ggml_object *)(mem_buffer + cur_end);
  2009. if (ctx->scratch.data == NULL || data != NULL) {
  2010. size_needed += sizeof(struct ggml_tensor);
  2011. if (cur_end + size_needed + GGML_OBJECT_SIZE > ctx->mem_size) {
  2012. GGML_PRINT("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
  2013. __func__, cur_end + size_needed + GGML_OBJECT_SIZE, ctx->mem_size);
  2014. assert(false);
  2015. return NULL;
  2016. }
  2017. *obj_new = (struct ggml_object) {
  2018. .offs = cur_end + GGML_OBJECT_SIZE,
  2019. .size = size_needed,
  2020. .next = NULL,
  2021. };
  2022. } else {
  2023. if (ctx->scratch.offs + size_needed > ctx->scratch.size) {
  2024. GGML_PRINT("%s: not enough space in the scratch memory\n", __func__);
  2025. assert(false);
  2026. return NULL;
  2027. }
  2028. if (cur_end + sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE > ctx->mem_size) {
  2029. GGML_PRINT("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
  2030. __func__, cur_end + sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE, ctx->mem_size);
  2031. assert(false);
  2032. return NULL;
  2033. }
  2034. data = (char * const) ctx->scratch.data + ctx->scratch.offs;
  2035. *obj_new = (struct ggml_object) {
  2036. .offs = cur_end + GGML_OBJECT_SIZE,
  2037. .size = sizeof(struct ggml_tensor),
  2038. .next = NULL,
  2039. };
  2040. //printf("scratch offs = %zu, size_needed = %zu\n", ctx->scratch.offs, size_needed);
  2041. ctx->scratch.offs += size_needed;
  2042. }
  2043. if (obj_cur != NULL) {
  2044. obj_cur->next = obj_new;
  2045. } else {
  2046. // this is the first object in this context
  2047. ctx->objects_begin = obj_new;
  2048. }
  2049. ctx->objects_end = obj_new;
  2050. //printf("%s: inserted new object at %zu, size = %zu\n", __func__, cur_end, obj_new->size);
  2051. struct ggml_tensor * const result = (struct ggml_tensor *)(mem_buffer + obj_new->offs);
  2052. ggml_assert_aligned(result);
  2053. *result = (struct ggml_tensor) {
  2054. /*.type =*/ type,
  2055. /*.n_dims =*/ n_dims,
  2056. /*.ne =*/ { 1, 1, 1, 1 },
  2057. /*.nb =*/ { 0, 0, 0, 0 },
  2058. /*.op =*/ GGML_OP_NONE,
  2059. /*.is_param =*/ false,
  2060. /*.grad =*/ NULL,
  2061. /*.src0 =*/ NULL,
  2062. /*.src1 =*/ NULL,
  2063. /*.opt =*/ { NULL },
  2064. /*.n_tasks =*/ 0,
  2065. /*.perf_runs =*/ 0,
  2066. /*.perf_cycles =*/ 0,
  2067. /*.perf_time_us =*/ 0,
  2068. /*.data =*/ data == NULL ? (void *)(result + 1) : data,
  2069. /*.pad =*/ { 0 },
  2070. };
  2071. ggml_assert_aligned(result->data);
  2072. for (int i = 0; i < n_dims; i++) {
  2073. result->ne[i] = ne[i];
  2074. }
  2075. result->nb[0] = GGML_TYPE_SIZE[type];
  2076. result->nb[1] = result->nb[0]*(result->ne[0]/GGML_BLCK_SIZE[type]);
  2077. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  2078. result->nb[i] = result->nb[i - 1]*result->ne[i - 1];
  2079. }
  2080. ctx->n_objects++;
  2081. return result;
  2082. }
  2083. struct ggml_tensor * ggml_new_tensor(
  2084. struct ggml_context * ctx,
  2085. enum ggml_type type,
  2086. int n_dims,
  2087. const int * ne) {
  2088. return ggml_new_tensor_impl(ctx, type, n_dims, ne, NULL);
  2089. }
  2090. struct ggml_tensor * ggml_new_tensor_1d(
  2091. struct ggml_context * ctx,
  2092. enum ggml_type type,
  2093. int ne0) {
  2094. return ggml_new_tensor(ctx, type, 1, &ne0);
  2095. }
  2096. struct ggml_tensor * ggml_new_tensor_2d(
  2097. struct ggml_context * ctx,
  2098. enum ggml_type type,
  2099. int ne0,
  2100. int ne1) {
  2101. const int ne[2] = { ne0, ne1 };
  2102. return ggml_new_tensor(ctx, type, 2, ne);
  2103. }
  2104. struct ggml_tensor * ggml_new_tensor_3d(
  2105. struct ggml_context * ctx,
  2106. enum ggml_type type,
  2107. int ne0,
  2108. int ne1,
  2109. int ne2) {
  2110. const int ne[3] = { ne0, ne1, ne2 };
  2111. return ggml_new_tensor(ctx, type, 3, ne);
  2112. }
  2113. struct ggml_tensor * ggml_new_tensor_4d(
  2114. struct ggml_context * ctx,
  2115. enum ggml_type type,
  2116. int ne0,
  2117. int ne1,
  2118. int ne2,
  2119. int ne3) {
  2120. const int ne[4] = { ne0, ne1, ne2, ne3 };
  2121. return ggml_new_tensor(ctx, type, 4, ne);
  2122. }
  2123. struct ggml_tensor * ggml_new_i32(struct ggml_context * ctx, int32_t value) {
  2124. ctx->scratch_save = ctx->scratch;
  2125. ctx->scratch.data = NULL;
  2126. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
  2127. ctx->scratch = ctx->scratch_save;
  2128. ggml_set_i32(result, value);
  2129. return result;
  2130. }
  2131. struct ggml_tensor * ggml_new_f32(struct ggml_context * ctx, float value) {
  2132. ctx->scratch_save = ctx->scratch;
  2133. ctx->scratch.data = NULL;
  2134. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
  2135. ctx->scratch = ctx->scratch_save;
  2136. ggml_set_f32(result, value);
  2137. return result;
  2138. }
  2139. struct ggml_tensor * ggml_dup_tensor(struct ggml_context * ctx, const struct ggml_tensor * src) {
  2140. return ggml_new_tensor_impl(ctx, src->type, src->n_dims, src->ne, NULL);
  2141. }
  2142. struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor) {
  2143. memset(tensor->data, 0, ggml_nbytes(tensor));
  2144. return tensor;
  2145. }
  2146. struct ggml_tensor * ggml_set_i32 (struct ggml_tensor * tensor, int32_t value) {
  2147. const int n = ggml_nrows(tensor);
  2148. const int nc = tensor->ne[0];
  2149. const size_t n1 = tensor->nb[1];
  2150. char * const data = tensor->data;
  2151. switch (tensor->type) {
  2152. case GGML_TYPE_Q4_0:
  2153. {
  2154. GGML_ASSERT(false);
  2155. } break;
  2156. case GGML_TYPE_Q4_1:
  2157. {
  2158. GGML_ASSERT(false);
  2159. } break;
  2160. case GGML_TYPE_I8:
  2161. {
  2162. assert(tensor->nb[0] == sizeof(int8_t));
  2163. for (int i = 0; i < n; i++) {
  2164. ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
  2165. }
  2166. } break;
  2167. case GGML_TYPE_I16:
  2168. {
  2169. assert(tensor->nb[0] == sizeof(int16_t));
  2170. for (int i = 0; i < n; i++) {
  2171. ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
  2172. }
  2173. } break;
  2174. case GGML_TYPE_I32:
  2175. {
  2176. assert(tensor->nb[0] == sizeof(int32_t));
  2177. for (int i = 0; i < n; i++) {
  2178. ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
  2179. }
  2180. } break;
  2181. case GGML_TYPE_F16:
  2182. {
  2183. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  2184. for (int i = 0; i < n; i++) {
  2185. ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), value);
  2186. }
  2187. } break;
  2188. case GGML_TYPE_F32:
  2189. {
  2190. assert(tensor->nb[0] == sizeof(float));
  2191. for (int i = 0; i < n; i++) {
  2192. ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
  2193. }
  2194. } break;
  2195. case GGML_TYPE_COUNT:
  2196. {
  2197. GGML_ASSERT(false);
  2198. } break;
  2199. }
  2200. return tensor;
  2201. }
  2202. struct ggml_tensor * ggml_set_f32(struct ggml_tensor * tensor, float value) {
  2203. const int n = ggml_nrows(tensor);
  2204. const int nc = tensor->ne[0];
  2205. const size_t n1 = tensor->nb[1];
  2206. char * const data = tensor->data;
  2207. switch (tensor->type) {
  2208. case GGML_TYPE_Q4_0:
  2209. {
  2210. GGML_ASSERT(false);
  2211. } break;
  2212. case GGML_TYPE_Q4_1:
  2213. {
  2214. GGML_ASSERT(false);
  2215. } break;
  2216. case GGML_TYPE_I8:
  2217. {
  2218. assert(tensor->nb[0] == sizeof(int8_t));
  2219. for (int i = 0; i < n; i++) {
  2220. ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
  2221. }
  2222. } break;
  2223. case GGML_TYPE_I16:
  2224. {
  2225. assert(tensor->nb[0] == sizeof(int16_t));
  2226. for (int i = 0; i < n; i++) {
  2227. ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
  2228. }
  2229. } break;
  2230. case GGML_TYPE_I32:
  2231. {
  2232. assert(tensor->nb[0] == sizeof(int32_t));
  2233. for (int i = 0; i < n; i++) {
  2234. ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
  2235. }
  2236. } break;
  2237. case GGML_TYPE_F16:
  2238. {
  2239. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  2240. for (int i = 0; i < n; i++) {
  2241. ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), value);
  2242. }
  2243. } break;
  2244. case GGML_TYPE_F32:
  2245. {
  2246. assert(tensor->nb[0] == sizeof(float));
  2247. for (int i = 0; i < n; i++) {
  2248. ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
  2249. }
  2250. } break;
  2251. case GGML_TYPE_COUNT:
  2252. {
  2253. GGML_ASSERT(false);
  2254. } break;
  2255. }
  2256. return tensor;
  2257. }
  2258. int32_t ggml_get_i32_1d(const struct ggml_tensor * tensor, int i) {
  2259. switch (tensor->type) {
  2260. case GGML_TYPE_Q4_0:
  2261. {
  2262. GGML_ASSERT(false);
  2263. } break;
  2264. case GGML_TYPE_Q4_1:
  2265. {
  2266. GGML_ASSERT(false);
  2267. } break;
  2268. case GGML_TYPE_I8:
  2269. {
  2270. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  2271. return ((int8_t *)(tensor->data))[i];
  2272. } break;
  2273. case GGML_TYPE_I16:
  2274. {
  2275. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  2276. return ((int16_t *)(tensor->data))[i];
  2277. } break;
  2278. case GGML_TYPE_I32:
  2279. {
  2280. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  2281. return ((int32_t *)(tensor->data))[i];
  2282. } break;
  2283. case GGML_TYPE_F16:
  2284. {
  2285. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  2286. return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
  2287. } break;
  2288. case GGML_TYPE_F32:
  2289. {
  2290. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  2291. return ((float *)(tensor->data))[i];
  2292. } break;
  2293. case GGML_TYPE_COUNT:
  2294. {
  2295. GGML_ASSERT(false);
  2296. } break;
  2297. }
  2298. return 0.0f;
  2299. }
  2300. void ggml_set_i32_1d(const struct ggml_tensor * tensor, int i, int32_t value) {
  2301. switch (tensor->type) {
  2302. case GGML_TYPE_Q4_0:
  2303. {
  2304. GGML_ASSERT(false);
  2305. } break;
  2306. case GGML_TYPE_Q4_1:
  2307. {
  2308. GGML_ASSERT(false);
  2309. } break;
  2310. case GGML_TYPE_I8:
  2311. {
  2312. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  2313. ((int8_t *)(tensor->data))[i] = value;
  2314. } break;
  2315. case GGML_TYPE_I16:
  2316. {
  2317. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  2318. ((int16_t *)(tensor->data))[i] = value;
  2319. } break;
  2320. case GGML_TYPE_I32:
  2321. {
  2322. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  2323. ((int32_t *)(tensor->data))[i] = value;
  2324. } break;
  2325. case GGML_TYPE_F16:
  2326. {
  2327. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  2328. ((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
  2329. } break;
  2330. case GGML_TYPE_F32:
  2331. {
  2332. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  2333. ((float *)(tensor->data))[i] = value;
  2334. } break;
  2335. case GGML_TYPE_COUNT:
  2336. {
  2337. GGML_ASSERT(false);
  2338. } break;
  2339. }
  2340. }
  2341. float ggml_get_f32_1d(const struct ggml_tensor * tensor, int i) {
  2342. switch (tensor->type) {
  2343. case GGML_TYPE_Q4_0:
  2344. {
  2345. GGML_ASSERT(false);
  2346. } break;
  2347. case GGML_TYPE_Q4_1:
  2348. {
  2349. GGML_ASSERT(false);
  2350. } break;
  2351. case GGML_TYPE_I8:
  2352. {
  2353. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  2354. return ((int8_t *)(tensor->data))[i];
  2355. } break;
  2356. case GGML_TYPE_I16:
  2357. {
  2358. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  2359. return ((int16_t *)(tensor->data))[i];
  2360. } break;
  2361. case GGML_TYPE_I32:
  2362. {
  2363. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  2364. return ((int32_t *)(tensor->data))[i];
  2365. } break;
  2366. case GGML_TYPE_F16:
  2367. {
  2368. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  2369. return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
  2370. } break;
  2371. case GGML_TYPE_F32:
  2372. {
  2373. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  2374. return ((float *)(tensor->data))[i];
  2375. } break;
  2376. case GGML_TYPE_COUNT:
  2377. {
  2378. GGML_ASSERT(false);
  2379. } break;
  2380. }
  2381. return 0.0f;
  2382. }
  2383. void ggml_set_f32_1d(const struct ggml_tensor * tensor, int i, float value) {
  2384. switch (tensor->type) {
  2385. case GGML_TYPE_Q4_0:
  2386. {
  2387. GGML_ASSERT(false);
  2388. } break;
  2389. case GGML_TYPE_Q4_1:
  2390. {
  2391. GGML_ASSERT(false);
  2392. } break;
  2393. case GGML_TYPE_I8:
  2394. {
  2395. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  2396. ((int8_t *)(tensor->data))[i] = value;
  2397. } break;
  2398. case GGML_TYPE_I16:
  2399. {
  2400. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  2401. ((int16_t *)(tensor->data))[i] = value;
  2402. } break;
  2403. case GGML_TYPE_I32:
  2404. {
  2405. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  2406. ((int32_t *)(tensor->data))[i] = value;
  2407. } break;
  2408. case GGML_TYPE_F16:
  2409. {
  2410. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  2411. ((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
  2412. } break;
  2413. case GGML_TYPE_F32:
  2414. {
  2415. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  2416. ((float *)(tensor->data))[i] = value;
  2417. } break;
  2418. case GGML_TYPE_COUNT:
  2419. {
  2420. GGML_ASSERT(false);
  2421. } break;
  2422. }
  2423. }
  2424. void * ggml_get_data(const struct ggml_tensor * tensor) {
  2425. return tensor->data;
  2426. }
  2427. float * ggml_get_data_f32(const struct ggml_tensor * tensor) {
  2428. assert(tensor->type == GGML_TYPE_F32);
  2429. return (float *)(tensor->data);
  2430. }
  2431. struct ggml_tensor * ggml_view_tensor(
  2432. struct ggml_context * ctx,
  2433. const struct ggml_tensor * src) {
  2434. return ggml_new_tensor_impl(ctx, src->type, src->n_dims, src->ne, src->data);
  2435. }
  2436. ////////////////////////////////////////////////////////////////////////////////
  2437. // ggml_dup
  2438. struct ggml_tensor * ggml_dup_impl(
  2439. struct ggml_context * ctx,
  2440. struct ggml_tensor * a,
  2441. bool inplace) {
  2442. bool is_node = false;
  2443. if (!inplace && (a->grad)) {
  2444. is_node = true;
  2445. }
  2446. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2447. result->op = GGML_OP_DUP;
  2448. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2449. result->src0 = a;
  2450. result->src1 = NULL;
  2451. return result;
  2452. }
  2453. struct ggml_tensor * ggml_dup(
  2454. struct ggml_context * ctx,
  2455. struct ggml_tensor * a) {
  2456. return ggml_dup_impl(ctx, a, false);
  2457. }
  2458. struct ggml_tensor * ggml_dup_inplace(
  2459. struct ggml_context * ctx,
  2460. struct ggml_tensor * a) {
  2461. return ggml_dup_impl(ctx, a, true);
  2462. }
  2463. // ggml_add
  2464. struct ggml_tensor * ggml_add_impl(
  2465. struct ggml_context * ctx,
  2466. struct ggml_tensor * a,
  2467. struct ggml_tensor * b,
  2468. bool inplace) {
  2469. GGML_ASSERT(ggml_are_same_shape(a, b));
  2470. bool is_node = false;
  2471. if (!inplace && (a->grad || b->grad)) {
  2472. is_node = true;
  2473. }
  2474. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2475. result->op = GGML_OP_ADD;
  2476. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2477. result->src0 = a;
  2478. result->src1 = b;
  2479. return result;
  2480. }
  2481. struct ggml_tensor * ggml_add(
  2482. struct ggml_context * ctx,
  2483. struct ggml_tensor * a,
  2484. struct ggml_tensor * b) {
  2485. return ggml_add_impl(ctx, a, b, false);
  2486. }
  2487. struct ggml_tensor * ggml_add_inplace(
  2488. struct ggml_context * ctx,
  2489. struct ggml_tensor * a,
  2490. struct ggml_tensor * b) {
  2491. return ggml_add_impl(ctx, a, b, true);
  2492. }
  2493. // ggml_sub
  2494. struct ggml_tensor * ggml_sub_impl(
  2495. struct ggml_context * ctx,
  2496. struct ggml_tensor * a,
  2497. struct ggml_tensor * b,
  2498. bool inplace) {
  2499. GGML_ASSERT(ggml_are_same_shape(a, b));
  2500. bool is_node = false;
  2501. if (!inplace && (a->grad || b->grad)) {
  2502. is_node = true;
  2503. }
  2504. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2505. result->op = GGML_OP_SUB;
  2506. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2507. result->src0 = a;
  2508. result->src1 = b;
  2509. return result;
  2510. }
  2511. struct ggml_tensor * ggml_sub(
  2512. struct ggml_context * ctx,
  2513. struct ggml_tensor * a,
  2514. struct ggml_tensor * b) {
  2515. return ggml_sub_impl(ctx, a, b, false);
  2516. }
  2517. struct ggml_tensor * ggml_sub_inplace(
  2518. struct ggml_context * ctx,
  2519. struct ggml_tensor * a,
  2520. struct ggml_tensor * b) {
  2521. return ggml_sub_impl(ctx, a, b, true);
  2522. }
  2523. // ggml_mul
  2524. struct ggml_tensor * ggml_mul_impl(
  2525. struct ggml_context * ctx,
  2526. struct ggml_tensor * a,
  2527. struct ggml_tensor * b,
  2528. bool inplace) {
  2529. GGML_ASSERT(ggml_are_same_shape(a, b));
  2530. bool is_node = false;
  2531. if (!inplace && (a->grad || b->grad)) {
  2532. is_node = true;
  2533. }
  2534. if (inplace) {
  2535. GGML_ASSERT(is_node == false);
  2536. }
  2537. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2538. result->op = GGML_OP_MUL;
  2539. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2540. result->src0 = a;
  2541. result->src1 = b;
  2542. return result;
  2543. }
  2544. struct ggml_tensor * ggml_mul(
  2545. struct ggml_context * ctx,
  2546. struct ggml_tensor * a,
  2547. struct ggml_tensor * b) {
  2548. return ggml_mul_impl(ctx, a, b, false);
  2549. }
  2550. struct ggml_tensor * ggml_mul_inplace(
  2551. struct ggml_context * ctx,
  2552. struct ggml_tensor * a,
  2553. struct ggml_tensor * b) {
  2554. return ggml_mul_impl(ctx, a, b, true);
  2555. }
  2556. // ggml_div
  2557. struct ggml_tensor * ggml_div_impl(
  2558. struct ggml_context * ctx,
  2559. struct ggml_tensor * a,
  2560. struct ggml_tensor * b,
  2561. bool inplace) {
  2562. GGML_ASSERT(ggml_are_same_shape(a, b));
  2563. bool is_node = false;
  2564. if (!inplace && (a->grad || b->grad)) {
  2565. is_node = true;
  2566. }
  2567. if (inplace) {
  2568. GGML_ASSERT(is_node == false);
  2569. }
  2570. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2571. result->op = GGML_OP_DIV;
  2572. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2573. result->src0 = a;
  2574. result->src1 = b;
  2575. return result;
  2576. }
  2577. struct ggml_tensor * ggml_div(
  2578. struct ggml_context * ctx,
  2579. struct ggml_tensor * a,
  2580. struct ggml_tensor * b) {
  2581. return ggml_div_impl(ctx, a, b, false);
  2582. }
  2583. struct ggml_tensor * ggml_div_inplace(
  2584. struct ggml_context * ctx,
  2585. struct ggml_tensor * a,
  2586. struct ggml_tensor * b) {
  2587. return ggml_div_impl(ctx, a, b, true);
  2588. }
  2589. // ggml_sqr
  2590. struct ggml_tensor * ggml_sqr_impl(
  2591. struct ggml_context * ctx,
  2592. struct ggml_tensor * a,
  2593. bool inplace) {
  2594. bool is_node = false;
  2595. if (!inplace && (a->grad)) {
  2596. is_node = true;
  2597. }
  2598. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2599. result->op = GGML_OP_SQR;
  2600. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2601. result->src0 = a;
  2602. result->src1 = NULL;
  2603. return result;
  2604. }
  2605. struct ggml_tensor * ggml_sqr(
  2606. struct ggml_context * ctx,
  2607. struct ggml_tensor * a) {
  2608. return ggml_sqr_impl(ctx, a, false);
  2609. }
  2610. struct ggml_tensor * ggml_sqr_inplace(
  2611. struct ggml_context * ctx,
  2612. struct ggml_tensor * a) {
  2613. return ggml_sqr_impl(ctx, a, true);
  2614. }
  2615. // ggml_sqrt
  2616. struct ggml_tensor * ggml_sqrt_impl(
  2617. struct ggml_context * ctx,
  2618. struct ggml_tensor * a,
  2619. bool inplace) {
  2620. bool is_node = false;
  2621. if (!inplace && (a->grad)) {
  2622. is_node = true;
  2623. }
  2624. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2625. result->op = GGML_OP_SQRT;
  2626. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2627. result->src0 = a;
  2628. result->src1 = NULL;
  2629. return result;
  2630. }
  2631. struct ggml_tensor * ggml_sqrt(
  2632. struct ggml_context * ctx,
  2633. struct ggml_tensor * a) {
  2634. return ggml_sqrt_impl(ctx, a, false);
  2635. }
  2636. struct ggml_tensor * ggml_sqrt_inplace(
  2637. struct ggml_context * ctx,
  2638. struct ggml_tensor * a) {
  2639. return ggml_sqrt_impl(ctx, a, true);
  2640. }
  2641. // ggml_sum
  2642. struct ggml_tensor * ggml_sum(
  2643. struct ggml_context * ctx,
  2644. struct ggml_tensor * a) {
  2645. bool is_node = false;
  2646. if (a->grad) {
  2647. is_node = true;
  2648. }
  2649. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  2650. result->op = GGML_OP_SUM;
  2651. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2652. result->src0 = a;
  2653. result->src1 = NULL;
  2654. return result;
  2655. }
  2656. // ggml_mean
  2657. struct ggml_tensor * ggml_mean(
  2658. struct ggml_context * ctx,
  2659. struct ggml_tensor * a) {
  2660. bool is_node = false;
  2661. if (a->grad) {
  2662. GGML_ASSERT(false); // TODO: implement
  2663. is_node = true;
  2664. }
  2665. int ne[GGML_MAX_DIMS] = { 1, a->ne[1], a->ne[2], a->ne[3] };
  2666. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, a->n_dims, ne);
  2667. result->op = GGML_OP_MEAN;
  2668. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2669. result->src0 = a;
  2670. result->src1 = NULL;
  2671. return result;
  2672. }
  2673. // ggml_repeat
  2674. struct ggml_tensor * ggml_repeat(
  2675. struct ggml_context * ctx,
  2676. struct ggml_tensor * a,
  2677. struct ggml_tensor * b) {
  2678. GGML_ASSERT(ggml_can_repeat(a, b));
  2679. bool is_node = false;
  2680. if (a->grad) {
  2681. is_node = true;
  2682. }
  2683. if (ggml_are_same_shape(a, b) && !is_node) {
  2684. return a;
  2685. }
  2686. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, b->n_dims, b->ne);
  2687. result->op = GGML_OP_REPEAT;
  2688. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2689. result->src0 = a;
  2690. result->src1 = b;
  2691. return result;
  2692. }
  2693. // ggml_abs
  2694. struct ggml_tensor * ggml_abs_impl(
  2695. struct ggml_context * ctx,
  2696. struct ggml_tensor * a,
  2697. bool inplace) {
  2698. bool is_node = false;
  2699. if (!inplace && (a->grad)) {
  2700. is_node = true;
  2701. }
  2702. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2703. result->op = GGML_OP_ABS;
  2704. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2705. result->src0 = a;
  2706. result->src1 = NULL;
  2707. return result;
  2708. }
  2709. struct ggml_tensor * ggml_abs(
  2710. struct ggml_context * ctx,
  2711. struct ggml_tensor * a) {
  2712. return ggml_abs_impl(ctx, a, false);
  2713. }
  2714. struct ggml_tensor * ggml_abs_inplace(
  2715. struct ggml_context * ctx,
  2716. struct ggml_tensor * a) {
  2717. return ggml_abs_impl(ctx, a, true);
  2718. }
  2719. // ggml_sgn
  2720. struct ggml_tensor * ggml_sgn_impl(
  2721. struct ggml_context * ctx,
  2722. struct ggml_tensor * a,
  2723. bool inplace) {
  2724. bool is_node = false;
  2725. if (!inplace && (a->grad)) {
  2726. is_node = true;
  2727. }
  2728. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2729. result->op = GGML_OP_SGN;
  2730. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2731. result->src0 = a;
  2732. result->src1 = NULL;
  2733. return result;
  2734. }
  2735. struct ggml_tensor * ggml_sgn(
  2736. struct ggml_context * ctx,
  2737. struct ggml_tensor * a) {
  2738. return ggml_sgn_impl(ctx, a, false);
  2739. }
  2740. struct ggml_tensor * ggml_sgn_inplace(
  2741. struct ggml_context * ctx,
  2742. struct ggml_tensor * a) {
  2743. return ggml_sgn_impl(ctx, a, true);
  2744. }
  2745. // ggml_neg
  2746. struct ggml_tensor * ggml_neg_impl(
  2747. struct ggml_context * ctx,
  2748. struct ggml_tensor * a,
  2749. bool inplace) {
  2750. bool is_node = false;
  2751. if (!inplace && (a->grad)) {
  2752. is_node = true;
  2753. }
  2754. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2755. result->op = GGML_OP_NEG;
  2756. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2757. result->src0 = a;
  2758. result->src1 = NULL;
  2759. return result;
  2760. }
  2761. struct ggml_tensor * ggml_neg(
  2762. struct ggml_context * ctx,
  2763. struct ggml_tensor * a) {
  2764. return ggml_neg_impl(ctx, a, false);
  2765. }
  2766. struct ggml_tensor * ggml_neg_inplace(
  2767. struct ggml_context * ctx,
  2768. struct ggml_tensor * a) {
  2769. return ggml_neg_impl(ctx, a, true);
  2770. }
  2771. // ggml_step
  2772. struct ggml_tensor * ggml_step_impl(
  2773. struct ggml_context * ctx,
  2774. struct ggml_tensor * a,
  2775. bool inplace) {
  2776. bool is_node = false;
  2777. if (!inplace && (a->grad)) {
  2778. is_node = true;
  2779. }
  2780. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2781. result->op = GGML_OP_STEP;
  2782. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2783. result->src0 = a;
  2784. result->src1 = NULL;
  2785. return result;
  2786. }
  2787. struct ggml_tensor * ggml_step(
  2788. struct ggml_context * ctx,
  2789. struct ggml_tensor * a) {
  2790. return ggml_step_impl(ctx, a, false);
  2791. }
  2792. struct ggml_tensor * ggml_step_inplace(
  2793. struct ggml_context * ctx,
  2794. struct ggml_tensor * a) {
  2795. return ggml_step_impl(ctx, a, true);
  2796. }
  2797. // ggml_relu
  2798. struct ggml_tensor * ggml_relu_impl(
  2799. struct ggml_context * ctx,
  2800. struct ggml_tensor * a,
  2801. bool inplace) {
  2802. bool is_node = false;
  2803. if (!inplace && (a->grad)) {
  2804. is_node = true;
  2805. }
  2806. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2807. result->op = GGML_OP_RELU;
  2808. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2809. result->src0 = a;
  2810. result->src1 = NULL;
  2811. return result;
  2812. }
  2813. struct ggml_tensor * ggml_relu(
  2814. struct ggml_context * ctx,
  2815. struct ggml_tensor * a) {
  2816. return ggml_relu_impl(ctx, a, false);
  2817. }
  2818. struct ggml_tensor * ggml_relu_inplace(
  2819. struct ggml_context * ctx,
  2820. struct ggml_tensor * a) {
  2821. return ggml_relu_impl(ctx, a, true);
  2822. }
  2823. // ggml_gelu
  2824. struct ggml_tensor * ggml_gelu_impl(
  2825. struct ggml_context * ctx,
  2826. struct ggml_tensor * a,
  2827. bool inplace) {
  2828. bool is_node = false;
  2829. if (!inplace && (a->grad)) {
  2830. is_node = true;
  2831. }
  2832. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2833. result->op = GGML_OP_GELU;
  2834. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2835. result->src0 = a;
  2836. result->src1 = NULL;
  2837. return result;
  2838. }
  2839. struct ggml_tensor * ggml_gelu(
  2840. struct ggml_context * ctx,
  2841. struct ggml_tensor * a) {
  2842. return ggml_gelu_impl(ctx, a, false);
  2843. }
  2844. struct ggml_tensor * ggml_gelu_inplace(
  2845. struct ggml_context * ctx,
  2846. struct ggml_tensor * a) {
  2847. return ggml_gelu_impl(ctx, a, true);
  2848. }
  2849. // ggml_silu
  2850. struct ggml_tensor * ggml_silu_impl(
  2851. struct ggml_context * ctx,
  2852. struct ggml_tensor * a,
  2853. bool inplace) {
  2854. bool is_node = false;
  2855. if (!inplace && (a->grad)) {
  2856. is_node = true;
  2857. }
  2858. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2859. result->op = GGML_OP_SILU;
  2860. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2861. result->src0 = a;
  2862. result->src1 = NULL;
  2863. return result;
  2864. }
  2865. struct ggml_tensor * ggml_silu(
  2866. struct ggml_context * ctx,
  2867. struct ggml_tensor * a) {
  2868. return ggml_silu_impl(ctx, a, false);
  2869. }
  2870. struct ggml_tensor * ggml_silu_inplace(
  2871. struct ggml_context * ctx,
  2872. struct ggml_tensor * a) {
  2873. return ggml_silu_impl(ctx, a, true);
  2874. }
  2875. // ggml_norm
  2876. struct ggml_tensor * ggml_norm_impl(
  2877. struct ggml_context * ctx,
  2878. struct ggml_tensor * a,
  2879. bool inplace) {
  2880. bool is_node = false;
  2881. if (!inplace && (a->grad)) {
  2882. GGML_ASSERT(false); // TODO: implement backward
  2883. is_node = true;
  2884. }
  2885. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2886. result->op = GGML_OP_NORM;
  2887. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2888. result->src0 = a;
  2889. result->src1 = NULL; // TODO: maybe store epsilon here?
  2890. return result;
  2891. }
  2892. struct ggml_tensor * ggml_norm(
  2893. struct ggml_context * ctx,
  2894. struct ggml_tensor * a) {
  2895. return ggml_norm_impl(ctx, a, false);
  2896. }
  2897. struct ggml_tensor * ggml_norm_inplace(
  2898. struct ggml_context * ctx,
  2899. struct ggml_tensor * a) {
  2900. return ggml_norm_impl(ctx, a, true);
  2901. }
  2902. struct ggml_tensor * ggml_rms_norm_impl(
  2903. struct ggml_context * ctx,
  2904. struct ggml_tensor * a,
  2905. bool inplace) {
  2906. bool is_node = false;
  2907. if (!inplace && (a->grad)) {
  2908. GGML_ASSERT(false); // TODO: implement backward
  2909. is_node = true;
  2910. }
  2911. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2912. result->op = GGML_OP_RMS_NORM;
  2913. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2914. result->src0 = a;
  2915. result->src1 = NULL; // TODO: maybe store epsilon here?
  2916. return result;
  2917. }
  2918. struct ggml_tensor * ggml_rms_norm(
  2919. struct ggml_context * ctx,
  2920. struct ggml_tensor * a) {
  2921. return ggml_rms_norm_impl(ctx, a, false);
  2922. }
  2923. struct ggml_tensor * ggml_rms_norm_inplace(
  2924. struct ggml_context * ctx,
  2925. struct ggml_tensor * a) {
  2926. return ggml_rms_norm_impl(ctx, a, true);
  2927. }
  2928. // ggml_mul_mat
  2929. struct ggml_tensor * ggml_mul_mat(
  2930. struct ggml_context * ctx,
  2931. struct ggml_tensor * a,
  2932. struct ggml_tensor * b) {
  2933. GGML_ASSERT(ggml_can_mul_mat(a, b));
  2934. bool is_node = false;
  2935. if (a->grad || b->grad) {
  2936. is_node = true;
  2937. }
  2938. const int ne[4] = { a->ne[1], b->ne[1], a->ne[2], b->ne[3] };
  2939. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, MIN(a->n_dims, b->n_dims), ne);
  2940. result->op = GGML_OP_MUL_MAT;
  2941. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2942. result->src0 = a;
  2943. result->src1 = b;
  2944. return result;
  2945. }
  2946. // ggml_scale
  2947. struct ggml_tensor * ggml_scale_impl(
  2948. struct ggml_context * ctx,
  2949. struct ggml_tensor * a,
  2950. struct ggml_tensor * b,
  2951. bool inplace) {
  2952. GGML_ASSERT(ggml_is_scalar(b));
  2953. GGML_ASSERT(ggml_is_padded_1d(a));
  2954. bool is_node = false;
  2955. if (!inplace && (a->grad || b->grad)) {
  2956. GGML_ASSERT(false); // TODO: implement backward
  2957. is_node = true;
  2958. }
  2959. // TODO: when implement backward, fix this:
  2960. //struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2961. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  2962. result->op = GGML_OP_SCALE;
  2963. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2964. result->src0 = a;
  2965. result->src1 = b;
  2966. return result;
  2967. }
  2968. struct ggml_tensor * ggml_scale(
  2969. struct ggml_context * ctx,
  2970. struct ggml_tensor * a,
  2971. struct ggml_tensor * b) {
  2972. return ggml_scale_impl(ctx, a, b, false);
  2973. }
  2974. struct ggml_tensor * ggml_scale_inplace(
  2975. struct ggml_context * ctx,
  2976. struct ggml_tensor * a,
  2977. struct ggml_tensor * b) {
  2978. return ggml_scale_impl(ctx, a, b, true);
  2979. }
  2980. // ggml_cpy
  2981. struct ggml_tensor * ggml_cpy_impl(
  2982. struct ggml_context * ctx,
  2983. struct ggml_tensor * a,
  2984. struct ggml_tensor * b,
  2985. bool inplace) {
  2986. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  2987. bool is_node = false;
  2988. if (!inplace && (a->grad || b->grad)) {
  2989. GGML_ASSERT(false); // TODO: implement backward
  2990. is_node = true;
  2991. }
  2992. // make a view of the destination
  2993. struct ggml_tensor * result = ggml_view_tensor(ctx, b);
  2994. result->op = GGML_OP_CPY;
  2995. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  2996. result->src0 = a;
  2997. result->src1 = b;
  2998. return result;
  2999. }
  3000. struct ggml_tensor * ggml_cpy(
  3001. struct ggml_context * ctx,
  3002. struct ggml_tensor * a,
  3003. struct ggml_tensor * b) {
  3004. return ggml_cpy_impl(ctx, a, b, false);
  3005. }
  3006. struct ggml_tensor * ggml_cpy_inplace(
  3007. struct ggml_context * ctx,
  3008. struct ggml_tensor * a,
  3009. struct ggml_tensor * b) {
  3010. return ggml_cpy_impl(ctx, a, b, true);
  3011. }
  3012. // ggml_reshape
  3013. struct ggml_tensor * ggml_reshape(
  3014. struct ggml_context * ctx,
  3015. struct ggml_tensor * a,
  3016. struct ggml_tensor * b) {
  3017. GGML_ASSERT(ggml_is_contiguous(a));
  3018. GGML_ASSERT(ggml_is_contiguous(b));
  3019. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  3020. bool is_node = false;
  3021. if (a->grad || b->grad) {
  3022. GGML_ASSERT(false); // TODO: implement backward
  3023. is_node = true;
  3024. }
  3025. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, b->n_dims, b->ne, a->data);
  3026. result->op = GGML_OP_RESHAPE;
  3027. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3028. result->src0 = a;
  3029. result->src1 = NULL;
  3030. return result;
  3031. }
  3032. struct ggml_tensor * ggml_reshape_2d(
  3033. struct ggml_context * ctx,
  3034. struct ggml_tensor * a,
  3035. int ne0,
  3036. int ne1) {
  3037. GGML_ASSERT(ggml_is_contiguous(a));
  3038. GGML_ASSERT(ggml_nelements(a) == ne0*ne1);
  3039. bool is_node = false;
  3040. if (a->grad) {
  3041. GGML_ASSERT(false); // TODO: implement backward
  3042. is_node = true;
  3043. }
  3044. const int ne[2] = { ne0, ne1 };
  3045. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, a->data);
  3046. result->op = GGML_OP_RESHAPE;
  3047. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3048. result->src0 = a;
  3049. result->src1 = NULL;
  3050. return result;
  3051. }
  3052. struct ggml_tensor * ggml_reshape_3d(
  3053. struct ggml_context * ctx,
  3054. struct ggml_tensor * a,
  3055. int ne0,
  3056. int ne1,
  3057. int ne2) {
  3058. GGML_ASSERT(ggml_is_contiguous(a));
  3059. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2);
  3060. bool is_node = false;
  3061. if (a->grad) {
  3062. GGML_ASSERT(false); // TODO: implement backward
  3063. is_node = true;
  3064. }
  3065. const int ne[3] = { ne0, ne1, ne2 };
  3066. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 3, ne, a->data);
  3067. result->op = GGML_OP_RESHAPE;
  3068. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3069. result->src0 = a;
  3070. result->src1 = NULL;
  3071. return result;
  3072. }
  3073. // ggml_view_1d
  3074. struct ggml_tensor * ggml_view_1d(
  3075. struct ggml_context * ctx,
  3076. struct ggml_tensor * a,
  3077. int ne0,
  3078. size_t offset) {
  3079. if (a->grad) {
  3080. GGML_ASSERT(false); // gradient propagation is not supported
  3081. }
  3082. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 1, &ne0, (char *) a->data + offset);
  3083. result->op = GGML_OP_VIEW;
  3084. result->grad = NULL;
  3085. result->src0 = a;
  3086. result->src1 = NULL; // TODO: maybe store the offset here?
  3087. return result;
  3088. }
  3089. // ggml_view_2d
  3090. struct ggml_tensor * ggml_view_2d(
  3091. struct ggml_context * ctx,
  3092. struct ggml_tensor * a,
  3093. int ne0,
  3094. int ne1,
  3095. size_t nb1,
  3096. size_t offset) {
  3097. if (a->grad) {
  3098. GGML_ASSERT(false); // gradient propagation is not supported
  3099. }
  3100. const int ne[GGML_MAX_DIMS] = { ne0, ne1, 1, 1 };
  3101. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, (char *) a->data + offset);
  3102. result->nb[1] = nb1;
  3103. result->nb[2] = result->nb[1]*ne1;
  3104. result->nb[3] = result->nb[2];
  3105. result->op = GGML_OP_VIEW;
  3106. result->grad = NULL;
  3107. result->src0 = a;
  3108. result->src1 = NULL; // TODO: maybe store the offset here?
  3109. return result;
  3110. }
  3111. // ggml_permute
  3112. struct ggml_tensor * ggml_permute(
  3113. struct ggml_context * ctx,
  3114. struct ggml_tensor * a,
  3115. int axis0,
  3116. int axis1,
  3117. int axis2,
  3118. int axis3) {
  3119. GGML_ASSERT(axis0 >= 0 && axis0 < GGML_MAX_DIMS);
  3120. GGML_ASSERT(axis1 >= 0 && axis1 < GGML_MAX_DIMS);
  3121. GGML_ASSERT(axis2 >= 0 && axis2 < GGML_MAX_DIMS);
  3122. GGML_ASSERT(axis3 >= 0 && axis3 < GGML_MAX_DIMS);
  3123. GGML_ASSERT(axis0 != axis1);
  3124. GGML_ASSERT(axis0 != axis2);
  3125. GGML_ASSERT(axis0 != axis3);
  3126. GGML_ASSERT(axis1 != axis2);
  3127. GGML_ASSERT(axis1 != axis3);
  3128. GGML_ASSERT(axis2 != axis3);
  3129. bool is_node = false;
  3130. if (a->grad) {
  3131. GGML_ASSERT(false); // TODO: implement backward
  3132. is_node = true;
  3133. }
  3134. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  3135. int ne[GGML_MAX_DIMS];
  3136. int nb[GGML_MAX_DIMS];
  3137. ne[axis0] = a->ne[0];
  3138. ne[axis1] = a->ne[1];
  3139. ne[axis2] = a->ne[2];
  3140. ne[axis3] = a->ne[3];
  3141. nb[axis0] = a->nb[0];
  3142. nb[axis1] = a->nb[1];
  3143. nb[axis2] = a->nb[2];
  3144. nb[axis3] = a->nb[3];
  3145. result->ne[0] = ne[0];
  3146. result->ne[1] = ne[1];
  3147. result->ne[2] = ne[2];
  3148. result->ne[3] = ne[3];
  3149. result->nb[0] = nb[0];
  3150. result->nb[1] = nb[1];
  3151. result->nb[2] = nb[2];
  3152. result->nb[3] = nb[3];
  3153. result->op = GGML_OP_PERMUTE;
  3154. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3155. result->src0 = a;
  3156. result->src1 = NULL; // TODO: maybe store the permutation here?
  3157. return result;
  3158. }
  3159. // ggml_transpose
  3160. struct ggml_tensor * ggml_transpose(
  3161. struct ggml_context * ctx,
  3162. struct ggml_tensor * a) {
  3163. bool is_node = false;
  3164. if (a->grad) {
  3165. GGML_ASSERT(false); // TODO: implement backward
  3166. is_node = true;
  3167. }
  3168. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  3169. result->ne[0] = a->ne[1];
  3170. result->ne[1] = a->ne[0];
  3171. result->nb[0] = a->nb[1];
  3172. result->nb[1] = a->nb[0];
  3173. result->op = GGML_OP_TRANSPOSE;
  3174. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3175. result->src0 = a;
  3176. result->src1 = NULL;
  3177. return result;
  3178. }
  3179. // ggml_get_rows
  3180. struct ggml_tensor * ggml_get_rows(
  3181. struct ggml_context * ctx,
  3182. struct ggml_tensor * a,
  3183. struct ggml_tensor * b) {
  3184. GGML_ASSERT(ggml_is_matrix(a) && ggml_is_vector(b) && b->type == GGML_TYPE_I32);
  3185. bool is_node = false;
  3186. if (a->grad || b->grad) {
  3187. GGML_ASSERT(false); // TODO: implement backward
  3188. is_node = true;
  3189. }
  3190. // TODO: implement non F32 return
  3191. //struct ggml_tensor * result = ggml_new_tensor_2d(ctx, a->type, a->ne[0], b->ne[0]);
  3192. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, a->ne[0], b->ne[0]);
  3193. result->op = GGML_OP_GET_ROWS;
  3194. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3195. result->src0 = a;
  3196. result->src1 = b;
  3197. return result;
  3198. }
  3199. // ggml_diag_mask_inf
  3200. struct ggml_tensor * ggml_diag_mask_inf(
  3201. struct ggml_context * ctx,
  3202. struct ggml_tensor * a,
  3203. int n_past) {
  3204. bool is_node = false;
  3205. if (a->grad) {
  3206. GGML_ASSERT(false); // TODO: implement backward
  3207. is_node = true;
  3208. }
  3209. // TODO: when implement backward, fix this:
  3210. //struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3211. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  3212. struct ggml_tensor * b = ggml_new_i32(ctx, n_past);
  3213. result->op = GGML_OP_DIAG_MASK_INF;
  3214. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3215. result->src0 = a;
  3216. result->src1 = b;
  3217. return result;
  3218. }
  3219. // ggml_soft_max
  3220. struct ggml_tensor * ggml_soft_max(
  3221. struct ggml_context * ctx,
  3222. struct ggml_tensor * a) {
  3223. bool is_node = false;
  3224. if (a->grad) {
  3225. GGML_ASSERT(false); // TODO: implement backward
  3226. is_node = true;
  3227. }
  3228. // TODO: when implement backward, fix this:
  3229. //struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3230. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  3231. result->op = GGML_OP_SOFT_MAX;
  3232. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3233. result->src0 = a;
  3234. result->src1 = NULL;
  3235. return result;
  3236. }
  3237. // ggml_rope
  3238. struct ggml_tensor * ggml_rope(
  3239. struct ggml_context * ctx,
  3240. struct ggml_tensor * a,
  3241. int n_past,
  3242. int n_dims,
  3243. int mode) {
  3244. GGML_ASSERT(n_past >= 0);
  3245. bool is_node = false;
  3246. if (a->grad) {
  3247. GGML_ASSERT(false); // TODO: implement backward
  3248. is_node = true;
  3249. }
  3250. // TODO: when implement backward, fix this:
  3251. //struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3252. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  3253. struct ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 3);
  3254. ((int32_t *) b->data)[0] = n_past;
  3255. ((int32_t *) b->data)[1] = n_dims;
  3256. ((int32_t *) b->data)[2] = mode;
  3257. result->op = GGML_OP_ROPE;
  3258. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3259. result->src0 = a;
  3260. result->src1 = b;
  3261. return result;
  3262. }
  3263. // ggml_conv_1d_1s
  3264. struct ggml_tensor * ggml_conv_1d_1s(
  3265. struct ggml_context * ctx,
  3266. struct ggml_tensor * a,
  3267. struct ggml_tensor * b) {
  3268. GGML_ASSERT(ggml_is_matrix(b));
  3269. GGML_ASSERT(a->ne[1] == b->ne[1]);
  3270. GGML_ASSERT(a->ne[3] == 1);
  3271. bool is_node = false;
  3272. if (a->grad || b->grad) {
  3273. GGML_ASSERT(false); // TODO: implement backward
  3274. is_node = true;
  3275. }
  3276. const int ne[4] = { b->ne[0], a->ne[2], 1, 1, };
  3277. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 2, ne);
  3278. result->op = GGML_OP_CONV_1D_1S;
  3279. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3280. result->src0 = a;
  3281. result->src1 = b;
  3282. return result;
  3283. }
  3284. // ggml_conv_1d_2s
  3285. struct ggml_tensor * ggml_conv_1d_2s(
  3286. struct ggml_context * ctx,
  3287. struct ggml_tensor * a,
  3288. struct ggml_tensor * b) {
  3289. GGML_ASSERT(ggml_is_matrix(b));
  3290. GGML_ASSERT(a->ne[1] == b->ne[1]);
  3291. GGML_ASSERT(a->ne[3] == 1);
  3292. bool is_node = false;
  3293. if (a->grad || b->grad) {
  3294. GGML_ASSERT(false); // TODO: implement backward
  3295. is_node = true;
  3296. }
  3297. const int ne[4] = { b->ne[0]/2, a->ne[2], 1, 1, };
  3298. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 2, ne);
  3299. result->op = GGML_OP_CONV_1D_2S;
  3300. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3301. result->src0 = a;
  3302. result->src1 = b;
  3303. return result;
  3304. }
  3305. // ggml_flash_attn
  3306. struct ggml_tensor * ggml_flash_attn(
  3307. struct ggml_context * ctx,
  3308. struct ggml_tensor * q,
  3309. struct ggml_tensor * k,
  3310. struct ggml_tensor * v,
  3311. bool masked) {
  3312. GGML_ASSERT(ggml_can_mul_mat(k, q));
  3313. // TODO: check if vT can be multiplied by (k*qT)
  3314. bool is_node = false;
  3315. if (q->grad || k->grad || v->grad) {
  3316. GGML_ASSERT(false); // TODO: implement backward
  3317. is_node = true;
  3318. }
  3319. //struct ggml_tensor * result = ggml_dup_tensor(ctx, q);
  3320. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, q->ne);
  3321. result->op = GGML_OP_FLASH_ATTN;
  3322. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3323. result->src0 = q;
  3324. result->src1 = k;
  3325. result->opt[0] = v;
  3326. result->opt[1] = ggml_new_i32(ctx, masked ? 1 : 0);
  3327. return result;
  3328. }
  3329. // ggml_flash_ff
  3330. struct ggml_tensor * ggml_flash_ff(
  3331. struct ggml_context * ctx,
  3332. struct ggml_tensor * a,
  3333. struct ggml_tensor * b0,
  3334. struct ggml_tensor * b1,
  3335. struct ggml_tensor * c0,
  3336. struct ggml_tensor * c1) {
  3337. GGML_ASSERT(ggml_can_mul_mat(b0, a));
  3338. // TODO: more checks
  3339. bool is_node = false;
  3340. if (a->grad || b0->grad || b1->grad || c0->grad || c1->grad) {
  3341. GGML_ASSERT(false); // TODO: implement backward
  3342. is_node = true;
  3343. }
  3344. //struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  3345. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, a->ne);
  3346. result->op = GGML_OP_FLASH_FF;
  3347. result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
  3348. result->src0 = a;
  3349. result->src1 = b0;
  3350. result->opt[0] = b1;
  3351. result->opt[1] = c0;
  3352. result->opt[2] = c1;
  3353. return result;
  3354. }
  3355. ////////////////////////////////////////////////////////////////////////////////
  3356. void ggml_set_param(
  3357. struct ggml_context * ctx,
  3358. struct ggml_tensor * tensor) {
  3359. tensor->is_param = true;
  3360. GGML_ASSERT(tensor->grad == NULL);
  3361. tensor->grad = ggml_dup_tensor(ctx, tensor);
  3362. }
  3363. // ggml_compute_forward_dup
  3364. static void ggml_compute_forward_dup_f16(
  3365. const struct ggml_compute_params * params,
  3366. const struct ggml_tensor * src0,
  3367. struct ggml_tensor * dst) {
  3368. GGML_ASSERT(params->ith == 0);
  3369. GGML_ASSERT(ggml_is_contiguous(dst));
  3370. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  3371. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3372. return;
  3373. }
  3374. const int ne00 = src0->ne[0];
  3375. const int ne01 = src0->ne[1];
  3376. const int ne02 = src0->ne[2];
  3377. const int ne03 = src0->ne[3];
  3378. const size_t nb00 = src0->nb[0];
  3379. const size_t nb01 = src0->nb[1];
  3380. const size_t nb02 = src0->nb[2];
  3381. const size_t nb03 = src0->nb[3];
  3382. if (ggml_is_contiguous(src0) && src0->type == dst->type) {
  3383. memcpy(dst->data, src0->data, ggml_nelements(dst) * GGML_TYPE_SIZE[src0->type]);
  3384. return;
  3385. }
  3386. if (src0->nb[0] == sizeof(ggml_fp16_t)) {
  3387. if (dst->type == GGML_TYPE_F16) {
  3388. int id = 0;
  3389. const size_t rs = ne00*nb00;
  3390. for (int i03 = 0; i03 < ne03; i03++) {
  3391. for (int i02 = 0; i02 < ne02; i02++) {
  3392. for (int i01 = 0; i01 < ne01; i01++) {
  3393. const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  3394. char * dst_ptr = (char *) dst->data + id*rs;
  3395. memcpy(dst_ptr, src0_ptr, rs);
  3396. id++;
  3397. }
  3398. }
  3399. }
  3400. } else if (dst->type == GGML_TYPE_F32) {
  3401. int id = 0;
  3402. float * dst_ptr = (float *) dst->data;
  3403. for (int i03 = 0; i03 < ne03; i03++) {
  3404. for (int i02 = 0; i02 < ne02; i02++) {
  3405. for (int i01 = 0; i01 < ne01; i01++) {
  3406. for (int i00 = 0; i00 < ne00; i00++) {
  3407. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  3408. dst_ptr[id] = GGML_FP16_TO_FP32(*src0_ptr);
  3409. id++;
  3410. }
  3411. }
  3412. }
  3413. }
  3414. } else {
  3415. GGML_ASSERT(false); // TODO: implement
  3416. }
  3417. } else {
  3418. //printf("%s: this is not optimal - fix me\n", __func__);
  3419. if (dst->type == GGML_TYPE_F32) {
  3420. int id = 0;
  3421. float * dst_ptr = (float *) dst->data;
  3422. for (int i03 = 0; i03 < ne03; i03++) {
  3423. for (int i02 = 0; i02 < ne02; i02++) {
  3424. for (int i01 = 0; i01 < ne01; i01++) {
  3425. for (int i00 = 0; i00 < ne00; i00++) {
  3426. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  3427. dst_ptr[id] = GGML_FP16_TO_FP32(*src0_ptr);
  3428. id++;
  3429. }
  3430. }
  3431. }
  3432. }
  3433. } else if (dst->type == GGML_TYPE_F16) {
  3434. int id = 0;
  3435. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  3436. for (int i03 = 0; i03 < ne03; i03++) {
  3437. for (int i02 = 0; i02 < ne02; i02++) {
  3438. for (int i01 = 0; i01 < ne01; i01++) {
  3439. for (int i00 = 0; i00 < ne00; i00++) {
  3440. const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  3441. dst_ptr[id] = *src0_ptr;
  3442. id++;
  3443. }
  3444. }
  3445. }
  3446. }
  3447. } else {
  3448. GGML_ASSERT(false); // TODO: implement
  3449. }
  3450. }
  3451. }
  3452. static void ggml_compute_forward_dup_f32(
  3453. const struct ggml_compute_params * params,
  3454. const struct ggml_tensor * src0,
  3455. struct ggml_tensor * dst) {
  3456. GGML_ASSERT(params->ith == 0);
  3457. GGML_ASSERT(ggml_is_contiguous(dst));
  3458. GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
  3459. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3460. return;
  3461. }
  3462. const int ne00 = src0->ne[0];
  3463. const int ne01 = src0->ne[1];
  3464. const int ne02 = src0->ne[2];
  3465. const int ne03 = src0->ne[3];
  3466. const size_t nb00 = src0->nb[0];
  3467. const size_t nb01 = src0->nb[1];
  3468. const size_t nb02 = src0->nb[2];
  3469. const size_t nb03 = src0->nb[3];
  3470. if (ggml_is_contiguous(src0) && src0->type == dst->type) {
  3471. memcpy(dst->data, src0->data, ggml_nelements(dst) * GGML_TYPE_SIZE[src0->type]);
  3472. return;
  3473. }
  3474. if (src0->nb[0] == sizeof(float)) {
  3475. if (dst->type == GGML_TYPE_F32) {
  3476. int id = 0;
  3477. const size_t rs = ne00*nb00;
  3478. for (int i03 = 0; i03 < ne03; i03++) {
  3479. for (int i02 = 0; i02 < ne02; i02++) {
  3480. for (int i01 = 0; i01 < ne01; i01++) {
  3481. const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
  3482. char * dst_ptr = (char *) dst->data + id*rs;
  3483. memcpy(dst_ptr, src0_ptr, rs);
  3484. id++;
  3485. }
  3486. }
  3487. }
  3488. } else if (dst->type == GGML_TYPE_F16) {
  3489. int id = 0;
  3490. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  3491. for (int i03 = 0; i03 < ne03; i03++) {
  3492. for (int i02 = 0; i02 < ne02; i02++) {
  3493. for (int i01 = 0; i01 < ne01; i01++) {
  3494. for (int i00 = 0; i00 < ne00; i00++) {
  3495. const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  3496. dst_ptr[id] = GGML_FP32_TO_FP16(*src0_ptr);
  3497. id++;
  3498. }
  3499. }
  3500. }
  3501. }
  3502. } else {
  3503. GGML_ASSERT(false); // TODO: implement
  3504. }
  3505. } else {
  3506. //printf("%s: this is not optimal - fix me\n", __func__);
  3507. if (dst->type == GGML_TYPE_F32) {
  3508. int id = 0;
  3509. float * dst_ptr = (float *) dst->data;
  3510. for (int i03 = 0; i03 < ne03; i03++) {
  3511. for (int i02 = 0; i02 < ne02; i02++) {
  3512. for (int i01 = 0; i01 < ne01; i01++) {
  3513. for (int i00 = 0; i00 < ne00; i00++) {
  3514. const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  3515. dst_ptr[id] = *src0_ptr;
  3516. id++;
  3517. }
  3518. }
  3519. }
  3520. }
  3521. } else if (dst->type == GGML_TYPE_F16) {
  3522. int id = 0;
  3523. ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
  3524. for (int i03 = 0; i03 < ne03; i03++) {
  3525. for (int i02 = 0; i02 < ne02; i02++) {
  3526. for (int i01 = 0; i01 < ne01; i01++) {
  3527. for (int i00 = 0; i00 < ne00; i00++) {
  3528. const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
  3529. dst_ptr[id] = GGML_FP32_TO_FP16(*src0_ptr);
  3530. id++;
  3531. }
  3532. }
  3533. }
  3534. }
  3535. } else {
  3536. GGML_ASSERT(false); // TODO: implement
  3537. }
  3538. }
  3539. }
  3540. static void ggml_compute_forward_dup(
  3541. const struct ggml_compute_params * params,
  3542. const struct ggml_tensor * src0,
  3543. struct ggml_tensor * dst) {
  3544. switch (src0->type) {
  3545. case GGML_TYPE_F16:
  3546. {
  3547. ggml_compute_forward_dup_f16(params, src0, dst);
  3548. } break;
  3549. case GGML_TYPE_F32:
  3550. {
  3551. ggml_compute_forward_dup_f32(params, src0, dst);
  3552. } break;
  3553. case GGML_TYPE_Q4_0:
  3554. case GGML_TYPE_Q4_1:
  3555. case GGML_TYPE_I8:
  3556. case GGML_TYPE_I16:
  3557. case GGML_TYPE_I32:
  3558. case GGML_TYPE_COUNT:
  3559. {
  3560. GGML_ASSERT(false);
  3561. } break;
  3562. }
  3563. }
  3564. // ggml_compute_forward_add
  3565. static void ggml_compute_forward_add_f32(
  3566. const struct ggml_compute_params * params,
  3567. const struct ggml_tensor * src0,
  3568. const struct ggml_tensor * src1,
  3569. struct ggml_tensor * dst) {
  3570. GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  3571. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3572. return;
  3573. }
  3574. const int ith = params->ith;
  3575. const int nth = params->nth;
  3576. const int n = ggml_nrows(src0);
  3577. const int nc = src0->ne[0];
  3578. const size_t nb00 = src0->nb[0];
  3579. const size_t nb01 = src0->nb[1];
  3580. const size_t nb10 = src1->nb[0];
  3581. const size_t nb11 = src1->nb[1];
  3582. const size_t nb0 = dst->nb[0];
  3583. const size_t nb1 = dst->nb[1];
  3584. GGML_ASSERT( nb0 == sizeof(float));
  3585. GGML_ASSERT(nb00 == sizeof(float));
  3586. if (nb10 == sizeof(float)) {
  3587. const int j0 = (n/nth)*ith;
  3588. const int j1 = ith == nth - 1 ? n : (n/nth)*(ith + 1);
  3589. for (int j = j0; j < j1; j++) {
  3590. ggml_vec_add_f32(nc,
  3591. (float *) ((char *) dst->data + j*nb1),
  3592. (float *) ((char *) src0->data + j*nb01),
  3593. (float *) ((char *) src1->data + j*nb11));
  3594. }
  3595. } else {
  3596. // src1 is not contiguous
  3597. for (int j = ith; j < n; j += nth) {
  3598. float * dst_ptr = (float *) ((char *) dst->data + j*nb1);
  3599. float * src0_ptr = (float *) ((char *) src0->data + j*nb01);
  3600. for (int i = 0; i < nc; i++) {
  3601. float * src1_ptr = (float *) ((char *) src1->data + j*nb11 + i*nb10);
  3602. dst_ptr[i] = src0_ptr[i] + *src1_ptr;
  3603. }
  3604. }
  3605. }
  3606. }
  3607. static void ggml_compute_forward_add(
  3608. const struct ggml_compute_params * params,
  3609. const struct ggml_tensor * src0,
  3610. const struct ggml_tensor * src1,
  3611. struct ggml_tensor * dst) {
  3612. switch (src0->type) {
  3613. case GGML_TYPE_F32:
  3614. {
  3615. ggml_compute_forward_add_f32(params, src0, src1, dst);
  3616. } break;
  3617. case GGML_TYPE_Q4_0:
  3618. case GGML_TYPE_Q4_1:
  3619. case GGML_TYPE_I8:
  3620. case GGML_TYPE_I16:
  3621. case GGML_TYPE_I32:
  3622. case GGML_TYPE_F16:
  3623. case GGML_TYPE_COUNT:
  3624. {
  3625. GGML_ASSERT(false);
  3626. } break;
  3627. }
  3628. }
  3629. // ggml_compute_forward_sub
  3630. static void ggml_compute_forward_sub_f32(
  3631. const struct ggml_compute_params * params,
  3632. const struct ggml_tensor * src0,
  3633. const struct ggml_tensor * src1,
  3634. struct ggml_tensor * dst) {
  3635. assert(params->ith == 0);
  3636. assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  3637. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3638. return;
  3639. }
  3640. const int n = ggml_nrows(src0);
  3641. const int nc = src0->ne[0];
  3642. assert( dst->nb[0] == sizeof(float));
  3643. assert(src0->nb[0] == sizeof(float));
  3644. assert(src1->nb[0] == sizeof(float));
  3645. for (int i = 0; i < n; i++) {
  3646. ggml_vec_sub_f32(nc,
  3647. (float *) ((char *) dst->data + i*( dst->nb[1])),
  3648. (float *) ((char *) src0->data + i*(src0->nb[1])),
  3649. (float *) ((char *) src1->data + i*(src1->nb[1])));
  3650. }
  3651. }
  3652. static void ggml_compute_forward_sub(
  3653. const struct ggml_compute_params * params,
  3654. const struct ggml_tensor * src0,
  3655. const struct ggml_tensor * src1,
  3656. struct ggml_tensor * dst) {
  3657. switch (src0->type) {
  3658. case GGML_TYPE_F32:
  3659. {
  3660. ggml_compute_forward_sub_f32(params, src0, src1, dst);
  3661. } break;
  3662. case GGML_TYPE_Q4_0:
  3663. case GGML_TYPE_Q4_1:
  3664. case GGML_TYPE_I8:
  3665. case GGML_TYPE_I16:
  3666. case GGML_TYPE_I32:
  3667. case GGML_TYPE_F16:
  3668. case GGML_TYPE_COUNT:
  3669. {
  3670. GGML_ASSERT(false);
  3671. } break;
  3672. }
  3673. }
  3674. // ggml_compute_forward_mul
  3675. static void ggml_compute_forward_mul_f32(
  3676. const struct ggml_compute_params * params,
  3677. const struct ggml_tensor * src0,
  3678. const struct ggml_tensor * src1,
  3679. struct ggml_tensor * dst) {
  3680. assert(params->ith == 0);
  3681. assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  3682. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3683. return;
  3684. }
  3685. const int n = ggml_nrows(src0);
  3686. const int nc = src0->ne[0];
  3687. assert( dst->nb[0] == sizeof(float));
  3688. assert(src0->nb[0] == sizeof(float));
  3689. assert(src1->nb[0] == sizeof(float));
  3690. for (int i = 0; i < n; i++) {
  3691. ggml_vec_mul_f32(nc,
  3692. (float *) ((char *) dst->data + i*( dst->nb[1])),
  3693. (float *) ((char *) src0->data + i*(src0->nb[1])),
  3694. (float *) ((char *) src1->data + i*(src1->nb[1])));
  3695. }
  3696. }
  3697. static void ggml_compute_forward_mul(
  3698. const struct ggml_compute_params * params,
  3699. const struct ggml_tensor * src0,
  3700. const struct ggml_tensor * src1,
  3701. struct ggml_tensor * dst) {
  3702. switch (src0->type) {
  3703. case GGML_TYPE_F32:
  3704. {
  3705. ggml_compute_forward_mul_f32(params, src0, src1, dst);
  3706. } break;
  3707. case GGML_TYPE_Q4_0:
  3708. case GGML_TYPE_Q4_1:
  3709. case GGML_TYPE_I8:
  3710. case GGML_TYPE_I16:
  3711. case GGML_TYPE_I32:
  3712. case GGML_TYPE_F16:
  3713. case GGML_TYPE_COUNT:
  3714. {
  3715. GGML_ASSERT(false);
  3716. } break;
  3717. }
  3718. }
  3719. // ggml_compute_forward_div
  3720. static void ggml_compute_forward_div_f32(
  3721. const struct ggml_compute_params * params,
  3722. const struct ggml_tensor * src0,
  3723. const struct ggml_tensor * src1,
  3724. struct ggml_tensor * dst) {
  3725. assert(params->ith == 0);
  3726. assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
  3727. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3728. return;
  3729. }
  3730. const int n = ggml_nrows(src0);
  3731. const int nc = src0->ne[0];
  3732. assert( dst->nb[0] == sizeof(float));
  3733. assert(src0->nb[0] == sizeof(float));
  3734. assert(src1->nb[0] == sizeof(float));
  3735. for (int i = 0; i < n; i++) {
  3736. ggml_vec_div_f32(nc,
  3737. (float *) ((char *) dst->data + i*( dst->nb[1])),
  3738. (float *) ((char *) src0->data + i*(src0->nb[1])),
  3739. (float *) ((char *) src1->data + i*(src1->nb[1])));
  3740. }
  3741. }
  3742. static void ggml_compute_forward_div(
  3743. const struct ggml_compute_params * params,
  3744. const struct ggml_tensor * src0,
  3745. const struct ggml_tensor * src1,
  3746. struct ggml_tensor * dst) {
  3747. switch (src0->type) {
  3748. case GGML_TYPE_F32:
  3749. {
  3750. ggml_compute_forward_div_f32(params, src0, src1, dst);
  3751. } break;
  3752. case GGML_TYPE_Q4_0:
  3753. case GGML_TYPE_Q4_1:
  3754. case GGML_TYPE_I8:
  3755. case GGML_TYPE_I16:
  3756. case GGML_TYPE_I32:
  3757. case GGML_TYPE_F16:
  3758. case GGML_TYPE_COUNT:
  3759. {
  3760. GGML_ASSERT(false);
  3761. } break;
  3762. }
  3763. }
  3764. // ggml_compute_forward_sqr
  3765. static void ggml_compute_forward_sqr_f32(
  3766. const struct ggml_compute_params * params,
  3767. const struct ggml_tensor * src0,
  3768. struct ggml_tensor * dst) {
  3769. assert(params->ith == 0);
  3770. assert(ggml_are_same_shape(src0, dst));
  3771. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3772. return;
  3773. }
  3774. const int n = ggml_nrows(src0);
  3775. const int nc = src0->ne[0];
  3776. assert( dst->nb[0] == sizeof(float));
  3777. assert(src0->nb[0] == sizeof(float));
  3778. for (int i = 0; i < n; i++) {
  3779. ggml_vec_sqr_f32(nc,
  3780. (float *) ((char *) dst->data + i*( dst->nb[1])),
  3781. (float *) ((char *) src0->data + i*(src0->nb[1])));
  3782. }
  3783. }
  3784. static void ggml_compute_forward_sqr(
  3785. const struct ggml_compute_params * params,
  3786. const struct ggml_tensor * src0,
  3787. struct ggml_tensor * dst) {
  3788. switch (src0->type) {
  3789. case GGML_TYPE_F32:
  3790. {
  3791. ggml_compute_forward_sqr_f32(params, src0, dst);
  3792. } break;
  3793. case GGML_TYPE_Q4_0:
  3794. case GGML_TYPE_Q4_1:
  3795. case GGML_TYPE_I8:
  3796. case GGML_TYPE_I16:
  3797. case GGML_TYPE_I32:
  3798. case GGML_TYPE_F16:
  3799. case GGML_TYPE_COUNT:
  3800. {
  3801. GGML_ASSERT(false);
  3802. } break;
  3803. }
  3804. }
  3805. // ggml_compute_forward_sqrt
  3806. static void ggml_compute_forward_sqrt_f32(
  3807. const struct ggml_compute_params * params,
  3808. const struct ggml_tensor * src0,
  3809. struct ggml_tensor * dst) {
  3810. assert(params->ith == 0);
  3811. assert(ggml_are_same_shape(src0, dst));
  3812. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3813. return;
  3814. }
  3815. const int n = ggml_nrows(src0);
  3816. const int nc = src0->ne[0];
  3817. assert( dst->nb[0] == sizeof(float));
  3818. assert(src0->nb[0] == sizeof(float));
  3819. for (int i = 0; i < n; i++) {
  3820. ggml_vec_sqrt_f32(nc,
  3821. (float *) ((char *) dst->data + i*( dst->nb[1])),
  3822. (float *) ((char *) src0->data + i*(src0->nb[1])));
  3823. }
  3824. }
  3825. static void ggml_compute_forward_sqrt(
  3826. const struct ggml_compute_params * params,
  3827. const struct ggml_tensor * src0,
  3828. struct ggml_tensor * dst) {
  3829. switch (src0->type) {
  3830. case GGML_TYPE_F32:
  3831. {
  3832. ggml_compute_forward_sqrt_f32(params, src0, dst);
  3833. } break;
  3834. case GGML_TYPE_Q4_0:
  3835. case GGML_TYPE_Q4_1:
  3836. case GGML_TYPE_I8:
  3837. case GGML_TYPE_I16:
  3838. case GGML_TYPE_I32:
  3839. case GGML_TYPE_F16:
  3840. case GGML_TYPE_COUNT:
  3841. {
  3842. GGML_ASSERT(false);
  3843. } break;
  3844. }
  3845. }
  3846. // ggml_compute_forward_sum
  3847. static void ggml_compute_forward_sum_f32(
  3848. const struct ggml_compute_params * params,
  3849. const struct ggml_tensor * src0,
  3850. struct ggml_tensor * dst) {
  3851. assert(params->ith == 0);
  3852. assert(ggml_is_scalar(dst));
  3853. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3854. return;
  3855. }
  3856. assert(ggml_is_scalar(dst));
  3857. assert(src0->nb[0] == sizeof(float));
  3858. const int ne00 = src0->ne[0];
  3859. const int ne01 = src0->ne[1];
  3860. const int ne02 = src0->ne[2];
  3861. const int ne03 = src0->ne[3];
  3862. const size_t nb01 = src0->nb[1];
  3863. const size_t nb02 = src0->nb[2];
  3864. const size_t nb03 = src0->nb[3];
  3865. for (int i03 = 0; i03 < ne03; i03++) {
  3866. for (int i02 = 0; i02 < ne02; i02++) {
  3867. for (int i01 = 0; i01 < ne01; i01++) {
  3868. ggml_vec_sum_f32(ne00,
  3869. (float *) (dst->data),
  3870. (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
  3871. }
  3872. }
  3873. }
  3874. }
  3875. static void ggml_compute_forward_sum(
  3876. const struct ggml_compute_params * params,
  3877. const struct ggml_tensor * src0,
  3878. struct ggml_tensor * dst) {
  3879. switch (src0->type) {
  3880. case GGML_TYPE_F32:
  3881. {
  3882. ggml_compute_forward_sum_f32(params, src0, dst);
  3883. } break;
  3884. case GGML_TYPE_Q4_0:
  3885. case GGML_TYPE_Q4_1:
  3886. case GGML_TYPE_I8:
  3887. case GGML_TYPE_I16:
  3888. case GGML_TYPE_I32:
  3889. case GGML_TYPE_F16:
  3890. case GGML_TYPE_COUNT:
  3891. {
  3892. GGML_ASSERT(false);
  3893. } break;
  3894. }
  3895. }
  3896. // ggml_compute_forward_mean
  3897. static void ggml_compute_forward_mean_f32(
  3898. const struct ggml_compute_params * params,
  3899. const struct ggml_tensor * src0,
  3900. struct ggml_tensor * dst) {
  3901. assert(params->ith == 0);
  3902. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3903. return;
  3904. }
  3905. assert(src0->nb[0] == sizeof(float));
  3906. const int ne00 = src0->ne[0];
  3907. const int ne01 = src0->ne[1];
  3908. const int ne02 = src0->ne[2];
  3909. const int ne03 = src0->ne[3];
  3910. const size_t nb01 = src0->nb[1];
  3911. const size_t nb02 = src0->nb[2];
  3912. const size_t nb03 = src0->nb[3];
  3913. const int ne0 = dst->ne[0];
  3914. const int ne1 = dst->ne[1];
  3915. const int ne2 = dst->ne[2];
  3916. const int ne3 = dst->ne[3];
  3917. assert(ne0 == 1);
  3918. assert(ne1 == ne01);
  3919. assert(ne2 == ne02);
  3920. assert(ne3 == ne03);
  3921. UNUSED(ne0);
  3922. UNUSED(ne1);
  3923. UNUSED(ne2);
  3924. UNUSED(ne3);
  3925. const size_t nb1 = dst->nb[1];
  3926. const size_t nb2 = dst->nb[2];
  3927. const size_t nb3 = dst->nb[3];
  3928. for (int i03 = 0; i03 < ne03; i03++) {
  3929. for (int i02 = 0; i02 < ne02; i02++) {
  3930. for (int i01 = 0; i01 < ne01; i01++) {
  3931. ggml_vec_sum_f32(ne00,
  3932. (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
  3933. (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
  3934. *(float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3) /= (float) ne00;
  3935. }
  3936. }
  3937. }
  3938. }
  3939. static void ggml_compute_forward_mean(
  3940. const struct ggml_compute_params * params,
  3941. const struct ggml_tensor * src0,
  3942. struct ggml_tensor * dst) {
  3943. switch (src0->type) {
  3944. case GGML_TYPE_F32:
  3945. {
  3946. ggml_compute_forward_mean_f32(params, src0, dst);
  3947. } break;
  3948. case GGML_TYPE_Q4_0:
  3949. case GGML_TYPE_Q4_1:
  3950. case GGML_TYPE_I8:
  3951. case GGML_TYPE_I16:
  3952. case GGML_TYPE_I32:
  3953. case GGML_TYPE_F16:
  3954. case GGML_TYPE_COUNT:
  3955. {
  3956. GGML_ASSERT(false);
  3957. } break;
  3958. }
  3959. }
  3960. // ggml_compute_forward_repeat
  3961. static void ggml_compute_forward_repeat_f32(
  3962. const struct ggml_compute_params * params,
  3963. const struct ggml_tensor * src0,
  3964. struct ggml_tensor * dst) {
  3965. assert(params->ith == 0);
  3966. assert(ggml_can_repeat(src0, dst));
  3967. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3968. return;
  3969. }
  3970. // TODO: implement support for rank > 2 tensors
  3971. assert(src0->ne[2] == 1);
  3972. assert(src0->ne[3] == 1);
  3973. assert( dst->ne[2] == 1);
  3974. assert( dst->ne[3] == 1);
  3975. const int nc = dst->ne[0];
  3976. const int nr = dst->ne[1];
  3977. const int nc0 = src0->ne[0];
  3978. const int nr0 = src0->ne[1];
  3979. const int ncr = nc/nc0; // guaranteed to be an integer due to the check in ggml_can_repeat
  3980. const int nrr = nr/nr0; // guaranteed to be an integer due to the check in ggml_can_repeat
  3981. // TODO: support for transposed / permuted tensors
  3982. assert( dst->nb[0] == sizeof(float));
  3983. assert(src0->nb[0] == sizeof(float));
  3984. // TODO: maybe this is not optimal?
  3985. for (int i = 0; i < nrr; i++) {
  3986. for (int j = 0; j < ncr; j++) {
  3987. for (int k = 0; k < nr0; k++) {
  3988. ggml_vec_cpy_f32(nc0,
  3989. (float *) ((char *) dst->data + (i*nr0 + k)*( dst->nb[1]) + j*nc0*( dst->nb[0])),
  3990. (float *) ((char *) src0->data + ( k)*(src0->nb[1])));
  3991. }
  3992. }
  3993. }
  3994. }
  3995. static void ggml_compute_forward_repeat(
  3996. const struct ggml_compute_params * params,
  3997. const struct ggml_tensor * src0,
  3998. struct ggml_tensor * dst) {
  3999. switch (src0->type) {
  4000. case GGML_TYPE_F32:
  4001. {
  4002. ggml_compute_forward_repeat_f32(params, src0, dst);
  4003. } break;
  4004. case GGML_TYPE_Q4_0:
  4005. case GGML_TYPE_Q4_1:
  4006. case GGML_TYPE_I8:
  4007. case GGML_TYPE_I16:
  4008. case GGML_TYPE_I32:
  4009. case GGML_TYPE_F16:
  4010. case GGML_TYPE_COUNT:
  4011. {
  4012. GGML_ASSERT(false);
  4013. } break;
  4014. }
  4015. }
  4016. // ggml_compute_forward_abs
  4017. static void ggml_compute_forward_abs_f32(
  4018. const struct ggml_compute_params * params,
  4019. const struct ggml_tensor * src0,
  4020. struct ggml_tensor * dst) {
  4021. assert(params->ith == 0);
  4022. assert(ggml_are_same_shape(src0, dst));
  4023. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  4024. return;
  4025. }
  4026. const int n = ggml_nrows(src0);
  4027. const int nc = src0->ne[0];
  4028. assert(dst->nb[0] == sizeof(float));
  4029. assert(src0->nb[0] == sizeof(float));
  4030. for (int i = 0; i < n; i++) {
  4031. ggml_vec_abs_f32(nc,
  4032. (float *) ((char *) dst->data + i*( dst->nb[1])),
  4033. (float *) ((char *) src0->data + i*(src0->nb[1])));
  4034. }
  4035. }
  4036. static void ggml_compute_forward_abs(
  4037. const struct ggml_compute_params * params,
  4038. const struct ggml_tensor * src0,
  4039. struct ggml_tensor * dst) {
  4040. switch (src0->type) {
  4041. case GGML_TYPE_F32:
  4042. {
  4043. ggml_compute_forward_abs_f32(params, src0, dst);
  4044. } break;
  4045. case GGML_TYPE_Q4_0:
  4046. case GGML_TYPE_Q4_1:
  4047. case GGML_TYPE_I8:
  4048. case GGML_TYPE_I16:
  4049. case GGML_TYPE_I32:
  4050. case GGML_TYPE_F16:
  4051. case GGML_TYPE_COUNT:
  4052. {
  4053. GGML_ASSERT(false);
  4054. } break;
  4055. }
  4056. }
  4057. // ggml_compute_forward_sgn
  4058. static void ggml_compute_forward_sgn_f32(
  4059. const struct ggml_compute_params * params,
  4060. const struct ggml_tensor * src0,
  4061. struct ggml_tensor * dst) {
  4062. assert(params->ith == 0);
  4063. assert(ggml_are_same_shape(src0, dst));
  4064. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  4065. return;
  4066. }
  4067. const int n = ggml_nrows(src0);
  4068. const int nc = src0->ne[0];
  4069. assert(dst->nb[0] == sizeof(float));
  4070. assert(src0->nb[0] == sizeof(float));
  4071. for (int i = 0; i < n; i++) {
  4072. ggml_vec_sgn_f32(nc,
  4073. (float *) ((char *) dst->data + i*( dst->nb[1])),
  4074. (float *) ((char *) src0->data + i*(src0->nb[1])));
  4075. }
  4076. }
  4077. static void ggml_compute_forward_sgn(
  4078. const struct ggml_compute_params * params,
  4079. const struct ggml_tensor * src0,
  4080. struct ggml_tensor * dst) {
  4081. switch (src0->type) {
  4082. case GGML_TYPE_F32:
  4083. {
  4084. ggml_compute_forward_sgn_f32(params, src0, dst);
  4085. } break;
  4086. case GGML_TYPE_Q4_0:
  4087. case GGML_TYPE_Q4_1:
  4088. case GGML_TYPE_I8:
  4089. case GGML_TYPE_I16:
  4090. case GGML_TYPE_I32:
  4091. case GGML_TYPE_F16:
  4092. case GGML_TYPE_COUNT:
  4093. {
  4094. GGML_ASSERT(false);
  4095. } break;
  4096. }
  4097. }
  4098. // ggml_compute_forward_neg
  4099. static void ggml_compute_forward_neg_f32(
  4100. const struct ggml_compute_params * params,
  4101. const struct ggml_tensor * src0,
  4102. struct ggml_tensor * dst) {
  4103. assert(params->ith == 0);
  4104. assert(ggml_are_same_shape(src0, dst));
  4105. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  4106. return;
  4107. }
  4108. const int n = ggml_nrows(src0);
  4109. const int nc = src0->ne[0];
  4110. assert(dst->nb[0] == sizeof(float));
  4111. assert(src0->nb[0] == sizeof(float));
  4112. for (int i = 0; i < n; i++) {
  4113. ggml_vec_neg_f32(nc,
  4114. (float *) ((char *) dst->data + i*( dst->nb[1])),
  4115. (float *) ((char *) src0->data + i*(src0->nb[1])));
  4116. }
  4117. }
  4118. static void ggml_compute_forward_neg(
  4119. const struct ggml_compute_params * params,
  4120. const struct ggml_tensor * src0,
  4121. struct ggml_tensor * dst) {
  4122. switch (src0->type) {
  4123. case GGML_TYPE_F32:
  4124. {
  4125. ggml_compute_forward_neg_f32(params, src0, dst);
  4126. } break;
  4127. case GGML_TYPE_Q4_0:
  4128. case GGML_TYPE_Q4_1:
  4129. case GGML_TYPE_I8:
  4130. case GGML_TYPE_I16:
  4131. case GGML_TYPE_I32:
  4132. case GGML_TYPE_F16:
  4133. case GGML_TYPE_COUNT:
  4134. {
  4135. GGML_ASSERT(false);
  4136. } break;
  4137. }
  4138. }
  4139. // ggml_compute_forward_step
  4140. static void ggml_compute_forward_step_f32(
  4141. const struct ggml_compute_params * params,
  4142. const struct ggml_tensor * src0,
  4143. struct ggml_tensor * dst) {
  4144. assert(params->ith == 0);
  4145. assert(ggml_are_same_shape(src0, dst));
  4146. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  4147. return;
  4148. }
  4149. const int n = ggml_nrows(src0);
  4150. const int nc = src0->ne[0];
  4151. assert(dst->nb[0] == sizeof(float));
  4152. assert(src0->nb[0] == sizeof(float));
  4153. for (int i = 0; i < n; i++) {
  4154. ggml_vec_step_f32(nc,
  4155. (float *) ((char *) dst->data + i*( dst->nb[1])),
  4156. (float *) ((char *) src0->data + i*(src0->nb[1])));
  4157. }
  4158. }
  4159. static void ggml_compute_forward_step(
  4160. const struct ggml_compute_params * params,
  4161. const struct ggml_tensor * src0,
  4162. struct ggml_tensor * dst) {
  4163. switch (src0->type) {
  4164. case GGML_TYPE_F32:
  4165. {
  4166. ggml_compute_forward_step_f32(params, src0, dst);
  4167. } break;
  4168. case GGML_TYPE_Q4_0:
  4169. case GGML_TYPE_Q4_1:
  4170. case GGML_TYPE_I8:
  4171. case GGML_TYPE_I16:
  4172. case GGML_TYPE_I32:
  4173. case GGML_TYPE_F16:
  4174. case GGML_TYPE_COUNT:
  4175. {
  4176. GGML_ASSERT(false);
  4177. } break;
  4178. }
  4179. }
  4180. // ggml_compute_forward_relu
  4181. static void ggml_compute_forward_relu_f32(
  4182. const struct ggml_compute_params * params,
  4183. const struct ggml_tensor * src0,
  4184. struct ggml_tensor * dst) {
  4185. assert(params->ith == 0);
  4186. assert(ggml_are_same_shape(src0, dst));
  4187. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  4188. return;
  4189. }
  4190. const int n = ggml_nrows(src0);
  4191. const int nc = src0->ne[0];
  4192. assert(dst->nb[0] == sizeof(float));
  4193. assert(src0->nb[0] == sizeof(float));
  4194. for (int i = 0; i < n; i++) {
  4195. ggml_vec_relu_f32(nc,
  4196. (float *) ((char *) dst->data + i*( dst->nb[1])),
  4197. (float *) ((char *) src0->data + i*(src0->nb[1])));
  4198. }
  4199. }
  4200. static void ggml_compute_forward_relu(
  4201. const struct ggml_compute_params * params,
  4202. const struct ggml_tensor * src0,
  4203. struct ggml_tensor * dst) {
  4204. switch (src0->type) {
  4205. case GGML_TYPE_F32:
  4206. {
  4207. ggml_compute_forward_relu_f32(params, src0, dst);
  4208. } break;
  4209. case GGML_TYPE_Q4_0:
  4210. case GGML_TYPE_Q4_1:
  4211. case GGML_TYPE_I8:
  4212. case GGML_TYPE_I16:
  4213. case GGML_TYPE_I32:
  4214. case GGML_TYPE_F16:
  4215. case GGML_TYPE_COUNT:
  4216. {
  4217. GGML_ASSERT(false);
  4218. } break;
  4219. }
  4220. }
  4221. // ggml_compute_forward_gelu
  4222. static void ggml_compute_forward_gelu_f32(
  4223. const struct ggml_compute_params * params,
  4224. const struct ggml_tensor * src0,
  4225. struct ggml_tensor * dst) {
  4226. GGML_ASSERT(ggml_is_contiguous(src0));
  4227. GGML_ASSERT(ggml_is_contiguous(dst));
  4228. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  4229. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  4230. return;
  4231. }
  4232. const int ith = params->ith;
  4233. const int nth = params->nth;
  4234. const int nc = src0->ne[0];
  4235. const int nr = ggml_nrows(src0);
  4236. // rows per thread
  4237. const int dr = (nr + nth - 1)/nth;
  4238. // row range for this thread
  4239. const int ir0 = dr*ith;
  4240. const int ir1 = MIN(ir0 + dr, nr);
  4241. for (int i1 = ir0; i1 < ir1; i1++) {
  4242. ggml_vec_gelu_f32(nc,
  4243. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  4244. (float *) ((char *) src0->data + i1*(src0->nb[1])));
  4245. #ifndef NDEBUG
  4246. for (int k = 0; k < nc; k++) {
  4247. const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
  4248. UNUSED(x);
  4249. assert(!isnan(x));
  4250. assert(!isinf(x));
  4251. }
  4252. #endif
  4253. }
  4254. }
  4255. static void ggml_compute_forward_gelu(
  4256. const struct ggml_compute_params * params,
  4257. const struct ggml_tensor * src0,
  4258. struct ggml_tensor * dst) {
  4259. switch (src0->type) {
  4260. case GGML_TYPE_F32:
  4261. {
  4262. ggml_compute_forward_gelu_f32(params, src0, dst);
  4263. } break;
  4264. case GGML_TYPE_Q4_0:
  4265. case GGML_TYPE_Q4_1:
  4266. case GGML_TYPE_I8:
  4267. case GGML_TYPE_I16:
  4268. case GGML_TYPE_I32:
  4269. case GGML_TYPE_F16:
  4270. case GGML_TYPE_COUNT:
  4271. {
  4272. GGML_ASSERT(false);
  4273. } break;
  4274. }
  4275. //printf("XXXXXXXX gelu\n");
  4276. }
  4277. // ggml_compute_forward_silu
  4278. static void ggml_compute_forward_silu_f32(
  4279. const struct ggml_compute_params * params,
  4280. const struct ggml_tensor * src0,
  4281. struct ggml_tensor * dst) {
  4282. GGML_ASSERT(ggml_is_contiguous(src0));
  4283. GGML_ASSERT(ggml_is_contiguous(dst));
  4284. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  4285. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  4286. return;
  4287. }
  4288. const int ith = params->ith;
  4289. const int nth = params->nth;
  4290. const int nc = src0->ne[0];
  4291. const int nr = ggml_nrows(src0);
  4292. // rows per thread
  4293. const int dr = (nr + nth - 1)/nth;
  4294. // row range for this thread
  4295. const int ir0 = dr*ith;
  4296. const int ir1 = MIN(ir0 + dr, nr);
  4297. for (int i1 = ir0; i1 < ir1; i1++) {
  4298. ggml_vec_silu_f32(nc,
  4299. (float *) ((char *) dst->data + i1*( dst->nb[1])),
  4300. (float *) ((char *) src0->data + i1*(src0->nb[1])));
  4301. #ifndef NDEBUG
  4302. for (int k = 0; k < nc; k++) {
  4303. const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
  4304. UNUSED(x);
  4305. assert(!isnan(x));
  4306. assert(!isinf(x));
  4307. }
  4308. #endif
  4309. }
  4310. }
  4311. static void ggml_compute_forward_silu(
  4312. const struct ggml_compute_params * params,
  4313. const struct ggml_tensor * src0,
  4314. struct ggml_tensor * dst) {
  4315. switch (src0->type) {
  4316. case GGML_TYPE_F32:
  4317. {
  4318. ggml_compute_forward_silu_f32(params, src0, dst);
  4319. } break;
  4320. case GGML_TYPE_Q4_0:
  4321. case GGML_TYPE_Q4_1:
  4322. case GGML_TYPE_I8:
  4323. case GGML_TYPE_I16:
  4324. case GGML_TYPE_I32:
  4325. case GGML_TYPE_F16:
  4326. case GGML_TYPE_COUNT:
  4327. {
  4328. GGML_ASSERT(false);
  4329. } break;
  4330. }
  4331. }
  4332. // ggml_compute_forward_norm
  4333. static void ggml_compute_forward_norm_f32(
  4334. const struct ggml_compute_params * params,
  4335. const struct ggml_tensor * src0,
  4336. struct ggml_tensor * dst) {
  4337. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  4338. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  4339. return;
  4340. }
  4341. GGML_ASSERT(src0->nb[0] == sizeof(float));
  4342. const int ith = params->ith;
  4343. const int nth = params->nth;
  4344. const int ne00 = src0->ne[0];
  4345. const int ne01 = src0->ne[1];
  4346. const int ne02 = src0->ne[2];
  4347. const int ne03 = src0->ne[3];
  4348. const size_t nb01 = src0->nb[1];
  4349. const size_t nb02 = src0->nb[2];
  4350. const size_t nb03 = src0->nb[3];
  4351. const size_t nb1 = dst->nb[1];
  4352. const size_t nb2 = dst->nb[2];
  4353. const size_t nb3 = dst->nb[3];
  4354. const ggml_float eps = 1e-5f; // TODO: make this a parameter
  4355. // TODO: optimize
  4356. for (int i03 = 0; i03 < ne03; i03++) {
  4357. for (int i02 = 0; i02 < ne02; i02++) {
  4358. for (int i01 = ith; i01 < ne01; i01 += nth) {
  4359. const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  4360. ggml_float mean = 0.0;
  4361. for (int i00 = 0; i00 < ne00; i00++) {
  4362. mean += x[i00];
  4363. }
  4364. mean /= ne00;
  4365. float * y = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
  4366. ggml_float sum2 = 0.0;
  4367. for (int i00 = 0; i00 < ne00; i00++) {
  4368. ggml_float v = x[i00] - mean;
  4369. y[i00] = v;
  4370. sum2 += v*v;
  4371. }
  4372. const float scale = 1.0/sqrt(sum2/ne00 + eps);
  4373. ggml_vec_scale_f32(ne00, y, scale);
  4374. }
  4375. }
  4376. }
  4377. }
  4378. static void ggml_compute_forward_norm(
  4379. const struct ggml_compute_params * params,
  4380. const struct ggml_tensor * src0,
  4381. struct ggml_tensor * dst) {
  4382. switch (src0->type) {
  4383. case GGML_TYPE_F32:
  4384. {
  4385. ggml_compute_forward_norm_f32(params, src0, dst);
  4386. } break;
  4387. case GGML_TYPE_Q4_0:
  4388. case GGML_TYPE_Q4_1:
  4389. case GGML_TYPE_I8:
  4390. case GGML_TYPE_I16:
  4391. case GGML_TYPE_I32:
  4392. case GGML_TYPE_F16:
  4393. case GGML_TYPE_COUNT:
  4394. {
  4395. GGML_ASSERT(false);
  4396. } break;
  4397. }
  4398. }
  4399. static void ggml_compute_forward_rms_norm_f32(
  4400. const struct ggml_compute_params * params,
  4401. const struct ggml_tensor * src0,
  4402. struct ggml_tensor * dst) {
  4403. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  4404. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  4405. return;
  4406. }
  4407. GGML_ASSERT(src0->nb[0] == sizeof(float));
  4408. const int ith = params->ith;
  4409. const int nth = params->nth;
  4410. const int ne00 = src0->ne[0];
  4411. const int ne01 = src0->ne[1];
  4412. const int ne02 = src0->ne[2];
  4413. const int ne03 = src0->ne[3];
  4414. const size_t nb01 = src0->nb[1];
  4415. const size_t nb02 = src0->nb[2];
  4416. const size_t nb03 = src0->nb[3];
  4417. const size_t nb1 = dst->nb[1];
  4418. const size_t nb2 = dst->nb[2];
  4419. const size_t nb3 = dst->nb[3];
  4420. const ggml_float eps = 1e-5f; // TODO: make this a parameter
  4421. // TODO: optimize
  4422. for (int i03 = 0; i03 < ne03; i03++) {
  4423. for (int i02 = 0; i02 < ne02; i02++) {
  4424. for (int i01 = ith; i01 < ne01; i01 += nth) {
  4425. const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
  4426. ggml_float mean = 0.0;
  4427. for (int i00 = 0; i00 < ne00; i00++) {
  4428. mean += x[i00] * x[i00];
  4429. }
  4430. mean /= ne00;
  4431. float * y = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
  4432. memcpy(y, x, ne00 * sizeof(float));
  4433. // for (int i00 = 0; i00 < ne00; i00++) {
  4434. // y[i00] = x[i00];
  4435. // }
  4436. const float scale = 1.0/sqrt(mean + eps);
  4437. ggml_vec_scale_f32(ne00, y, scale);
  4438. }
  4439. }
  4440. }
  4441. }
  4442. static void ggml_compute_forward_rms_norm(
  4443. const struct ggml_compute_params * params,
  4444. const struct ggml_tensor * src0,
  4445. struct ggml_tensor * dst) {
  4446. switch (src0->type) {
  4447. case GGML_TYPE_F32:
  4448. {
  4449. ggml_compute_forward_rms_norm_f32(params, src0, dst);
  4450. } break;
  4451. case GGML_TYPE_Q4_0:
  4452. case GGML_TYPE_Q4_1:
  4453. case GGML_TYPE_I8:
  4454. case GGML_TYPE_I16:
  4455. case GGML_TYPE_I32:
  4456. case GGML_TYPE_F16:
  4457. case GGML_TYPE_COUNT:
  4458. {
  4459. GGML_ASSERT(false);
  4460. } break;
  4461. }
  4462. }
  4463. // ggml_compute_forward_mul_mat
  4464. #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
  4465. // helper function to determine if it is better to use BLAS or not
  4466. // for large matrices, BLAS is faster
  4467. static bool ggml_compute_forward_mul_mat_use_blas(
  4468. const struct ggml_tensor * src0,
  4469. const struct ggml_tensor * src1,
  4470. struct ggml_tensor * dst) {
  4471. UNUSED(src0);
  4472. const int ne10 = src1->ne[0];
  4473. const int ne0 = dst->ne[0];
  4474. const int ne1 = dst->ne[1];
  4475. // TODO: find the optimal values for these
  4476. if (ggml_is_contiguous(src0) &&
  4477. ggml_is_contiguous(src1) && ((ne0 >= 32 && ne1 >= 32 && ne10 >= 32))) {
  4478. //printf("BLAS: %d %d %d\n", ne0, ne1, ne10);
  4479. return true;
  4480. }
  4481. return false;
  4482. }
  4483. #endif
  4484. static void ggml_compute_forward_mul_mat_f32(
  4485. const struct ggml_compute_params * params,
  4486. const struct ggml_tensor * src0,
  4487. const struct ggml_tensor * src1,
  4488. struct ggml_tensor * dst) {
  4489. int64_t t0 = ggml_perf_time_us();
  4490. UNUSED(t0);
  4491. const int ne00 = src0->ne[0];
  4492. const int ne01 = src0->ne[1];
  4493. const int ne02 = src0->ne[2];
  4494. const int ne03 = src0->ne[3];
  4495. const int ne10 = src1->ne[0];
  4496. const int ne11 = src1->ne[1];
  4497. const int ne12 = src1->ne[2];
  4498. const int ne13 = src1->ne[3];
  4499. const int ne0 = dst->ne[0];
  4500. const int ne1 = dst->ne[1];
  4501. const int ne2 = dst->ne[2];
  4502. const int ne3 = dst->ne[3];
  4503. const int ne = ne0*ne1*ne2*ne3;
  4504. const int nb00 = src0->nb[0];
  4505. const int nb01 = src0->nb[1];
  4506. const int nb02 = src0->nb[2];
  4507. const int nb03 = src0->nb[3];
  4508. const int nb10 = src1->nb[0];
  4509. const int nb11 = src1->nb[1];
  4510. const int nb12 = src1->nb[2];
  4511. const int nb13 = src1->nb[3];
  4512. const int nb0 = dst->nb[0];
  4513. const int nb1 = dst->nb[1];
  4514. const int nb2 = dst->nb[2];
  4515. const int nb3 = dst->nb[3];
  4516. const int ith = params->ith;
  4517. const int nth = params->nth;
  4518. assert(ne02 == ne12);
  4519. assert(ne03 == ne13);
  4520. assert(ne2 == ne12);
  4521. assert(ne3 == ne13);
  4522. // TODO: we don't support permuted src0
  4523. assert(nb00 == sizeof(float) || nb01 == sizeof(float));
  4524. // dst cannot be transposed or permuted
  4525. assert(nb0 == sizeof(float));
  4526. assert(nb0 <= nb1);
  4527. assert(nb1 <= nb2);
  4528. assert(nb2 <= nb3);
  4529. assert(ne0 == ne01);
  4530. assert(ne1 == ne11);
  4531. assert(ne2 == ne02);
  4532. assert(ne3 == ne03);
  4533. // nb01 >= nb00 - src0 is not transposed
  4534. // compute by src0 rows
  4535. //
  4536. // nb00 < nb01 - src0 is transposed
  4537. // compute by src0 columns
  4538. #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
  4539. if (ggml_compute_forward_mul_mat_use_blas(src0, src1, dst)) {
  4540. GGML_ASSERT(nb10 == sizeof(float));
  4541. if (params->ith != 0) {
  4542. return;
  4543. }
  4544. if (params->type == GGML_TASK_INIT) {
  4545. return;
  4546. }
  4547. if (params->type == GGML_TASK_FINALIZE) {
  4548. return;
  4549. }
  4550. for (int i03 = 0; i03 < ne03; i03++) {
  4551. for (int i02 = 0; i02 < ne02; i02++) {
  4552. const float * x = (float *) (src0->data);
  4553. const float * y = (float *) ((char *) src1->data + i02*nb12 + i03*nb13);
  4554. float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
  4555. // zT = y * xT
  4556. {
  4557. cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
  4558. ne11, ne01, ne10,
  4559. 1.0f, y, ne10,
  4560. x, ne10,
  4561. 0.0f, d, ne01);
  4562. }
  4563. }
  4564. }
  4565. //printf("CBLAS F32 = %f ms, %d x %d x %d x %d\n", (ggml_perf_time_us() - t0)/1000.0, ne0, ne1, ne2, ne3);
  4566. return;
  4567. }
  4568. #endif
  4569. if (params->type == GGML_TASK_INIT) {
  4570. if (nb01 >= nb00) {
  4571. return;
  4572. }
  4573. // TODO: fix this memset (wsize is overestimated)
  4574. memset(params->wdata, 0, params->wsize);
  4575. return;
  4576. }
  4577. if (params->type == GGML_TASK_FINALIZE) {
  4578. if (nb01 >= nb00) {
  4579. return;
  4580. }
  4581. // TODO: fix this memset (wsize is overestimated)
  4582. //assert(params->wsize == (ggml_nbytes(dst) + CACHE_LINE_SIZE)*nth);
  4583. float * const wdata = params->wdata;
  4584. // cols per thread
  4585. const int dc = (ne + nth - 1)/nth;
  4586. // col range for this thread
  4587. const int ic0 = dc*ith;
  4588. const int ic1 = MIN(ic0 + dc, ne);
  4589. ggml_vec_cpy_f32(ic1 - ic0, (float *) dst->data + ic0, wdata + ic0);
  4590. for (int k = 1; k < nth; k++) {
  4591. ggml_vec_acc_f32(ic1 - ic0, (float *) dst->data + ic0, wdata + (ne + CACHE_LINE_SIZE_F32)*k + ic0);
  4592. }
  4593. return;
  4594. }
  4595. if (nb01 >= nb00) {
  4596. // TODO: do not support transposed src1
  4597. assert(nb10 == sizeof(float));
  4598. // parallelize by src0 rows using ggml_vec_dot_f32
  4599. // total rows in src0
  4600. const int nr = ne01*ne02*ne03;
  4601. // rows per thread
  4602. const int dr = (nr + nth - 1)/nth;
  4603. // row range for this thread
  4604. const int ir0 = dr*ith;
  4605. const int ir1 = MIN(ir0 + dr, nr);
  4606. for (int ir = ir0; ir < ir1; ++ir) {
  4607. // src0 indices
  4608. const int i03 = ir/(ne02*ne01);
  4609. const int i02 = (ir - i03*ne02*ne01)/ne01;
  4610. const int i01 = (ir - i03*ne02*ne01 - i02*ne01);
  4611. for (int ic = 0; ic < ne11; ++ic) {
  4612. // src1 indices
  4613. const int i13 = i03;
  4614. const int i12 = i02;
  4615. const int i11 = ic;
  4616. // dst indices
  4617. const int i0 = i01;
  4618. const int i1 = i11;
  4619. const int i2 = i02;
  4620. const int i3 = i03;
  4621. ggml_vec_dot_f32(ne00,
  4622. (float *) ((char *) dst->data + (i0*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
  4623. (float *) ((char *) src0->data + (i01*nb01 + i02*nb02 + i03*nb03)),
  4624. (float *) ((char *) src1->data + (i11*nb11 + i12*nb12 + i13*nb13)));
  4625. }
  4626. }
  4627. } else {
  4628. // parallelize by src1 columns using ggml_vec_mad_f32
  4629. // each thread has its own work data
  4630. // during FINALIZE we accumulate all work data into dst
  4631. // total columns in src1
  4632. const int nc = ne10;
  4633. // columns per thread
  4634. const int dc = (nc + nth - 1)/nth;
  4635. // column range for this thread
  4636. const int ic0 = dc*ith;
  4637. const int ic1 = MIN(ic0 + dc, nc);
  4638. // work data for thread
  4639. const int wo = (ne + CACHE_LINE_SIZE_F32)*ith;
  4640. float * const wdata = params->wdata;
  4641. for (int i13 = 0; i13 < ne13; ++i13) {
  4642. for (int i12 = 0; i12 < ne12; ++i12) {
  4643. for (int i11 = 0; i11 < ne11; ++i11) {
  4644. for (int ic = ic0; ic < ic1; ++ic) {
  4645. // src1 indices
  4646. const int i10 = ic;
  4647. // src0 indices
  4648. const int i03 = i13;
  4649. const int i02 = i12;
  4650. const int i00 = ic;
  4651. // dst indices
  4652. const int i1 = i11;
  4653. const int i2 = i12;
  4654. const int i3 = i13;
  4655. assert(sizeof(float)*(wo + i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0 + ne01) <= params->wsize);
  4656. ggml_vec_mad_f32(ne01,
  4657. (float *) (wdata + wo + i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0),
  4658. (float *) ((char *) src0->data + (i00*nb00 + i02*nb02 + i03*nb03)),
  4659. *(float *) ((char *) src1->data + (i10*nb10 + i11*nb11 + i12*nb12 + i13*nb13)));
  4660. }
  4661. }
  4662. }
  4663. }
  4664. }
  4665. //int64_t t1 = ggml_perf_time_us();
  4666. //static int64_t acc = 0;
  4667. //acc += t1 - t0;
  4668. //if (t1 - t0 > 10) {
  4669. // printf("\n");
  4670. // printf("ne00 = %5d, ne01 = %5d, ne02 = %5d, ne03 = %5d\n", ne00, ne01, ne02, ne03);
  4671. // printf("nb00 = %5d, nb01 = %5d, nb02 = %5d, nb03 = %5d\n", nb00, nb01, nb02, nb03);
  4672. // printf("ne10 = %5d, ne11 = %5d, ne12 = %5d, ne13 = %5d\n", ne10, ne11, ne12, ne13);
  4673. // printf("nb10 = %5d, nb11 = %5d, nb12 = %5d, nb13 = %5d\n", nb10, nb11, nb12, nb13);
  4674. // printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX task %d/%d: %d us, acc = %d\n", ith, nth, (int) (t1 - t0), (int) acc);
  4675. //}
  4676. }
  4677. static void ggml_compute_forward_mul_mat_f16_f32(
  4678. const struct ggml_compute_params * params,
  4679. const struct ggml_tensor * src0,
  4680. const struct ggml_tensor * src1,
  4681. struct ggml_tensor * dst) {
  4682. int64_t t0 = ggml_perf_time_us();
  4683. UNUSED(t0);
  4684. const int ne00 = src0->ne[0];
  4685. const int ne01 = src0->ne[1];
  4686. const int ne02 = src0->ne[2];
  4687. const int ne03 = src0->ne[3];
  4688. const int ne10 = src1->ne[0];
  4689. const int ne11 = src1->ne[1];
  4690. const int ne12 = src1->ne[2];
  4691. const int ne13 = src1->ne[3];
  4692. const int ne0 = dst->ne[0];
  4693. const int ne1 = dst->ne[1];
  4694. const int ne2 = dst->ne[2];
  4695. const int ne3 = dst->ne[3];
  4696. const int ne = ne0*ne1*ne2*ne3;
  4697. const int nb00 = src0->nb[0];
  4698. const int nb01 = src0->nb[1];
  4699. const int nb02 = src0->nb[2];
  4700. const int nb03 = src0->nb[3];
  4701. const int nb10 = src1->nb[0];
  4702. const int nb11 = src1->nb[1];
  4703. const int nb12 = src1->nb[2];
  4704. const int nb13 = src1->nb[3];
  4705. const int nb0 = dst->nb[0];
  4706. const int nb1 = dst->nb[1];
  4707. const int nb2 = dst->nb[2];
  4708. const int nb3 = dst->nb[3];
  4709. const int ith = params->ith;
  4710. const int nth = params->nth;
  4711. GGML_ASSERT(ne02 == ne12);
  4712. GGML_ASSERT(ne03 == ne13);
  4713. GGML_ASSERT(ne2 == ne12);
  4714. GGML_ASSERT(ne3 == ne13);
  4715. // TODO: we don't support permuted src0
  4716. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t) || nb01 == sizeof(ggml_fp16_t));
  4717. // dst cannot be transposed or permuted
  4718. GGML_ASSERT(nb0 == sizeof(float));
  4719. GGML_ASSERT(nb0 <= nb1);
  4720. GGML_ASSERT(nb1 <= nb2);
  4721. GGML_ASSERT(nb2 <= nb3);
  4722. GGML_ASSERT(ne0 == ne01);
  4723. GGML_ASSERT(ne1 == ne11);
  4724. GGML_ASSERT(ne2 == ne02);
  4725. GGML_ASSERT(ne3 == ne03);
  4726. // nb01 >= nb00 - src0 is not transposed
  4727. // compute by src0 rows
  4728. //
  4729. // nb00 < nb01 - src0 is transposed
  4730. // compute by src0 columns
  4731. #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
  4732. if (ggml_compute_forward_mul_mat_use_blas(src0, src1, dst)) {
  4733. GGML_ASSERT(nb10 == sizeof(float));
  4734. if (params->ith != 0) {
  4735. return;
  4736. }
  4737. if (params->type == GGML_TASK_INIT) {
  4738. return;
  4739. }
  4740. if (params->type == GGML_TASK_FINALIZE) {
  4741. return;
  4742. }
  4743. float * const wdata = params->wdata;
  4744. for (int i03 = 0; i03 < ne03; i03++) {
  4745. for (int i02 = 0; i02 < ne02; i02++) {
  4746. {
  4747. int id = 0;
  4748. for (int i01 = 0; i01 < ne01; ++i01) {
  4749. for (int i00 = 0; i00 < ne00; ++i00) {
  4750. wdata[id++] = GGML_FP16_TO_FP32(*(ggml_fp16_t *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00));
  4751. }
  4752. }
  4753. }
  4754. const float * x = wdata;
  4755. const float * y = (float *) ((char *) src1->data + i02*nb12 + i03*nb13);
  4756. // float * z = wdata + ne00*ne01;
  4757. // z = x * yT
  4758. //{
  4759. // cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
  4760. // ne01, ne11, ne00,
  4761. // 1.0f, x, ne00,
  4762. // y, ne00,
  4763. // 0.0f, z, ne11);
  4764. //}
  4765. float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
  4766. // transpose z
  4767. //for (int j = 0; j < ne11; ++j) {
  4768. // for (int i = 0; i < ne01; ++i) {
  4769. // d[j*ne01 + i] = z[i*ne11 + j];
  4770. // }
  4771. //}
  4772. {
  4773. #if 1
  4774. // zT = y * xT
  4775. cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
  4776. ne11, ne01, ne10,
  4777. 1.0f, y, ne00,
  4778. x, ne00,
  4779. 0.0f, d, ne01);
  4780. #else
  4781. // zT = (xT * y)T
  4782. cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans,
  4783. ne01, ne11, ne10,
  4784. 1.0f, x, ne00,
  4785. y, ne00,
  4786. 0.0f, d, ne01);
  4787. #endif
  4788. }
  4789. }
  4790. }
  4791. /*printf("CBLAS F16 = %f ms, %d x %d x %d x %d\n", (ggml_perf_time_us() - t0)/1000.0, ne0, ne1, ne2, ne3);*/
  4792. return;
  4793. }
  4794. #endif
  4795. if (params->type == GGML_TASK_INIT) {
  4796. if (nb01 >= nb00) {
  4797. ggml_fp16_t * const wdata = params->wdata;
  4798. int id = 0;
  4799. for (int i13 = 0; i13 < ne13; ++i13) {
  4800. for (int i12 = 0; i12 < ne12; ++i12) {
  4801. for (int i11 = 0; i11 < ne11; ++i11) {
  4802. for (int i10 = 0; i10 < ne10; ++i10) {
  4803. wdata[id++] = GGML_FP32_TO_FP16(*(float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10));
  4804. }
  4805. }
  4806. }
  4807. }
  4808. GGML_ASSERT(id*sizeof(ggml_fp16_t) <= params->wsize);
  4809. return;
  4810. }
  4811. // TODO: fix this memset (wsize is overestimated)
  4812. memset(params->wdata, 0, params->wsize);
  4813. return;
  4814. }
  4815. if (params->type == GGML_TASK_FINALIZE) {
  4816. if (nb01 >= nb00) {
  4817. return;
  4818. }
  4819. // TODO: fix this memset (wsize is overestimated)
  4820. //assert(params->wsize == (ggml_nbytes(dst) + CACHE_LINE_SIZE)*nth);
  4821. ggml_fp16_t * const wdata = params->wdata;
  4822. // cols per thread
  4823. const int dc = (ne + nth - 1)/nth;
  4824. // col range for this thread
  4825. const int ic0 = dc*ith;
  4826. const int ic1 = MIN(ic0 + dc, ne);
  4827. for (int i = ic0; i < ic1; ++i) {
  4828. ((float *) dst->data)[i] = GGML_FP16_TO_FP32(wdata[i]);
  4829. }
  4830. for (int k = 1; k < nth; k++) {
  4831. for (int i = ic0; i < ic1; ++i) {
  4832. ((float *) dst->data)[i] += GGML_FP16_TO_FP32(wdata[(ne + CACHE_LINE_SIZE_F32)*k + i]);
  4833. }
  4834. }
  4835. return;
  4836. }
  4837. if (nb01 >= nb00) {
  4838. // fp16 -> half the size, so divide by 2
  4839. // TODO: do not support transposed src1
  4840. assert(nb10/2 == sizeof(ggml_fp16_t));
  4841. // parallelize by src0 rows using ggml_vec_dot_f16
  4842. // total rows in src0
  4843. const int nr = ne01*ne02*ne03;
  4844. // rows per thread
  4845. const int dr = (nr + nth - 1)/nth;
  4846. // row range for this thread
  4847. const int ir0 = dr*ith;
  4848. const int ir1 = MIN(ir0 + dr, nr);
  4849. ggml_fp16_t * wdata = params->wdata;
  4850. for (int ir = ir0; ir < ir1; ++ir) {
  4851. // src0 indices
  4852. const int i03 = ir/(ne02*ne01);
  4853. const int i02 = (ir - i03*ne02*ne01)/ne01;
  4854. const int i01 = (ir - i03*ne02*ne01 - i02*ne01);
  4855. const int i13 = i03;
  4856. const int i12 = i02;
  4857. const int i0 = i01;
  4858. const int i2 = i02;
  4859. const int i3 = i03;
  4860. ggml_fp16_t * src0_row = (ggml_fp16_t *) ((char *) src0->data + (i01*nb01 + i02*nb02 + i03*nb03));
  4861. ggml_fp16_t * src1_col = wdata + ( 0 + i12*ne11 + i13*ne12*ne11)*ne00;
  4862. float * dst_col = (float *) ((char *) dst->data + (i0*nb0 + 0*nb1 + i2*nb2 + i3*nb3));
  4863. assert(ne00 % 32 == 0);
  4864. for (int ic = 0; ic < ne11; ++ic) {
  4865. ggml_vec_dot_f16(ne00, &dst_col[ic*ne0], src0_row, src1_col + ic*ne00);
  4866. }
  4867. }
  4868. } else {
  4869. // parallelize by src1 columns using ggml_vec_mad_f16
  4870. // each thread has its own work data
  4871. // during FINALIZE we accumulate all work data into dst
  4872. // total columns in src1
  4873. const int nc = ne10;
  4874. // columns per thread
  4875. const int dc = (nc + nth - 1)/nth;
  4876. // column range for this thread
  4877. const int ic0 = dc*ith;
  4878. const int ic1 = MIN(ic0 + dc, nc);
  4879. // work data for thread
  4880. const int wo = (ne + CACHE_LINE_SIZE_F32)*ith;
  4881. ggml_fp16_t * const wdata = params->wdata;
  4882. for (int i13 = 0; i13 < ne13; ++i13) {
  4883. for (int i12 = 0; i12 < ne12; ++i12) {
  4884. for (int i11 = 0; i11 < ne11; ++i11) {
  4885. // dst indices
  4886. const int i1 = i11;
  4887. const int i2 = i12;
  4888. const int i3 = i13;
  4889. ggml_fp16_t * dst_row = wdata + wo + i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0;
  4890. for (int ic = ic0; ic < ic1; ++ic) {
  4891. // src1 indices
  4892. const int i10 = ic;
  4893. // src0 indices
  4894. const int i03 = i13;
  4895. const int i02 = i12;
  4896. const int i00 = ic;
  4897. assert(sizeof(ggml_fp16_t)*(wo + i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0 + ne01) <= params->wsize);
  4898. ggml_fp16_t * src0_col = (ggml_fp16_t *) ((char *) src0->data + (i00*nb00 + i02*nb02 + i03*nb03));
  4899. float src1_val = * (float *) ((char *) src1->data + (i10*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  4900. ggml_vec_mad_f16(ne01, dst_row, src0_col, src1_val);
  4901. }
  4902. }
  4903. }
  4904. }
  4905. }
  4906. //int64_t t1 = ggml_time_us();
  4907. //static int64_t acc = 0;
  4908. //acc += t1 - t0;
  4909. //if (t1 - t0 > 10) {
  4910. // printf("\n");
  4911. // printf("ne00 = %5d, ne01 = %5d, ne02 = %5d, ne03 = %5d\n", ne00, ne01, ne02, ne03);
  4912. // printf("nb00 = %5d, nb01 = %5d, nb02 = %5d, nb03 = %5d\n", nb00, nb01, nb02, nb03);
  4913. // printf("ne10 = %5d, ne11 = %5d, ne12 = %5d, ne13 = %5d\n", ne10, ne11, ne12, ne13);
  4914. // printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX task %d/%d: %d us, acc = %d\n", ith, nth, (int) (t1 - t0), (int) acc);
  4915. //}
  4916. }
  4917. static void ggml_compute_forward_mul_mat_q4_0_f32(
  4918. const struct ggml_compute_params * params,
  4919. const struct ggml_tensor * src0,
  4920. const struct ggml_tensor * src1,
  4921. struct ggml_tensor * dst) {
  4922. int64_t t0 = ggml_perf_time_us();
  4923. UNUSED(t0);
  4924. const int ne00 = src0->ne[0];
  4925. const int ne01 = src0->ne[1];
  4926. const int ne02 = src0->ne[2];
  4927. const int ne03 = src0->ne[3];
  4928. const int ne10 = src1->ne[0];
  4929. const int ne11 = src1->ne[1];
  4930. const int ne12 = src1->ne[2];
  4931. const int ne13 = src1->ne[3];
  4932. const int ne0 = dst->ne[0];
  4933. const int ne1 = dst->ne[1];
  4934. const int ne2 = dst->ne[2];
  4935. const int ne3 = dst->ne[3];
  4936. const int ne = ne0*ne1*ne2*ne3;
  4937. const int nb00 = src0->nb[0];
  4938. const int nb01 = src0->nb[1];
  4939. const int nb02 = src0->nb[2];
  4940. const int nb03 = src0->nb[3];
  4941. const int nb10 = src1->nb[0];
  4942. const int nb11 = src1->nb[1];
  4943. const int nb12 = src1->nb[2];
  4944. const int nb13 = src1->nb[3];
  4945. const int nb0 = dst->nb[0];
  4946. const int nb1 = dst->nb[1];
  4947. const int nb2 = dst->nb[2];
  4948. const int nb3 = dst->nb[3];
  4949. const int ith = params->ith;
  4950. const int nth = params->nth;
  4951. GGML_ASSERT(ne02 == ne12);
  4952. GGML_ASSERT(ne03 == ne13);
  4953. GGML_ASSERT(ne2 == ne12);
  4954. GGML_ASSERT(ne3 == ne13);
  4955. // TODO: we don't support permuted src0
  4956. GGML_ASSERT(nb00 == (int) GGML_TYPE_SIZE[GGML_TYPE_Q4_0] || nb01 == (int) GGML_TYPE_SIZE[GGML_TYPE_Q4_0]);
  4957. // dst cannot be transposed or permuted
  4958. GGML_ASSERT(nb0 == sizeof(float));
  4959. GGML_ASSERT(nb0 <= nb1);
  4960. GGML_ASSERT(nb1 <= nb2);
  4961. GGML_ASSERT(nb2 <= nb3);
  4962. GGML_ASSERT(ne0 == ne01);
  4963. GGML_ASSERT(ne1 == ne11);
  4964. GGML_ASSERT(ne2 == ne02);
  4965. GGML_ASSERT(ne3 == ne03);
  4966. // nb01 >= nb00 - src0 is not transposed
  4967. // compute by src0 rows
  4968. //
  4969. // nb00 < nb01 - src0 is transposed
  4970. // compute by src0 columns
  4971. #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
  4972. if (ggml_compute_forward_mul_mat_use_blas(src0, src1, dst)) {
  4973. GGML_ASSERT(nb10 == sizeof(float));
  4974. if (params->ith != 0) {
  4975. return;
  4976. }
  4977. if (params->type == GGML_TASK_INIT) {
  4978. return;
  4979. }
  4980. if (params->type == GGML_TASK_FINALIZE) {
  4981. return;
  4982. }
  4983. float * const wdata = params->wdata;
  4984. for (int i03 = 0; i03 < ne03; i03++) {
  4985. for (int i02 = 0; i02 < ne02; i02++) {
  4986. {
  4987. int id = 0;
  4988. for (int i01 = 0; i01 < ne01; ++i01) {
  4989. //for (int i00 = 0; i00 < ne00; ++i00) {
  4990. // wdata[id++] = GGML_FP16_TO_FP32(*(ggml_fp16_t *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00));
  4991. //}
  4992. dequantize_row_q4_0((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01, wdata + id, ne00);
  4993. id += ne00;
  4994. }
  4995. }
  4996. const float * x = wdata;
  4997. const float * y = (float *) ((char *) src1->data + i02*nb12 + i03*nb13);
  4998. // float * z = wdata + ne00*ne01;
  4999. // z = x * yT
  5000. //{
  5001. // cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
  5002. // ne01, ne11, ne00,
  5003. // 1.0f, x, ne00,
  5004. // y, ne00,
  5005. // 0.0f, z, ne11);
  5006. //}
  5007. float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
  5008. // transpose z
  5009. //for (int j = 0; j < ne11; ++j) {
  5010. // for (int i = 0; i < ne01; ++i) {
  5011. // d[j*ne01 + i] = z[i*ne11 + j];
  5012. // }
  5013. //}
  5014. {
  5015. #if 1
  5016. // zT = y * xT
  5017. cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
  5018. ne11, ne01, ne10,
  5019. 1.0f, y, ne00,
  5020. x, ne00,
  5021. 0.0f, d, ne01);
  5022. #else
  5023. // zT = (xT * y)T
  5024. cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans,
  5025. ne01, ne11, ne10,
  5026. 1.0f, x, ne00,
  5027. y, ne00,
  5028. 0.0f, d, ne01);
  5029. #endif
  5030. }
  5031. }
  5032. }
  5033. /*printf("CBLAS Q4_0 = %f ms, %d x %d x %d x %d\n", (ggml_perf_time_us() - t0)/1000.0, ne0, ne1, ne2, ne3);*/
  5034. return;
  5035. }
  5036. #endif
  5037. if (params->type == GGML_TASK_INIT) {
  5038. //printf("HHHHHHHHH ith = %d, nth = %d\n", ith, nth);
  5039. if (nb01 >= nb00) {
  5040. char * wdata = params->wdata;
  5041. for (int i13 = 0; i13 < ne13; ++i13) {
  5042. for (int i12 = 0; i12 < ne12; ++i12) {
  5043. for (int i11 = 0; i11 < ne11; ++i11) {
  5044. //for (int i10 = 0; i10 < ne10; ++i10) {
  5045. // wdata[id++] = GGML_FP32_TO_FP16(*(float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10));
  5046. //}
  5047. quantize_row_q4_0((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11), (void *) wdata, ne10);
  5048. wdata += (ne10*GGML_TYPE_SIZE[GGML_TYPE_Q4_0])/GGML_BLCK_SIZE[GGML_TYPE_Q4_0];
  5049. }
  5050. }
  5051. }
  5052. return;
  5053. }
  5054. // TODO: fix this memset (wsize is overestimated)
  5055. memset(params->wdata, 0, params->wsize);
  5056. return;
  5057. }
  5058. if (params->type == GGML_TASK_FINALIZE) {
  5059. if (nb01 >= nb00) {
  5060. return;
  5061. }
  5062. float * const wdata = params->wdata;
  5063. // cols per thread
  5064. const int dc = (ne + nth - 1)/nth;
  5065. // col range for this thread
  5066. const int ic0 = dc*ith;
  5067. const int ic1 = MIN(ic0 + dc, ne);
  5068. ggml_vec_cpy_f32(ic1 - ic0, (float *) dst->data + ic0, wdata + ic0);
  5069. for (int k = 1; k < nth; k++) {
  5070. ggml_vec_acc_f32(ic1 - ic0, (float *) dst->data + ic0, wdata + (ne + CACHE_LINE_SIZE_F32)*k + ic0);
  5071. }
  5072. return;
  5073. }
  5074. if (nb01 >= nb00) {
  5075. // TODO: do not support transposed src1
  5076. // parallelize by src0 rows using ggml_vec_dot_q4_0
  5077. // total rows in src0
  5078. const int nr = ne01*ne02*ne03;
  5079. // rows per thread
  5080. const int dr = (nr + nth - 1)/nth;
  5081. // row range for this thread
  5082. const int ir0 = dr*ith;
  5083. const int ir1 = MIN(ir0 + dr, nr);
  5084. void * wdata = params->wdata;
  5085. for (int ir = ir0; ir < ir1; ++ir) {
  5086. // src0 indices
  5087. const int i03 = ir/(ne02*ne01);
  5088. const int i02 = (ir - i03*ne02*ne01)/ne01;
  5089. const int i01 = (ir - i03*ne02*ne01 - i02*ne01);
  5090. const int i13 = i03;
  5091. const int i12 = i02;
  5092. const int i0 = i01;
  5093. const int i2 = i02;
  5094. const int i3 = i03;
  5095. void * src0_row = (void *) ((char *) src0->data + (i01*nb01 + i02*nb02 + i03*nb03));
  5096. char * src1_col = ((char *) wdata + ( (0 + i12*ne11 + i13*ne12*ne11)*ne00*GGML_TYPE_SIZE[GGML_TYPE_Q4_0])/GGML_BLCK_SIZE[GGML_TYPE_Q4_0]);
  5097. float * dst_col = (float *) ((char *) dst->data + (i0*nb0 + 0*nb1 + i2*nb2 + i3*nb3));
  5098. assert(ne00 % 32 == 0);
  5099. for (int ic = 0; ic < ne11; ++ic) {
  5100. ggml_vec_dot_q4_0(ne00, &dst_col[ic*ne0], src0_row, ((void *) (src1_col + (ic*ne00*GGML_TYPE_SIZE[GGML_TYPE_Q4_0])/GGML_BLCK_SIZE[GGML_TYPE_Q4_0])));
  5101. }
  5102. }
  5103. } else {
  5104. //printf("AAAAA ith = %d, nth = %d\n", ith, nth);
  5105. // parallelize by src1 columns using ggml_vec_mad_q4_0
  5106. // each thread has its own work data
  5107. // during FINALIZE we accumulate all work data into dst
  5108. // total columns in src1
  5109. const int nc = ne10;
  5110. // columns per thread
  5111. const int dc = (nc + nth - 1)/nth;
  5112. // column range for this thread
  5113. const int ic0 = dc*ith;
  5114. const int ic1 = MIN(ic0 + dc, nc);
  5115. // work data for thread
  5116. const int wo = (ne + CACHE_LINE_SIZE_F32)*ith;
  5117. float * const wdata = params->wdata;
  5118. for (int i13 = 0; i13 < ne13; ++i13) {
  5119. for (int i12 = 0; i12 < ne12; ++i12) {
  5120. for (int i11 = 0; i11 < ne11; ++i11) {
  5121. // dst indices
  5122. const int i1 = i11;
  5123. const int i2 = i12;
  5124. const int i3 = i13;
  5125. float * dst_row = wdata + wo + i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0;
  5126. for (int ic = ic0; ic < ic1; ++ic) {
  5127. // src1 indices
  5128. const int i10 = ic;
  5129. // src0 indices
  5130. const int i03 = i13;
  5131. const int i02 = i12;
  5132. const int i00 = ic;
  5133. assert(sizeof(float)*(wo + i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0 + ne01) <= params->wsize);
  5134. void * src0_col = (void *) ((char *) src0->data + (i00*nb00 + i02*nb02 + i03*nb03));
  5135. float src1_val = *(float *) ((char *) src1->data + (i10*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  5136. ggml_vec_mad_q4_0(ne01, dst_row, src0_col, src1_val);
  5137. }
  5138. }
  5139. }
  5140. }
  5141. }
  5142. //int64_t t1 = ggml_time_us();
  5143. //static int64_t acc = 0;
  5144. //acc += t1 - t0;
  5145. //if (t1 - t0 > 10) {
  5146. // printf("\n");
  5147. // printf("ne00 = %5d, ne01 = %5d, ne02 = %5d, ne03 = %5d\n", ne00, ne01, ne02, ne03);
  5148. // printf("nb00 = %5d, nb01 = %5d, nb02 = %5d, nb03 = %5d\n", nb00, nb01, nb02, nb03);
  5149. // printf("ne10 = %5d, ne11 = %5d, ne12 = %5d, ne13 = %5d\n", ne10, ne11, ne12, ne13);
  5150. // printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX task %d/%d: %d us, acc = %d\n", ith, nth, (int) (t1 - t0), (int) acc);
  5151. //}
  5152. }
  5153. static void ggml_compute_forward_mul_mat_q4_1_f32(
  5154. const struct ggml_compute_params * params,
  5155. const struct ggml_tensor * src0,
  5156. const struct ggml_tensor * src1,
  5157. struct ggml_tensor * dst) {
  5158. int64_t t0 = ggml_perf_time_us();
  5159. UNUSED(t0);
  5160. const int ne00 = src0->ne[0];
  5161. const int ne01 = src0->ne[1];
  5162. const int ne02 = src0->ne[2];
  5163. const int ne03 = src0->ne[3];
  5164. const int ne10 = src1->ne[0];
  5165. const int ne11 = src1->ne[1];
  5166. const int ne12 = src1->ne[2];
  5167. const int ne13 = src1->ne[3];
  5168. const int ne0 = dst->ne[0];
  5169. const int ne1 = dst->ne[1];
  5170. const int ne2 = dst->ne[2];
  5171. const int ne3 = dst->ne[3];
  5172. const int ne = ne0*ne1*ne2*ne3;
  5173. const int nb00 = src0->nb[0];
  5174. const int nb01 = src0->nb[1];
  5175. const int nb02 = src0->nb[2];
  5176. const int nb03 = src0->nb[3];
  5177. const int nb10 = src1->nb[0];
  5178. const int nb11 = src1->nb[1];
  5179. const int nb12 = src1->nb[2];
  5180. const int nb13 = src1->nb[3];
  5181. const int nb0 = dst->nb[0];
  5182. const int nb1 = dst->nb[1];
  5183. const int nb2 = dst->nb[2];
  5184. const int nb3 = dst->nb[3];
  5185. const int ith = params->ith;
  5186. const int nth = params->nth;
  5187. GGML_ASSERT(ne02 == ne12);
  5188. GGML_ASSERT(ne03 == ne13);
  5189. GGML_ASSERT(ne2 == ne12);
  5190. GGML_ASSERT(ne3 == ne13);
  5191. // TODO: we don't support permuted src0
  5192. GGML_ASSERT(nb00 == (int) GGML_TYPE_SIZE[GGML_TYPE_Q4_1] || nb01 == (int) GGML_TYPE_SIZE[GGML_TYPE_Q4_1]);
  5193. // dst cannot be transposed or permuted
  5194. GGML_ASSERT(nb0 == sizeof(float));
  5195. GGML_ASSERT(nb0 <= nb1);
  5196. GGML_ASSERT(nb1 <= nb2);
  5197. GGML_ASSERT(nb2 <= nb3);
  5198. GGML_ASSERT(ne0 == ne01);
  5199. GGML_ASSERT(ne1 == ne11);
  5200. GGML_ASSERT(ne2 == ne02);
  5201. GGML_ASSERT(ne3 == ne03);
  5202. // nb01 >= nb00 - src0 is not transposed
  5203. // compute by src0 rows
  5204. //
  5205. // nb00 < nb01 - src0 is transposed
  5206. // compute by src0 columns
  5207. #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
  5208. if (ggml_compute_forward_mul_mat_use_blas(src0, src1, dst)) {
  5209. GGML_ASSERT(nb10 == sizeof(float));
  5210. if (params->ith != 0) {
  5211. return;
  5212. }
  5213. if (params->type == GGML_TASK_INIT) {
  5214. return;
  5215. }
  5216. if (params->type == GGML_TASK_FINALIZE) {
  5217. return;
  5218. }
  5219. float * const wdata = params->wdata;
  5220. for (int i03 = 0; i03 < ne03; i03++) {
  5221. for (int i02 = 0; i02 < ne02; i02++) {
  5222. {
  5223. int id = 0;
  5224. for (int i01 = 0; i01 < ne01; ++i01) {
  5225. //for (int i00 = 0; i00 < ne00; ++i00) {
  5226. // wdata[id++] = GGML_FP16_TO_FP32(*(ggml_fp16_t *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00));
  5227. //}
  5228. dequantize_row_q4_1((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01, wdata + id, ne00);
  5229. id += ne00;
  5230. }
  5231. }
  5232. const float * x = wdata;
  5233. const float * y = (float *) ((char *) src1->data + i02*nb12 + i03*nb13);
  5234. // float * z = wdata + ne00*ne01;
  5235. // z = x * yT
  5236. //{
  5237. // cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
  5238. // ne01, ne11, ne00,
  5239. // 1.0f, x, ne00,
  5240. // y, ne00,
  5241. // 0.0f, z, ne11);
  5242. //}
  5243. float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
  5244. // transpose z
  5245. //for (int j = 0; j < ne11; ++j) {
  5246. // for (int i = 0; i < ne01; ++i) {
  5247. // d[j*ne01 + i] = z[i*ne11 + j];
  5248. // }
  5249. //}
  5250. {
  5251. #if 1
  5252. // zT = y * xT
  5253. cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
  5254. ne11, ne01, ne10,
  5255. 1.0f, y, ne00,
  5256. x, ne00,
  5257. 0.0f, d, ne01);
  5258. #else
  5259. // zT = (xT * y)T
  5260. cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans,
  5261. ne01, ne11, ne10,
  5262. 1.0f, x, ne00,
  5263. y, ne00,
  5264. 0.0f, d, ne01);
  5265. #endif
  5266. }
  5267. }
  5268. }
  5269. //printf("CBLAS = %f ms, %d x %d x %d x %d\n", (ggml_perf_time_us() - t0)/1000.0, ne0, ne1, ne2, ne3);
  5270. return;
  5271. }
  5272. #endif
  5273. if (params->type == GGML_TASK_INIT) {
  5274. //printf("HHHHHHHHH ith = %d, nth = %d\n", ith, nth);
  5275. if (nb01 >= nb00) {
  5276. char * wdata = params->wdata;
  5277. for (int i13 = 0; i13 < ne13; ++i13) {
  5278. for (int i12 = 0; i12 < ne12; ++i12) {
  5279. for (int i11 = 0; i11 < ne11; ++i11) {
  5280. //for (int i10 = 0; i10 < ne10; ++i10) {
  5281. // wdata[id++] = GGML_FP32_TO_FP16(*(float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10));
  5282. //}
  5283. quantize_row_q4_1((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11), (void *) wdata, ne10);
  5284. wdata += (ne10*GGML_TYPE_SIZE[GGML_TYPE_Q4_1])/GGML_BLCK_SIZE[GGML_TYPE_Q4_1];
  5285. }
  5286. }
  5287. }
  5288. return;
  5289. }
  5290. // TODO: fix this memset (wsize is overestimated)
  5291. memset(params->wdata, 0, params->wsize);
  5292. return;
  5293. }
  5294. if (params->type == GGML_TASK_FINALIZE) {
  5295. if (nb01 >= nb00) {
  5296. return;
  5297. }
  5298. float * const wdata = params->wdata;
  5299. // cols per thread
  5300. const int dc = (ne + nth - 1)/nth;
  5301. // col range for this thread
  5302. const int ic0 = dc*ith;
  5303. const int ic1 = MIN(ic0 + dc, ne);
  5304. ggml_vec_cpy_f32(ic1 - ic0, (float *) dst->data + ic0, wdata + ic0);
  5305. for (int k = 1; k < nth; k++) {
  5306. ggml_vec_acc_f32(ic1 - ic0, (float *) dst->data + ic0, wdata + (ne + CACHE_LINE_SIZE_F32)*k + ic0);
  5307. }
  5308. return;
  5309. }
  5310. if (nb01 >= nb00) {
  5311. // TODO: do not support transposed src1
  5312. // parallelize by src0 rows using ggml_vec_dot_q4_1
  5313. // total rows in src0
  5314. const int nr = ne01*ne02*ne03;
  5315. // rows per thread
  5316. const int dr = (nr + nth - 1)/nth;
  5317. // row range for this thread
  5318. const int ir0 = dr*ith;
  5319. const int ir1 = MIN(ir0 + dr, nr);
  5320. void * wdata = params->wdata;
  5321. for (int ir = ir0; ir < ir1; ++ir) {
  5322. // src0 indices
  5323. const int i03 = ir/(ne02*ne01);
  5324. const int i02 = (ir - i03*ne02*ne01)/ne01;
  5325. const int i01 = (ir - i03*ne02*ne01 - i02*ne01);
  5326. const int i13 = i03;
  5327. const int i12 = i02;
  5328. const int i0 = i01;
  5329. const int i2 = i02;
  5330. const int i3 = i03;
  5331. void * src0_row = (void *) ((char *) src0->data + (i01*nb01 + i02*nb02 + i03*nb03));
  5332. char * src1_col = ((char *) wdata + ( (0 + i12*ne11 + i13*ne12*ne11)*ne00*GGML_TYPE_SIZE[GGML_TYPE_Q4_1])/GGML_BLCK_SIZE[GGML_TYPE_Q4_1]);
  5333. float * dst_col = (float *) ((char *) dst->data + (i0*nb0 + 0*nb1 + i2*nb2 + i3*nb3));
  5334. assert(ne00 % 32 == 0);
  5335. for (int ic = 0; ic < ne11; ++ic) {
  5336. ggml_vec_dot_q4_1(ne00, &dst_col[ic*ne0], src0_row, ((void *) (src1_col + (ic*ne00*GGML_TYPE_SIZE[GGML_TYPE_Q4_1])/GGML_BLCK_SIZE[GGML_TYPE_Q4_1])));
  5337. }
  5338. }
  5339. } else {
  5340. //printf("AAAAA ith = %d, nth = %d\n", ith, nth);
  5341. // parallelize by src1 columns using ggml_vec_mad_q4_1
  5342. // each thread has its own work data
  5343. // during FINALIZE we accumulate all work data into dst
  5344. // total columns in src1
  5345. const int nc = ne10;
  5346. // columns per thread
  5347. const int dc = (nc + nth - 1)/nth;
  5348. // column range for this thread
  5349. const int ic0 = dc*ith;
  5350. const int ic1 = MIN(ic0 + dc, nc);
  5351. // work data for thread
  5352. const int wo = (ne + CACHE_LINE_SIZE_F32)*ith;
  5353. float * const wdata = params->wdata;
  5354. for (int i13 = 0; i13 < ne13; ++i13) {
  5355. for (int i12 = 0; i12 < ne12; ++i12) {
  5356. for (int i11 = 0; i11 < ne11; ++i11) {
  5357. // dst indices
  5358. const int i1 = i11;
  5359. const int i2 = i12;
  5360. const int i3 = i13;
  5361. float * dst_row = wdata + wo + i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0;
  5362. for (int ic = ic0; ic < ic1; ++ic) {
  5363. // src1 indices
  5364. const int i10 = ic;
  5365. // src0 indices
  5366. const int i03 = i13;
  5367. const int i02 = i12;
  5368. const int i00 = ic;
  5369. assert(sizeof(float)*(wo + i3*ne2*ne1*ne0 + i2*ne1*ne0 + i1*ne0 + ne01) <= params->wsize);
  5370. void * src0_col = (void *) ((char *) src0->data + (i00*nb00 + i02*nb02 + i03*nb03));
  5371. float src1_val = *(float *) ((char *) src1->data + (i10*nb10 + i11*nb11 + i12*nb12 + i13*nb13));
  5372. ggml_vec_mad_q4_1(ne01, dst_row, src0_col, src1_val);
  5373. }
  5374. }
  5375. }
  5376. }
  5377. }
  5378. //int64_t t1 = ggml_time_us();
  5379. //static int64_t acc = 0;
  5380. //acc += t1 - t0;
  5381. //if (t1 - t0 > 10) {
  5382. // printf("\n");
  5383. // printf("ne00 = %5d, ne01 = %5d, ne02 = %5d, ne03 = %5d\n", ne00, ne01, ne02, ne03);
  5384. // printf("nb00 = %5d, nb01 = %5d, nb02 = %5d, nb03 = %5d\n", nb00, nb01, nb02, nb03);
  5385. // printf("ne10 = %5d, ne11 = %5d, ne12 = %5d, ne13 = %5d\n", ne10, ne11, ne12, ne13);
  5386. // printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX task %d/%d: %d us, acc = %d\n", ith, nth, (int) (t1 - t0), (int) acc);
  5387. //}
  5388. }
  5389. static void ggml_compute_forward_mul_mat(
  5390. const struct ggml_compute_params * params,
  5391. const struct ggml_tensor * src0,
  5392. const struct ggml_tensor * src1,
  5393. struct ggml_tensor * dst) {
  5394. switch (src0->type) {
  5395. case GGML_TYPE_Q4_0:
  5396. {
  5397. ggml_compute_forward_mul_mat_q4_0_f32(params, src0, src1, dst);
  5398. } break;
  5399. case GGML_TYPE_Q4_1:
  5400. {
  5401. ggml_compute_forward_mul_mat_q4_1_f32(params, src0, src1, dst);
  5402. } break;
  5403. case GGML_TYPE_F16:
  5404. {
  5405. ggml_compute_forward_mul_mat_f16_f32(params, src0, src1, dst);
  5406. } break;
  5407. case GGML_TYPE_F32:
  5408. {
  5409. ggml_compute_forward_mul_mat_f32(params, src0, src1, dst);
  5410. } break;
  5411. case GGML_TYPE_I8:
  5412. case GGML_TYPE_I16:
  5413. case GGML_TYPE_I32:
  5414. case GGML_TYPE_COUNT:
  5415. {
  5416. GGML_ASSERT(false);
  5417. } break;
  5418. }
  5419. #if 0
  5420. if (src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_Q4_1) {
  5421. static int first = 8;
  5422. printf("src0: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", src0->ne[0], src0->ne[1], src0->ne[2]);
  5423. printf("src1: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", src1->ne[0], src1->ne[1], src1->ne[2]);
  5424. printf("dst: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
  5425. if (first) {
  5426. --first;
  5427. } else {
  5428. for (int k = 0; k < dst->ne[1]; ++k) {
  5429. for (int j = 0; j < dst->ne[0]/16; ++j) {
  5430. for (int i = 0; i < 16; ++i) {
  5431. printf("%8.4f ", ((float *) dst->data)[k*dst->ne[0] + j*16 + i]);
  5432. }
  5433. printf("\n");
  5434. }
  5435. printf("\n");
  5436. }
  5437. printf("\n");
  5438. exit(0);
  5439. }
  5440. } else {
  5441. printf("aaaa src0: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", src0->ne[0], src0->ne[1], src0->ne[2]);
  5442. printf("aaaa src1: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", src1->ne[0], src1->ne[1], src1->ne[2]);
  5443. printf("aaaa dst: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
  5444. }
  5445. #endif
  5446. }
  5447. // ggml_compute_forward_scale
  5448. static void ggml_compute_forward_scale_f32(
  5449. const struct ggml_compute_params * params,
  5450. const struct ggml_tensor * src0,
  5451. const struct ggml_tensor * src1,
  5452. struct ggml_tensor * dst) {
  5453. GGML_ASSERT(ggml_is_contiguous(src0));
  5454. GGML_ASSERT(ggml_is_contiguous(dst));
  5455. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  5456. GGML_ASSERT(ggml_is_scalar(src1));
  5457. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  5458. return;
  5459. }
  5460. // scale factor
  5461. const float v = *(float *) src1->data;
  5462. const int ith = params->ith;
  5463. const int nth = params->nth;
  5464. const int nc = src0->ne[0];
  5465. const int nr = ggml_nrows(src0);
  5466. // rows per thread
  5467. const int dr = (nr + nth - 1)/nth;
  5468. // row range for this thread
  5469. const int ir0 = dr*ith;
  5470. const int ir1 = MIN(ir0 + dr, nr);
  5471. for (int i1 = ir0; i1 < ir1; i1++) {
  5472. ggml_vec_scale_f32(nc, (float *) ((char *) dst->data + i1*(dst->nb[1])), v);
  5473. }
  5474. }
  5475. static void ggml_compute_forward_scale(
  5476. const struct ggml_compute_params * params,
  5477. const struct ggml_tensor * src0,
  5478. const struct ggml_tensor * src1,
  5479. struct ggml_tensor * dst) {
  5480. switch (src0->type) {
  5481. case GGML_TYPE_F32:
  5482. {
  5483. ggml_compute_forward_scale_f32(params, src0, src1, dst);
  5484. } break;
  5485. case GGML_TYPE_Q4_0:
  5486. case GGML_TYPE_Q4_1:
  5487. case GGML_TYPE_I8:
  5488. case GGML_TYPE_I16:
  5489. case GGML_TYPE_I32:
  5490. case GGML_TYPE_F16:
  5491. case GGML_TYPE_COUNT:
  5492. {
  5493. GGML_ASSERT(false);
  5494. } break;
  5495. }
  5496. }
  5497. // ggml_compute_forward_cpy
  5498. static void ggml_compute_forward_cpy(
  5499. const struct ggml_compute_params * params,
  5500. const struct ggml_tensor * src0,
  5501. struct ggml_tensor * dst) {
  5502. ggml_compute_forward_dup(params, src0, dst);
  5503. }
  5504. // ggml_compute_forward_reshape
  5505. static void ggml_compute_forward_reshape(
  5506. const struct ggml_compute_params * params,
  5507. const struct ggml_tensor * src0,
  5508. struct ggml_tensor * dst) {
  5509. // NOP
  5510. UNUSED(params);
  5511. UNUSED(src0);
  5512. UNUSED(dst);
  5513. }
  5514. // ggml_compute_forward_view
  5515. static void ggml_compute_forward_view(
  5516. const struct ggml_compute_params * params,
  5517. const struct ggml_tensor * src0) {
  5518. // NOP
  5519. UNUSED(params);
  5520. UNUSED(src0);
  5521. }
  5522. // ggml_compute_forward_permute
  5523. static void ggml_compute_forward_permute(
  5524. const struct ggml_compute_params * params,
  5525. const struct ggml_tensor * src0) {
  5526. // NOP
  5527. UNUSED(params);
  5528. UNUSED(src0);
  5529. }
  5530. // ggml_compute_forward_transpose
  5531. static void ggml_compute_forward_transpose(
  5532. const struct ggml_compute_params * params,
  5533. const struct ggml_tensor * src0) {
  5534. // NOP
  5535. UNUSED(params);
  5536. UNUSED(src0);
  5537. }
  5538. // ggml_compute_forward_get_rows
  5539. static void ggml_compute_forward_get_rows_q4_0(
  5540. const struct ggml_compute_params * params,
  5541. const struct ggml_tensor * src0,
  5542. const struct ggml_tensor * src1,
  5543. struct ggml_tensor * dst) {
  5544. assert(params->ith == 0);
  5545. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  5546. return;
  5547. }
  5548. const int nc = src0->ne[0];
  5549. const int nr = ggml_nelements(src1);
  5550. assert( dst->ne[0] == nc);
  5551. assert( dst->ne[1] == nr);
  5552. assert(src0->nb[0] == GGML_TYPE_SIZE[GGML_TYPE_Q4_0]);
  5553. for (int i = 0; i < nr; ++i) {
  5554. const int r = ((int32_t *) src1->data)[i];
  5555. dequantize_row_q4_0(
  5556. (const void *) ((char *) src0->data + r*src0->nb[1]),
  5557. (float *) ((char *) dst->data + i*dst->nb[1]), nc);
  5558. }
  5559. }
  5560. static void ggml_compute_forward_get_rows_q4_1(
  5561. const struct ggml_compute_params * params,
  5562. const struct ggml_tensor * src0,
  5563. const struct ggml_tensor * src1,
  5564. struct ggml_tensor * dst) {
  5565. assert(params->ith == 0);
  5566. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  5567. return;
  5568. }
  5569. const int nc = src0->ne[0];
  5570. const int nr = ggml_nelements(src1);
  5571. assert( dst->ne[0] == nc);
  5572. assert( dst->ne[1] == nr);
  5573. assert(src0->nb[0] == GGML_TYPE_SIZE[GGML_TYPE_Q4_1]);
  5574. for (int i = 0; i < nr; ++i) {
  5575. const int r = ((int32_t *) src1->data)[i];
  5576. dequantize_row_q4_1(
  5577. (const void *) ((char *) src0->data + r*src0->nb[1]),
  5578. (float *) ((char *) dst->data + i*dst->nb[1]), nc);
  5579. }
  5580. }
  5581. static void ggml_compute_forward_get_rows_f16(
  5582. const struct ggml_compute_params * params,
  5583. const struct ggml_tensor * src0,
  5584. const struct ggml_tensor * src1,
  5585. struct ggml_tensor * dst) {
  5586. assert(params->ith == 0);
  5587. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  5588. return;
  5589. }
  5590. const int nc = src0->ne[0];
  5591. const int nr = ggml_nelements(src1);
  5592. assert( dst->ne[0] == nc);
  5593. assert( dst->ne[1] == nr);
  5594. assert(src0->nb[0] == sizeof(ggml_fp16_t));
  5595. for (int i = 0; i < nr; ++i) {
  5596. const int r = ((int32_t *) src1->data)[i];
  5597. for (int j = 0; j < nc; ++j) {
  5598. ggml_fp16_t v = ((ggml_fp16_t *) ((char *) src0->data + r*src0->nb[1]))[j];
  5599. ((float *) ((char *) dst->data + i*dst->nb[1]))[j] = GGML_FP16_TO_FP32(v);
  5600. }
  5601. }
  5602. }
  5603. static void ggml_compute_forward_get_rows_f32(
  5604. const struct ggml_compute_params * params,
  5605. const struct ggml_tensor * src0,
  5606. const struct ggml_tensor * src1,
  5607. struct ggml_tensor * dst) {
  5608. assert(params->ith == 0);
  5609. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  5610. return;
  5611. }
  5612. const int nc = src0->ne[0];
  5613. const int nr = ggml_nelements(src1);
  5614. assert( dst->ne[0] == nc);
  5615. assert( dst->ne[1] == nr);
  5616. assert(src0->nb[0] == sizeof(float));
  5617. for (int i = 0; i < nr; ++i) {
  5618. const int r = ((int32_t *) src1->data)[i];
  5619. ggml_vec_cpy_f32(nc,
  5620. (float *) ((char *) dst->data + i*dst->nb[1]),
  5621. (float *) ((char *) src0->data + r*src0->nb[1]));
  5622. }
  5623. }
  5624. static void ggml_compute_forward_get_rows(
  5625. const struct ggml_compute_params * params,
  5626. const struct ggml_tensor * src0,
  5627. const struct ggml_tensor * src1,
  5628. struct ggml_tensor * dst) {
  5629. switch (src0->type) {
  5630. case GGML_TYPE_Q4_0:
  5631. {
  5632. ggml_compute_forward_get_rows_q4_0(params, src0, src1, dst);
  5633. } break;
  5634. case GGML_TYPE_Q4_1:
  5635. {
  5636. ggml_compute_forward_get_rows_q4_1(params, src0, src1, dst);
  5637. } break;
  5638. case GGML_TYPE_F16:
  5639. {
  5640. ggml_compute_forward_get_rows_f16(params, src0, src1, dst);
  5641. } break;
  5642. case GGML_TYPE_F32:
  5643. {
  5644. ggml_compute_forward_get_rows_f32(params, src0, src1, dst);
  5645. } break;
  5646. case GGML_TYPE_I8:
  5647. case GGML_TYPE_I16:
  5648. case GGML_TYPE_I32:
  5649. case GGML_TYPE_COUNT:
  5650. {
  5651. GGML_ASSERT(false);
  5652. } break;
  5653. }
  5654. //static bool first = true;
  5655. //printf("ne0 = %d, ne1 = %d, ne2 = %d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
  5656. //if (first) {
  5657. // first = false;
  5658. //} else {
  5659. // for (int k = 0; k < dst->ne[1]; ++k) {
  5660. // for (int j = 0; j < dst->ne[0]/16; ++j) {
  5661. // for (int i = 0; i < 16; ++i) {
  5662. // printf("%8.4f ", ((float *) dst->data)[k*dst->ne[0] + j*16 + i]);
  5663. // }
  5664. // printf("\n");
  5665. // }
  5666. // printf("\n");
  5667. // }
  5668. // printf("\n");
  5669. // exit(0);
  5670. //}
  5671. }
  5672. // ggml_compute_forward_diag_mask_inf
  5673. static void ggml_compute_forward_diag_mask_inf_f32(
  5674. const struct ggml_compute_params * params,
  5675. const struct ggml_tensor * src0,
  5676. const struct ggml_tensor * src1,
  5677. struct ggml_tensor * dst) {
  5678. assert(params->ith == 0);
  5679. assert(src1->type == GGML_TYPE_I32);
  5680. assert(ggml_nelements(src1) == 1);
  5681. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  5682. return;
  5683. }
  5684. const int n_past = ((int32_t *) src1->data)[0];
  5685. // TODO: handle transposed/permuted matrices
  5686. const int n = ggml_nrows(src0);
  5687. const int nc = src0->ne[0];
  5688. const int nr = src0->ne[1];
  5689. const int nz = n/nr;
  5690. assert( dst->nb[0] == sizeof(float));
  5691. assert(src0->nb[0] == sizeof(float));
  5692. for (int k = 0; k < nz; k++) {
  5693. for (int j = 0; j < nr; j++) {
  5694. for (int i = n_past; i < nc; i++) {
  5695. if (i > n_past + j) {
  5696. *(float *)((char *) dst->data + k*dst->nb[2] + j*dst->nb[1] + i*dst->nb[0]) = -INFINITY;
  5697. }
  5698. }
  5699. }
  5700. }
  5701. }
  5702. static void ggml_compute_forward_diag_mask_inf(
  5703. const struct ggml_compute_params * params,
  5704. const struct ggml_tensor * src0,
  5705. const struct ggml_tensor * src1,
  5706. struct ggml_tensor * dst) {
  5707. switch (src0->type) {
  5708. case GGML_TYPE_F32:
  5709. {
  5710. ggml_compute_forward_diag_mask_inf_f32(params, src0, src1, dst);
  5711. } break;
  5712. case GGML_TYPE_Q4_0:
  5713. case GGML_TYPE_Q4_1:
  5714. case GGML_TYPE_I8:
  5715. case GGML_TYPE_I16:
  5716. case GGML_TYPE_I32:
  5717. case GGML_TYPE_F16:
  5718. case GGML_TYPE_COUNT:
  5719. {
  5720. GGML_ASSERT(false);
  5721. } break;
  5722. }
  5723. }
  5724. // ggml_compute_forward_soft_max
  5725. static void ggml_compute_forward_soft_max_f32(
  5726. const struct ggml_compute_params * params,
  5727. const struct ggml_tensor * src0,
  5728. struct ggml_tensor * dst) {
  5729. GGML_ASSERT(ggml_is_contiguous(src0));
  5730. GGML_ASSERT(ggml_is_contiguous(dst));
  5731. GGML_ASSERT(ggml_are_same_shape(src0, dst));
  5732. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  5733. return;
  5734. }
  5735. // TODO: handle transposed/permuted matrices
  5736. const int ith = params->ith;
  5737. const int nth = params->nth;
  5738. const int nc = src0->ne[0];
  5739. const int nr = ggml_nrows(src0);
  5740. // rows per thread
  5741. const int dr = (nr + nth - 1)/nth;
  5742. // row range for this thread
  5743. const int ir0 = dr*ith;
  5744. const int ir1 = MIN(ir0 + dr, nr);
  5745. for (int i1 = ir0; i1 < ir1; i1++) {
  5746. float *p = (float *)((char *) dst->data + i1*dst->nb[1]);
  5747. #ifndef NDEBUG
  5748. for (int i = 0; i < nc; ++i) {
  5749. //printf("p[%d] = %f\n", i, p[i]);
  5750. assert(!isnan(p[i]));
  5751. }
  5752. #endif
  5753. float max = -INFINITY;
  5754. ggml_vec_max_f32(nc, &max, p);
  5755. ggml_float sum = 0.0;
  5756. uint16_t scvt;
  5757. for (int i = 0; i < nc; i++) {
  5758. if (p[i] == -INFINITY) {
  5759. p[i] = 0.0f;
  5760. } else {
  5761. //const float val = (p[i] == -INFINITY) ? 0.0 : exp(p[i] - max);
  5762. ggml_fp16_t s = GGML_FP32_TO_FP16(p[i] - max);
  5763. memcpy(&scvt, &s, sizeof(scvt));
  5764. const float val = GGML_FP16_TO_FP32(table_exp_f16[scvt]);
  5765. sum += val;
  5766. p[i] = val;
  5767. }
  5768. }
  5769. assert(sum > 0.0f);
  5770. sum = 1.0/sum;
  5771. ggml_vec_scale_f32(nc, p, sum);
  5772. #ifndef NDEBUG
  5773. for (int i = 0; i < nc; ++i) {
  5774. assert(!isnan(p[i]));
  5775. assert(!isinf(p[i]));
  5776. }
  5777. #endif
  5778. }
  5779. }
  5780. static void ggml_compute_forward_soft_max(
  5781. const struct ggml_compute_params * params,
  5782. const struct ggml_tensor * src0,
  5783. struct ggml_tensor * dst) {
  5784. switch (src0->type) {
  5785. case GGML_TYPE_F32:
  5786. {
  5787. ggml_compute_forward_soft_max_f32(params, src0, dst);
  5788. } break;
  5789. case GGML_TYPE_Q4_0:
  5790. case GGML_TYPE_Q4_1:
  5791. case GGML_TYPE_I8:
  5792. case GGML_TYPE_I16:
  5793. case GGML_TYPE_I32:
  5794. case GGML_TYPE_F16:
  5795. case GGML_TYPE_COUNT:
  5796. {
  5797. GGML_ASSERT(false);
  5798. } break;
  5799. }
  5800. }
  5801. // ggml_compute_forward_rope
  5802. static void ggml_compute_forward_rope_f32(
  5803. const struct ggml_compute_params * params,
  5804. const struct ggml_tensor * src0,
  5805. const struct ggml_tensor * src1,
  5806. struct ggml_tensor * dst) {
  5807. assert(params->ith == 0);
  5808. assert(src1->type == GGML_TYPE_I32);
  5809. assert(ggml_nelements(src1) == 3);
  5810. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  5811. return;
  5812. }
  5813. const int n_past = ((int32_t *) src1->data)[0];
  5814. const int n_dims = ((int32_t *) src1->data)[1];
  5815. const int mode = ((int32_t *) src1->data)[2];
  5816. //const int ne0 = src0->ne[0];
  5817. const int ne1 = src0->ne[1];
  5818. const int ne2 = src0->ne[2];
  5819. const int ne3 = src0->ne[3];
  5820. const int nb0 = src0->nb[0];
  5821. const int nb1 = src0->nb[1];
  5822. const int nb2 = src0->nb[2];
  5823. const int nb3 = src0->nb[3];
  5824. //printf("ne0: %d, ne1: %d, ne2: %d, ne3: %d\n", ne0, ne1, ne2, ne3);
  5825. //printf("n_past = %d, ne2 = %d\n", n_past, ne2);
  5826. assert(nb0 == sizeof(float));
  5827. // TODO: optimize
  5828. for (int i3 = 0; i3 < ne3; i3++) {
  5829. for (int i2 = (mode == 0 ? 0 : n_past); i2 < ne2; i2++) {
  5830. const int p = (mode == 0 ? n_past + i2 : i2);
  5831. for (int i1 = 0; i1 < ne1; i1++) {
  5832. for (int i0 = 0; i0 < n_dims; i0 += 2) {
  5833. const double theta = pow(10000.0, ((double)-i0)/n_dims);
  5834. const double cos_theta = cos(p*theta);
  5835. const double sin_theta = sin(p*theta);
  5836. const float * const src = (float *)((char *) src0->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  5837. float * dst_data = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  5838. double x0 = src[0];
  5839. double x1 = src[1];
  5840. dst_data[0] = x0*cos_theta - x1*sin_theta;
  5841. dst_data[1] = x0*sin_theta + x1*cos_theta;
  5842. }
  5843. }
  5844. }
  5845. }
  5846. }
  5847. static void ggml_compute_forward_rope_f16(
  5848. const struct ggml_compute_params * params,
  5849. const struct ggml_tensor * src0,
  5850. const struct ggml_tensor * src1,
  5851. struct ggml_tensor * dst) {
  5852. assert(params->ith == 0);
  5853. assert(src1->type == GGML_TYPE_I32);
  5854. assert(ggml_nelements(src1) == 3);
  5855. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  5856. return;
  5857. }
  5858. const int n_past = ((int32_t *) src1->data)[0];
  5859. const int n_dims = ((int32_t *) src1->data)[1];
  5860. const int mode = ((int32_t *) src1->data)[2];
  5861. //const int ne0 = src0->ne[0];
  5862. const int ne1 = src0->ne[1];
  5863. const int ne2 = src0->ne[2];
  5864. const int ne3 = src0->ne[3];
  5865. const int nb0 = src0->nb[0];
  5866. const int nb1 = src0->nb[1];
  5867. const int nb2 = src0->nb[2];
  5868. const int nb3 = src0->nb[3];
  5869. //printf("ne0: %d, ne1: %d, ne2: %d, ne3: %d\n", ne0, ne1, ne2, ne3);
  5870. //printf("n_past = %d, ne2 = %d\n", n_past, ne2);
  5871. assert(nb0 == sizeof(ggml_fp16_t));
  5872. for (int i3 = 0; i3 < ne3; i3++) {
  5873. for (int i2 = (mode == 0 ? 0 : n_past); i2 < ne2; i2++) {
  5874. const int p = (mode == 0 ? n_past + i2 : i2);
  5875. for (int i1 = 0; i1 < ne1; i1++) {
  5876. for (int i0 = 0; i0 < n_dims; i0 += 2) {
  5877. const double theta = pow(10000.0, ((double)-i0)/n_dims);
  5878. const double cos_theta = cos(p*theta);
  5879. const double sin_theta = sin(p*theta);
  5880. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  5881. ggml_fp16_t * dst_data = (ggml_fp16_t *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
  5882. double x0 = ggml_fp16_to_fp32(src[0]);
  5883. double x1 = ggml_fp16_to_fp32(src[1]);
  5884. dst_data[0] = ggml_fp32_to_fp16(x0*cos_theta - x1*sin_theta);
  5885. dst_data[1] = ggml_fp32_to_fp16(x0*sin_theta + x1*cos_theta);
  5886. }
  5887. }
  5888. }
  5889. }
  5890. }
  5891. static void ggml_compute_forward_rope(
  5892. const struct ggml_compute_params * params,
  5893. const struct ggml_tensor * src0,
  5894. const struct ggml_tensor * src1,
  5895. struct ggml_tensor * dst) {
  5896. switch (src0->type) {
  5897. case GGML_TYPE_F16:
  5898. {
  5899. ggml_compute_forward_rope_f16(params, src0, src1, dst);
  5900. } break;
  5901. case GGML_TYPE_F32:
  5902. {
  5903. ggml_compute_forward_rope_f32(params, src0, src1, dst);
  5904. } break;
  5905. case GGML_TYPE_Q4_0:
  5906. case GGML_TYPE_Q4_1:
  5907. case GGML_TYPE_I8:
  5908. case GGML_TYPE_I16:
  5909. case GGML_TYPE_I32:
  5910. case GGML_TYPE_COUNT:
  5911. {
  5912. GGML_ASSERT(false);
  5913. } break;
  5914. }
  5915. }
  5916. // ggml_compute_forward_conv_1d_1s
  5917. static void ggml_compute_forward_conv_1d_1s_f16_f32(
  5918. const struct ggml_compute_params * params,
  5919. const struct ggml_tensor * src0,
  5920. const struct ggml_tensor * src1,
  5921. struct ggml_tensor * dst) {
  5922. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5923. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5924. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  5925. int64_t t0 = ggml_perf_time_us();
  5926. UNUSED(t0);
  5927. const int ne00 = src0->ne[0];
  5928. const int ne01 = src0->ne[1];
  5929. const int ne02 = src0->ne[2];
  5930. //const int ne03 = src0->ne[3];
  5931. const int ne10 = src1->ne[0];
  5932. const int ne11 = src1->ne[1];
  5933. //const int ne12 = src1->ne[2];
  5934. //const int ne13 = src1->ne[3];
  5935. //const int ne0 = dst->ne[0];
  5936. //const int ne1 = dst->ne[1];
  5937. //const int ne2 = dst->ne[2];
  5938. //const int ne3 = dst->ne[3];
  5939. //const int ne = ne0*ne1*ne2*ne3;
  5940. const int nb00 = src0->nb[0];
  5941. const int nb01 = src0->nb[1];
  5942. const int nb02 = src0->nb[2];
  5943. //const int nb03 = src0->nb[3];
  5944. const int nb10 = src1->nb[0];
  5945. const int nb11 = src1->nb[1];
  5946. //const int nb12 = src1->nb[2];
  5947. //const int nb13 = src1->nb[3];
  5948. //const int nb0 = dst->nb[0];
  5949. const int nb1 = dst->nb[1];
  5950. //const int nb2 = dst->nb[2];
  5951. //const int nb3 = dst->nb[3];
  5952. const int ith = params->ith;
  5953. const int nth = params->nth;
  5954. const int nk = ne00;
  5955. const int nh = nk/2;
  5956. const int ew0 = ggml_up32(ne01);
  5957. GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
  5958. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  5959. GGML_ASSERT(nb10 == sizeof(float));
  5960. if (params->type == GGML_TASK_INIT) {
  5961. // TODO: fix this memset (wsize is overestimated)
  5962. memset(params->wdata, 0, params->wsize);
  5963. // prepare kernel data (src0)
  5964. {
  5965. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  5966. for (int i02 = 0; i02 < ne02; i02++) {
  5967. for (int i01 = 0; i01 < ne01; i01++) {
  5968. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i02*nb02 + i01*nb01);
  5969. ggml_fp16_t * dst_data = wdata + i02*ew0*ne00;
  5970. for (int i00 = 0; i00 < ne00; i00++) {
  5971. dst_data[i00*ew0 + i01] = src[i00];
  5972. }
  5973. }
  5974. }
  5975. }
  5976. // prepare source data (src1)
  5977. {
  5978. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + ne02*ew0*ne00;
  5979. for (int i11 = 0; i11 < ne11; i11++) {
  5980. const float * const src = (float *)((char *) src1->data + i11*nb11);
  5981. ggml_fp16_t * dst_data = wdata;
  5982. for (int i10 = 0; i10 < ne10; i10++) {
  5983. dst_data[(i10 + nh)*ew0 + i11] = GGML_FP32_TO_FP16(src[i10]);
  5984. }
  5985. }
  5986. }
  5987. return;
  5988. }
  5989. if (params->type == GGML_TASK_FINALIZE) {
  5990. return;
  5991. }
  5992. // total rows in dst
  5993. const int nr = ne02;
  5994. // rows per thread
  5995. const int dr = (nr + nth - 1)/nth;
  5996. // row range for this thread
  5997. const int ir0 = dr*ith;
  5998. const int ir1 = MIN(ir0 + dr, nr);
  5999. for (int i1 = ir0; i1 < ir1; i1++) {
  6000. float * dst_data = (float *)((char *) dst->data + i1*nb1);
  6001. for (int i0 = 0; i0 < ne10; ++i0) {
  6002. dst_data[i0] = 0;
  6003. for (int k = -nh; k <= nh; k++) {
  6004. float v = 0.0f;
  6005. ggml_vec_dot_f16(ew0, &v,
  6006. (ggml_fp16_t *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
  6007. (ggml_fp16_t *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
  6008. dst_data[i0] += v;
  6009. }
  6010. }
  6011. }
  6012. }
  6013. static void ggml_compute_forward_conv_1d_1s_f32(
  6014. const struct ggml_compute_params * params,
  6015. const struct ggml_tensor * src0,
  6016. const struct ggml_tensor * src1,
  6017. struct ggml_tensor * dst) {
  6018. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  6019. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6020. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  6021. int64_t t0 = ggml_perf_time_us();
  6022. UNUSED(t0);
  6023. const int ne00 = src0->ne[0];
  6024. const int ne01 = src0->ne[1];
  6025. const int ne02 = src0->ne[2];
  6026. //const int ne03 = src0->ne[3];
  6027. const int ne10 = src1->ne[0];
  6028. const int ne11 = src1->ne[1];
  6029. //const int ne12 = src1->ne[2];
  6030. //const int ne13 = src1->ne[3];
  6031. //const int ne0 = dst->ne[0];
  6032. //const int ne1 = dst->ne[1];
  6033. //const int ne2 = dst->ne[2];
  6034. //const int ne3 = dst->ne[3];
  6035. //const int ne = ne0*ne1*ne2*ne3;
  6036. const int nb00 = src0->nb[0];
  6037. const int nb01 = src0->nb[1];
  6038. const int nb02 = src0->nb[2];
  6039. //const int nb03 = src0->nb[3];
  6040. const int nb10 = src1->nb[0];
  6041. const int nb11 = src1->nb[1];
  6042. //const int nb12 = src1->nb[2];
  6043. //const int nb13 = src1->nb[3];
  6044. //const int nb0 = dst->nb[0];
  6045. const int nb1 = dst->nb[1];
  6046. //const int nb2 = dst->nb[2];
  6047. //const int nb3 = dst->nb[3];
  6048. const int ith = params->ith;
  6049. const int nth = params->nth;
  6050. const int nk = ne00;
  6051. const int nh = nk/2;
  6052. const int ew0 = ggml_up32(ne01);
  6053. GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
  6054. GGML_ASSERT(nb00 == sizeof(float));
  6055. GGML_ASSERT(nb10 == sizeof(float));
  6056. if (params->type == GGML_TASK_INIT) {
  6057. // TODO: fix this memset (wsize is overestimated)
  6058. memset(params->wdata, 0, params->wsize);
  6059. // prepare kernel data (src0)
  6060. {
  6061. float * const wdata = (float *) params->wdata + 0;
  6062. for (int i02 = 0; i02 < ne02; i02++) {
  6063. for (int i01 = 0; i01 < ne01; i01++) {
  6064. const float * const src = (float *)((char *) src0->data + i02*nb02 + i01*nb01);
  6065. float * dst_data = wdata + i02*ew0*ne00;
  6066. for (int i00 = 0; i00 < ne00; i00++) {
  6067. dst_data[i00*ew0 + i01] = src[i00];
  6068. }
  6069. }
  6070. }
  6071. }
  6072. // prepare source data (src1)
  6073. {
  6074. float * const wdata = (float *) params->wdata + ne02*ew0*ne00;
  6075. for (int i11 = 0; i11 < ne11; i11++) {
  6076. const float * const src = (float *)((char *) src1->data + i11*nb11);
  6077. float * dst_data = wdata;
  6078. for (int i10 = 0; i10 < ne10; i10++) {
  6079. dst_data[(i10 + nh)*ew0 + i11] = src[i10];
  6080. }
  6081. }
  6082. }
  6083. return;
  6084. }
  6085. if (params->type == GGML_TASK_FINALIZE) {
  6086. return;
  6087. }
  6088. // total rows in dst
  6089. const int nr = ne02;
  6090. // rows per thread
  6091. const int dr = (nr + nth - 1)/nth;
  6092. // row range for this thread
  6093. const int ir0 = dr*ith;
  6094. const int ir1 = MIN(ir0 + dr, nr);
  6095. for (int i1 = ir0; i1 < ir1; i1++) {
  6096. float * dst_data = (float *)((char *) dst->data + i1*nb1);
  6097. for (int i0 = 0; i0 < ne10; ++i0) {
  6098. dst_data[i0] = 0;
  6099. for (int k = -nh; k <= nh; k++) {
  6100. float v = 0.0f;
  6101. ggml_vec_dot_f32(ew0, &v,
  6102. (float *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
  6103. (float *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
  6104. dst_data[i0] += v;
  6105. }
  6106. }
  6107. }
  6108. }
  6109. static void ggml_compute_forward_conv_1d_1s(
  6110. const struct ggml_compute_params * params,
  6111. const struct ggml_tensor * src0,
  6112. const struct ggml_tensor * src1,
  6113. struct ggml_tensor * dst) {
  6114. switch (src0->type) {
  6115. case GGML_TYPE_F16:
  6116. {
  6117. ggml_compute_forward_conv_1d_1s_f16_f32(params, src0, src1, dst);
  6118. } break;
  6119. case GGML_TYPE_F32:
  6120. {
  6121. ggml_compute_forward_conv_1d_1s_f32(params, src0, src1, dst);
  6122. } break;
  6123. case GGML_TYPE_Q4_0:
  6124. case GGML_TYPE_Q4_1:
  6125. case GGML_TYPE_I8:
  6126. case GGML_TYPE_I16:
  6127. case GGML_TYPE_I32:
  6128. case GGML_TYPE_COUNT:
  6129. {
  6130. GGML_ASSERT(false);
  6131. } break;
  6132. }
  6133. }
  6134. // ggml_compute_forward_conv_1d_2s
  6135. static void ggml_compute_forward_conv_1d_2s_f16_f32(
  6136. const struct ggml_compute_params * params,
  6137. const struct ggml_tensor * src0,
  6138. const struct ggml_tensor * src1,
  6139. struct ggml_tensor * dst) {
  6140. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6141. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6142. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  6143. int64_t t0 = ggml_perf_time_us();
  6144. UNUSED(t0);
  6145. const int ne00 = src0->ne[0];
  6146. const int ne01 = src0->ne[1];
  6147. const int ne02 = src0->ne[2];
  6148. //const int ne03 = src0->ne[3];
  6149. const int ne10 = src1->ne[0];
  6150. const int ne11 = src1->ne[1];
  6151. //const int ne12 = src1->ne[2];
  6152. //const int ne13 = src1->ne[3];
  6153. //const int ne0 = dst->ne[0];
  6154. //const int ne1 = dst->ne[1];
  6155. //const int ne2 = dst->ne[2];
  6156. //const int ne3 = dst->ne[3];
  6157. //const int ne = ne0*ne1*ne2*ne3;
  6158. const int nb00 = src0->nb[0];
  6159. const int nb01 = src0->nb[1];
  6160. const int nb02 = src0->nb[2];
  6161. //const int nb03 = src0->nb[3];
  6162. const int nb10 = src1->nb[0];
  6163. const int nb11 = src1->nb[1];
  6164. //const int nb12 = src1->nb[2];
  6165. //const int nb13 = src1->nb[3];
  6166. //const int nb0 = dst->nb[0];
  6167. const int nb1 = dst->nb[1];
  6168. //const int nb2 = dst->nb[2];
  6169. //const int nb3 = dst->nb[3];
  6170. const int ith = params->ith;
  6171. const int nth = params->nth;
  6172. const int nk = ne00;
  6173. const int nh = nk/2;
  6174. const int ew0 = ggml_up32(ne01);
  6175. GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
  6176. GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
  6177. GGML_ASSERT(nb10 == sizeof(float));
  6178. if (params->type == GGML_TASK_INIT) {
  6179. // TODO: fix this memset (wsize is overestimated)
  6180. memset(params->wdata, 0, params->wsize);
  6181. // prepare kernel data (src0)
  6182. {
  6183. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
  6184. for (int i02 = 0; i02 < ne02; i02++) {
  6185. for (int i01 = 0; i01 < ne01; i01++) {
  6186. const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i02*nb02 + i01*nb01);
  6187. ggml_fp16_t * dst_data = wdata + i02*ew0*ne00;
  6188. for (int i00 = 0; i00 < ne00; i00++) {
  6189. dst_data[i00*ew0 + i01] = src[i00];
  6190. }
  6191. }
  6192. }
  6193. }
  6194. // prepare source data (src1)
  6195. {
  6196. ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + ne02*ew0*ne00;
  6197. for (int i11 = 0; i11 < ne11; i11++) {
  6198. const float * const src = (float *)((char *) src1->data + i11*nb11);
  6199. ggml_fp16_t * dst_data = wdata;
  6200. for (int i10 = 0; i10 < ne10; i10++) {
  6201. dst_data[(i10 + nh)*ew0 + i11] = GGML_FP32_TO_FP16(src[i10]);
  6202. }
  6203. }
  6204. }
  6205. return;
  6206. }
  6207. if (params->type == GGML_TASK_FINALIZE) {
  6208. return;
  6209. }
  6210. // total rows in dst
  6211. const int nr = ne02;
  6212. // rows per thread
  6213. const int dr = (nr + nth - 1)/nth;
  6214. // row range for this thread
  6215. const int ir0 = dr*ith;
  6216. const int ir1 = MIN(ir0 + dr, nr);
  6217. for (int i1 = ir0; i1 < ir1; i1++) {
  6218. float * dst_data = (float *)((char *) dst->data + i1*nb1);
  6219. for (int i0 = 0; i0 < ne10; i0 += 2) {
  6220. dst_data[i0/2] = 0;
  6221. for (int k = -nh; k <= nh; k++) {
  6222. float v = 0.0f;
  6223. ggml_vec_dot_f16(ew0, &v,
  6224. (ggml_fp16_t *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
  6225. (ggml_fp16_t *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
  6226. dst_data[i0/2] += v;
  6227. }
  6228. }
  6229. }
  6230. }
  6231. static void ggml_compute_forward_conv_1d_2s_f32(
  6232. const struct ggml_compute_params * params,
  6233. const struct ggml_tensor * src0,
  6234. const struct ggml_tensor * src1,
  6235. struct ggml_tensor * dst) {
  6236. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  6237. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6238. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  6239. int64_t t0 = ggml_perf_time_us();
  6240. UNUSED(t0);
  6241. const int ne00 = src0->ne[0];
  6242. const int ne01 = src0->ne[1];
  6243. const int ne02 = src0->ne[2];
  6244. //const int ne03 = src0->ne[3];
  6245. const int ne10 = src1->ne[0];
  6246. const int ne11 = src1->ne[1];
  6247. //const int ne12 = src1->ne[2];
  6248. //const int ne13 = src1->ne[3];
  6249. //const int ne0 = dst->ne[0];
  6250. //const int ne1 = dst->ne[1];
  6251. //const int ne2 = dst->ne[2];
  6252. //const int ne3 = dst->ne[3];
  6253. //const int ne = ne0*ne1*ne2*ne3;
  6254. const int nb00 = src0->nb[0];
  6255. const int nb01 = src0->nb[1];
  6256. const int nb02 = src0->nb[2];
  6257. //const int nb03 = src0->nb[3];
  6258. const int nb10 = src1->nb[0];
  6259. const int nb11 = src1->nb[1];
  6260. //const int nb12 = src1->nb[2];
  6261. //const int nb13 = src1->nb[3];
  6262. //const int nb0 = dst->nb[0];
  6263. const int nb1 = dst->nb[1];
  6264. //const int nb2 = dst->nb[2];
  6265. //const int nb3 = dst->nb[3];
  6266. const int ith = params->ith;
  6267. const int nth = params->nth;
  6268. const int nk = ne00;
  6269. const int nh = nk/2;
  6270. const int ew0 = ggml_up32(ne01);
  6271. GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
  6272. GGML_ASSERT(nb00 == sizeof(float));
  6273. GGML_ASSERT(nb10 == sizeof(float));
  6274. if (params->type == GGML_TASK_INIT) {
  6275. // TODO: fix this memset (wsize is overestimated)
  6276. memset(params->wdata, 0, params->wsize);
  6277. // prepare kernel data (src0)
  6278. {
  6279. float * const wdata = (float *) params->wdata + 0;
  6280. for (int i02 = 0; i02 < ne02; i02++) {
  6281. for (int i01 = 0; i01 < ne01; i01++) {
  6282. const float * const src = (float *)((char *) src0->data + i02*nb02 + i01*nb01);
  6283. float * dst_data = wdata + i02*ew0*ne00;
  6284. for (int i00 = 0; i00 < ne00; i00++) {
  6285. dst_data[i00*ew0 + i01] = src[i00];
  6286. }
  6287. }
  6288. }
  6289. }
  6290. // prepare source data (src1)
  6291. {
  6292. float * const wdata = (float *) params->wdata + ne02*ew0*ne00;
  6293. for (int i11 = 0; i11 < ne11; i11++) {
  6294. const float * const src = (float *)((char *) src1->data + i11*nb11);
  6295. float * dst_data = wdata;
  6296. for (int i10 = 0; i10 < ne10; i10++) {
  6297. dst_data[(i10 + nh)*ew0 + i11] = src[i10];
  6298. }
  6299. }
  6300. }
  6301. return;
  6302. }
  6303. if (params->type == GGML_TASK_FINALIZE) {
  6304. return;
  6305. }
  6306. // total rows in dst
  6307. const int nr = ne02;
  6308. // rows per thread
  6309. const int dr = (nr + nth - 1)/nth;
  6310. // row range for this thread
  6311. const int ir0 = dr*ith;
  6312. const int ir1 = MIN(ir0 + dr, nr);
  6313. for (int i1 = ir0; i1 < ir1; i1++) {
  6314. float * dst_data = (float *)((char *) dst->data + i1*nb1);
  6315. for (int i0 = 0; i0 < ne10; i0 += 2) {
  6316. dst_data[i0/2] = 0;
  6317. for (int k = -nh; k <= nh; k++) {
  6318. float v = 0.0f;
  6319. ggml_vec_dot_f32(ew0, &v,
  6320. (float *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
  6321. (float *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
  6322. dst_data[i0/2] += v;
  6323. }
  6324. }
  6325. }
  6326. }
  6327. static void ggml_compute_forward_conv_1d_2s(
  6328. const struct ggml_compute_params * params,
  6329. const struct ggml_tensor * src0,
  6330. const struct ggml_tensor * src1,
  6331. struct ggml_tensor * dst) {
  6332. switch (src0->type) {
  6333. case GGML_TYPE_F16:
  6334. {
  6335. ggml_compute_forward_conv_1d_2s_f16_f32(params, src0, src1, dst);
  6336. } break;
  6337. case GGML_TYPE_F32:
  6338. {
  6339. ggml_compute_forward_conv_1d_2s_f32(params, src0, src1, dst);
  6340. } break;
  6341. case GGML_TYPE_Q4_0:
  6342. case GGML_TYPE_Q4_1:
  6343. case GGML_TYPE_I8:
  6344. case GGML_TYPE_I16:
  6345. case GGML_TYPE_I32:
  6346. case GGML_TYPE_COUNT:
  6347. {
  6348. GGML_ASSERT(false);
  6349. } break;
  6350. }
  6351. }
  6352. // ggml_compute_forward_flash_attn
  6353. static void ggml_compute_forward_flash_attn_f32(
  6354. const struct ggml_compute_params * params,
  6355. const struct ggml_tensor * q,
  6356. const struct ggml_tensor * k,
  6357. const struct ggml_tensor * v,
  6358. const bool masked,
  6359. struct ggml_tensor * dst) {
  6360. int64_t t0 = ggml_perf_time_us();
  6361. UNUSED(t0);
  6362. const int neq0 = q->ne[0];
  6363. const int neq1 = q->ne[1];
  6364. const int neq2 = q->ne[2];
  6365. const int neq3 = q->ne[3];
  6366. const int nek0 = k->ne[0];
  6367. const int nek1 = k->ne[1];
  6368. //const int nek2 = k->ne[2];
  6369. //const int nek3 = k->ne[3];
  6370. //const int nev0 = v->ne[0];
  6371. const int nev1 = v->ne[1];
  6372. //const int nev2 = v->ne[2];
  6373. //const int nev3 = v->ne[3];
  6374. const int ne0 = dst->ne[0];
  6375. const int ne1 = dst->ne[1];
  6376. //const int ne2 = dst->ne[2];
  6377. //const int ne3 = dst->ne[3];
  6378. const int nbk0 = k->nb[0];
  6379. const int nbk1 = k->nb[1];
  6380. const int nbk2 = k->nb[2];
  6381. const int nbk3 = k->nb[3];
  6382. const int nbq0 = q->nb[0];
  6383. const int nbq1 = q->nb[1];
  6384. const int nbq2 = q->nb[2];
  6385. const int nbq3 = q->nb[3];
  6386. const int nbv0 = v->nb[0];
  6387. const int nbv1 = v->nb[1];
  6388. const int nbv2 = v->nb[2];
  6389. const int nbv3 = v->nb[3];
  6390. const int nb0 = dst->nb[0];
  6391. const int nb1 = dst->nb[1];
  6392. const int nb2 = dst->nb[2];
  6393. const int nb3 = dst->nb[3];
  6394. const int ith = params->ith;
  6395. const int nth = params->nth;
  6396. const int D = neq0;
  6397. const int N = neq1;
  6398. const int P = nek1 - N;
  6399. const int M = P + N;
  6400. const int Mup = ggml_up(M, GGML_SOFT_MAX_UNROLL);
  6401. GGML_ASSERT(ne0 == D);
  6402. GGML_ASSERT(ne1 == N);
  6403. GGML_ASSERT(P >= 0);
  6404. GGML_ASSERT(nbq0 == sizeof(float));
  6405. GGML_ASSERT(nbk0 == sizeof(float));
  6406. GGML_ASSERT(nbv0 == sizeof(float));
  6407. GGML_ASSERT(neq0 == D);
  6408. GGML_ASSERT(nek0 == D);
  6409. GGML_ASSERT(nev1 == D);
  6410. GGML_ASSERT(neq1 == N);
  6411. GGML_ASSERT(nek1 == N + P);
  6412. GGML_ASSERT(nev1 == D);
  6413. // dst cannot be transposed or permuted
  6414. GGML_ASSERT(nb0 == sizeof(float));
  6415. GGML_ASSERT(nb0 <= nb1);
  6416. GGML_ASSERT(nb1 <= nb2);
  6417. GGML_ASSERT(nb2 <= nb3);
  6418. if (params->type == GGML_TASK_INIT) {
  6419. return;
  6420. }
  6421. if (params->type == GGML_TASK_FINALIZE) {
  6422. return;
  6423. }
  6424. // parallelize by q rows using ggml_vec_dot_f32
  6425. // total rows in q
  6426. const int nr = neq1*neq2*neq3;
  6427. // rows per thread
  6428. const int dr = (nr + nth - 1)/nth;
  6429. // row range for this thread
  6430. const int ir0 = dr*ith;
  6431. const int ir1 = MIN(ir0 + dr, nr);
  6432. const float scale = 1.0/sqrt((double) D);
  6433. //printf("P=%d N=%d D=%d ir0=%d ir1=%d scale = %f\n", P, N, D, ir0, ir1, scale);
  6434. for (int ir = ir0; ir < ir1; ++ir) {
  6435. // q indices
  6436. const int iq3 = ir/(neq2*neq1);
  6437. const int iq2 = (ir - iq3*neq2*neq1)/neq1;
  6438. const int iq1 = (ir - iq3*neq2*neq1 - iq2*neq1);
  6439. float * S = (float *) params->wdata + ith*(Mup + CACHE_LINE_SIZE_F32);
  6440. for (int i = M; i < Mup; ++i) {
  6441. S[i] = -INFINITY;
  6442. }
  6443. for (int ic = 0; ic < nek1; ++ic) {
  6444. // k indices
  6445. const int ik3 = iq3;
  6446. const int ik2 = iq2;
  6447. const int ik1 = ic;
  6448. // S indices
  6449. const int i1 = ik1;
  6450. ggml_vec_dot_f32(neq0,
  6451. S + i1,
  6452. (float *) ((char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3)),
  6453. (float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)));
  6454. }
  6455. // scale
  6456. ggml_vec_scale_f32(nek1, S, scale);
  6457. if (masked) {
  6458. for (int i = P; i < M; i++) {
  6459. if (i > P + iq1) {
  6460. S[i] = -INFINITY;
  6461. }
  6462. }
  6463. }
  6464. // softmax
  6465. {
  6466. float max = -INFINITY;
  6467. ggml_vec_max_f32(M, &max, S);
  6468. float sum = 0.0f;
  6469. {
  6470. #ifdef GGML_SOFT_MAX_ACCELERATE
  6471. max = -max;
  6472. vDSP_vsadd(S, 1, &max, S, 1, Mup);
  6473. vvexpf(S, S, &Mup);
  6474. ggml_vec_sum_f32(Mup, &sum, S);
  6475. #else
  6476. uint16_t scvt[GGML_SOFT_MAX_UNROLL];
  6477. ggml_float sump[GGML_SOFT_MAX_UNROLL] = { 0.0 };
  6478. for (int i = 0; i < Mup; i += GGML_SOFT_MAX_UNROLL) {
  6479. float * SS = S + i;
  6480. for (int j = 0; j < GGML_SOFT_MAX_UNROLL; ++j) {
  6481. if (SS[j] == -INFINITY) {
  6482. SS[j] = 0.0f;
  6483. } else {
  6484. ggml_fp16_t s = GGML_FP32_TO_FP16(SS[j] - max);
  6485. memcpy(&scvt[j], &s, sizeof(uint16_t));
  6486. const float val = GGML_FP16_TO_FP32(table_exp_f16[scvt[j]]);
  6487. sump[j] += val;
  6488. SS[j] = val;
  6489. }
  6490. }
  6491. }
  6492. for (int i = 0; i < GGML_SOFT_MAX_UNROLL; i++) {
  6493. sum += sump[i];
  6494. }
  6495. #endif
  6496. }
  6497. assert(sum > 0.0f);
  6498. sum = 1.0/sum;
  6499. ggml_vec_scale_f32(M, S, sum);
  6500. #ifndef NDEBUG
  6501. for (int i = 0; i < M; ++i) {
  6502. assert(!isnan(S[i]));
  6503. assert(!isinf(S[i]));
  6504. }
  6505. #endif
  6506. }
  6507. for (int ic = 0; ic < nev1; ++ic) {
  6508. // dst indices
  6509. const int i1 = iq1;
  6510. const int i2 = iq2;
  6511. const int i3 = iq3;
  6512. ggml_vec_dot_f32(nek1,
  6513. (float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
  6514. (float *) ((char *) v->data + ( ic*nbv1 + i2*nbv2 + i3*nbv3)),
  6515. S);
  6516. }
  6517. }
  6518. }
  6519. static void ggml_compute_forward_flash_attn_f16(
  6520. const struct ggml_compute_params * params,
  6521. const struct ggml_tensor * q,
  6522. const struct ggml_tensor * k,
  6523. const struct ggml_tensor * v,
  6524. const bool masked,
  6525. struct ggml_tensor * dst) {
  6526. int64_t t0 = ggml_perf_time_us();
  6527. UNUSED(t0);
  6528. const int neq0 = q->ne[0];
  6529. const int neq1 = q->ne[1];
  6530. const int neq2 = q->ne[2];
  6531. const int neq3 = q->ne[3];
  6532. const int nek0 = k->ne[0];
  6533. const int nek1 = k->ne[1];
  6534. //const int nek2 = k->ne[2];
  6535. //const int nek3 = k->ne[3];
  6536. //const int nev0 = v->ne[0];
  6537. const int nev1 = v->ne[1];
  6538. //const int nev2 = v->ne[2];
  6539. //const int nev3 = v->ne[3];
  6540. const int ne0 = dst->ne[0];
  6541. const int ne1 = dst->ne[1];
  6542. //const int ne2 = dst->ne[2];
  6543. //const int ne3 = dst->ne[3];
  6544. const int nbk0 = k->nb[0];
  6545. const int nbk1 = k->nb[1];
  6546. const int nbk2 = k->nb[2];
  6547. const int nbk3 = k->nb[3];
  6548. const int nbq0 = q->nb[0];
  6549. const int nbq1 = q->nb[1];
  6550. const int nbq2 = q->nb[2];
  6551. const int nbq3 = q->nb[3];
  6552. const int nbv0 = v->nb[0];
  6553. const int nbv1 = v->nb[1];
  6554. const int nbv2 = v->nb[2];
  6555. const int nbv3 = v->nb[3];
  6556. const int nb0 = dst->nb[0];
  6557. const int nb1 = dst->nb[1];
  6558. const int nb2 = dst->nb[2];
  6559. const int nb3 = dst->nb[3];
  6560. const int ith = params->ith;
  6561. const int nth = params->nth;
  6562. const int D = neq0;
  6563. const int N = neq1;
  6564. const int P = nek1 - N;
  6565. const int M = P + N;
  6566. const int Mup = ggml_up(M, GGML_SOFT_MAX_UNROLL);
  6567. GGML_ASSERT(ne0 == D);
  6568. GGML_ASSERT(ne1 == N);
  6569. GGML_ASSERT(P >= 0);
  6570. GGML_ASSERT(nbq0 == sizeof(ggml_fp16_t));
  6571. GGML_ASSERT(nbk0 == sizeof(ggml_fp16_t));
  6572. GGML_ASSERT(nbv0 == sizeof(ggml_fp16_t));
  6573. GGML_ASSERT(neq0 == D);
  6574. GGML_ASSERT(nek0 == D);
  6575. GGML_ASSERT(nev1 == D);
  6576. GGML_ASSERT(neq1 == N);
  6577. GGML_ASSERT(nek1 == N + P);
  6578. GGML_ASSERT(nev1 == D);
  6579. // dst cannot be transposed or permuted
  6580. GGML_ASSERT(nb0 == sizeof(float));
  6581. GGML_ASSERT(nb0 <= nb1);
  6582. GGML_ASSERT(nb1 <= nb2);
  6583. GGML_ASSERT(nb2 <= nb3);
  6584. if (params->type == GGML_TASK_INIT) {
  6585. return;
  6586. }
  6587. if (params->type == GGML_TASK_FINALIZE) {
  6588. return;
  6589. }
  6590. // parallelize by q rows using ggml_vec_dot_f32
  6591. // total rows in q
  6592. const int nr = neq1*neq2*neq3;
  6593. // rows per thread
  6594. const int dr = (nr + nth - 1)/nth;
  6595. // row range for this thread
  6596. const int ir0 = dr*ith;
  6597. const int ir1 = MIN(ir0 + dr, nr);
  6598. const float scale = 1.0/sqrt((double) D);
  6599. //printf("P=%d N=%d D=%d ir0=%d ir1=%d scale = %f\n", P, N, D, ir0, ir1, scale);
  6600. for (int ir = ir0; ir < ir1; ++ir) {
  6601. // q indices
  6602. const int iq3 = ir/(neq2*neq1);
  6603. const int iq2 = (ir - iq3*neq2*neq1)/neq1;
  6604. const int iq1 = (ir - iq3*neq2*neq1 - iq2*neq1);
  6605. float * S = (float *) params->wdata + ith*(2*Mup + CACHE_LINE_SIZE_F32);
  6606. for (int i = M; i < Mup; ++i) {
  6607. S[i] = -INFINITY;
  6608. }
  6609. if (GGML_VEC_DOT_UNROLL > 2 || nek1 % GGML_VEC_DOT_UNROLL != 0) {
  6610. for (int ic = 0; ic < nek1; ++ic) {
  6611. // k indices
  6612. const int ik3 = iq3;
  6613. const int ik2 = iq2;
  6614. const int ik1 = ic;
  6615. // S indices
  6616. const int i1 = ik1;
  6617. ggml_vec_dot_f16(neq0,
  6618. S + i1,
  6619. (ggml_fp16_t *) ((char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3)),
  6620. (ggml_fp16_t *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)));
  6621. }
  6622. } else {
  6623. for (int ic = 0; ic < nek1; ic += GGML_VEC_DOT_UNROLL) {
  6624. // k indices
  6625. const int ik3 = iq3;
  6626. const int ik2 = iq2;
  6627. const int ik1 = ic;
  6628. // S indices
  6629. const int i1 = ik1;
  6630. ggml_vec_dot_f16_unroll(neq0, nbk1,
  6631. S + i1,
  6632. ((char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3)),
  6633. (ggml_fp16_t *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)));
  6634. }
  6635. }
  6636. // scale
  6637. ggml_vec_scale_f32(nek1, S, scale);
  6638. if (masked) {
  6639. for (int i = P; i < M; i++) {
  6640. if (i > P + iq1) {
  6641. S[i] = -INFINITY;
  6642. }
  6643. }
  6644. }
  6645. // softmax
  6646. {
  6647. float max = -INFINITY;
  6648. ggml_vec_max_f32(M, &max, S);
  6649. float sum = 0.0f;
  6650. {
  6651. #ifdef GGML_SOFT_MAX_ACCELERATE
  6652. max = -max;
  6653. vDSP_vsadd(S, 1, &max, S, 1, Mup);
  6654. vvexpf(S, S, &Mup);
  6655. ggml_vec_sum_f32(Mup, &sum, S);
  6656. #else
  6657. uint16_t scvt[GGML_SOFT_MAX_UNROLL];
  6658. ggml_float sump[GGML_SOFT_MAX_UNROLL] = { 0.0 };
  6659. for (int i = 0; i < Mup; i += GGML_SOFT_MAX_UNROLL) {
  6660. float * SS = S + i;
  6661. for (int j = 0; j < GGML_SOFT_MAX_UNROLL; ++j) {
  6662. if (SS[j] == -INFINITY) {
  6663. SS[j] = 0.0f;
  6664. } else {
  6665. ggml_fp16_t s = GGML_FP32_TO_FP16(SS[j] - max);
  6666. memcpy(&scvt[j], &s, sizeof(uint16_t));
  6667. const float val = GGML_FP16_TO_FP32(table_exp_f16[scvt[j]]);
  6668. sump[j] += val;
  6669. SS[j] = val;
  6670. }
  6671. }
  6672. }
  6673. for (int i = 0; i < GGML_SOFT_MAX_UNROLL; i++) {
  6674. sum += sump[i];
  6675. }
  6676. #endif
  6677. }
  6678. assert(sum > 0.0f);
  6679. sum = 1.0/sum;
  6680. ggml_vec_scale_f32(M, S, sum);
  6681. #ifndef NDEBUG
  6682. for (int i = 0; i < M; ++i) {
  6683. assert(!isnan(S[i]));
  6684. assert(!isinf(S[i]));
  6685. }
  6686. #endif
  6687. }
  6688. ggml_fp16_t * S16 = (ggml_fp16_t *) ((float *) params->wdata + ith*(2*Mup + CACHE_LINE_SIZE_F32) + Mup);
  6689. for (int i = 0; i < M; i++) {
  6690. S16[i] = GGML_FP32_TO_FP16(S[i]);
  6691. }
  6692. if (GGML_VEC_DOT_UNROLL == 1 || (nev1 % GGML_VEC_DOT_UNROLL != 0)) {
  6693. for (int ic = 0; ic < nev1; ++ic) {
  6694. // dst indices
  6695. const int i1 = iq1;
  6696. const int i2 = iq2;
  6697. const int i3 = iq3;
  6698. ggml_vec_dot_f16(nek1,
  6699. (float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
  6700. (ggml_fp16_t *) ((char *) v->data + ( ic*nbv1 + i2*nbv2 + i3*nbv3)),
  6701. S16);
  6702. }
  6703. } else {
  6704. for (int ic = 0; ic < nev1; ic += GGML_VEC_DOT_UNROLL) {
  6705. // dst indices
  6706. const int i1 = iq1;
  6707. const int i2 = iq2;
  6708. const int i3 = iq3;
  6709. ggml_vec_dot_f16_unroll(nek1, nbv1,
  6710. (float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
  6711. ((char *) v->data + ( ic*nbv1 + i2*nbv2 + i3*nbv3)),
  6712. S16);
  6713. }
  6714. }
  6715. }
  6716. }
  6717. static void ggml_compute_forward_flash_attn(
  6718. const struct ggml_compute_params * params,
  6719. const struct ggml_tensor * q,
  6720. const struct ggml_tensor * k,
  6721. const struct ggml_tensor * v,
  6722. const bool masked,
  6723. struct ggml_tensor * dst) {
  6724. switch (q->type) {
  6725. case GGML_TYPE_F16:
  6726. {
  6727. ggml_compute_forward_flash_attn_f16(params, q, k, v, masked, dst);
  6728. } break;
  6729. case GGML_TYPE_F32:
  6730. {
  6731. ggml_compute_forward_flash_attn_f32(params, q, k, v, masked, dst);
  6732. } break;
  6733. case GGML_TYPE_Q4_0:
  6734. case GGML_TYPE_Q4_1:
  6735. case GGML_TYPE_I8:
  6736. case GGML_TYPE_I16:
  6737. case GGML_TYPE_I32:
  6738. case GGML_TYPE_COUNT:
  6739. {
  6740. GGML_ASSERT(false);
  6741. } break;
  6742. }
  6743. }
  6744. // ggml_compute_forward_flash_ff
  6745. static void ggml_compute_forward_flash_ff_f16(
  6746. const struct ggml_compute_params * params,
  6747. const struct ggml_tensor * a, // F16
  6748. const struct ggml_tensor * b0, // F16 fc_w
  6749. const struct ggml_tensor * b1, // F32 fc_b
  6750. const struct ggml_tensor * c0, // F16 proj_w
  6751. const struct ggml_tensor * c1, // F32 proj_b
  6752. struct ggml_tensor * dst) {
  6753. int64_t t0 = ggml_perf_time_us();
  6754. UNUSED(t0);
  6755. const int nea0 = a->ne[0];
  6756. const int nea1 = a->ne[1];
  6757. const int nea2 = a->ne[2];
  6758. const int nea3 = a->ne[3];
  6759. const int neb00 = b0->ne[0];
  6760. const int neb01 = b0->ne[1];
  6761. //const int neb02 = b0->ne[2];
  6762. //const int neb03 = b0->ne[3];
  6763. const int neb10 = b1->ne[0];
  6764. const int neb11 = b1->ne[1];
  6765. //const int neb12 = b1->ne[2];
  6766. //const int neb13 = b1->ne[3];
  6767. const int nec00 = c0->ne[0];
  6768. const int nec01 = c0->ne[1];
  6769. //const int nec02 = c0->ne[2];
  6770. //const int nec03 = c0->ne[3];
  6771. const int nec10 = c1->ne[0];
  6772. const int nec11 = c1->ne[1];
  6773. //const int nec12 = c1->ne[2];
  6774. //const int nec13 = c1->ne[3];
  6775. const int ne0 = dst->ne[0];
  6776. const int ne1 = dst->ne[1];
  6777. const int ne2 = dst->ne[2];
  6778. //const int ne3 = dst->ne[3];
  6779. const int nba0 = a->nb[0];
  6780. const int nba1 = a->nb[1];
  6781. const int nba2 = a->nb[2];
  6782. const int nba3 = a->nb[3];
  6783. const int nbb00 = b0->nb[0];
  6784. const int nbb01 = b0->nb[1];
  6785. const int nbb02 = b0->nb[2];
  6786. const int nbb03 = b0->nb[3];
  6787. const int nbb10 = b1->nb[0];
  6788. //const int nbb11 = b1->nb[1];
  6789. //const int nbb12 = b1->nb[2];
  6790. //const int nbb13 = b1->nb[3];
  6791. const int nbc00 = c0->nb[0];
  6792. const int nbc01 = c0->nb[1];
  6793. const int nbc02 = c0->nb[2];
  6794. const int nbc03 = c0->nb[3];
  6795. const int nbc10 = c1->nb[0];
  6796. //const int nbc11 = c1->nb[1];
  6797. //const int nbc12 = c1->nb[2];
  6798. //const int nbc13 = c1->nb[3];
  6799. const int nb0 = dst->nb[0];
  6800. const int nb1 = dst->nb[1];
  6801. const int nb2 = dst->nb[2];
  6802. const int nb3 = dst->nb[3];
  6803. const int ith = params->ith;
  6804. const int nth = params->nth;
  6805. const int D = nea0;
  6806. //const int N = nea1;
  6807. const int M = neb01;
  6808. GGML_ASSERT(ne0 == nea0);
  6809. GGML_ASSERT(ne1 == nea1);
  6810. GGML_ASSERT(ne2 == nea2);
  6811. GGML_ASSERT(nba0 == sizeof(ggml_fp16_t));
  6812. GGML_ASSERT(nbb00 == sizeof(ggml_fp16_t));
  6813. GGML_ASSERT(nbb10 == sizeof(float));
  6814. GGML_ASSERT(nbc00 == sizeof(ggml_fp16_t));
  6815. GGML_ASSERT(nbc10 == sizeof(float));
  6816. GGML_ASSERT(neb00 == D);
  6817. GGML_ASSERT(neb01 == M);
  6818. GGML_ASSERT(neb10 == M);
  6819. GGML_ASSERT(neb11 == 1);
  6820. GGML_ASSERT(nec00 == M);
  6821. GGML_ASSERT(nec01 == D);
  6822. GGML_ASSERT(nec10 == D);
  6823. GGML_ASSERT(nec11 == 1);
  6824. // dst cannot be transposed or permuted
  6825. GGML_ASSERT(nb0 == sizeof(float));
  6826. GGML_ASSERT(nb0 <= nb1);
  6827. GGML_ASSERT(nb1 <= nb2);
  6828. GGML_ASSERT(nb2 <= nb3);
  6829. if (params->type == GGML_TASK_INIT) {
  6830. return;
  6831. }
  6832. if (params->type == GGML_TASK_FINALIZE) {
  6833. return;
  6834. }
  6835. // parallelize by a rows using ggml_vec_dot_f32
  6836. // total rows in a
  6837. const int nr = nea1*nea2*nea3;
  6838. // rows per thread
  6839. const int dr = (nr + nth - 1)/nth;
  6840. // row range for this thread
  6841. const int ir0 = dr*ith;
  6842. const int ir1 = MIN(ir0 + dr, nr);
  6843. for (int ir = ir0; ir < ir1; ++ir) {
  6844. // a indices
  6845. const int ia3 = ir/(nea2*nea1);
  6846. const int ia2 = (ir - ia3*nea2*nea1)/nea1;
  6847. const int ia1 = (ir - ia3*nea2*nea1 - ia2*nea1);
  6848. float * S = (float *) params->wdata + ith*(2*M + CACHE_LINE_SIZE_F32);
  6849. for (int ic = 0; ic < neb01; ++ic) {
  6850. // b0 indices
  6851. const int ib03 = ia3;
  6852. const int ib02 = ia2;
  6853. const int ib01 = ic;
  6854. // S indices
  6855. const int i1 = ib01;
  6856. ggml_vec_dot_f16(nea0,
  6857. S + i1,
  6858. (ggml_fp16_t *) ((char *) b0->data + (ib01*nbb01 + ib02*nbb02 + ib03*nbb03)),
  6859. (ggml_fp16_t *) ((char *) a->data + ( ia1*nba1 + ia2*nba2 + ia3*nba3)));
  6860. }
  6861. ggml_vec_add_f32(neb01, S, S, (float *) b1->data);
  6862. //ggml_vec_gelu_f32(neb01, S, S);
  6863. ggml_fp16_t * S16 = (ggml_fp16_t *) ((float *) params->wdata + ith*(2*M + CACHE_LINE_SIZE_F32) + M);
  6864. for (int i = 0; i < M; i++) {
  6865. S16[i] = GGML_FP32_TO_FP16(S[i]);
  6866. }
  6867. ggml_vec_gelu_f16(neb01, S16, S16);
  6868. {
  6869. // dst indices
  6870. const int i1 = ia1;
  6871. const int i2 = ia2;
  6872. const int i3 = ia3;
  6873. for (int ic = 0; ic < nec01; ++ic) {
  6874. ggml_vec_dot_f16(neb01,
  6875. (float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
  6876. (ggml_fp16_t *) ((char *) c0->data + ( ic*nbc01 + i2*nbc02 + i3*nbc03)),
  6877. S16);
  6878. }
  6879. ggml_vec_add_f32(nec01,
  6880. (float *) ((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb3)),
  6881. (float *) ((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb3)),
  6882. (float *) c1->data);
  6883. }
  6884. }
  6885. }
  6886. static void ggml_compute_forward_flash_ff(
  6887. const struct ggml_compute_params * params,
  6888. const struct ggml_tensor * a,
  6889. const struct ggml_tensor * b0,
  6890. const struct ggml_tensor * b1,
  6891. const struct ggml_tensor * c0,
  6892. const struct ggml_tensor * c1,
  6893. struct ggml_tensor * dst) {
  6894. switch (b0->type) {
  6895. case GGML_TYPE_F16:
  6896. {
  6897. ggml_compute_forward_flash_ff_f16(params, a, b0, b1, c0, c1, dst);
  6898. } break;
  6899. case GGML_TYPE_F32:
  6900. {
  6901. GGML_ASSERT(false); // TODO
  6902. } break;
  6903. case GGML_TYPE_Q4_0:
  6904. case GGML_TYPE_Q4_1:
  6905. case GGML_TYPE_I8:
  6906. case GGML_TYPE_I16:
  6907. case GGML_TYPE_I32:
  6908. case GGML_TYPE_COUNT:
  6909. {
  6910. GGML_ASSERT(false);
  6911. } break;
  6912. }
  6913. }
  6914. /////////////////////////////////
  6915. static void ggml_compute_forward(struct ggml_compute_params * params, struct ggml_tensor * tensor) {
  6916. GGML_ASSERT(params);
  6917. switch (tensor->op) {
  6918. case GGML_OP_DUP:
  6919. {
  6920. ggml_compute_forward_dup(params, tensor->src0, tensor);
  6921. } break;
  6922. case GGML_OP_ADD:
  6923. {
  6924. ggml_compute_forward_add(params, tensor->src0, tensor->src1, tensor);
  6925. } break;
  6926. case GGML_OP_SUB:
  6927. {
  6928. ggml_compute_forward_sub(params, tensor->src0, tensor->src1, tensor);
  6929. } break;
  6930. case GGML_OP_MUL:
  6931. {
  6932. ggml_compute_forward_mul(params, tensor->src0, tensor->src1, tensor);
  6933. } break;
  6934. case GGML_OP_DIV:
  6935. {
  6936. ggml_compute_forward_div(params, tensor->src0, tensor->src1, tensor);
  6937. } break;
  6938. case GGML_OP_SQR:
  6939. {
  6940. ggml_compute_forward_sqr(params, tensor->src0, tensor);
  6941. } break;
  6942. case GGML_OP_SQRT:
  6943. {
  6944. ggml_compute_forward_sqrt(params, tensor->src0, tensor);
  6945. } break;
  6946. case GGML_OP_SUM:
  6947. {
  6948. ggml_compute_forward_sum(params, tensor->src0, tensor);
  6949. } break;
  6950. case GGML_OP_MEAN:
  6951. {
  6952. ggml_compute_forward_mean(params, tensor->src0, tensor);
  6953. } break;
  6954. case GGML_OP_REPEAT:
  6955. {
  6956. ggml_compute_forward_repeat(params, tensor->src0, tensor);
  6957. } break;
  6958. case GGML_OP_ABS:
  6959. {
  6960. ggml_compute_forward_abs(params, tensor->src0, tensor);
  6961. } break;
  6962. case GGML_OP_SGN:
  6963. {
  6964. ggml_compute_forward_sgn(params, tensor->src0, tensor);
  6965. } break;
  6966. case GGML_OP_NEG:
  6967. {
  6968. ggml_compute_forward_neg(params, tensor->src0, tensor);
  6969. } break;
  6970. case GGML_OP_STEP:
  6971. {
  6972. ggml_compute_forward_step(params, tensor->src0, tensor);
  6973. } break;
  6974. case GGML_OP_RELU:
  6975. {
  6976. ggml_compute_forward_relu(params, tensor->src0, tensor);
  6977. } break;
  6978. case GGML_OP_GELU:
  6979. {
  6980. ggml_compute_forward_gelu(params, tensor->src0, tensor);
  6981. } break;
  6982. case GGML_OP_SILU:
  6983. {
  6984. ggml_compute_forward_silu(params, tensor->src0, tensor);
  6985. } break;
  6986. case GGML_OP_NORM:
  6987. {
  6988. ggml_compute_forward_norm(params, tensor->src0, tensor);
  6989. } break;
  6990. case GGML_OP_RMS_NORM:
  6991. {
  6992. ggml_compute_forward_rms_norm(params, tensor->src0, tensor);
  6993. } break;
  6994. case GGML_OP_MUL_MAT:
  6995. {
  6996. ggml_compute_forward_mul_mat(params, tensor->src0, tensor->src1, tensor);
  6997. } break;
  6998. case GGML_OP_SCALE:
  6999. {
  7000. ggml_compute_forward_scale(params, tensor->src0, tensor->src1, tensor);
  7001. } break;
  7002. case GGML_OP_CPY:
  7003. {
  7004. ggml_compute_forward_cpy(params, tensor->src0, tensor);
  7005. } break;
  7006. case GGML_OP_RESHAPE:
  7007. {
  7008. ggml_compute_forward_reshape(params, tensor->src0, tensor);
  7009. } break;
  7010. case GGML_OP_VIEW:
  7011. {
  7012. ggml_compute_forward_view(params, tensor->src0);
  7013. } break;
  7014. case GGML_OP_PERMUTE:
  7015. {
  7016. ggml_compute_forward_permute(params, tensor->src0);
  7017. } break;
  7018. case GGML_OP_TRANSPOSE:
  7019. {
  7020. ggml_compute_forward_transpose(params, tensor->src0);
  7021. } break;
  7022. case GGML_OP_GET_ROWS:
  7023. {
  7024. ggml_compute_forward_get_rows(params, tensor->src0, tensor->src1, tensor);
  7025. } break;
  7026. case GGML_OP_DIAG_MASK_INF:
  7027. {
  7028. ggml_compute_forward_diag_mask_inf(params, tensor->src0, tensor->src1, tensor);
  7029. } break;
  7030. case GGML_OP_SOFT_MAX:
  7031. {
  7032. ggml_compute_forward_soft_max(params, tensor->src0, tensor);
  7033. } break;
  7034. case GGML_OP_ROPE:
  7035. {
  7036. ggml_compute_forward_rope(params, tensor->src0, tensor->src1, tensor);
  7037. } break;
  7038. case GGML_OP_CONV_1D_1S:
  7039. {
  7040. ggml_compute_forward_conv_1d_1s(params, tensor->src0, tensor->src1, tensor);
  7041. } break;
  7042. case GGML_OP_CONV_1D_2S:
  7043. {
  7044. ggml_compute_forward_conv_1d_2s(params, tensor->src0, tensor->src1, tensor);
  7045. } break;
  7046. case GGML_OP_FLASH_ATTN:
  7047. {
  7048. int32_t t = ggml_get_i32_1d(tensor->opt[1], 0);
  7049. GGML_ASSERT(t == 0 || t == 1);
  7050. bool masked = t != 0;
  7051. ggml_compute_forward_flash_attn(params, tensor->src0, tensor->src1, tensor->opt[0], masked, tensor);
  7052. } break;
  7053. case GGML_OP_FLASH_FF:
  7054. {
  7055. ggml_compute_forward_flash_ff(params, tensor->src0, tensor->src1, tensor->opt[0], tensor->opt[1], tensor->opt[2], tensor);
  7056. } break;
  7057. case GGML_OP_NONE:
  7058. {
  7059. // nop
  7060. } break;
  7061. case GGML_OP_COUNT:
  7062. {
  7063. GGML_ASSERT(false);
  7064. } break;
  7065. }
  7066. }
  7067. ////////////////////////////////////////////////////////////////////////////////
  7068. static void ggml_compute_backward(struct ggml_context * ctx, struct ggml_tensor * tensor, bool inplace) {
  7069. struct ggml_tensor * src0 = tensor->src0;
  7070. struct ggml_tensor * src1 = tensor->src1;
  7071. switch (tensor->op) {
  7072. case GGML_OP_DUP:
  7073. {
  7074. if (src0->grad) {
  7075. src0->grad = ggml_add_impl(ctx, src0->grad, tensor->grad, inplace);
  7076. }
  7077. } break;
  7078. case GGML_OP_ADD:
  7079. {
  7080. if (src0->grad) {
  7081. src0->grad = ggml_add_impl(ctx, src0->grad, tensor->grad, inplace);
  7082. }
  7083. if (src1->grad) {
  7084. src1->grad = ggml_add_impl(ctx, src1->grad, tensor->grad, inplace);
  7085. }
  7086. } break;
  7087. case GGML_OP_SUB:
  7088. {
  7089. if (src0->grad) {
  7090. src0->grad = ggml_add_impl(ctx, src0->grad, tensor->grad, inplace);
  7091. }
  7092. if (src1->grad) {
  7093. src1->grad = ggml_sub_impl(ctx, src1->grad, tensor->grad, inplace);
  7094. }
  7095. } break;
  7096. case GGML_OP_MUL:
  7097. {
  7098. if (src0->grad) {
  7099. src0->grad =
  7100. ggml_add_impl(ctx,
  7101. src0->grad,
  7102. ggml_mul(ctx, src1, tensor->grad),
  7103. inplace);
  7104. }
  7105. if (src1->grad) {
  7106. src1->grad =
  7107. ggml_add_impl(ctx,
  7108. src1->grad,
  7109. ggml_mul(ctx, src0, tensor->grad),
  7110. inplace);
  7111. }
  7112. } break;
  7113. case GGML_OP_DIV:
  7114. {
  7115. if (src0->grad) {
  7116. src0->grad =
  7117. ggml_add_impl(ctx,
  7118. src0->grad,
  7119. ggml_div(ctx, tensor->grad, src1),
  7120. inplace);
  7121. }
  7122. if (src1->grad) {
  7123. src1->grad =
  7124. ggml_sub_impl(ctx,
  7125. src1->grad,
  7126. ggml_mul(ctx,
  7127. tensor->grad,
  7128. ggml_div(ctx, tensor, src1)),
  7129. inplace);
  7130. }
  7131. } break;
  7132. case GGML_OP_SQR:
  7133. {
  7134. if (src0->grad) {
  7135. src0->grad =
  7136. ggml_add_impl(ctx,
  7137. src0->grad,
  7138. ggml_mul(ctx,
  7139. ggml_mul(ctx, src0, tensor->grad),
  7140. ggml_repeat(ctx, ggml_new_f32(ctx, 2.0f), src0)),
  7141. inplace);
  7142. }
  7143. } break;
  7144. case GGML_OP_SQRT:
  7145. {
  7146. if (src0->grad) {
  7147. src0->grad =
  7148. ggml_add_impl(ctx,
  7149. src0->grad,
  7150. ggml_div(ctx,
  7151. ggml_repeat(ctx, ggml_new_f32(ctx, 0.5f), tensor),
  7152. tensor),
  7153. inplace);
  7154. }
  7155. } break;
  7156. case GGML_OP_SUM:
  7157. {
  7158. if (src0->grad) {
  7159. src0->grad =
  7160. ggml_add_impl(ctx,
  7161. src0->grad,
  7162. ggml_repeat(ctx, tensor->grad, src0->grad),
  7163. inplace);
  7164. }
  7165. } break;
  7166. case GGML_OP_MEAN:
  7167. {
  7168. GGML_ASSERT(false); // TODO: implement
  7169. } break;
  7170. case GGML_OP_REPEAT:
  7171. {
  7172. if (src0->grad) {
  7173. src0->grad =
  7174. ggml_add_impl(ctx,
  7175. src0->grad,
  7176. ggml_sum(ctx, tensor->grad),
  7177. inplace);
  7178. }
  7179. } break;
  7180. case GGML_OP_ABS:
  7181. {
  7182. if (src0->grad) {
  7183. src0->grad =
  7184. ggml_add_impl(ctx,
  7185. src0->grad,
  7186. ggml_mul(ctx,
  7187. ggml_sgn(ctx, src0),
  7188. tensor->grad),
  7189. inplace);
  7190. }
  7191. } break;
  7192. case GGML_OP_SGN:
  7193. {
  7194. if (src0->grad) {
  7195. // noop
  7196. }
  7197. } break;
  7198. case GGML_OP_NEG:
  7199. {
  7200. if (src0->grad) {
  7201. src0->grad = ggml_sub_impl(ctx, src0->grad, tensor->grad, inplace);
  7202. }
  7203. } break;
  7204. case GGML_OP_STEP:
  7205. {
  7206. if (src0->grad) {
  7207. // noop
  7208. }
  7209. } break;
  7210. case GGML_OP_RELU:
  7211. {
  7212. if (src0->grad) {
  7213. src0->grad = ggml_sub_impl(ctx,
  7214. src0->grad,
  7215. ggml_mul(ctx,
  7216. ggml_step(ctx, src0),
  7217. tensor->grad),
  7218. inplace);
  7219. }
  7220. } break;
  7221. case GGML_OP_GELU:
  7222. {
  7223. GGML_ASSERT(false); // TODO: not implemented
  7224. } break;
  7225. case GGML_OP_SILU:
  7226. {
  7227. GGML_ASSERT(false); // TODO: not implemented
  7228. } break;
  7229. case GGML_OP_NORM:
  7230. {
  7231. GGML_ASSERT(false); // TODO: not implemented
  7232. } break;
  7233. case GGML_OP_RMS_NORM:
  7234. {
  7235. GGML_ASSERT(false); // TODO: not implemented
  7236. } break;
  7237. case GGML_OP_MUL_MAT:
  7238. {
  7239. if (src0->grad) {
  7240. // TODO: this requires outer product - ggml_out_prod(ctx, src1, tensor->grad);
  7241. GGML_ASSERT(false);
  7242. }
  7243. if (src1->grad) {
  7244. src1->grad =
  7245. ggml_add_impl(ctx,
  7246. src1->grad,
  7247. // TODO: fix transpose, the node will break the graph connections
  7248. ggml_mul_mat(ctx, ggml_transpose(ctx, src0), tensor->grad),
  7249. inplace);
  7250. }
  7251. } break;
  7252. case GGML_OP_SCALE:
  7253. {
  7254. GGML_ASSERT(false); // TODO: not implemented
  7255. } break;
  7256. case GGML_OP_CPY:
  7257. {
  7258. GGML_ASSERT(false); // TODO: not implemented
  7259. } break;
  7260. case GGML_OP_RESHAPE:
  7261. {
  7262. GGML_ASSERT(false); // TODO: not implemented
  7263. } break;
  7264. case GGML_OP_VIEW:
  7265. {
  7266. GGML_ASSERT(false); // not supported
  7267. } break;
  7268. case GGML_OP_PERMUTE:
  7269. {
  7270. GGML_ASSERT(false); // TODO: not implemented
  7271. } break;
  7272. case GGML_OP_TRANSPOSE:
  7273. {
  7274. GGML_ASSERT(false); // TODO: not implemented
  7275. } break;
  7276. case GGML_OP_GET_ROWS:
  7277. {
  7278. GGML_ASSERT(false); // TODO: not implemented
  7279. } break;
  7280. case GGML_OP_DIAG_MASK_INF:
  7281. {
  7282. GGML_ASSERT(false); // TODO: not implemented
  7283. } break;
  7284. case GGML_OP_SOFT_MAX:
  7285. {
  7286. GGML_ASSERT(false); // TODO: not implemented
  7287. } break;
  7288. case GGML_OP_ROPE:
  7289. {
  7290. GGML_ASSERT(false); // TODO: not implemented
  7291. } break;
  7292. case GGML_OP_CONV_1D_1S:
  7293. {
  7294. GGML_ASSERT(false); // TODO: not implemented
  7295. } break;
  7296. case GGML_OP_CONV_1D_2S:
  7297. {
  7298. GGML_ASSERT(false); // TODO: not implemented
  7299. } break;
  7300. case GGML_OP_FLASH_ATTN:
  7301. {
  7302. GGML_ASSERT(false); // not supported
  7303. } break;
  7304. case GGML_OP_FLASH_FF:
  7305. {
  7306. GGML_ASSERT(false); // not supported
  7307. } break;
  7308. case GGML_OP_NONE:
  7309. {
  7310. // nop
  7311. } break;
  7312. case GGML_OP_COUNT:
  7313. {
  7314. GGML_ASSERT(false);
  7315. } break;
  7316. }
  7317. }
  7318. static void ggml_visit_parents(struct ggml_cgraph * cgraph, struct ggml_tensor * node) {
  7319. if (node->grad == NULL) {
  7320. // this usually happens when we generate intermediate nodes from constants in the backward pass
  7321. // it can also happen during forward pass, if the user performs computations with constants
  7322. if (node->op != GGML_OP_NONE) {
  7323. //GGML_PRINT_DEBUG("%s: warning: node %p has no grad, but op %d\n", __func__, (void *) node, node->op);
  7324. }
  7325. }
  7326. // check if already visited
  7327. for (int i = 0; i < cgraph->n_nodes; i++) {
  7328. if (cgraph->nodes[i] == node) {
  7329. return;
  7330. }
  7331. }
  7332. for (int i = 0; i < cgraph->n_leafs; i++) {
  7333. if (cgraph->leafs[i] == node) {
  7334. return;
  7335. }
  7336. }
  7337. if (node->src0) {
  7338. ggml_visit_parents(cgraph, node->src0);
  7339. }
  7340. if (node->src1) {
  7341. ggml_visit_parents(cgraph, node->src1);
  7342. }
  7343. for (int i = 0; i < GGML_MAX_OPT; ++i) {
  7344. if (node->opt[i]) {
  7345. ggml_visit_parents(cgraph, node->opt[i]);
  7346. }
  7347. }
  7348. if (node->op == GGML_OP_NONE && node->grad == NULL) {
  7349. // reached a leaf node, not part of the gradient graph (e.g. a constant)
  7350. GGML_ASSERT(cgraph->n_leafs < GGML_MAX_NODES);
  7351. cgraph->leafs[cgraph->n_leafs] = node;
  7352. cgraph->n_leafs++;
  7353. } else {
  7354. GGML_ASSERT(cgraph->n_nodes < GGML_MAX_NODES);
  7355. cgraph->nodes[cgraph->n_nodes] = node;
  7356. cgraph->grads[cgraph->n_nodes] = node->grad;
  7357. cgraph->n_nodes++;
  7358. }
  7359. }
  7360. static void ggml_build_forward_impl(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor, bool expand) {
  7361. if (!expand) {
  7362. cgraph->n_nodes = 0;
  7363. cgraph->n_leafs = 0;
  7364. }
  7365. const int n0 = cgraph->n_nodes;
  7366. UNUSED(n0);
  7367. ggml_visit_parents(cgraph, tensor);
  7368. const int n_new = cgraph->n_nodes - n0;
  7369. GGML_PRINT_DEBUG("%s: visited %d new nodes\n", __func__, n_new);
  7370. if (n_new > 0) {
  7371. // the last added node should always be starting point
  7372. GGML_ASSERT(cgraph->nodes[cgraph->n_nodes - 1] == tensor);
  7373. }
  7374. }
  7375. void ggml_build_forward_expand(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  7376. ggml_build_forward_impl(cgraph, tensor, true);
  7377. }
  7378. struct ggml_cgraph ggml_build_forward(struct ggml_tensor * tensor) {
  7379. struct ggml_cgraph result = {
  7380. /*.n_nodes =*/ 0,
  7381. /*.n_leafs =*/ 0,
  7382. /*.n_threads =*/ 0,
  7383. /*.work_size =*/ 0,
  7384. /*.work =*/ NULL,
  7385. /*.nodes =*/ { NULL },
  7386. /*.grads =*/ { NULL },
  7387. /*.leafs =*/ { NULL },
  7388. /*.perf_runs =*/ 0,
  7389. /*.perf_cycles =*/ 0,
  7390. /*.perf_time_us =*/ 0,
  7391. };
  7392. ggml_build_forward_impl(&result, tensor, false);
  7393. return result;
  7394. }
  7395. struct ggml_cgraph ggml_build_backward(struct ggml_context * ctx, struct ggml_cgraph * gf, bool keep) {
  7396. struct ggml_cgraph result = *gf;
  7397. GGML_ASSERT(gf->n_nodes > 0);
  7398. // if we are keeping the gradient graph, we have to detach the gradient nodes from the original graph
  7399. if (keep) {
  7400. for (int i = 0; i < gf->n_nodes; i++) {
  7401. struct ggml_tensor * node = gf->nodes[i];
  7402. if (node->grad) {
  7403. node->grad = ggml_dup_tensor(ctx, node);
  7404. gf->grads[i] = node->grad;
  7405. }
  7406. }
  7407. }
  7408. for (int i = gf->n_nodes - 1; i >= 0; i--) {
  7409. struct ggml_tensor * node = gf->nodes[i];
  7410. // because we detached the grad nodes from the original graph, we can afford inplace operations
  7411. if (node->grad) {
  7412. ggml_compute_backward(ctx, node, keep);
  7413. }
  7414. }
  7415. for (int i = gf->n_nodes - 1; i >= 0; i--) {
  7416. struct ggml_tensor * node = gf->nodes[i];
  7417. if (node->is_param) {
  7418. GGML_PRINT_DEBUG("%s: found root node %p\n", __func__, (void *) node);
  7419. ggml_build_forward_impl(&result, node->grad, true);
  7420. }
  7421. }
  7422. return result;
  7423. }
  7424. //
  7425. // thread data
  7426. //
  7427. // synchronization is done via busy loops
  7428. // I tried using spin locks, but not sure how to use them correctly - the things I tried were slower than busy loops
  7429. //
  7430. #ifdef __APPLE__
  7431. //#include <os/lock.h>
  7432. //
  7433. //typedef os_unfair_lock ggml_lock_t;
  7434. //
  7435. //#define ggml_lock_init(x) UNUSED(x)
  7436. //#define ggml_lock_destroy(x) UNUSED(x)
  7437. //#define ggml_lock_lock os_unfair_lock_lock
  7438. //#define ggml_lock_unlock os_unfair_lock_unlock
  7439. //
  7440. //#define GGML_LOCK_INITIALIZER OS_UNFAIR_LOCK_INIT
  7441. typedef int ggml_lock_t;
  7442. #define ggml_lock_init(x) UNUSED(x)
  7443. #define ggml_lock_destroy(x) UNUSED(x)
  7444. #define ggml_lock_lock(x) UNUSED(x)
  7445. #define ggml_lock_unlock(x) UNUSED(x)
  7446. #define GGML_LOCK_INITIALIZER 0
  7447. typedef pthread_t ggml_thread_t;
  7448. #define ggml_thread_create pthread_create
  7449. #define ggml_thread_join pthread_join
  7450. #else
  7451. //typedef pthread_spinlock_t ggml_lock_t;
  7452. //#define ggml_lock_init(x) pthread_spin_init(x, PTHREAD_PROCESS_PRIVATE)
  7453. //#define ggml_lock_destroy pthread_spin_destroy
  7454. //#define ggml_lock_lock pthread_spin_lock
  7455. //#define ggml_lock_unlock pthread_spin_unlock
  7456. typedef int ggml_lock_t;
  7457. #define ggml_lock_init(x) UNUSED(x)
  7458. #define ggml_lock_destroy(x) UNUSED(x)
  7459. #define ggml_lock_lock(x) UNUSED(x)
  7460. #define ggml_lock_unlock(x) UNUSED(x)
  7461. #define GGML_LOCK_INITIALIZER 0
  7462. typedef pthread_t ggml_thread_t;
  7463. #define ggml_thread_create pthread_create
  7464. #define ggml_thread_join pthread_join
  7465. #endif
  7466. struct ggml_compute_state_shared {
  7467. ggml_lock_t spin;
  7468. int n_threads;
  7469. // synchronization primitives
  7470. atomic_int n_ready;
  7471. atomic_bool has_work;
  7472. atomic_bool stop; // stop all threads
  7473. };
  7474. struct ggml_compute_state {
  7475. ggml_thread_t thrd;
  7476. struct ggml_compute_params params;
  7477. struct ggml_tensor * node;
  7478. struct ggml_compute_state_shared * shared;
  7479. };
  7480. static thread_ret_t ggml_graph_compute_thread(void * data) {
  7481. struct ggml_compute_state * state = (struct ggml_compute_state *) data;
  7482. const int n_threads = state->shared->n_threads;
  7483. while (true) {
  7484. if (atomic_fetch_add(&state->shared->n_ready, 1) == n_threads - 1) {
  7485. atomic_store(&state->shared->has_work, false);
  7486. } else {
  7487. while (atomic_load(&state->shared->has_work)) {
  7488. if (atomic_load(&state->shared->stop)) {
  7489. return 0;
  7490. }
  7491. ggml_lock_lock (&state->shared->spin);
  7492. ggml_lock_unlock(&state->shared->spin);
  7493. }
  7494. }
  7495. atomic_fetch_sub(&state->shared->n_ready, 1);
  7496. // wait for work
  7497. while (!atomic_load(&state->shared->has_work)) {
  7498. if (atomic_load(&state->shared->stop)) {
  7499. return 0;
  7500. }
  7501. ggml_lock_lock (&state->shared->spin);
  7502. ggml_lock_unlock(&state->shared->spin);
  7503. }
  7504. // check if we should stop
  7505. if (atomic_load(&state->shared->stop)) {
  7506. break;
  7507. }
  7508. if (state->node) {
  7509. if (state->params.ith < state->params.nth) {
  7510. ggml_compute_forward(&state->params, state->node);
  7511. }
  7512. state->node = NULL;
  7513. } else {
  7514. break;
  7515. }
  7516. }
  7517. return 0;
  7518. }
  7519. void ggml_graph_compute(struct ggml_context * ctx, struct ggml_cgraph * cgraph) {
  7520. if (cgraph->n_threads <= 0) {
  7521. cgraph->n_threads = 8;
  7522. }
  7523. const int n_threads = cgraph->n_threads;
  7524. struct ggml_compute_state_shared state_shared = {
  7525. /*.spin =*/ GGML_LOCK_INITIALIZER,
  7526. /*.n_threads =*/ n_threads,
  7527. /*.n_ready =*/ 0,
  7528. /*.has_work =*/ false,
  7529. /*.stop =*/ false,
  7530. };
  7531. struct ggml_compute_state * workers = n_threads > 1 ? alloca(sizeof(struct ggml_compute_state)*(n_threads - 1)) : NULL;
  7532. // create thread pool
  7533. if (n_threads > 1) {
  7534. ggml_lock_init(&state_shared.spin);
  7535. atomic_store(&state_shared.has_work, true);
  7536. for (int j = 0; j < n_threads - 1; j++) {
  7537. workers[j] = (struct ggml_compute_state) {
  7538. .thrd = 0,
  7539. .params = {
  7540. .type = GGML_TASK_COMPUTE,
  7541. .ith = j + 1,
  7542. .nth = n_threads,
  7543. .wsize = cgraph->work ? ggml_nbytes(cgraph->work) : 0,
  7544. .wdata = cgraph->work ? cgraph->work->data : NULL,
  7545. },
  7546. .node = NULL,
  7547. .shared = &state_shared,
  7548. };
  7549. int rc = ggml_thread_create(&workers[j].thrd, NULL, ggml_graph_compute_thread, &workers[j]);
  7550. GGML_ASSERT(rc == 0);
  7551. UNUSED(rc);
  7552. }
  7553. }
  7554. // initialize tasks + work buffer
  7555. {
  7556. size_t work_size = 0;
  7557. // thread scheduling for the different operations
  7558. for (int i = 0; i < cgraph->n_nodes; i++) {
  7559. struct ggml_tensor * node = cgraph->nodes[i];
  7560. switch (node->op) {
  7561. case GGML_OP_DUP:
  7562. {
  7563. node->n_tasks = 1;
  7564. } break;
  7565. case GGML_OP_ADD:
  7566. {
  7567. node->n_tasks = n_threads;
  7568. } break;
  7569. case GGML_OP_SUB:
  7570. case GGML_OP_MUL:
  7571. case GGML_OP_DIV:
  7572. case GGML_OP_SQR:
  7573. case GGML_OP_SQRT:
  7574. case GGML_OP_SUM:
  7575. case GGML_OP_MEAN:
  7576. case GGML_OP_REPEAT:
  7577. case GGML_OP_ABS:
  7578. case GGML_OP_SGN:
  7579. case GGML_OP_NEG:
  7580. case GGML_OP_STEP:
  7581. case GGML_OP_RELU:
  7582. {
  7583. node->n_tasks = 1;
  7584. } break;
  7585. case GGML_OP_GELU:
  7586. {
  7587. node->n_tasks = n_threads;
  7588. } break;
  7589. case GGML_OP_SILU:
  7590. {
  7591. node->n_tasks = n_threads;
  7592. } break;
  7593. case GGML_OP_NORM:
  7594. {
  7595. node->n_tasks = n_threads;
  7596. } break;
  7597. case GGML_OP_MUL_MAT:
  7598. {
  7599. node->n_tasks = n_threads;
  7600. // TODO: use different scheduling for different matrix sizes
  7601. //const int nr0 = ggml_nrows(node->src0);
  7602. //const int nr1 = ggml_nrows(node->src1);
  7603. //node->n_tasks = MIN(n_threads, MAX(1, nr0/128));
  7604. //printf("nr0 = %8d, nr1 = %8d, nr0*nr1 = %8d, n_tasks = %d\n", nr0, nr1, nr0*nr1, node->n_tasks);
  7605. size_t cur = 0;
  7606. // TODO: better way to determine if the matrix is transposed
  7607. if (node->src0->nb[1] < node->src0->nb[0]) {
  7608. cur = ggml_nbytes(node)*node->n_tasks; // TODO: this can become (n_tasks-1)
  7609. // TODO: overestimated by factor of x2 for FP16
  7610. } else {
  7611. if (node->src0->type == GGML_TYPE_F16 &&
  7612. node->src1->type == GGML_TYPE_F32) {
  7613. #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
  7614. if (ggml_compute_forward_mul_mat_use_blas(node->src0, node->src1, node)) {
  7615. node->n_tasks = 1; // TODO: this actually is doing nothing
  7616. // the threads are still spinning
  7617. cur = GGML_TYPE_SIZE[GGML_TYPE_F32]*(node->src0->ne[0]*node->src0->ne[1]);
  7618. //printf("src0: ne0 = %d, ne1 = %d, ne = %d\n", node->src0->ne[0], node->src0->ne[1], node->src0->ne[0]*node->src0->ne[1]);
  7619. //printf("src1: ne0 = %d, ne1 = %d, ne = %d\n", node->src1->ne[0], node->src1->ne[1], node->src1->ne[0]*node->src1->ne[1]);
  7620. //printf("cur = %zu\n", cur);
  7621. } else {
  7622. cur = GGML_TYPE_SIZE[GGML_TYPE_F16]*ggml_nelements(node->src1);
  7623. }
  7624. #else
  7625. cur = GGML_TYPE_SIZE[GGML_TYPE_F16]*ggml_nelements(node->src1);
  7626. #endif
  7627. } else if (node->src0->type == GGML_TYPE_F32 &&
  7628. node->src1->type == GGML_TYPE_F32) {
  7629. cur = 0;
  7630. } else if (node->src0->type == GGML_TYPE_Q4_0 &&
  7631. node->src1->type == GGML_TYPE_F32) {
  7632. #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
  7633. if (ggml_compute_forward_mul_mat_use_blas(node->src0, node->src1, node)) {
  7634. node->n_tasks = 1;
  7635. cur = GGML_TYPE_SIZE[GGML_TYPE_F32]*(node->src0->ne[0]*node->src0->ne[1]);
  7636. } else {
  7637. cur = (GGML_TYPE_SIZE[GGML_TYPE_Q4_0]*ggml_nelements(node->src1))/GGML_BLCK_SIZE[GGML_TYPE_Q4_0];
  7638. }
  7639. #else
  7640. cur = (GGML_TYPE_SIZE[GGML_TYPE_Q4_0]*ggml_nelements(node->src1))/GGML_BLCK_SIZE[GGML_TYPE_Q4_0];
  7641. #endif
  7642. } else if (node->src0->type == GGML_TYPE_Q4_1 &&
  7643. node->src1->type == GGML_TYPE_F32) {
  7644. #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
  7645. if (ggml_compute_forward_mul_mat_use_blas(node->src0, node->src1, node)) {
  7646. node->n_tasks = 1;
  7647. cur = GGML_TYPE_SIZE[GGML_TYPE_F32]*(node->src0->ne[0]*node->src0->ne[1]);
  7648. } else {
  7649. cur = (GGML_TYPE_SIZE[GGML_TYPE_Q4_1]*ggml_nelements(node->src1))/GGML_BLCK_SIZE[GGML_TYPE_Q4_1];
  7650. }
  7651. #else
  7652. cur = (GGML_TYPE_SIZE[GGML_TYPE_Q4_1]*ggml_nelements(node->src1))/GGML_BLCK_SIZE[GGML_TYPE_Q4_1];
  7653. #endif
  7654. } else {
  7655. GGML_ASSERT(false);
  7656. }
  7657. }
  7658. work_size = MAX(work_size, cur);
  7659. } break;
  7660. case GGML_OP_SCALE:
  7661. {
  7662. node->n_tasks = n_threads;
  7663. } break;
  7664. case GGML_OP_CPY:
  7665. case GGML_OP_RESHAPE:
  7666. case GGML_OP_VIEW:
  7667. case GGML_OP_PERMUTE:
  7668. case GGML_OP_TRANSPOSE:
  7669. case GGML_OP_GET_ROWS:
  7670. case GGML_OP_DIAG_MASK_INF:
  7671. {
  7672. node->n_tasks = 1;
  7673. } break;
  7674. case GGML_OP_SOFT_MAX:
  7675. {
  7676. node->n_tasks = n_threads;
  7677. } break;
  7678. case GGML_OP_ROPE:
  7679. {
  7680. node->n_tasks = 1;
  7681. } break;
  7682. case GGML_OP_CONV_1D_1S:
  7683. case GGML_OP_CONV_1D_2S:
  7684. {
  7685. node->n_tasks = n_threads;
  7686. GGML_ASSERT(node->src0->ne[3] == 1);
  7687. GGML_ASSERT(node->src1->ne[2] == 1);
  7688. GGML_ASSERT(node->src1->ne[3] == 1);
  7689. size_t cur = 0;
  7690. const int nk = node->src0->ne[0];
  7691. if (node->src0->type == GGML_TYPE_F16 &&
  7692. node->src1->type == GGML_TYPE_F32) {
  7693. cur = sizeof(ggml_fp16_t)*(
  7694. nk*ggml_up32(node->src0->ne[1])*node->src0->ne[2] +
  7695. ( 2*(nk/2) + node->src1->ne[0])*node->src1->ne[1]
  7696. );
  7697. } else if (node->src0->type == GGML_TYPE_F32 &&
  7698. node->src1->type == GGML_TYPE_F32) {
  7699. cur = sizeof(float)*(
  7700. nk*ggml_up32(node->src0->ne[1])*node->src0->ne[2] +
  7701. ( 2*(nk/2) + node->src1->ne[0])*node->src1->ne[1]
  7702. );
  7703. } else {
  7704. GGML_ASSERT(false);
  7705. }
  7706. work_size = MAX(work_size, cur);
  7707. } break;
  7708. case GGML_OP_FLASH_ATTN:
  7709. {
  7710. node->n_tasks = n_threads;
  7711. size_t cur = 0;
  7712. const int ne11 = ggml_up(node->src1->ne[1], GGML_SOFT_MAX_UNROLL);
  7713. if (node->src1->type == GGML_TYPE_F32) {
  7714. cur = sizeof(float)*ne11*node->n_tasks; // TODO: this can become (n_tasks-1)
  7715. cur += sizeof(float)*ne11*node->n_tasks; // this is overestimated by x2
  7716. }
  7717. if (node->src1->type == GGML_TYPE_F16) {
  7718. cur = sizeof(float)*ne11*node->n_tasks; // TODO: this can become (n_tasks-1)
  7719. cur += sizeof(float)*ne11*node->n_tasks; // this is overestimated by x2
  7720. }
  7721. work_size = MAX(work_size, cur);
  7722. } break;
  7723. case GGML_OP_FLASH_FF:
  7724. {
  7725. node->n_tasks = n_threads;
  7726. size_t cur = 0;
  7727. if (node->src1->type == GGML_TYPE_F32) {
  7728. cur = sizeof(float)*node->src1->ne[1]*node->n_tasks; // TODO: this can become (n_tasks-1)
  7729. cur += sizeof(float)*node->src1->ne[1]*node->n_tasks; // this is overestimated by x2
  7730. }
  7731. if (node->src1->type == GGML_TYPE_F16) {
  7732. cur = sizeof(float)*node->src1->ne[1]*node->n_tasks; // TODO: this can become (n_tasks-1)
  7733. cur += sizeof(float)*node->src1->ne[1]*node->n_tasks; // this is overestimated by x2
  7734. }
  7735. work_size = MAX(work_size, cur);
  7736. } break;
  7737. case GGML_OP_NONE:
  7738. {
  7739. node->n_tasks = 1;
  7740. } break;
  7741. case GGML_OP_COUNT:
  7742. {
  7743. GGML_ASSERT(false);
  7744. } break;
  7745. }
  7746. }
  7747. if (cgraph->work != NULL && work_size > cgraph->work_size) {
  7748. GGML_ASSERT(false); // TODO: better handling
  7749. }
  7750. if (work_size > 0 && cgraph->work == NULL) {
  7751. cgraph->work_size = work_size + CACHE_LINE_SIZE*(n_threads - 1);
  7752. GGML_PRINT_DEBUG("%s: allocating work buffer for graph (%zu bytes)\n", __func__, cgraph->work_size);
  7753. cgraph->work = ggml_new_tensor_1d(ctx, GGML_TYPE_I8, cgraph->work_size);
  7754. }
  7755. }
  7756. const int64_t perf_start_cycles = ggml_perf_cycles();
  7757. const int64_t perf_start_time_us = ggml_perf_time_us();
  7758. for (int i = 0; i < cgraph->n_nodes; i++) {
  7759. GGML_PRINT_DEBUG_5("%s: %d/%d\n", __func__, i, cgraph->n_nodes);
  7760. struct ggml_tensor * node = cgraph->nodes[i];
  7761. // TODO: this could be used to avoid unnecessary computations, but it needs to be improved
  7762. //if (node->grad == NULL && node->perf_runs > 0) {
  7763. // continue;
  7764. //}
  7765. const int64_t perf_node_start_cycles = ggml_perf_cycles();
  7766. const int64_t perf_node_start_time_us = ggml_perf_time_us();
  7767. // INIT
  7768. struct ggml_compute_params params = {
  7769. /*.type =*/ GGML_TASK_INIT,
  7770. /*.ith =*/ 0,
  7771. /*.nth =*/ node->n_tasks,
  7772. /*.wsize =*/ cgraph->work ? ggml_nbytes(cgraph->work) : 0,
  7773. /*.wdata =*/ cgraph->work ? cgraph->work->data : NULL,
  7774. };
  7775. ggml_compute_forward(&params, node);
  7776. // COMPUTE
  7777. if (node->n_tasks > 1) {
  7778. if (atomic_fetch_add(&state_shared.n_ready, 1) == n_threads - 1) {
  7779. atomic_store(&state_shared.has_work, false);
  7780. }
  7781. while (atomic_load(&state_shared.has_work)) {
  7782. ggml_lock_lock (&state_shared.spin);
  7783. ggml_lock_unlock(&state_shared.spin);
  7784. }
  7785. // launch thread pool
  7786. for (int j = 0; j < n_threads - 1; j++) {
  7787. workers[j].params = (struct ggml_compute_params) {
  7788. .type = GGML_TASK_COMPUTE,
  7789. .ith = j + 1,
  7790. .nth = node->n_tasks,
  7791. .wsize = cgraph->work ? ggml_nbytes(cgraph->work) : 0,
  7792. .wdata = cgraph->work ? cgraph->work->data : NULL,
  7793. };
  7794. workers[j].node = node;
  7795. }
  7796. atomic_fetch_sub(&state_shared.n_ready, 1);
  7797. while (atomic_load(&state_shared.n_ready) > 0) {
  7798. ggml_lock_lock (&state_shared.spin);
  7799. ggml_lock_unlock(&state_shared.spin);
  7800. }
  7801. atomic_store(&state_shared.has_work, true);
  7802. }
  7803. params.type = GGML_TASK_COMPUTE;
  7804. ggml_compute_forward(&params, node);
  7805. // wait for thread pool
  7806. if (node->n_tasks > 1) {
  7807. if (atomic_fetch_add(&state_shared.n_ready, 1) == n_threads - 1) {
  7808. atomic_store(&state_shared.has_work, false);
  7809. }
  7810. while (atomic_load(&state_shared.has_work)) {
  7811. ggml_lock_lock (&state_shared.spin);
  7812. ggml_lock_unlock(&state_shared.spin);
  7813. }
  7814. atomic_fetch_sub(&state_shared.n_ready, 1);
  7815. while (atomic_load(&state_shared.n_ready) != 0) {
  7816. ggml_lock_lock (&state_shared.spin);
  7817. ggml_lock_unlock(&state_shared.spin);
  7818. }
  7819. }
  7820. // FINALIZE
  7821. if (node->n_tasks > 1) {
  7822. if (atomic_fetch_add(&state_shared.n_ready, 1) == n_threads - 1) {
  7823. atomic_store(&state_shared.has_work, false);
  7824. }
  7825. while (atomic_load(&state_shared.has_work)) {
  7826. ggml_lock_lock (&state_shared.spin);
  7827. ggml_lock_unlock(&state_shared.spin);
  7828. }
  7829. // launch thread pool
  7830. for (int j = 0; j < n_threads - 1; j++) {
  7831. workers[j].params = (struct ggml_compute_params) {
  7832. .type = GGML_TASK_FINALIZE,
  7833. .ith = j + 1,
  7834. .nth = node->n_tasks,
  7835. .wsize = cgraph->work ? ggml_nbytes(cgraph->work) : 0,
  7836. .wdata = cgraph->work ? cgraph->work->data : NULL,
  7837. };
  7838. workers[j].node = node;
  7839. }
  7840. atomic_fetch_sub(&state_shared.n_ready, 1);
  7841. while (atomic_load(&state_shared.n_ready) > 0) {
  7842. ggml_lock_lock (&state_shared.spin);
  7843. ggml_lock_unlock(&state_shared.spin);
  7844. }
  7845. atomic_store(&state_shared.has_work, true);
  7846. }
  7847. params.type = GGML_TASK_FINALIZE;
  7848. ggml_compute_forward(&params, node);
  7849. // wait for thread pool
  7850. if (node->n_tasks > 1) {
  7851. if (atomic_fetch_add(&state_shared.n_ready, 1) == n_threads - 1) {
  7852. atomic_store(&state_shared.has_work, false);
  7853. }
  7854. while (atomic_load(&state_shared.has_work)) {
  7855. ggml_lock_lock (&state_shared.spin);
  7856. ggml_lock_unlock(&state_shared.spin);
  7857. }
  7858. atomic_fetch_sub(&state_shared.n_ready, 1);
  7859. while (atomic_load(&state_shared.n_ready) != 0) {
  7860. ggml_lock_lock (&state_shared.spin);
  7861. ggml_lock_unlock(&state_shared.spin);
  7862. }
  7863. }
  7864. // performance stats (node)
  7865. {
  7866. int64_t perf_cycles_cur = ggml_perf_cycles() - perf_node_start_cycles;
  7867. int64_t perf_time_us_cur = ggml_perf_time_us() - perf_node_start_time_us;
  7868. node->perf_runs++;
  7869. node->perf_cycles += perf_cycles_cur;
  7870. node->perf_time_us += perf_time_us_cur;
  7871. }
  7872. }
  7873. // join thread pool
  7874. if (n_threads > 1) {
  7875. atomic_store(&state_shared.stop, true);
  7876. atomic_store(&state_shared.has_work, true);
  7877. for (int j = 0; j < n_threads - 1; j++) {
  7878. int rc = ggml_thread_join(workers[j].thrd, NULL);
  7879. GGML_ASSERT(rc == 0);
  7880. UNUSED(rc);
  7881. }
  7882. ggml_lock_destroy(&state_shared.spin);
  7883. }
  7884. // performance stats (graph)
  7885. {
  7886. int64_t perf_cycles_cur = ggml_perf_cycles() - perf_start_cycles;
  7887. int64_t perf_time_us_cur = ggml_perf_time_us() - perf_start_time_us;
  7888. cgraph->perf_runs++;
  7889. cgraph->perf_cycles += perf_cycles_cur;
  7890. cgraph->perf_time_us += perf_time_us_cur;
  7891. GGML_PRINT_DEBUG("%s: perf (%d) - cpu = %.3f / %.3f ms, wall = %.3f / %.3f ms\n",
  7892. __func__, cgraph->perf_runs,
  7893. (double) perf_cycles_cur / (double) ggml_cycles_per_ms(),
  7894. (double) cgraph->perf_cycles / (double) ggml_cycles_per_ms() / (double) cgraph->perf_runs,
  7895. (double) perf_time_us_cur / 1000.0,
  7896. (double) cgraph->perf_time_us / 1000.0 / cgraph->perf_runs);
  7897. }
  7898. }
  7899. void ggml_graph_reset(struct ggml_cgraph * cgraph) {
  7900. for (int i = 0; i < cgraph->n_nodes; i++) {
  7901. struct ggml_tensor * grad = cgraph->grads[i];
  7902. if (grad) {
  7903. ggml_set_zero(grad);
  7904. }
  7905. }
  7906. }
  7907. void ggml_graph_print(const struct ggml_cgraph * cgraph) {
  7908. int64_t perf_total_per_op_us[GGML_OP_COUNT] = {0};
  7909. GGML_PRINT("=== GRAPH ===\n");
  7910. GGML_PRINT_DEBUG("n_threads = %d\n", cgraph->n_threads);
  7911. GGML_PRINT_DEBUG("total work size = %zu bytes\n",cgraph->work_size);
  7912. GGML_PRINT("n_nodes = %d\n", cgraph->n_nodes);
  7913. for (int i = 0; i < cgraph->n_nodes; i++) {
  7914. struct ggml_tensor * node = cgraph->nodes[i];
  7915. perf_total_per_op_us[node->op] += node->perf_time_us;
  7916. GGML_PRINT(" - %3d: [ %6d, %6d, %6d] %16s %s (%3d) cpu = %7.3f / %7.3f ms, wall = %7.3f / %7.3f ms\n",
  7917. i,
  7918. node->ne[0], node->ne[1], node->ne[2],
  7919. GGML_OP_LABEL[node->op], node->is_param ? "x" : node->grad ? "g" : " ", node->perf_runs,
  7920. (double) node->perf_cycles / (double) ggml_cycles_per_ms(),
  7921. (double) node->perf_cycles / (double) ggml_cycles_per_ms() / (double) node->perf_runs,
  7922. (double) node->perf_time_us / 1000.0,
  7923. (double) node->perf_time_us / 1000.0 / node->perf_runs);
  7924. }
  7925. GGML_PRINT("n_leafs = %d\n", cgraph->n_leafs);
  7926. for (int i = 0; i < cgraph->n_leafs; i++) {
  7927. struct ggml_tensor * node = cgraph->leafs[i];
  7928. GGML_PRINT(" - %3d: [ %6d, %6d] %8s\n",
  7929. i,
  7930. node->ne[0], node->ne[1],
  7931. GGML_OP_LABEL[node->op]);
  7932. }
  7933. for (int i = 0; i < GGML_OP_COUNT; i++) {
  7934. GGML_PRINT("perf_total_per_op_us[%16s] = %7.3f ms\n", GGML_OP_LABEL[i], (double) perf_total_per_op_us[i] / 1000.0);
  7935. }
  7936. GGML_PRINT("========================================\n");
  7937. }
  7938. // check if node is part of the graph
  7939. static bool ggml_graph_find(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  7940. if (cgraph == NULL) {
  7941. return true;
  7942. }
  7943. for (int i = 0; i < cgraph->n_nodes; i++) {
  7944. if (cgraph->nodes[i] == node) {
  7945. return true;
  7946. }
  7947. }
  7948. return false;
  7949. }
  7950. static struct ggml_tensor * ggml_graph_get_parent(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  7951. for (int i = 0; i < cgraph->n_nodes; i++) {
  7952. struct ggml_tensor * parent = cgraph->nodes[i];
  7953. if (parent->grad == node) {
  7954. return parent;
  7955. }
  7956. }
  7957. return NULL;
  7958. }
  7959. void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * gf, const char * filename) {
  7960. char color[16];
  7961. FILE * fp = fopen(filename, "w");
  7962. GGML_ASSERT(fp);
  7963. fprintf(fp, "digraph G {\n");
  7964. fprintf(fp, " newrank = true;\n");
  7965. fprintf(fp, " rankdir = LR;\n");
  7966. for (int i = 0; i < gb->n_nodes; i++) {
  7967. struct ggml_tensor * node = gb->nodes[i];
  7968. if (ggml_graph_get_parent(gb, node) != NULL) {
  7969. continue;
  7970. }
  7971. if (node->is_param) {
  7972. snprintf(color, sizeof(color), "yellow");
  7973. } else if (node->grad) {
  7974. if (ggml_graph_find(gf, node)) {
  7975. snprintf(color, sizeof(color), "green");
  7976. } else {
  7977. snprintf(color, sizeof(color), "lightblue");
  7978. }
  7979. } else {
  7980. snprintf(color, sizeof(color), "white");
  7981. }
  7982. fprintf(fp, " \"%p\" [ \
  7983. style = filled; fillcolor = %s; shape = record; \
  7984. label=\"%d [%d, %d] | <x>%s",
  7985. (void *) node, color,
  7986. i, node->ne[0], node->ne[1],
  7987. GGML_OP_SYMBOL[node->op]);
  7988. if (node->grad) {
  7989. fprintf(fp, " | <g>%s\"; ]\n", GGML_OP_SYMBOL[node->grad->op]);
  7990. } else {
  7991. fprintf(fp, "\"; ]\n");
  7992. }
  7993. }
  7994. for (int i = 0; i < gb->n_leafs; i++) {
  7995. struct ggml_tensor * node = gb->leafs[i];
  7996. snprintf(color, sizeof(color), "pink");
  7997. if (ggml_nelements(node) == 1) {
  7998. fprintf(fp, " \"%p\" [ \
  7999. style = filled; fillcolor = %s; shape = record; \
  8000. label=\"<x>%.1e\"; ]\n",
  8001. (void *) node, color, ggml_get_f32_1d(node, 0));
  8002. } else {
  8003. fprintf(fp, " \"%p\" [ \
  8004. style = filled; fillcolor = %s; shape = record; \
  8005. label=\"<x>CONST %d [%d, %d]\"; ]\n",
  8006. (void *) node, color,
  8007. i, node->ne[0], node->ne[1]);
  8008. }
  8009. }
  8010. for (int i = 0; i < gb->n_nodes; i++) {
  8011. struct ggml_tensor * node = gb->nodes[i];
  8012. struct ggml_tensor * parent = ggml_graph_get_parent(gb, node);
  8013. if (node->src0) {
  8014. struct ggml_tensor * parent0 = ggml_graph_get_parent(gb, node->src0);
  8015. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ arrowhead = %s; style = %s; label = \"x\"; ]\n",
  8016. parent0 ? (void *) parent0 : (void *) node->src0,
  8017. parent0 ? "g" : "x",
  8018. parent ? (void *) parent : (void *) node,
  8019. parent ? "g" : "x",
  8020. parent ? "empty" : "vee",
  8021. parent ? "dashed" : "solid");
  8022. }
  8023. if (node->src1) {
  8024. struct ggml_tensor * parent1 = ggml_graph_get_parent(gb, node->src1);
  8025. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ arrowhead = %s; style = %s; label = \"y\"; ]\n",
  8026. parent1 ? (void *) parent1 : (void *) node->src1,
  8027. parent1 ? "g" : "x",
  8028. parent ? (void *) parent : (void *) node,
  8029. parent ? "g" : "x",
  8030. parent ? "empty" : "vee",
  8031. parent ? "dashed" : "solid");
  8032. }
  8033. }
  8034. for (int i = 0; i < gb->n_leafs; i++) {
  8035. struct ggml_tensor * node = gb->leafs[i];
  8036. if (node->src0) {
  8037. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ label = \"x\"; ]\n",
  8038. (void *) node->src0, "x",
  8039. (void *) node, "x");
  8040. }
  8041. if (node->src1) {
  8042. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ label = \"y\"; ]\n",
  8043. (void *) node->src1, "x",
  8044. (void *) node, "x");
  8045. }
  8046. }
  8047. fprintf(fp, "}\n");
  8048. fclose(fp);
  8049. GGML_PRINT("%s: dot -Tpng %s -o %s.png && open %s.png\n", __func__, filename, filename, filename);
  8050. }
  8051. ////////////////////////////////////////////////////////////////////////////////
  8052. static void ggml_opt_set_params(int np, struct ggml_tensor * const ps[], const float * x) {
  8053. int i = 0;
  8054. for (int p = 0; p < np; ++p) {
  8055. const int ne = ggml_nelements(ps[p]) ;
  8056. // TODO: add function to set tensor from array
  8057. for (int j = 0; j < ne; ++j) {
  8058. ggml_set_f32_1d(ps[p], j, x[i++]);
  8059. }
  8060. }
  8061. }
  8062. static void ggml_opt_get_params(int np, struct ggml_tensor * const ps[], float * x) {
  8063. int i = 0;
  8064. for (int p = 0; p < np; ++p) {
  8065. const int ne = ggml_nelements(ps[p]) ;
  8066. // TODO: add function to get all elements at once
  8067. for (int j = 0; j < ne; ++j) {
  8068. x[i++] = ggml_get_f32_1d(ps[p], j);
  8069. }
  8070. }
  8071. }
  8072. static void ggml_opt_get_grad(int np, struct ggml_tensor * const ps[], float * g) {
  8073. int i = 0;
  8074. for (int p = 0; p < np; ++p) {
  8075. const int ne = ggml_nelements(ps[p]) ;
  8076. // TODO: add function to get all elements at once
  8077. for (int j = 0; j < ne; ++j) {
  8078. g[i++] = ggml_get_f32_1d(ps[p]->grad, j);
  8079. }
  8080. }
  8081. }
  8082. //
  8083. // ADAM
  8084. //
  8085. // ref: https://arxiv.org/pdf/1412.6980.pdf
  8086. //
  8087. static enum ggml_opt_result ggml_opt_adam(
  8088. struct ggml_context * ctx,
  8089. struct ggml_opt_params params,
  8090. struct ggml_tensor * f,
  8091. struct ggml_cgraph * gf,
  8092. struct ggml_cgraph * gb) {
  8093. GGML_ASSERT(ggml_is_scalar(f));
  8094. gf->n_threads = params.n_threads;
  8095. gb->n_threads = params.n_threads;
  8096. // these will store the parameters we want to optimize
  8097. struct ggml_tensor * ps[GGML_MAX_PARAMS];
  8098. int np = 0;
  8099. int nx = 0;
  8100. for (int i = 0; i < gf->n_nodes; ++i) {
  8101. if (gf->nodes[i]->is_param) {
  8102. GGML_PRINT_DEBUG("found param %d: grad->op = %d\n", np, gf->nodes[i]->grad->op);
  8103. GGML_ASSERT(np < GGML_MAX_PARAMS);
  8104. ps[np++] = gf->nodes[i];
  8105. nx += ggml_nelements(gf->nodes[i]);
  8106. }
  8107. }
  8108. // constants
  8109. const float alpha = params.adam.alpha;
  8110. const float beta1 = params.adam.beta1;
  8111. const float beta2 = params.adam.beta2;
  8112. const float eps = params.adam.eps;
  8113. float * x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // view of the parameters
  8114. float * g1 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // gradient
  8115. float * g2 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // gradient squared
  8116. float * m = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // first moment
  8117. float * v = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // second moment
  8118. float * mh = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // first moment hat
  8119. float * vh = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // second moment hat
  8120. float * pf = params.past > 0 ? ggml_new_tensor_1d(ctx, GGML_TYPE_F32, params.past)->data : NULL; // past function values
  8121. // initialize
  8122. ggml_vec_set_f32(nx, m, 0.0f);
  8123. ggml_vec_set_f32(nx, v, 0.0f);
  8124. // update view
  8125. ggml_opt_get_params(np, ps, x);
  8126. // compute the function value
  8127. ggml_graph_reset (gf);
  8128. ggml_set_f32 (f->grad, 1.0f);
  8129. ggml_graph_compute(ctx, gb);
  8130. float fx_prev = ggml_get_f32_1d(f, 0);
  8131. if (pf) {
  8132. pf[0] = fx_prev;
  8133. }
  8134. int n_no_improvement = 0;
  8135. float fx_best = fx_prev;
  8136. // run the optimizer
  8137. for (int t = 0; t < params.adam.n_iter; ++t) {
  8138. GGML_PRINT_DEBUG ("=== iter %d ===\n", t);
  8139. GGML_PRINT_DEBUG ("f = %10.6f\n", ggml_get_f32_1d(f, 0));
  8140. GGML_PRINT_DEBUG_5("df/dx0 = %10.6f\n", ggml_get_f32_1d(ps[0]->grad, 0));
  8141. GGML_PRINT_DEBUG_5("df/dx1 = %10.6f\n", ggml_get_f32_1d(ps[1]->grad, 0));
  8142. for (int i = 0; i < np; ++i) {
  8143. GGML_PRINT_DEBUG("param %d: %10.6f, g = %10.6f\n", i,
  8144. ggml_get_f32_1d(ps[i], 0), ggml_get_f32_1d(ps[i]->grad, 0));
  8145. }
  8146. const int64_t t_start_wall = ggml_time_us();
  8147. const int64_t t_start_cpu = ggml_cycles();
  8148. UNUSED(t_start_wall);
  8149. UNUSED(t_start_cpu);
  8150. {
  8151. // update the gradient
  8152. ggml_opt_get_grad(np, ps, g1);
  8153. // m_t = beta1*m_t-1 + (1 - beta1)*g_t
  8154. ggml_vec_scale_f32(nx, m, beta1);
  8155. ggml_vec_mad_f32 (nx, m, g1, 1.0f - beta1);
  8156. // g2 = g1^2
  8157. ggml_vec_sqr_f32 (nx, g2, g1);
  8158. // v_t = beta2*v_t-1 + (1 - beta2)*g_t^2
  8159. ggml_vec_scale_f32(nx, v, beta2);
  8160. ggml_vec_mad_f32 (nx, v, g2, 1.0f - beta2);
  8161. // m^hat = m_t / (1 - beta1^t)
  8162. // v^hat = v_t / (1 - beta2^t)
  8163. // x_t = x_t-1 - alpha*m^hat/(sqrt(v^hat) + eps)
  8164. ggml_vec_cpy_f32 (nx, mh, m);
  8165. ggml_vec_cpy_f32 (nx, vh, v);
  8166. ggml_vec_scale_f32(nx, mh, alpha/(1.0f - powf(beta1, t + 1)));
  8167. ggml_vec_scale_f32(nx, vh, 1.0f/(1.0f - powf(beta2, t + 1)));
  8168. ggml_vec_sqrt_f32 (nx, vh, vh);
  8169. ggml_vec_acc1_f32 (nx, vh, eps);
  8170. ggml_vec_div_f32 (nx, mh, mh, vh);
  8171. ggml_vec_sub_f32 (nx, x, x, mh);
  8172. // update the parameters
  8173. ggml_opt_set_params(np, ps, x);
  8174. }
  8175. ggml_graph_reset (gf);
  8176. ggml_set_f32 (f->grad, 1.0f);
  8177. ggml_graph_compute(ctx, gb);
  8178. const float fx = ggml_get_f32_1d(f, 0);
  8179. // check convergence
  8180. if (fabsf(fx - fx_prev)/fx < params.adam.eps_f) {
  8181. GGML_PRINT_DEBUG("converged\n");
  8182. return GGML_OPT_OK;
  8183. }
  8184. // delta-based convergence test
  8185. if (pf != NULL) {
  8186. // need at least params.past iterations to start checking for convergence
  8187. if (params.past <= t) {
  8188. const float rate = (pf[t%params.past] - fx)/fx;
  8189. if (fabs(rate) < params.delta) {
  8190. return GGML_OPT_OK;
  8191. }
  8192. }
  8193. pf[t%params.past] = fx;
  8194. }
  8195. // check for improvement
  8196. if (params.max_no_improvement > 0) {
  8197. if (fx_best > fx) {
  8198. fx_best = fx;
  8199. n_no_improvement = 0;
  8200. } else {
  8201. ++n_no_improvement;
  8202. if (n_no_improvement >= params.max_no_improvement) {
  8203. return GGML_OPT_OK;
  8204. }
  8205. }
  8206. }
  8207. fx_prev = fx;
  8208. {
  8209. const int64_t t_end_cpu = ggml_cycles();
  8210. GGML_PRINT_DEBUG("time iter: %5.3f s\n", ((float)(t_end_cpu - t_start_cpu))/CLOCKS_PER_SEC);
  8211. UNUSED(t_end_cpu);
  8212. const int64_t t_end_wall = ggml_time_us();
  8213. GGML_PRINT_DEBUG("wall time iter: %5.3f s\n", (t_end_wall - t_start_wall)/1e6);
  8214. UNUSED(t_end_wall);
  8215. }
  8216. }
  8217. return GGML_OPT_DID_NOT_CONVERGE;
  8218. }
  8219. //
  8220. // L-BFGS
  8221. //
  8222. // the L-BFGS implementation below is based on the following implementation:
  8223. //
  8224. // https://github.com/chokkan/liblbfgs
  8225. //
  8226. struct ggml_lbfgs_iteration_data {
  8227. float alpha;
  8228. float ys;
  8229. float * s;
  8230. float * y;
  8231. };
  8232. static enum ggml_opt_result linesearch_backtracking(
  8233. struct ggml_context * ctx,
  8234. const struct ggml_opt_params * params,
  8235. int nx,
  8236. float * x,
  8237. float * fx,
  8238. float * g,
  8239. float * d,
  8240. float * step,
  8241. const float * xp,
  8242. struct ggml_tensor * f,
  8243. struct ggml_cgraph * gf,
  8244. struct ggml_cgraph * gb,
  8245. const int np,
  8246. struct ggml_tensor * ps[]) {
  8247. int count = 0;
  8248. float width = 0.0f;
  8249. float dg = 0.0f;
  8250. float finit = 0.0f;
  8251. float dginit = 0.0f;
  8252. float dgtest = 0.0f;
  8253. const float dec = 0.5f;
  8254. const float inc = 2.1f;
  8255. if (*step <= 0.) {
  8256. return GGML_LINESEARCH_INVALID_PARAMETERS;
  8257. }
  8258. // compute the initial gradient in the search direction
  8259. ggml_vec_dot_f32(nx, &dginit, g, d);
  8260. // make sure that d points to a descent direction
  8261. if (0 < dginit) {
  8262. return GGML_LINESEARCH_FAIL;
  8263. }
  8264. // initialize local variables
  8265. finit = *fx;
  8266. dgtest = params->lbfgs.ftol*dginit;
  8267. while (true) {
  8268. ggml_vec_cpy_f32(nx, x, xp);
  8269. ggml_vec_mad_f32(nx, x, d, *step);
  8270. // evaluate the function and gradient values
  8271. {
  8272. ggml_opt_set_params(np, ps, x);
  8273. ggml_graph_reset (gf);
  8274. ggml_set_f32 (f->grad, 1.0f);
  8275. ggml_graph_compute(ctx, gb);
  8276. ggml_opt_get_grad(np, ps, g);
  8277. *fx = ggml_get_f32_1d(f, 0);
  8278. }
  8279. ++count;
  8280. if (*fx > finit + (*step)*dgtest) {
  8281. width = dec;
  8282. } else {
  8283. // Armijo condition is satisfied
  8284. if (params->lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_ARMIJO) {
  8285. return count;
  8286. }
  8287. ggml_vec_dot_f32(nx, &dg, g, d);
  8288. // check the Wolfe condition
  8289. if (dg < params->lbfgs.wolfe * dginit) {
  8290. width = inc;
  8291. } else {
  8292. if(params->lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_WOLFE) {
  8293. // regular Wolfe conditions
  8294. return count;
  8295. }
  8296. if(dg > -params->lbfgs.wolfe*dginit) {
  8297. width = dec;
  8298. } else {
  8299. // strong Wolfe condition (GGML_LINESEARCH_BACKTRACKING_STRONG_WOLFE)
  8300. return count;
  8301. }
  8302. return count;
  8303. }
  8304. }
  8305. if (*step < params->lbfgs.min_step) {
  8306. return GGML_LINESEARCH_MINIMUM_STEP;
  8307. }
  8308. if (*step > params->lbfgs.max_step) {
  8309. return GGML_LINESEARCH_MAXIMUM_STEP;
  8310. }
  8311. if (params->lbfgs.max_linesearch <= count) {
  8312. return GGML_LINESEARCH_MAXIMUM_ITERATIONS;
  8313. }
  8314. (*step) *= width;
  8315. }
  8316. return GGML_LINESEARCH_FAIL;
  8317. }
  8318. static enum ggml_opt_result ggml_opt_lbfgs(
  8319. struct ggml_context * ctx,
  8320. struct ggml_opt_params params,
  8321. struct ggml_tensor * f,
  8322. struct ggml_cgraph * gf,
  8323. struct ggml_cgraph * gb) {
  8324. if (params.lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_WOLFE ||
  8325. params.lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_STRONG_WOLFE) {
  8326. if (params.lbfgs.wolfe <= params.lbfgs.ftol || 1. <= params.lbfgs.wolfe) {
  8327. return GGML_OPT_INVALID_WOLFE;
  8328. }
  8329. }
  8330. gf->n_threads = params.n_threads;
  8331. gb->n_threads = params.n_threads;
  8332. const int m = params.lbfgs.m;
  8333. // these will store the parameters we want to optimize
  8334. struct ggml_tensor * ps[GGML_MAX_PARAMS];
  8335. int np = 0;
  8336. int nx = 0;
  8337. for (int i = 0; i < gf->n_nodes; ++i) {
  8338. if (gf->nodes[i]->is_param) {
  8339. GGML_PRINT_DEBUG("found param %d: grad->op = %d\n", np, gf->nodes[i]->grad->op);
  8340. GGML_ASSERT(np < GGML_MAX_PARAMS);
  8341. ps[np++] = gf->nodes[i];
  8342. nx += ggml_nelements(gf->nodes[i]);
  8343. }
  8344. }
  8345. float * x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // current parameters
  8346. float * xp = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // previous parameters
  8347. float * g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // current gradient
  8348. float * gp = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // previous gradient
  8349. float * d = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // search direction
  8350. float * pf = params.past > 0 ? ggml_new_tensor_1d(ctx, GGML_TYPE_F32, params.past)->data : NULL; // past function values
  8351. float fx = 0.0f; // cost function value
  8352. float xnorm = 0.0f; // ||x||
  8353. float gnorm = 0.0f; // ||g||
  8354. float step = 0.0f;
  8355. // initialize x from the graph nodes
  8356. ggml_opt_get_params(np, ps, x);
  8357. // the L-BFGS memory
  8358. struct ggml_lbfgs_iteration_data * lm = alloca(sizeof(struct ggml_lbfgs_iteration_data)*m);
  8359. for (int i = 0; i < m; ++i) {
  8360. lm[i].alpha = 0.0f;
  8361. lm[i].ys = 0.0f;
  8362. lm[i].s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data;
  8363. lm[i].y = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data;
  8364. }
  8365. // evaluate the function value and its gradient
  8366. {
  8367. ggml_opt_set_params(np, ps, x);
  8368. ggml_graph_reset (gf);
  8369. ggml_set_f32 (f->grad, 1.0f);
  8370. ggml_graph_compute(ctx, gb);
  8371. ggml_opt_get_grad(np, ps, g);
  8372. fx = ggml_get_f32_1d(f, 0);
  8373. }
  8374. if (pf) {
  8375. pf[0] = fx;
  8376. }
  8377. float fx_best = fx;
  8378. // search direction = -gradient
  8379. ggml_vec_neg_f32(nx, d, g);
  8380. // ||x||, ||g||
  8381. ggml_vec_norm_f32(nx, &xnorm, x);
  8382. ggml_vec_norm_f32(nx, &gnorm, g);
  8383. if (xnorm < 1.0f) {
  8384. xnorm = 1.0f;
  8385. }
  8386. // already optimized
  8387. if (gnorm/xnorm <= params.lbfgs.eps) {
  8388. return GGML_OPT_OK;
  8389. }
  8390. // initial step
  8391. ggml_vec_norm_inv_f32(nx, &step, d);
  8392. int j = 0;
  8393. int k = 1;
  8394. int ls = 0;
  8395. int end = 0;
  8396. int bound = 0;
  8397. int n_no_improvement = 0;
  8398. float ys = 0.0f;
  8399. float yy = 0.0f;
  8400. float beta = 0.0f;
  8401. while (true) {
  8402. // store the current position and gradient vectors
  8403. ggml_vec_cpy_f32(nx, xp, x);
  8404. ggml_vec_cpy_f32(nx, gp, g);
  8405. ls = linesearch_backtracking(ctx, &params, nx, x, &fx, g, d, &step, xp, f, gf, gb, np, ps);
  8406. if (ls < 0) {
  8407. // linesearch failed - go back to the previous point and return
  8408. ggml_vec_cpy_f32(nx, x, xp);
  8409. ggml_vec_cpy_f32(nx, g, gp);
  8410. return ls;
  8411. }
  8412. ggml_vec_norm_f32(nx, &xnorm, x);
  8413. ggml_vec_norm_f32(nx, &gnorm, g);
  8414. GGML_PRINT_DEBUG("f = %10.6f\n", ggml_get_f32_1d(f, 0));
  8415. if (xnorm < 1.0) {
  8416. xnorm = 1.0;
  8417. }
  8418. if (gnorm/xnorm <= params.lbfgs.eps) {
  8419. // converged
  8420. return GGML_OPT_OK;
  8421. }
  8422. // delta-based convergence test
  8423. if (pf != NULL) {
  8424. // need at least params.past iterations to start checking for convergence
  8425. if (params.past <= k) {
  8426. const float rate = (pf[k%params.past] - fx)/fx;
  8427. if (fabs(rate) < params.delta) {
  8428. return GGML_OPT_OK;
  8429. }
  8430. }
  8431. pf[k%params.past] = fx;
  8432. }
  8433. // check for improvement
  8434. if (params.max_no_improvement > 0) {
  8435. if (fx < fx_best) {
  8436. fx_best = fx;
  8437. n_no_improvement = 0;
  8438. } else {
  8439. n_no_improvement++;
  8440. if (n_no_improvement >= params.max_no_improvement) {
  8441. return GGML_OPT_OK;
  8442. }
  8443. }
  8444. }
  8445. if (params.lbfgs.n_iter != 0 && params.lbfgs.n_iter < k + 1) {
  8446. // reached the maximum number of iterations
  8447. return GGML_OPT_DID_NOT_CONVERGE;
  8448. }
  8449. // update vectors s and y:
  8450. // s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}.
  8451. // y_{k+1} = g_{k+1} - g_{k}.
  8452. //
  8453. ggml_vec_sub_f32(nx, lm[end].s, x, xp);
  8454. ggml_vec_sub_f32(nx, lm[end].y, g, gp);
  8455. // compute scalars ys and yy:
  8456. // ys = y^t \cdot s -> 1 / \rho.
  8457. // yy = y^t \cdot y.
  8458. //
  8459. ggml_vec_dot_f32(nx, &ys, lm[end].y, lm[end].s);
  8460. ggml_vec_dot_f32(nx, &yy, lm[end].y, lm[end].y);
  8461. lm[end].ys = ys;
  8462. // find new search direction
  8463. // ref: https://en.wikipedia.org/wiki/Limited-memory_BFGS
  8464. bound = (m <= k) ? m : k;
  8465. k++;
  8466. end = (end + 1)%m;
  8467. // initialize search direction with -g
  8468. ggml_vec_neg_f32(nx, d, g);
  8469. j = end;
  8470. for (int i = 0; i < bound; ++i) {
  8471. j = (j + m - 1) % m;
  8472. // \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}
  8473. ggml_vec_dot_f32(nx, &lm[j].alpha, lm[j].s, d);
  8474. lm[j].alpha /= lm[j].ys;
  8475. // q_{i} = q_{i+1} - \alpha_{i} y_{i}
  8476. ggml_vec_mad_f32(nx, d, lm[j].y, -lm[j].alpha);
  8477. }
  8478. ggml_vec_scale_f32(nx, d, ys/yy);
  8479. for (int i = 0; i < bound; ++i) {
  8480. // \beta_{j} = \rho_{j} y^t_{j} \cdot \gamma_{i}
  8481. ggml_vec_dot_f32(nx, &beta, lm[j].y, d);
  8482. beta /= lm[j].ys;
  8483. // \gamma_{i+1} = \gamma_{i} + (\alpha_{j} - \beta_{j}) s_{j}
  8484. ggml_vec_mad_f32(nx, d, lm[j].s, lm[j].alpha - beta);
  8485. j = (j + 1)%m;
  8486. }
  8487. step = 1.0;
  8488. }
  8489. return GGML_OPT_DID_NOT_CONVERGE;
  8490. }
  8491. struct ggml_opt_params ggml_opt_default_params(enum ggml_opt_type type) {
  8492. struct ggml_opt_params result;
  8493. switch (type) {
  8494. case GGML_OPT_ADAM:
  8495. {
  8496. result = (struct ggml_opt_params) {
  8497. .type = GGML_OPT_ADAM,
  8498. .n_threads = 1,
  8499. .past = 0,
  8500. .delta = 1e-5f,
  8501. .max_no_improvement = 100,
  8502. .print_forward_graph = true,
  8503. .print_backward_graph = true,
  8504. .adam = {
  8505. .n_iter = 10000,
  8506. .alpha = 0.001f,
  8507. .beta1 = 0.9f,
  8508. .beta2 = 0.999f,
  8509. .eps = 1e-8f,
  8510. .eps_f = 1e-5f,
  8511. .eps_g = 1e-3f,
  8512. },
  8513. };
  8514. } break;
  8515. case GGML_OPT_LBFGS:
  8516. {
  8517. result = (struct ggml_opt_params) {
  8518. .type = GGML_OPT_LBFGS,
  8519. .n_threads = 1,
  8520. .past = 0,
  8521. .delta = 1e-5f,
  8522. .max_no_improvement = 0,
  8523. .print_forward_graph = true,
  8524. .print_backward_graph = true,
  8525. .lbfgs = {
  8526. .m = 6,
  8527. .n_iter = 100,
  8528. .max_linesearch = 20,
  8529. .eps = 1e-5f,
  8530. .ftol = 1e-4f,
  8531. .wolfe = 0.9f,
  8532. .min_step = 1e-20f,
  8533. .max_step = 1e+20f,
  8534. .linesearch = GGML_LINESEARCH_DEFAULT,
  8535. },
  8536. };
  8537. } break;
  8538. }
  8539. return result;
  8540. }
  8541. enum ggml_opt_result ggml_opt(
  8542. struct ggml_context * ctx,
  8543. struct ggml_opt_params params,
  8544. struct ggml_tensor * f) {
  8545. bool free_ctx = false;
  8546. if (ctx == NULL) {
  8547. struct ggml_init_params params_ctx = {
  8548. .mem_size = 16*1024*1024,
  8549. .mem_buffer = NULL,
  8550. };
  8551. ctx = ggml_init(params_ctx);
  8552. if (ctx == NULL) {
  8553. return GGML_OPT_NO_CONTEXT;
  8554. }
  8555. free_ctx = true;
  8556. }
  8557. enum ggml_opt_result result = GGML_OPT_OK;
  8558. // build forward + backward compute graphs
  8559. struct ggml_cgraph gf = ggml_build_forward (f);
  8560. struct ggml_cgraph gb = ggml_build_backward(ctx, &gf, false);
  8561. switch (params.type) {
  8562. case GGML_OPT_ADAM:
  8563. {
  8564. result = ggml_opt_adam(ctx, params, f, &gf, &gb);
  8565. } break;
  8566. case GGML_OPT_LBFGS:
  8567. {
  8568. result = ggml_opt_lbfgs(ctx, params, f, &gf, &gb);
  8569. } break;
  8570. }
  8571. if (params.print_forward_graph) {
  8572. ggml_graph_print (&gf);
  8573. ggml_graph_dump_dot(&gf, NULL, "opt-forward.dot");
  8574. }
  8575. if (params.print_backward_graph) {
  8576. ggml_graph_print (&gb);
  8577. ggml_graph_dump_dot(&gb, &gf, "opt-backward.dot");
  8578. }
  8579. if (free_ctx) {
  8580. ggml_free(ctx);
  8581. }
  8582. return result;
  8583. }
  8584. ////////////////////////////////////////////////////////////////////////////////
  8585. int ggml_cpu_has_avx(void) {
  8586. #if defined(__AVX__)
  8587. return 1;
  8588. #else
  8589. return 0;
  8590. #endif
  8591. }
  8592. int ggml_cpu_has_avx2(void) {
  8593. #if defined(__AVX2__)
  8594. return 1;
  8595. #else
  8596. return 0;
  8597. #endif
  8598. }
  8599. int ggml_cpu_has_avx512(void) {
  8600. #if defined(__AVX512F__)
  8601. return 1;
  8602. #else
  8603. return 0;
  8604. #endif
  8605. }
  8606. int ggml_cpu_has_fma(void) {
  8607. #if defined(__FMA__)
  8608. return 1;
  8609. #else
  8610. return 0;
  8611. #endif
  8612. }
  8613. int ggml_cpu_has_neon(void) {
  8614. #if defined(__ARM_NEON)
  8615. return 1;
  8616. #else
  8617. return 0;
  8618. #endif
  8619. }
  8620. int ggml_cpu_has_arm_fma(void) {
  8621. #if defined(__ARM_FEATURE_FMA)
  8622. return 1;
  8623. #else
  8624. return 0;
  8625. #endif
  8626. }
  8627. int ggml_cpu_has_f16c(void) {
  8628. #if defined(__F16C__)
  8629. return 1;
  8630. #else
  8631. return 0;
  8632. #endif
  8633. }
  8634. int ggml_cpu_has_fp16_va(void) {
  8635. #if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
  8636. return 1;
  8637. #else
  8638. return 0;
  8639. #endif
  8640. }
  8641. int ggml_cpu_has_wasm_simd(void) {
  8642. #if defined(__wasm_simd128__)
  8643. return 1;
  8644. #else
  8645. return 0;
  8646. #endif
  8647. }
  8648. int ggml_cpu_has_blas(void) {
  8649. #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
  8650. return 1;
  8651. #else
  8652. return 0;
  8653. #endif
  8654. }
  8655. int ggml_cpu_has_sse3(void) {
  8656. #if defined(__SSE3__)
  8657. return 1;
  8658. #else
  8659. return 0;
  8660. #endif
  8661. }
  8662. int ggml_cpu_has_vsx(void) {
  8663. #if defined(__POWER9_VECTOR__)
  8664. return 1;
  8665. #else
  8666. return 0;
  8667. #endif
  8668. }
  8669. ////////////////////////////////////////////////////////////////////////////////