ggml.c 317 KB

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