1
0

ggml.c 316 KB

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