ggml.c 316 KB

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