ggml.c 321 KB

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