ggml.c 316 KB

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