ggml.c 310 KB

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