ggml.c 309 KB

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