human/dist/tfjs.esm.js

8527 lines
1.2 MiB
JavaScript
Raw Permalink Normal View History

2022-11-18 17:13:29 +01:00
/*
Human
homepage: <https://github.com/vladmandic/human>
author: <https://github.com/vladmandic>'
*/
var q4=Object.create;var lw=Object.defineProperty;var j4=Object.getOwnPropertyDescriptor;var X4=Object.getOwnPropertyNames;var Y4=Object.getPrototypeOf,Q4=Object.prototype.hasOwnProperty;var jt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),qe=(r,e)=>{for(var t in e)lw(r,t,{get:e[t],enumerable:!0})},Z4=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of X4(e))!Q4.call(r,n)&&n!==t&&lw(r,n,{get:()=>e[n],enumerable:!(o=j4(e,n))||o.enumerable});return r};var Kp=(r,e,t)=>(t=r!=null?q4(Y4(r)):{},Z4(e||!r||!r.__esModule?lw(t,"default",{value:r,enumerable:!0}):t,r));var _k=jt((Lme,Tk)=>{Tk.exports=Tt;var Yo=null;try{Yo=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(r){}function Tt(r,e,t){this.low=r|0,this.high=e|0,this.unsigned=!!t}Tt.prototype.__isLong__;Object.defineProperty(Tt.prototype,"__isLong__",{value:!0});function jr(r){return(r&&r.__isLong__)===!0}Tt.isLong=jr;var yk={},bk={};function zu(r,e){var t,o,n;return e?(r>>>=0,(n=0<=r&&r<256)&&(o=bk[r],o)?o:(t=_t(r,(r|0)<0?-1:0,!0),n&&(bk[r]=t),t)):(r|=0,(n=-128<=r&&r<128)&&(o=yk[r],o)?o:(t=_t(r,r<0?-1:0,!1),n&&(yk[r]=t),t))}Tt.fromInt=zu;function Qo(r,e){if(isNaN(r))return e?Bu:Zo;if(e){if(r<0)return Bu;if(r>=Ik)return Nk}else{if(r<=-wk)return qr;if(r+1>=wk)return kk}return r<0?Qo(-r,e).neg():_t(r%ol|0,r/ol|0,e)}Tt.fromNumber=Qo;function _t(r,e,t){return new Tt(r,e,t)}Tt.fromBits=_t;var ud=Math.pow;function Iw(r,e,t){if(r.length===0)throw Error("empty string");if(r==="NaN"||r==="Infinity"||r==="+Infinity"||r==="-Infinity")return Zo;if(typeof e=="number"?(t=e,e=!1):e=!!e,t=t||10,t<2||36<t)throw RangeError("radix");var o;if((o=r.indexOf("-"))>0)throw Error("interior hyphen");if(o===0)return Iw(r.substring(1),e,t).neg();for(var n=Qo(ud(t,8)),s=Zo,a=0;a<r.length;a+=8){var i=Math.min(8,r.length-a),p=parseInt(r.substring(a,a+i),t);if(i<8){var u=Qo(ud(t,i));s=s.mul(u).add(Qo(p))}else s=s.mul(n),s=s.add(Qo(p))}return s.unsigned=e,s}Tt.fromString=Iw;function Ws(r,e){return typeof r=="number"?Qo(r,e):typeof r=="string"?Iw(r,e):_t(r.low,r.high,typeof e=="boolean"?e:r.unsigned)}Tt.fromValue=Ws;var Ck=65536,wH=1<<24,ol=Ck*Ck,Ik=ol*ol,wk=Ik/2,Sk=zu(wH),Zo=zu(0);Tt.ZERO=Zo;var Bu=zu(0,!0);Tt.UZERO=Bu;var rl=zu(1);Tt.ONE=rl;var vk=zu(1,!0);Tt.UONE=vk;var Sw=zu(-1);Tt.NEG_ONE=Sw;var kk=_t(-1,2147483647,!1);Tt.MAX_VALUE=kk;var Nk=_t(-1,-1,!0);Tt.MAX_UNSIGNED_VALUE=Nk;var qr=_t(0,-2147483648,!1);Tt.MIN_VALUE=qr;var de=Tt.prototype;de.toInt=function(){return this.unsigned?this.low>>>0:this.low};de.toNumber=function(){return this.unsigned?(this.high>>>0)*ol+(this.low>>>0):this.high*ol+(this.low>>>0)};de.toString=function(e){if(e=e||10,e<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(qr)){var t=Qo(e),o=this.div(t),n=o.mul(t).sub(this);return o.toString(e)+n.toInt().toString(e)}else return"-"+this.neg().toString(e);for(var s=Qo(ud(e,6),this.unsigned),a=this,i="";;){var p=a.div(s),u=a.sub(p.mul(s)).toInt()>>>0,l=u.toString(e);if(a=p,a.isZero())return l+i;for(;l.length<6;)l="0"+l;i=""+l+i}};de.getHighBits=function(){return this.high};de.getHighBitsUnsigned=function(){return this.high>>>0};de.getLowBits=function(){return this.low};de.getLowBi
`),z=P=>M.writeSync(2,P+`
`));var U=u.print||B,j=u.printErr||z;Object.assign(u,d),d=null,u.arguments&&(f=u.arguments),u.thisProgram&&(h=u.thisProgram),u.quit&&(g=u.quit);var q=4,Y=Atomics.load,J=Atomics.store,re=Atomics.compareExchange,ne;u.wasmBinary&&(ne=u.wasmBinary);var ee=u.noExitRuntime||!0;typeof WebAssembly!="object"&&Ru("no native wasm support detected");var oe,ue,me=!1,be;function _e(P,V){P||Ru(V)}var ve=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Fe(P,V,pe){V>>>=0;for(var $e=V+pe,Be=V;P[Be]&&!(Be>=$e);)++Be;if(Be-V>16&&P.buffer&&ve)return ve.decode(P.buffer instanceof SharedArrayBuffer?P.slice(V,Be):P.subarray(V,Be));for(var Le="";V<Be;){var ge=P[V++];if(!(ge&128)){Le+=String.fromCharCode(ge);continue}var Ne=P[V++]&63;if((ge&224)==192){Le+=String.fromCharCode((ge&31)<<6|Ne);continue}var Ot=P[V++]&63;if((ge&240)==224?ge=(ge&15)<<12|Ne<<6|Ot:ge=(ge&7)<<18|Ne<<12|Ot<<6|P[V++]&63,ge<65536)Le+=String.fromCharCode(ge);else{var co=ge-65536;Le+=String.fromCharCode(55296|co>>10,56320|co&1023)}}return Le}function Pe(P,V){return P>>>=0,P?Fe(o(),P,V):""}function at(P,V,pe,$e){if(pe>>>=0,!($e>0))return 0;for(var Be=pe,Le=pe+$e-1,ge=0;ge<P.length;++ge){var Ne=P.charCodeAt(ge);if(Ne>=55296&&Ne<=57343){var Ot=P.charCodeAt(++ge);Ne=65536+((Ne&1023)<<10)|Ot&1023}if(Ne<=127){if(pe>=Le)break;V[pe++>>>0]=Ne}else if(Ne<=2047){if(pe+1>=Le)break;V[pe++>>>0]=192|Ne>>6,V[pe++>>>0]=128|Ne&63}else if(Ne<=65535){if(pe+2>=Le)break;V[pe++>>>0]=224|Ne>>12,V[pe++>>>0]=128|Ne>>6&63,V[pe++>>>0]=128|Ne&63}else{if(pe+3>=Le)break;V[pe++>>>0]=240|Ne>>18,V[pe++>>>0]=128|Ne>>12&63,V[pe++>>>0]=128|Ne>>6&63,V[pe++>>>0]=128|Ne&63}}return V[pe>>>0]=0,pe-Be}function ct(P,V,pe){return at(P,o(),V,pe)}var Ke,mt,ut,gt,xt,Ur,Bt,io,sr;S&&(Ke=u.buffer);function Et(P){Ke=P,u.HEAP8=mt=new Int8Array(P),u.HEAP16=gt=new Int16Array(P),u.HEAP32=Ur=new Int32Array(P),u.HEAPU8=ut=new Uint8Array(P),u.HEAPU16=xt=new Uint16Array(P),u.HEAPU32=Bt=new Uint32Array(P),u.HEAPF32=io=new Float32Array(P),u.HEAPF64=sr=new Float64Array(P)}var ar=u.INITIAL_MEMORY||16777216;if(S)oe=u.wasmMemory,Ke=u.buffer;else if(u.wasmMemory)oe=u.wasmMemory;else if(oe=new WebAssembly.Memory({initial:ar/65536,maximum:65536,shared:!0}),!(oe.buffer instanceof SharedArrayBuffer))throw j("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),w&&j("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");oe&&(Ke=oe.buffer),ar=Ke.byteLength,Et(Ke);var ir,uo=[],po=[],xr=[],ja=!1;function cn(){return ee}function ta(){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)lc(u.preRun.shift());dc(uo)}function Zt(){ja=!0,!S&&dc(po)}function Xa(){if(!S){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)Zv(u.postRun.shift());dc(xr)}}function lc(P){uo.unshift(P)}function cc(P){po.unshift(P)}function Zv(P){xr.unshift(P)}var Pi=0,Bp=null,Ya=null;function Ay(P){Pi++,u.monitorRunDependencies&&u.monitorRunDependencies(Pi)}function Rm(P){if(Pi--,u.monitorRunDependencies&&u.monitorRunDependencies(Pi),Pi==0&&(Bp!==null&&(clearInterval(Bp),Bp=null),Ya)){var V=Ya;Ya=null,V()}}function Ru(P){u.onAbort&&u.onAbort(P),P="Aborted("+P+")",j(P),me=!0,be=1,P+=". Build with -sASSERTIONS for more info.";var V=new WebAssembly.RuntimeError(P);throw c(V),V}var Fy="data:application/octet-stream;base64,";function Dm(P){return P.startsWith(Fy)}function zp(P){return P.startsWith("file://")}var yr;yr="tfjs-backend-wasm-threaded-simd.wasm",Dm(yr)||(yr=T(yr));function Am(P){try{if(P==yr&&ne)return new Uint8Array(ne);if(D)return D(P);throw"both async and sync fetching of the wasm failed"}catch(V){Ru(V)}}function Py(){if(!ne&&(x||b)){if(typeof fetch=="function"&&!zp(yr))return fetch(yr,{credentials:"same-origin"}).then(function(P){if(!P.ok)throw"failed to load wasm binary file at '"+yr+"'";return P.arrayBuffer()}).catch(function(){return Am(yr)
");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob=="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};`});var Ez=jt((ex,sv)=>{var nv=(()=>{var r=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(r=r||__filename),function(e){e=e||{};var t=typeof e!="undefined"?e:{},o,n;t.ready=new Promise(function(K,ae){o=K,n=ae});var s;typeof process!="undefined"&&process.listeners&&(s={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var a=Object.assign({},t),i=[],p="./this.program",u=(K,ae)=>{throw ae},l=typeof window=="object",c=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",d="";function f(K){return t.locateFile?t.locateFile(K,d):d+K}var h,g,x,b;function w(K){if(K instanceof Bp)return;E("exiting due to exception: "+K)}if(m){var S=ev(),k=tv();c?d=k.dirname(d)+"/":d=__dirname+"/",h=(K,ae)=>(K=ta(K)?new URL(K):k.normalize(K),S.readFileSync(K,ae?void 0:"utf8")),x=K=>{var ae=h(K,!0);return ae.buffer||(ae=new Uint8Array(ae)),ae},g=(K,ae,Ee)=>{K=ta(K)?new URL(K):k.normalize(K),S.readFile(K,function(it,$t){it?Ee(it):ae($t.buffer)})},process.argv.length>1&&(p=process.argv[1].replace(/\\/g,"/")),i=process.argv.slice(2),process.on("uncaughtException",function(K){if(!(K instanceof Bp))throw K}),process.on("unhandledRejection",function(K){throw K}),u=(K,ae)=>{if(ut())throw process.exitCode=K,ae;w(ae),process.exit(K)},t.inspect=function(){return"[Emscripten Module object]"}}else(l||c)&&(c?d=self.location.href:typeof document!="undefined"&&document.currentScript&&(d=document.currentScript.src),r&&(d=r),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="",h=K=>{var ae=new XMLHttpRequest;return ae.open("GET",K,!1),ae.send(null),ae.responseText},c&&(x=K=>{var ae=new XMLHttpRequest;return ae.open("GET",K,!1),ae.responseTy
2022-11-18 17:13:29 +01:00
`)),p.join(`
`)}function RH(r,e,t,o){let n=ze(e),s=o[o.length-1],a=new Array(s).fill(0),i=e.length,p=t==="complex64"?Nc(r):r;if(i>1)for(let u=0;u<n/s;u++){let l=u*s;for(let c=0;c<s;c++)a[c]=Math.max(a[c],kc(p[l+c],0,t).length)}return a}function kc(r,e,t){let o;return Array.isArray(r)?o=`${parseFloat(r[0].toFixed(Tw))} + ${parseFloat(r[1].toFixed(Tw))}j`:dn(r)?o=`'${r}'`:t==="bool"?o=Ok(r):o=parseFloat(r.toFixed(Tw)).toString(),Pu(o,e)}function Ok(r){return r===0?"false":"true"}function cd(r,e,t,o,n,s=!0){let a=t==="complex64"?2:1,i=e[0],p=e.length;if(p===0){if(t==="complex64"){let h=Nc(r);return[kc(h[0],0,t)]}return t==="bool"?[Ok(r[0])]:[r[0].toString()]}if(p===1){if(i>Fk){let g=vc*a,x=Array.from(r.slice(0,g)),b=Array.from(r.slice((i-vc)*a,i*a));return t==="complex64"&&(x=Nc(x),b=Nc(b)),["["+x.map((w,S)=>kc(w,n[S],t)).join(", ")+", ..., "+b.map((w,S)=>kc(w,n[i-vc+S],t)).join(", ")+"]"]}return["["+(t==="complex64"?Nc(r):Array.from(r)).map((g,x)=>kc(g,n[x],t)).join(", ")+"]"]}let u=e.slice(1),l=o.slice(1),c=o[0]*a,m=[];if(i>Fk){for(let h=0;h<vc;h++){let g=h*c,x=g+c;m.push(...cd(r.slice(g,x),u,t,l,n,!1))}m.push("...");for(let h=i-vc;h<i;h++){let g=h*c,x=g+c;m.push(...cd(r.slice(g,x),u,t,l,n,h===i-1))}}else for(let h=0;h<i;h++){let g=h*c,x=g+c;m.push(...cd(r.slice(g,x),u,t,l,n,h===i-1))}let d=p===2?",":"";m[0]="["+(i>0?m[0]+d:"");for(let h=1;h<m.length-1;h++)m[h]=" "+m[h]+d;let f=`,
2022-11-20 22:20:02 +01:00
`;for(let h=2;h<p;h++)f+=`
`;return m[m.length-1]=" "+m[m.length-1]+"]"+(s?"":f),m}function Nc(r){let e=[];for(let t=0;t<r.length;t+=2)e.push([r[t],r[t+1]]);return e}var Ge=class{constructor(e,t,o){if(this.dtype=t,this.shape=e.slice(),this.size=ze(e),o!=null){let n=o.length;$(n===this.size,()=>`Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=o||sd(t,this.size),this.strides=oa(e)}set(e,...t){t.length===0&&(t=[0]),$(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let o=this.locToIndex(t);this.values[o]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let n of e){if(n<0||n>=this.shape[t]){let s=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(s)}t++}let o=e[e.length-1];for(let n=0;n<e.length-1;++n)o+=this.strides[n]*e[n];return this.values[o]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let o=0;o<e.length-1;++o)t+=this.strides[o]*e[o];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let o=0;o<t.length-1;++o)t[o]=Math.floor(e/this.strides[o]),e-=t[o]*this.strides[o];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Gs().makeTensor(this.values,this.shape,this.dtype)}},Gs=null,al=null,DH=null;function Mk(r){Gs=r}function Lk(r){al=r}function Bk(r){DH=r}var dt=class{constructor(e,t,o,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=ze(e),this.strides=oa(e),this.dataId=o,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return al.buffer(this.shape,this.dtype,e)}bufferSync(){return al.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Fu(this.shape,e,this.dtype==="complex64")}arraySync(){return Fu(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Gs().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(o=>sl(o))}catch(o){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Gs().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Gs().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>sl(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await Gs().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Gs().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return al.print(this,e)}clone(){return this.throwIfDisposed(),al.clone(this)}toString(e=!1){let t=this.dataSync();return Pk(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),al.cast(this,e)}variable(e=!0,t,o){return this.throwIfDisposed(),Gs().makeVariable(this,e,t,o)}};Object.defineProperty(dt,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});function _w(){return wc("Tensor",()=>dt)}_w();var ci=class extends dt{constructor(e,t,o,n){super(e.shape,e.dtype,e.dataId,n),this.trainable=t,this.name=o}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Sr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Gs().disposeTensor(this),this.dataId=e.dataId,Gs().incRef(this,null)}dispose(){Gs().disposeVaria
with dtype ${s.dtype}. `)}),t.length===1)return Xr(t[0]);let o=t,n={axis:e};return _.runKernel(pa,o,n)}var bt=N({concat_:PK});function OK(r,e,t=!1,o=!1){let n=v(r,"a","matMul"),s=v(e,"b","matMul");[n,s]=Oe(n,s);let a={a:n,b:s},i={transposeA:t,transposeB:o};return _.runKernel(Nn,a,i)}var Je=N({matMul_:OK});function MK(r){let t={x:v(r,"x","sigmoid","float32")};return _.runKernel(Ao,t)}var Pa=N({sigmoid_:MK});function LK(r,e,t){let o=v(r,"x","slice","string_or_numeric");if(o.rank===0)throw new Error("Slicing scalar is not possible");let n={x:o},s={begin:e,size:t};return _.runKernel(_s,n,s)}var Ye=N({slice_:LK});function BK(r){let t={x:v(r,"x","tanh","float32")};return _.runKernel(Ls,t)}var Dc=N({tanh_:BK});function zK(r,e,t,o,n,s){let a=v(r,"forgetBias","basicLSTMCell"),i=v(e,"lstmKernel","basicLSTMCell"),p=v(t,"lstmBias","basicLSTMCell"),u=v(o,"data","basicLSTMCell"),l=v(n,"c","basicLSTMCell"),c=v(s,"h","basicLSTMCell"),m=bt([u,c],1),d=Je(m,i),f=Ce(d,p),h=f.shape[0],g=f.shape[1]/4,x=[h,g],b=Ye(f,[0,0],x),w=Ye(f,[0,g],x),S=Ye(f,[0,g*2],x),k=Ye(f,[0,g*3],x),T=Ce(se(Pa(b),Dc(w)),se(l,Pa(Ce(a,S)))),E=se(Dc(T),Pa(k));return[T,E]}var R1=N({basicLSTMCell_:zK});function VK(r,e,t){let o=v(r,"x","batchToSpaceND"),n=e.reduce((i,p)=>i*p);$(o.rank>=1+e.length,()=>`input rank is ${o.rank} but should be > than blockShape.length ${e.length}`),$(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),$(o.shape[0]%n===0,()=>`input tensor batch is ${o.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${n}`);let s={x:o},a={blockShape:e,crops:t};return _.runKernel(ia,s,a)}var vd=N({batchToSpaceND_:VK});function D1(r){let e;return r.rank===0||r.rank===1?e=W(r,[1,1,1,r.size]):r.rank===2?e=W(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?e=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]):e=r,e}function WK(r,e,t,o,n,s){s==null&&(s=.001);let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),p=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let l;o!=null&&(l=v(o,"offset","batchNorm")),$(i.rank===p.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),$(l==null||i.rank===l.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),$(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:D1(a),scale:u,offset:l,mean:i,variance:p},d={varianceEpsilon:s},f=_.runKernel(Hn,m,d);return W(f,a.shape)}var mu=N({batchNorm_:WK});function UK(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),p=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let l;return o!=null&&(l=v(o,"offset","batchNorm")),$(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),$(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),$(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${p.rank}.`),u!=null&&$(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),l!=null&&$(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${l.rank}.`),mu(a,i,p,l,u,s)}var A1=N({batchNorm2d_:UK});function GK(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),p=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let l;return o!=null&&(l=v(o,"offset","batchNorm")),$(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),$(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),$(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${p.rank}.`),u!=null&&$(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),l!=null&&$(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${l.rank}.`),mu(
${n} and ${e} for depthToSpace with input shape
${o.shape}`),$(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying
${s} and ${e} for depthToSpace with input shape
${o.shape}`),$(a%(e*e)===0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${a} for depthToSpace with input shape ${o.shape}`);let i={x:o},p={blockSize:e,dataFormat:t};return _.runKernel(Ln,i,p)}var e2=N({depthToSpace_:fq});function hq(r,e,t,o,n="NHWC",s=[1,1],a){let i=v(r,"x","depthwiseConv2d","float32"),p=v(e,"filter","depthwiseConv2d","float32"),u=i,l=!1;i.rank===3&&(l=!0,u=W(i,[1,i.shape[0],i.shape[1],i.shape[2]])),$(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),$(p.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`);let c=n==="NHWC"?u.shape[3]:u.shape[1];$(c===p.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c}) must match the inChannels dimension in filter ${p.shape[2]}.`),zt("depthwiseConv2d",o,a);let m={x:u,filter:p},d={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a},f=_.runKernel(Bn,m,d);return l?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var cl=N({depthwiseConv2d_:hq});function gq(r){let t={x:v(r,"x","diag")};return _.runKernel(ca,t)}var t2=N({diag_:gq});function xq(r,e,t,o,n=[1,1],s="NHWC"){let a=v(r,"x","dilation2d"),i=v(e,"filter","dilation2d");$(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),$(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),$(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let p=a,u=!1;a.rank===3&&(p=W(a,[1,a.shape[0],a.shape[1],a.shape[2]]),u=!0),$(p.shape[3]===i.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${p.shape[3]} vs ${i.shape[2]}`);let l={x:p,filter:i},c={strides:t,pad:o,dilations:n},m=_.runKernel(zn,l,c);return u?W(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var r2=N({dilation2d_:xq});var kr={};qe(kr,{assertAndGetBroadcastShape:()=>rt,getBroadcastDims:()=>o2,getReductionAxes:()=>Td});function o2(r,e){let t=r.length,o=[];for(let n=0;n<t;n++){let s=t-1-n,a=r[s]||1;(e[e.length-1-n]||1)>1&&a===1&&o.unshift(s)}return o}function Td(r,e){let t=[];for(let o=0;o<e.length;o++){let n=r[r.length-o-1],s=e.length-o-1,a=e[s];(n==null||n===1&&a>1)&&t.unshift(s)}return t}function rt(r,e){let t=Math.max(r.length,e.length),o=new Array(t);for(let n=0;n<t;n++){let s=r[r.length-n-1];s==null&&(s=1);let a=e[e.length-n-1];if(a==null&&(a=1),s===1)o[t-n-1]=a;else if(a===1)o[t-n-1]=s;else if(s!==a){let i=`Operands could not be broadcast together with shapes ${r} and ${e}.`;throw Error(i)}else o[t-n-1]=s}return o}function yq(r,e){let t=v(r,"a","equal","string_or_numeric"),o=v(e,"b","equal","string_or_numeric");[t,o]=Oe(t,o),rt(t.shape,o.shape);let n={a:t,b:o};return _.runKernel(xo,n)}var _d=N({equal_:yq});function bq(r,e,t){let o=v(e,"a","where"),n=v(t,"b","where"),s=v(r,"condition","where","bool"),a=rt(rt(s.shape,o.shape),n.shape),i=Oa(s,a),p=Oa(o,a),u=Oa(n,a),l={condition:i,t:p,e:u};return _.runKernel(wa,l)}var Lo=N({where_:bq});function Cq(r){let t={x:v(r,"x","zerosLike")};return _.runKernel(_a,t)}var Kt=N({zerosLike_:Cq});function wq(r,e){let t=v(r,"a","div"),o=v(e,"b","div");[t,o]=Oe(t,o);let n=Xe(t,o),s=Kt(n),a=_d(o,s);return Lo(a,s,n)}var n2=N({divNoNan_:wq});function Sq(r,e){let t=v(r,"t1","dot"),o=v(e,"t2","dot");$((t.rank===1||t.rank===2)&&(o.rank===1||o.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${t.rank} and ${o.rank}.`);let n=t.rank===1?t.size:t.shape[1],s=o.rank===1?o.size:o.shape[0];if($(n===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${n} and ${s}.`),t.rank===1&&o.rank===1){let a=W(t,[1,-1]),i=W(o,[-1,1]),p=Je(a,i);return W(p,[])}else if(t.rank===1&&o.rank===2){let a=W(t,[1,-1]),i=W(o,[o.shape[0],o.shape[1]]),p=Je(a,i);return W(p,[p.size])}else if(t.rank===2&&o.rank===1){let a=W(o,[-1,1]),i=Je(t,a);return W(i,[i.size])}else{let a=W(o,[o.shape[0],o.shape[1]]);return Je(t,a)}}var s2=N({dot_:Sq});function Iq(r,...e){let t=e.map((n,s)=>v(n,`tensors${s}`,"einsum")),o={equation:r};return _.runKernel(ji,t,o)}var fu=N({einsum_:Iq});function
rank ${s.rank}.`),$(Ja(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let a=s,i=!1;s.rank===3&&(i=!0,a=W(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let p={x:a},u={depthRadius:e,bias:t,alpha:o,beta:n},l=_.runKernel(rs,p,u);return i?W(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var g2=N({localResponseNormalization_:o6});function n6(r){let t={x:v(r,"x","log","float32")};return _.runKernel(To,t)}var yi=N({log_:n6});function s6(r){let t={x:v(r,"x","log1p")};return _.runKernel(Zn,t)}var Pd=N({log1p_:s6});function a6(r){return $(ra(r),()=>"The f passed in grad(f) must be a function"),(e,t)=>{let o=v(e,"x","tf.grad","string_or_numeric"),n=t!=null?v(t,"dy","tf.grad"):null;return _.tidy(()=>{let{value:s,grads:a}=_.gradients(()=>r(o),[o],n);return n!=null&&yt(s.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Od(a),a[0]})}}function i6(r){return $(ra(r),()=>"The f passed in grads(f) must be a function"),(e,t)=>{$(Array.isArray(e),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let o=di(e,"args","tf.grads","string_or_numeric"),n=t!=null?v(t,"dy","tf.grads"):null;return _.tidy(()=>{let{value:s,grads:a}=_.gradients(()=>r(...o),o,n);return n!=null&&yt(s.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Od(a),a})}}function u6(r){return $(ra(r),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{$(e instanceof dt,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),$(t==null||t instanceof dt,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:o,value:n}=_.gradients(()=>r(e),[e],t);return Od(o),{grad:o[0],value:n}}}function p6(r){return $(ra(r),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{$(Array.isArray(e)&&e.every(n=>n instanceof dt),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),$(t==null||t instanceof dt,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let o=_.gradients(()=>r(...e),e,t);return t!=null&&yt(o.value.shape,t.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Od(o.grads),o}}function eS(r,e){$(ra(r),()=>"The f passed in variableGrads(f) must be a function"),$(e==null||Array.isArray(e)&&e.every(u=>u instanceof ci),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let t=e!=null;if(!t){e=[];for(let u in _.registeredVariables)e.push(_.registeredVariables[u])}let o=t?e.filter(u=>!u.trainable):null,n=e.length;e=e.filter(u=>u.trainable),$(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${n} variables is trainable.`);let s=!0,{value:a,grads:i}=_.gradients(r,e,null,s);$(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),$(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);let p={};return e.forEach((u,l)=>{i[l]!=null&&(p[u.name]=i[l])}),o!=null&&o.forEach(u=>p[u.name]=null),{value:a,grads:p}}function Nr(r){return _.customGrad(r)}function Od(r){if(r.filter(t=>t==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
the f you passed encloses all operations that lead from x to y.`)}function l6(r){let t={x:v(r,"x","neg")};return _.runKernel(ls,t)}var mr=N({neg_:l6});function c6(r){let t={x:v(r,"x","softplus")};return _.runKernel(Ds,t)}var Md=N({softplus_:c6});function m6(r){let e=v(r,"x","logSigmoid");return Nr(o=>({value:mr(Md(mr(o))),gradFunc:a=>se(a,Pa(mr(o)))}))(e)}var x2=N({logSigmoid_:m6});function d6(r,e){let t=v(r,"a","sub"),o=v(e,"b","sub");[t,o]=Oe(t,o);let n={a:t,b:o};return _.runKernel(Oo,n)}var Te=N({sub_:d6});function f6(r,e=-1){let t=v(r,"logits","logSoftmax");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and axis was ${e}`);return Nr((n,s)=>{let i=La(n,e,!0),p=Te(n,i),u=Te(Ue(p,"float32"),yi(ot(Jo(p),e,!0)));return s([u]),{value:u,gradFunc:(c,m)=>{let[d]=m,f=!0,h=Jo(d);return Te(c,se(ot(c,e,f),h))}}})(t)}var y2=N({logSoftmax_:f6});function h6(r,e=null,t=!1){let o=v(r,"x","logSumExp"),n=Li(e,o.shape),s=La(o,n,!0),a=Te(o,s),i=Jo(a),p=ot(i,n),u=yi(p),l=Ce(W(s,u.shape),u);if(t){let c=gi(l.shape,n);return W(l,c)}return l}var Ld=N({logSumExp_:h6});function g6(r,e){let t=v(r,"a","logicalAnd","bool"),o=v(e,"b","logicalAnd","bool");rt(t.shape,o.shape);let n={a:t,b:o};return _.runKernel(Jn,n)}var Xu=N({logicalAnd_:g6});function x6(r){let t={x:v(r,"x","logicalNot","bool")};return _.runKernel(es,t)}var Bd=N({logicalNot_:x6});function y6(r,e){let t=v(r,"a","logicalOr","bool"),o=v(e,"b","logicalOr","bool");rt(t.shape,o.shape);let n={a:t,b:o};return _.runKernel(ts,n)}var zd=N({logicalOr_:y6});function b6(r,e){let t=v(r,"a","logicalXor","bool"),o=v(e,"b","logicalXor","bool");return rt(t.shape,o.shape),Xu(zd(r,e),Bd(Xu(r,e)))}var b2=N({logicalXor_:b6});var Vd=2147483648;function C6(r,e,t="left"){let o=v(r,"sortedSequence","searchSorted"),n=v(e,"values","searchSorted"),s=o.shape[o.shape.length-1],a=n.shape[n.shape.length-1],i=W(o,[-1,s]),p=W(n,[-1,a]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==p.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(ze(p.shape)>=Vd)throw new Error(`values tensor size must less than ${Vd}`);if(i.shape[1]>=Vd)throw new Error(`trailing dim_size must less than ${Vd} for int32 output type, was ${i.shape[1]}`);let u={sortedSequence:i,values:p},l={side:t};return _.runKernel(Ns,u,l)}var Pc=N({searchSorted_:C6});function C2(r,e){return Pc(r,e,"left")}function w6(r,e,t,o,n){let s=v(r,"x","maxPool"),a=1,i=s,p=!1;s.rank===3&&(p=!0,i=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),$(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),$(br(t,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),zt("maxPool",o,n);let u={x:i},l={filterSize:e,strides:t,pad:o,dimRoundingMode:n},c=_.runKernel(ns,u,l);return p?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Wd=N({maxPool_:w6});function S6(r,e=[1,1,1],t,o,n,s="NDHWC"){let a=v(r,"x","maxPool3d"),i=a,p=!1;a.rank===4&&(p=!0,i=W(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),$(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),$(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),zt("maxPool3d",o,n);let u={x:i},l={filterSize:e,strides:t,pad:o,dimRoundingMode:n,dataFormat:s},c=_.runKernel(ha,u,l);return p?W(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var w2=N({maxPool3d_:S6});function I6(r,e,t,o,n=!1){let a={x:v(r,"x","maxPoolWithArgmax")},i={filterSize:e,strides:t,pad:o,includeBatchInIndex:n},p=_.runKernel(ga,a,i);return{result:p[0],indexes:p[1]}}var S2=N({maxPoolWithArgmax_:I6});function v6(r,e){let t=v(r,"a","maximum"),o=v(e,"b","maximum");[t,o]=Oe(t,o),t.dtype==="bool"&&(t=Ue(t,"int32"),o=Ue(o,"int32")),rt(t.shape,o.shape);let n={a:t,b:o};return _.runKernel(_o,n)}var Ud=N({maximum_:v6});function k6(r,e=null,t=!1){let n={x:v(r,"x","mean")},s={axis:e,keepDims:t};return _.runKernel(ss,n,s)}var Yu=N({mean_:k6});function Yr(r,e="flo
2022-11-18 17:13:29 +01:00
Actual: ${n}.
Expected: ${s}.`);for(let a=0;a<s.length;++a){let i=n[a],p=s[a];if(!t(i,p))throw new Error(`Arrays differ: actual[${a}] = ${i}, expected[${a}] = ${p}.
2022-11-18 17:13:29 +01:00
Actual: ${n}.
Expected: ${s}.`)}typeof expect!="undefined"&&expect().nothing()}function sj(r,e){r().then(()=>e.fail(),()=>e()),typeof expect!="undefined"&&expect().nothing()}function aj(r,e){let t=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return dn(r)||dn(r[0])||dn(e)||dn(e[0])?uS(r,t,(o,n)=>o==n):uS(r,e,(o,n)=>pS(o,n,0))}function nN(r,e,t){if(t==null&&(t=jd()),!pS(r,e,t))throw new Error(`Numbers differ: actual === ${r}, expected === ${e}`);typeof expect!="undefined"&&expect().nothing()}function pS(r,e,t){return!isFinite(r)&&!isFinite(e)?!0:!(isNaN(r)||isNaN(e)||Math.abs(r-e)>t)}function ij(r,e,t){for(let o=0;o<r.length;o++)if(r[o]<e||r[o]>t)throw new Error(`Value out of range:${r[o]} low: ${e}, high: ${t}`)}function uj(r,e){let t=new Float32Array(r),o=new Float32Array(e);if(t.length!==o.length)throw new Error(`Expected ArrayBuffer to be of length ${o.length}, but it was ${t.length}`);for(let n=0;n<o.length;n++)if(t[n]!==o[n])throw new Error(`Expected ArrayBuffer value at ${n} to be ${o[n]} but got ${t[n]} instead`)}function sN(r){for(let e=0;e<r.length;e++){let t=r[e];Array.isArray(t)?sN(t):r[e]=iu(t)}return r}function pj(r){let e=document.createElement("video");return"playsInline"in e&&(e.playsInline=!0),e.muted=!0,e.loop=!0,e.style.position="fixed",e.style.left="0px",e.style.top="0px",e.preload="auto",e.appendChild(r),new Promise(t=>{e.addEventListener("loadeddata",o=>t(e)),e.load()})}async function lj(r){await r.play(),"requestVideoFrameCallback"in r&&await new Promise(e=>{r.requestVideoFrameCallback(e)})}var Ju=class{constructor(e,t,o,n,s){this.mean=e,this.stdDev=t,this.dtype=o,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let a=s||Math.random();this.random=Qd.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){let n=this.nextVal;return this.nextVal=NaN,n}let e,t,o=!1;for(;!o;){let n,s,a;do n=2*this.random()-1,s=2*this.random()-1,a=n*n+s*s;while(a>=1||a===0);let i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*n*i,t=this.mean+this.stdDev*s*i,(!this.truncated||this.isValidTruncated(e))&&(o=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},Xd=class{constructor(e,t,o,n){this.alpha=e,this.beta=1/t,this.dtype=o;let s=n||Math.random();this.randu=Qd.alea(s.toString()),this.randn=new Ju(0,1,o,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,o,n,s,a;for(;;){do n=this.randn.nextValue(),a=1+this.c*n;while(a<=0);if(a*=a*a,e=n*n,t=1-.331*e*e,o=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),s<t||Math.log(s)<o)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},Yd=class{constructor(e=0,t=1,o,n){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=o,n==null&&(n=Math.random()),typeof n=="number"&&(n=n.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Qd.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function cj(r,e,t=1,o="float32",n){if(St(r),t==null&&(t=1),o==null&&(o="float32"),o!=="float32"&&o!=="int32")throw new Error(`Unsupported data type ${o}`);let s=new Xd(e,t,o,n),a=ie(r,o);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var iN=N({randomGamma_:cj});function mj(r,e=0,t=1,o,n){if(St(r),o!=null&&o==="bool")throw new Error(`Unsupported data type ${o}`);let s=new Ju(e,t,o,!1,n),a=ie(r,o);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var Zd=N({randomNormal_:mj});function dj(r,e,t){if(e!=null&&e==="bool")throw new Error(`Unsupported data type ${e}`);return Zd(r,0,1,e,t)}va
${n.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(a.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${a.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let p={indices:n,values:s,denseShape:a,defaultValue:i},u=_.runKernel(eu,p);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var kT=N({sparseFillEmptyRows_:p5});function l5(r,e,t){let o=v(r,"inputIndices","sparseReshape","int32"),n=v(e,"inputShape","sparseReshape","int32"),s=v(t,"newShape","sparseReshape","int32");if(o.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
${o.shape}`);if(n.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${n.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let a={inputIndices:o,inputShape:n,newShape:s},i=_.runKernel(ui,a);return{outputIndices:i[0],outputShape:i[1]}}var NT=N({sparseReshape_:l5});function c5(r,e,t){let o=v(r,"data","sparseSegmentMean"),n=v(e,"indices","sparseSegmentMean","int32"),s=v(t,"segmentIds","sparseSegmentMean","int32");if(o.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
2022-11-18 17:13:29 +01:00
${n.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);let a={data:o,indices:n,segmentIds:s};return _.runKernel(va,a)}var TT=N({sparseSegmentMean_:c5});function m5(r,e,t){let o=v(r,"data","sparseSegmentSum"),n=v(e,"indices","sparseSegmentSum","int32"),s=v(t,"segmentIds","sparseSegmentSum","int32");if(o.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
2022-11-18 17:13:29 +01:00
${n.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);let a={data:o,indices:n,segmentIds:s};return _.runKernel(ka,a)}var _T=N({sparseSegmentSum_:m5});function d5(r,e,t,o,n,s,a,i){let p=v(r,"data","stringNGrams","string");if(p.dtype!=="string")throw new Error("Data must be of datatype string");if(p.shape.length!==1)throw new Error(`Data must be a vector, saw: ${p.shape}`);let u=v(e,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let l={separator:t,nGramWidths:o,leftPad:n,rightPad:s,padWidth:a,preserveShortSequences:i},c={data:p,dataSplits:u},m=_.runKernel(Na,c,l);return{nGrams:m[0],nGramsSplits:m[1]}}var ET=N({stringNGrams_:d5});function f5(r,e,t=!0){let o=v(r,"input","stringSplit","string"),n=v(e,"delimiter","stringSplit","string");if(o.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${o.shape}`);if(n.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${n.shape}`);let s={skipEmpty:t},a={input:o,delimiter:n},i=_.runKernel(ru,a,s);return{indices:i[0],values:i[1],shape:i[2]}}var $T=N({stringSplit_:f5});function h5(r,e){let t=v(r,"input","stringToHashBucketFast","string"),o={numBuckets:e};if(e<=0)throw new Error("Number of buckets must be at least 1");let n={input:t};return _.runKernel(ou,n,o)}var RT=N({stringToHashBucketFast_:h5});function g5(r,e,t,o=!0){let n=v(r,"input","staticRegexReplace","string"),s={pattern:e,rewrite:t,replaceGlobal:o};return _.runKernel(pi,{x:n},s)}var DT=N({staticRegexReplace_:g5});var x5={fft:fl,ifft:ep,rfft:hl,irfft:tf},y5={hammingWindow:jN,hannWindow:uf,frame:pf,stft:XN},b5={flipLeftRight:QN,grayscaleToRGB:ZN,resizeNearestNeighbor:lT,resizeBilinear:pT,rgbToGrayscale:JN,rotateWithOffset:eT,cropAndResize:YN,nonMaxSuppression:tT,nonMaxSuppressionAsync:nT,nonMaxSuppressionWithScore:sT,nonMaxSuppressionWithScoreAsync:aT,nonMaxSuppressionPadded:iT,nonMaxSuppressionPaddedAsync:uT,threshold:cT,transform:mT},C5={bandPart:dT,gramSchmidt:fT,qr:gT},w5={absoluteDifference:xT,computeWeightedLoss:dr,cosineDistance:yT,hingeLoss:bT,huberLoss:CT,logLoss:wT,meanSquaredError:ST,sigmoidCrossEntropy:IT,softmaxCrossEntropy:vT},S5={sparseFillEmptyRows:kT,sparseReshape:NT,sparseSegmentMean:TT,sparseSegmentSum:_T},I5={stringNGrams:ET,stringSplit:$T,stringToHashBucketFast:RT,staticRegexReplace:DT};var AT={};qe(AT,{Serializable:()=>Lc,SerializationMap:()=>df,getRegisteredName:()=>k5,registerClass:()=>hS});var v5=new Map,fS=new Map,Lc=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},df=class r{constructor(){this.classNameMap={}}static getMap(){return r.instance==null&&(r.instance=new r),r.instance}static register(e){r.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function hS(r,e,t){$(r.className!=null,()=>"Class being registered does not have the static className property defined."),$(typeof r.className=="string",()=>"className is required to be a string, but got type "+typeof r.className),$(r.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),typeof e=="undefined"&&(e="Custom"),typeof t=="undefined"&&(t=r.className);let o=t,n=e+">"+o;return df.register(r),v5.set(n,r),fS.set(r,n),r}function k5(r){return fS.has(r)?fS.get(r):r.className}var _r=class extends Lc{minimize(e,t=!1,o){let{value:n,grads:s}=this.computeGradients(e,o);if(o!=null){let a=o.map(i=>({name:i.name,tensor:s[i.name]}));this.applyGradients(a)}else this.applyGradients(s);return Lt(s),t?n:(n.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return eS(e,t)}dispose(){this.iterations_!=null&&Lt(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:ke(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extrac
Manifest JSON has weights with names: ${i.join(", ")}.`)}let p=n.reduce((d,f,h)=>(f&&d.push(h),d),[]),u=[];p.forEach(d=>{e[d].paths.forEach(f=>{let h=t+(t.endsWith("/")?"":"/")+f;u.push(h)})});let l=await r(u),c={},m=0;return p.forEach(d=>{let f=e[d].paths.length,h=new lr(l.slice(m,m+f));s[d].forEach(x=>{let b=h.slice(x.groupOffset,x.groupOffset+x.sizeBytes),w=hd(b,[x.manifestEntry]);for(let S in w)c[S]=w[S]}),m+=f}),c}}var D5="application/octet-stream",A5="application/json",Bc=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?($(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=A().platform.fetch,$(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&$(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let o=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n=xd(e,o);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:A5}),"model.json"),e.weightData!=null){let a=lr.join(e.weightData);t.body.append("model.weights.bin",new Blob([a],{type:D5}),"model.weights.bin")}let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:$a(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async loadModelJSON(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(s){let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let o=t.modelTopology,n=t.weightsManifest;if(o==null&&n==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();let e=await this.loadModelJSON();return il(e,t=>this.loadWeights(t))}async loadStream(){let e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),o=Ec(e.weightsManifest),n=()=>MT(t,this.loadOptions);return Object.assign(Object.assign({},e),{weightSpecs:o,getWeightStream:n})}async getWeightUrls(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[o,n]=F5(t),s=this.weightPathPrefix||o,a=[],i=[];for(let p of e)for(let u of p.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):a.push(s+u+n);return this.weightUrlConverter&&a.push(...await Promise.all(i)),a}async loadWeights(e){let t=await this.getWeightUrls(e),o=Ec(e),n=await yS(t,this.loadOptions);return[o,n]}};Bc.URL_SCHEME_REGEX=/^https?:\/\//;function F5(r){let e=r.lastIndexOf("/"),t=r.lastIndexOf("?"),o=r.substring(0,e),n=t>e?r.substring(t):"";return[o+"/",n]}function ff(r){return r.match(Bc.URL_SCHEME_REGEX)!=null}var BT=(r,e)=>{if(typeof fetch=="undefined"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(Array.isArray(r)?t=r.every(o=>ff(o)
indices.shape[0] = ${r}`}function V8(r,e){return`indices(${r}, 0) is invalid: ${e} < 0`}function W8(r,e,t){return`indices(${r}, 0) is invalid: ${e} >= ${t}`}function U8(r,e){return`only one output dimension may be -1, not both ${r} and ${e}`}function G8(r,e){return`size ${r} must be non-negative, not ${e}`}function H8(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function K8(r,e){let t=ze(r),o=ze(e);return`Input to reshape is a SparseTensor with ${t}
dense values, but the requested shape requires a multiple of ${o}. inputShape=${r} outputShape= ${e}`}function q8(r,e){let t=ze(r),o=ze(e);return`Input to reshape is a tensor with ${t} dense values, but the requested shape has ${o}. inputShape=${r} outputShape=${e}`}function j8(){return"segment ids must be >= 0"}function X8(){return"segment ids are not increasing"}function Y8(r,e){return`Segment id ${r} out of range [0, ${e}), possibly because segmentIds input is not sorted.`}function Q8(r,e,t){return`Bad: indices[${r}] == ${e} out of range [0, ${t})`}var kS={};qe(kS,{collectGatherOpShapeInfo:()=>eY,computeOutShape:()=>J8,segOpComputeOptimalWindowSize:()=>Z8});function Z8(r,e){let t=!1,o;for(r<=yf?(o=r,t=!0):o=Xp(r,Math.floor(Math.sqrt(r)));!t;)o>e||o===r?t=!0:o=Xp(r,o+1);return o}function J8(r,e,t){let o=[],n=r.length;for(let s=0;s<n;s++)s!==e?o.push(r[s]):o.push(t);return o}function eY(r,e,t,o){let n=e.shape.length,s=r.shape.length;if(o!==0&&(o<-n||o>n))throw new Error(`Expect batchDims in the range of [-${n}, ${n}], but got ${o}`);if(o<0&&(o+=n),o>s)throw new Error(`batchDims (${o}) must be less than rank(x) (
${s}).`);if(t<o)throw new Error(`batchDims (${o}) must be less than or equal to axis (${t}).`);for(let c=0;c<o;++c)if(r.shape[c]!==e.shape[c])throw new Error(`x.shape[${c}]: ${r.shape[c]} should be equal to indices.shape[${c}]: ${e.shape[c]}.`);let a=r.shape[t],i=[],p=1,u=1,l=1;for(let c=0;c<o;++c)i.push(r.shape[c]),p*=r.shape[c];for(let c=o;c<t;c++)i.push(r.shape[c]),u*=r.shape[c];for(let c=o;c<n;c++)i.push(e.shape[c]);for(let c=t+1;c<s;c++)i.push(r.shape[c]),l*=r.shape[c];return{batchSize:p,sliceSize:l,outerSize:u,dimSize:a,outputShape:i}}function tY(r){try{return r.map(e=>sl(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function rY(r){return r.map(e=>iu(e))}var Ut={};qe(Ut,{nonMaxSuppressionV3Impl:()=>lf,nonMaxSuppressionV4Impl:()=>cf,nonMaxSuppressionV5Impl:()=>mf,whereImpl:()=>sf});FT();var oY=A();oY.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,r=>{r&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});var Or;(function(r){r[r.DT_INVALID=0]="DT_INVALID",r[r.DT_FLOAT=1]="DT_FLOAT",r[r.DT_DOUBLE=2]="DT_DOUBLE",r[r.DT_INT32=3]="DT_INT32",r[r.DT_UINT8=4]="DT_UINT8",r[r.DT_INT16=5]="DT_INT16",r[r.DT_INT8=6]="DT_INT8",r[r.DT_STRING=7]="DT_STRING",r[r.DT_COMPLEX64=8]="DT_COMPLEX64",r[r.DT_INT64=9]="DT_INT64",r[r.DT_BOOL=10]="DT_BOOL",r[r.DT_QINT8=11]="DT_QINT8",r[r.DT_QUINT8=12]="DT_QUINT8",r[r.DT_QINT32=13]="DT_QINT32",r[r.DT_BFLOAT16=14]="DT_BFLOAT16",r[r.DT_QINT16=15]="DT_QINT16",r[r.DT_QUINT16=16]="DT_QUINT16",r[r.DT_UINT16=17]="DT_UINT16",r[r.DT_COMPLEX128=18]="DT_COMPLEX128",r[r.DT_HALF=19]="DT_HALF",r[r.DT_RESOURCE=20]="DT_RESOURCE",r[r.DT_VARIANT=21]="DT_VARIANT",r[r.DT_UINT32=22]="DT_UINT32",r[r.DT_UINT64=23]="DT_UINT64",r[r.DT_FLOAT_REF=101]="DT_FLOAT_REF",r[r.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",r[r.DT_INT32_REF=103]="DT_INT32_REF",r[r.DT_UINT8_REF=104]="DT_UINT8_REF",r[r.DT_INT16_REF=105]="DT_INT16_REF",r[r.DT_INT8_REF=106]="DT_INT8_REF",r[r.DT_STRING_REF=107]="DT_STRING_REF",r[r.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",r[r.DT_INT64_REF=109]="DT_INT64_REF",r[r.DT_BOOL_REF=110]="DT_BOOL_REF",r[r.DT_QINT8_REF=111]="DT_QINT8_REF",r[r.DT_QUINT8_REF=112]="DT_QUINT8_REF",r[r.DT_QINT32_REF=113]="DT_QINT32_REF",r[r.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",r[r.DT_QINT16_REF=115]="DT_QINT16_REF",r[r.DT_QUINT16_REF=116]="DT_QUINT16_REF",r[r.DT_UINT16_REF=117]="DT_UINT16_REF",r[r.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",r[r.DT_HALF_REF=119]="DT_HALF_REF",r[r.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",r[r.DT_VARIANT_REF=121]="DT_VARIANT_REF",r[r.DT_UINT32_REF=122]="DT_UINT32_REF",r[r.DT_UINT64_REF=123]="DT_UINT64_REF"})(Or||(Or={}));var u_;(function(r){let e;(function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"})(e=r.CheckpointFormatVersion||(r.CheckpointFormatVersion={}))})(u_||(u_={}));var TS={};function sY(r,e){let t={tfOpName:r,category:"custom",inputs:[],attrs:[],customExecutor:e};TS[r]=t}function bf(r){return TS[r]}function aY(r){delete TS[r]}function I(r,e,t,o,n){let s=e.inputParams[r];if(s&&s.inputIndexStart!==void 0){let i=s.inputIndexStart,p=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?i+1:s.inputIndexEnd,u=i<0?e.inputNames.length+i:i;if(s.type==="tensor")return Vt(e.inputNames[u],t,o,n);if(s.type==="tensors"){let m=e.inputs.slice(i,p);return e.inputNames.slice(i,p).filter((f,h)=>{var g;return((g=m[h])===null||g===void 0?void 0:g.op)!=="NoOp"}).map(f=>Vt(f,t,o,n))}let l=Vt(e.inputNames[u],t,o,n),c=l.dataSync();return s.type==="number"?c[0]:y.toNestedArray(l.shape,c)}let a=e.attrParams[r];return a&&a.value}function Vt(r,e,t,o){let[n,s]=Er(r,t);if(o!=null){let i=o.getHashTableHandleByName(n);if(i!=null)return i}let a=t.currentContextIds.find(i=>!!e[Cf(n,i)]);return a!==void 0?e[Cf(n,a)][s]:void 0}function _S(r,e,t){return e[Cf(r,t.currentContextId)]}function qs(r,e){let[t,o,n]=Er(r,e);return[Cf(t,e&&e.currentContextId),o,n]}function Cf(r,e){return
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Qr(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),o.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(o.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);o.tensor=t,Fr(t),o.written=!0,this.tensors[e]=o}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((o,n)=>this.write(o,t[n]))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let n=0;n<this.size();n++)e.push(n)}if(e.length===0)return pr([],[0].concat(this.elementShape));let o=this.readMany(e);return Qr(this.elementShape,o[0].shape,"TensorArray shape mismatch: "),Tr(o,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return pr([],[0].concat(this.elementShape));let t=[];for(let n=0;n<this.size();n++)t.push(n);let o=this.readMany(t);return Qr(this.elementShape,o[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${o[0].shape})`),bt(o,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let o=Math.max(...e);if(!this.dynamicSize&&o>=this.maxSize)throw new Error(`Max index must be < array size (${o} vs. ${this.maxSize})`);this.writeMany(e,zo(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let o=0,n=e.map(p=>(o+=p,o));if(o!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
2022-11-18 17:13:29 +01:00
tensor.shape[0], but sum of lengths is
${o}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let s=o===0?0:t.size/o,a=[];De(()=>{t=W(t,[1,o,s]);for(let p=0;p<e.length;++p){let l=[0,p===0?0:n[p-1],0],c=[1,e[p],s];a[p]=W(Ye(t,l,c),this.elementShape)}return a});let i=[];for(let p=0;p<e.length;p++)i[p]=p;this.writeMany(i,a)}};var wl=class r{get id(){return this.idTensor.id}constructor(e,t,o,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=o,e!=null&&e.forEach(s=>{if(o!==s.dtype)throw new Error(`Invalid data types; op elements ${o}, but list elements ${s.dtype}`);Qr(t,s.shape,"TensorList shape mismatch: "),Fr(s)}),this.idTensor=ke(0),this.maxNumElements=n,Fr(this.idTensor)}copy(){return new r([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,o=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(o!==-1&&this.tensors.length!==o)throw new Error(`Operation expected a list with ${o} elements but got a list with ${this.tensors.length} elements.`);Qr(e,this.elementShape,"TensorList shape mismatch: ");let n=Cl(this.elementShape,this.tensors,e);return De(()=>{let s=this.tensors.map(a=>W(a,n));return Tr(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let o=Cl(this.elementShape,this.tensors,e),n=this.tensors.pop();return n.kept=!1,Qr(n.shape,e,"TensorList shape mismatch: "),W(n,o)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Qr(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Fr(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);let t=new r([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let o=0;o<Math.min(this.tensors.length,e);++o)t.tensors[o]=this.tensors[o];return t}getItem(e,t,o){if(o!==this.elementDtype)throw new Error(`Invalid data types; op elements ${o}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);Qr(this.tensors[e].shape,t,"TensorList shape mismatch: ");let n=Cl(this.elementShape,this.tensors,t);return W(this.tensors[e],n)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Qr(this.elementShape,t.shape,"TensorList shape mismatch: "),Fr(t),this.tensors[e]!=null&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,o){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Qr(this.elementShape,o,"TensorList shape mismatch: "),e=e.slice(0,this.size());let n=Cl(this.elementShape,this.tensors,o);return e.length===0?pr([],[0].concat(n)):De(()=>{let s=e.map(a=>W(this.tensors[a],n));return Tr(s,0)})}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Qr(this.elementShape,t,"TensorList shape mismatch: ");let o=C
2022-11-18 17:13:29 +01:00
tensor.shape[0], but sum of lengths is
${o}, and tensor's shape is: ${r.shape}`);let s=r.shape.slice(1),a=Df(s,t),i=o===0?0:r.size/o,p=De(()=>{let l=[];r=W(r,[1,o,i]);for(let c=0;c<e.length;++c){let d=[0,c===0?0:n[c-1],0],f=[1,e[c],i];l[c]=W(Ye(r,d,f),a)}return r.dispose(),l}),u=new wl([],t,r.dtype,e.length);for(let l=0;l<p.length;l++)u.setItem(l,p[l]);return u}var b_=async(r,e,t)=>{switch(r.op){case"If":case"StatelessIf":{let o=I("thenBranch",r,e,t),n=I("elseBranch",r,e,t),s=I("cond",r,e,t),a=I("args",r,e,t);return(await s.data())[0]?t.functionMap[o].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap):t.functionMap[n].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap)}case"While":case"StatelessWhile":{let o=I("body",r,e,t),n=I("cond",r,e,t),s=I("args",r,e,t),a=await t.functionMap[n].executeFunctionAsync(s,t.tensorArrayMap,t.tensorListMap),i=s.map(l=>l.id),p=await a[0].data();a.forEach(l=>{!l.kept&&i.indexOf(l.id)===-1&&l.dispose()});let u=s;for(;p[0];){let l=u;u=await t.functionMap[o].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);let c=u.map(d=>d.id);l.forEach(d=>{!d.kept&&i.indexOf(d.id)===-1&&c.indexOf(d.id)===-1&&d.dispose()});let m=await t.functionMap[n].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);p=await m[0].data(),m.forEach(d=>{!d.kept&&i.indexOf(d.id)===-1&&c.indexOf(d.id)===-1&&d.dispose()})}return u}case"LoopCond":{let o=I("pred",r,e,t);return[js(o)]}case"Switch":{let o=I("pred",r,e,t),n=I("data",r,e,t);return n.kept||(n=js(n)),(await o.data())[0]?[void 0,n]:[n,void 0]}case"Merge":{let o=r.inputNames.find(n=>Vt(n,e,t)!==void 0);if(o){let n=Vt(o,e,t);return[js(n)]}return}case"Enter":{let o=I("frameName",r,e,t),n=I("tensor",r,e,t);return t.enterFrame(o),[js(n)]}case"Exit":{let o=I("tensor",r,e,t);return t.exitFrame(),[js(o)]}case"NextIteration":{let o=I("tensor",r,e,t);return t.nextIteration(),[js(o)]}case"TensorArrayV3":{let o=I("size",r,e,t),n=I("dtype",r,e,t),s=I("elementShape",r,e,t),a=I("dynamicSize",r,e,t),i=I("clearAfterRead",r,e,t),p=I("identicalElementShapes",r,e,t),u=I("name",r,e,t),l=new Af(u,n,o,s,p,a,i);return t.addTensorArray(l),[l.idTensor,ke(1)]}case"TensorArrayWriteV3":{let o=I("tensorArrayId",r,e,t),n=I("index",r,e,t),s=I("tensor",r,e,t),a=t.getTensorArray(o.id);return a.write(n,s),[a.idTensor]}case"TensorArrayReadV3":{let o=I("tensorArrayId",r,e,t),n=I("index",r,e,t);return[t.getTensorArray(o.id).read(n)]}case"TensorArrayGatherV3":{let o=I("tensorArrayId",r,e,t),n=I("indices",r,e,t),s=I("dtype",r,e,t);return[t.getTensorArray(o.id).gather(n,s)]}case"TensorArrayScatterV3":{let o=I("tensorArrayId",r,e,t),n=I("indices",r,e,t),s=I("tensor",r,e,t),a=t.getTensorArray(o.id);return a.scatter(n,s),[a.idTensor]}case"TensorArrayConcatV3":{let o=I("tensorArrayId",r,e,t),n=t.getTensorArray(o.id),s=I("dtype",r,e,t);return[n.concat(s)]}case"TensorArraySplitV3":{let o=I("tensorArrayId",r,e,t),n=I("tensor",r,e,t),s=I("lengths",r,e,t),a=t.getTensorArray(o.id);return a.split(s,n),[a.idTensor]}case"TensorArraySizeV3":{let o=I("tensorArrayId",r,e,t),n=t.getTensorArray(o.id);return[ke(n.size(),"int32")]}case"TensorArrayCloseV3":{let o=I("tensorArrayId",r,e,t),n=t.getTensorArray(o.id);return n.clearAndClose(),[n.idTensor]}case"TensorListSetItem":{let o=I("tensorListId",r,e,t),n=I("index",r,e,t),s=I("tensor",r,e,t),a=t.getTensorList(o.id);return a.setItem(n,s),[a.idTensor]}case"TensorListGetItem":{let o=I("tensorListId",r,e,t),n=I("index",r,e,t),s=I("elementShape",r,e,t),a=I("elementDType",r,e,t);return[t.getTensorList(o.id).getItem(n,s,a)]}case"TensorListScatterV2":case"TensorListScatter":{let o=I("indices",r,e,t),n=I("tensor",r,e,t),s=I("elementShape",r,e,t),a=I("numElements",r,e,t),i=x_(n,o,s,a);return t.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let o=I("elementShape",r,e,t),n=I("elementDType",r,e,t),s;r.op==="TensorListReserve"?s="numElements":s="maxNumElements";let a=I(s,r,e,t),i=r.op==="TensorListReserve"?-1:a,p=g_(o,n,a,i);return t.addTensorList(p),[p.idTensor]}case"TensorListGather":{let o=I("tensorListId",r,e,t),n=I("indices",r,e,t),s=I("elementShape",r,e,t),a=I("elemen
2022-11-18 17:13:29 +01:00
============================
Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details.
============================`));let n={id:this.nextDataId()};return this.data.set(n,{values:e,dtype:o,refCount:1}),n}makeTensorInfo(e,t,o){let n;if(t==="string"&&o!=null&&o.length>0&&y.isString(o[0])){let s=o.map(a=>y.encodeString(a));n=this.write(s,e,t)}else n=this.write(o,e,t);return{dataId:n,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,o,n,s){this.data.set(e,{values:t,dtype:n,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:o}=this.data.get(e);if(t==="complex64"){let n=this.readSync(o.real.dataId),s=this.readSync(o.imag.dataId);return C.mergeRealAndImagArrays(n,s)}return y.convertBackendValuesAndArrayBuffer(this.data.get(e).values,t)}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let o=t.map(n=>y.decodeString(n));return ie(e.shape,e.dtype,o)}catch(o){throw new Error("Failed to decode encoded string bytes into utf-8")}return ie(e.shape,e.dtype,t)}makeOutput(e,t,o){return cr().makeTensorFromTensorInfo(this.makeTensorInfo(t,o,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:o}=this.data.get(e);o!=null&&(this.disposeData(o.real.dataId,!0),this.disposeData(o.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=y.now();return e(),{kernelMs:y.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Q([e],"where");let t=this.readSync(e.dataId);return a7(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Il.nextDataId=0;var Xf={};qe(Xf,{addImpl:()=>eI,bincountImpl:()=>Nl,bincountReduceImpl:()=>Of,bitwiseAndImpl:()=>tI,castImpl:()=>JS,ceilImpl:()=>rI,concatImpl:()=>mp,equalImpl:()=>oI,expImpl:()=>sI,expm1Impl:()=>iI,floorDivImpl:()=>pI,floorImpl:()=>uI,gatherNdImpl:()=>Mf,gatherV2Impl:()=>Lf,greaterEqualImpl:()=>cI,greaterImpl:()=>lI,lessEqualImpl:()=>dI,lessImpl:()=>mI,linSpaceImpl:()=>Bf,logImpl:()=>fI,maxImpl:()=>zf,maximumImpl:()=>hI,minimumImpl:()=>gI,multiplyImpl:()=>qc,negImpl:()=>xI,notEqualImpl:()=>yI,prodImpl:()=>bI,raggedGatherImpl:()=>Vf,raggedRangeImpl:()=>Wf,raggedTensorToTensorImpl:()=>Uf,rangeImpl:()=>fp,rsqrtImpl:()=>wI,scatterImpl:()=>Xs,sigmoidImpl:()=>gE,simpleAbsImpl:()=>ZS,sliceImpl:()=>hp,sparseFillEmptyRowsImpl:()=>Gf,sparseReshapeImpl:()=>Hf,sparseSegmentReductionImpl:()=>_l,sqrtImpl:()=>bE,squaredDifferenceImpl:()=>II,staticRegexReplaceImpl:()=>vI,stridedSliceImpl:()=>Kf,stringNGramsImpl:()=>gp,stringSplitImpl:()=>xp,stringToHashBucketFastImpl:()=>yp,subImpl:()=>NI,tileImpl:()=>qf,topKImpl:()=>jf,transposeImpl:()=>Tl,uniqueImpl:()=>bp});function ZS(r){let e=new Float32Array(r.length);for(let t=0;t<r.length;++t)e[t]=Math.abs(r[t]);return e}var i7=r=>{let{x:e}=r.inputs,t=r.backend;Q(e,"abs");let o=new Float32Array(y.sizeFromShape(e.shape)),n=t.data.get(e.dataId).values;return o=ZS(n),t.makeOutput(o,e.shape,e.dtype)},z_={kernelName:fn,backendName:"cpu",kernelFunc:i7};function Ve(r){return(e,t,o,n,s)=>{let a=C.assertAndGetBroadcastShape(e,t),i=a.length,p=y.computeStrides(a),u=y.sizeFromShape(a),l=y.getTypedArrayFromDType(s,u),c=e.length,m=t.length,d=y.computeStrides(e),f=y.computeStrides(t),h=C.getBroadcastDims(e,a),g=C.getBroadcastDims(t,a);if(h.length+g.length===0)for(let x=0;x<l.length;++x)l[x]=r(o[x%o.length],n[x%n.length]);else for(let x=0;x<l.length;++x){let b=y.indexToLoc(x,i,p),w=b.slice(-c);h.forEach(E=>w[E]=0);let S=y.locToIndex(w,c,d),k=b.slice(-m);g.forEach(E=>k[E]=0);let T=y.locToIndex(k,m,f);l[x]=r(o[S],n[T])}return[l,a]}}function qt(r){let{inputs:e,backend:t}=r,{real:o,imag:n}=e,s=t.data.get(o.dataId).values,a=t.data.get(n.dataId).values,i=t.makeTensorInfo(o.shape,"complex64"),p=t.data.get(i.dataId);return p.co
2022-11-18 17:13:29 +01:00
${s.shape}`);if(o.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${o.shape}`);if(n.shape.length!==1)throw new Error(`Values must be a vector, saw:
${n.shape}`);if(a.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${a.shape}`);let i=t.data.get(o.dataId).values,p=t.data.get(n.dataId).values,u=t.data.get(s.dataId).values,l=t.data.get(a.dataId).values[0],[c,m,d,f,h]=Gf(i,o.shape,o.dtype,p,n.dtype,u,l);return[t.makeTensorInfo(m,o.dtype,c),t.makeTensorInfo([m[0]],n.dtype,d),t.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),t.makeTensorInfo([h.length],o.dtype,new Int32Array(h))]}var zR={kernelName:eu,backendName:"cpu",kernelFunc:jZ};function XZ(r){let{inputs:e,backend:t}=r,{inputIndices:o,inputShape:n,newShape:s}=e;if(o.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
2022-11-18 17:13:29 +01:00
${o.shape}`);if(n.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
${n.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let a=Array.from(t.data.get(n.dataId).values),i=t.data.get(o.dataId).values,p=Array.from(t.data.get(s.dataId).values),[u,l,c]=Hf(i,o.shape,o.dtype,a,p);return[t.makeTensorInfo(l,o.dtype,u),t.makeTensorInfo([c.length],s.dtype,new Int32Array(c))]}var VR={kernelName:ui,backendName:"cpu",kernelFunc:XZ};function YZ(r){let{inputs:e,backend:t}=r,{data:o,indices:n,segmentIds:s}=e;if(o.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2022-11-18 17:13:29 +01:00
${n.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);if(n.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let a=t.data.get(o.dataId).values,i=t.data.get(n.dataId).values,p=t.data.get(s.dataId).values,[u,l]=_l(a,o.shape,o.dtype,i,p,!0);return t.makeTensorInfo(l,o.dtype,u)}var WR={kernelName:va,backendName:"cpu",kernelFunc:YZ};function QZ(r){let{inputs:e,backend:t}=r,{data:o,indices:n,segmentIds:s}=e;if(o.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2022-11-18 17:13:29 +01:00
${n.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);if(n.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let a=t.data.get(o.dataId).values,i=t.data.get(n.dataId).values,p=t.data.get(s.dataId).values,[u,l]=_l(a,o.shape,o.dtype,i,p);return t.makeTensorInfo(l,o.dtype,u)}var UR={kernelName:ka,backendName:"cpu",kernelFunc:QZ};function ZZ(r){let{inputs:e,backend:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=e,{outputShape:i}=o,{sliceRank:p,numUpdates:u,sliceSize:l,strides:c,outputSize:m}=C.calculateShapes(s,n,i),d=!1,f=t.bufferSync(n),h;switch(s.dtype){case"bool":{let g=t.bufferSync(s),x=!!t.data.get(a.dataId).values[0];h=Xs(f,g,i,m,l,u,p,c,x,d);break}case"float32":{let g=t.bufferSync(s),x=t.data.get(a.dataId).values[0];h=Xs(f,g,i,m,l,u,p,c,x,d);break}case"int32":{let g=t.bufferSync(s),x=t.data.get(a.dataId).values[0];h=Xs(f,g,i,m,l,u,p,c,x,d);break}case"string":{let g=t.bufferSync(s),x=y.decodeString(t.data.get(a.dataId).values[0]);h=Xs(f,g,i,m,l,u,p,c,x,d);break}default:throw new Error(`Unsupported type ${s.dtype}`)}return t.makeTensorInfo(i,h.dtype,h.values)}var GR={kernelName:Ps,backendName:"cpu",kernelFunc:ZZ};function JZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=o,i=y.parseAxisParam(a,n.shape)[0],p=C.prepareSplitSize(n,s,i),u=new Array(n.shape.length).fill(0),l=n.shape.slice();return p.map(c=>{let m=[...l];m[i]=c;let d=nn({inputs:{x:n},backend:t,attrs:{begin:u,size:m}});return u[i]+=c,d})}var HR={kernelName:Ia,backendName:"cpu",kernelFunc:JZ};var KR={kernelName:tu,backendName:"cpu",kernelFunc:({inputs:r,backend:e})=>{let{x:t}=r,o=e;Q(t,"square");let n=o.data.get(t.dataId).values,s=new Float32Array(n.length);for(let i=0;i<n.length;++i){let p=n[i];s[i]=p*p}return{dataId:o.write(s,t.shape,t.dtype),shape:t.shape,dtype:t.dtype}}};var e9=Ie(Ko,(r,e)=>{let t=e;return isNaN(r)?NaN:r>0?1:t.alpha}),qR={kernelName:Ko,backendName:"cpu",kernelFunc:e9};function t9(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,end:a,strides:i,beginMask:p,endMask:u,ellipsisMask:l,newAxisMask:c,shrinkAxisMask:m}=o;Q(n,"stridedSlice");let{finalShapeSparse:d,finalShape:f,isIdentity:h,sliceDim0:g,isSimpleSlice:x,begin:b,end:w,strides:S}=nt.sliceInfo(n.shape,s,a,i,p,u,l,c,m),k;if(h)k=We({inputs:{x:n},backend:t,attrs:{shape:f}});else if(g||x){y.assert(n.shape.length>=1,()=>`Input must have rank at least 1, got: ${n.shape.length}`);let T=nt.computeOutShape(b,w,S),E=nn({inputs:{x:n},backend:t,attrs:{begin:b,size:T}});k=We({inputs:{x:E},backend:t,attrs:{shape:f}}),t.disposeIntermediateTensorInfo(E)}else{let T=t.bufferSync(n),E=Kf(d,T,S,b);k=t.makeTensorInfo(f,E.dtype,E.values)}return k}var jR={kernelName:Os,backendName:"cpu",kernelFunc:t9};function r9(r){let{inputs:e,backend:t,attrs:o}=r,{separator:n,nGramWidths:s,leftPad:a,rightPad:i,padWidth:p,preserveShortSequences:u}=o,{data:l,dataSplits:c}=e,m=t.data.get(l.dataId).values,d=t.data.get(c.dataId).values,[f,h]=gp(m,d,n,s,a,i,p,u);return[t.makeTensorInfo([f.length],"string",f),t.makeTensorInfo(c.shape,"int32",h)]}var XR={kernelName:Na,backendName:"cpu",kernelFunc:r9};function o9(r){let{inputs:e,backend:t,attrs:o}=r,{skipEmpty:n}=o,{input:s,delimiter:a}=e;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(a.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${a.shape}`);let i=t.data.get(s.dataId).values,p=t.data.get(a.dataId).values[0],[u,l,c]=xp(i,p,n),m=l.length;return[t.makeTensorInfo([m,2],"int32",u),t.makeTensorInfo([m],"string",l),t.makeTensorInfo([2],"int32",new Int32Array(c))]}var YR={kernelName:ru,backendName:"cpu",kernelFunc:o9};function n9(r){let{inputs:e,backend:t,attrs:o}=r,{numBuckets:n}=o,{input:s}=e;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(n<=0)throw new Error("Number of buckets must be at least 1");let a=t.data.get(s.dataId).values,i=yp(a,n);return t.makeTensorInfo(s.shape,"int32",i)}var QR={kernelName:ou,backendName:"cpu",kernelFunc:n9};var s9=Ie(Ms,r=>Math.tan(r)),
`),s=n.length.toString().length+2,a=n.map((c,m)=>y.rightPad((m+1).toString(),s)+c),i=0;for(let c=0;c<a.length;c++)i=Math.max(a[c].length,i);let p=a.slice(0,o-1),u=a.slice(o-1,o),l=a.slice(o);console.log(p.join(`
`)),console.log(e.split(`
`)[0]),console.log(`%c ${y.rightPad(u[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(l.join(`
`))}function HI(r){return vi(r,()=>r.createProgram(),"Unable to create WebGLProgram.")}function KI(r,e){if(ce(r,()=>r.linkProgram(e)),!A().get("ENGINE_COMPILE_ONLY")&&r.getProgramParameter(e,r.LINK_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function om(r,e){if(ce(r,()=>r.validateProgram(e)),r.getProgramParameter(e,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function qI(r,e){let t=vi(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return ce(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),ce(r,()=>r.bufferData(r.ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function jI(r,e){let t=vi(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return ce(r,()=>r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t)),ce(r,()=>r.bufferData(r.ELEMENT_ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function T9(){return A().getNumber("WEBGL_VERSION")===2?1:4}function XI(r){return vi(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function YI(r,e){let t=A().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(r<=0||e<=0){let o=`[${r}x${e}]`;throw new Error("Requested texture size "+o+" is invalid.")}if(r>t||e>t){let o=`[${r}x${e}]`,n=`[${t}x${t}]`;throw new Error("Requested texture size "+o+" greater than WebGL maximum on this browser / GPU "+n+".")}}function QI(r){return vi(r,()=>r.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function sh(r,e,t,o,n,s,a){let i=r.getAttribLocation(e,t);return i===-1?!1:(ce(r,()=>r.bindBuffer(r.ARRAY_BUFFER,o)),ce(r,()=>r.vertexAttribPointer(i,n,r.FLOAT,!1,s,a)),ce(r,()=>r.enableVertexAttribArray(i)),!0)}function cD(r,e,t){dD(r,t),ce(r,()=>r.activeTexture(r.TEXTURE0+t)),ce(r,()=>r.bindTexture(r.TEXTURE_2D,e))}function _9(r,e){dD(r,e),ce(r,()=>r.activeTexture(r.TEXTURE0+e)),ce(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function ZI(r,e,t){return vi(r,()=>r.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function JI(r,e,t){return r.getUniformLocation(e,t)}function e0(r,e,t,o){ce(r,()=>cD(r,e,o)),ce(r,()=>r.uniform1i(t,o))}function E9(r){ce(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,null)),ce(r,()=>r.viewport(0,0,r.canvas.width,r.canvas.height)),ce(r,()=>r.scissor(0,0,r.canvas.width,r.canvas.height))}function nm(r,e,t){ce(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,t)),ce(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0))}function ah(r,e){ce(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,e)),ce(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0))}function Dl(r){let e=r.checkFramebufferStatus(r.FRAMEBUFFER);if(e!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+mD(r,e))}function mD(r,e){switch(e){case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${e}`}}function vi(r,e,t){let o=ce(r,()=>e());if(o==null)throw new Error(t);return o}function dD(r,e){let t=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,o=e+r.TEXTURE0;if(o<r.TEXTURE0||o>t){let n=`[gl.TEXTURE0, gl.TEXTURE${t}]`;throw new Error(`textureUnit must be in ${n}.`)}}function ki(r,e=2){return y.sizeFromShape(r.slice(0,r.length-e))}function Ni(r){if(r.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[r.length>1?r[r.length-2]:1,r[r.length-1]]}function Al(r){let e=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(e=[ki(r),...Ni(r)]),e}function t0(r,e=!1){let t=A().getNumber("WEBGL_MAX_TEXTURE_SIZE"),o=A().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");o===1/0&&A().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(o=t/2),e&&(t=t*2,o=o*2,r=r.map((i,p)=>p>=r.length-2?y.nearestLargerEven(r[p]):r[p]),r.length===1&&(r=[2,r[0]])),r.length!==2&&(r=y.squeezeShape(r).newShape);let n=y.sizeFromShape(r),s=null;r.length<=1&&n<=t?s=[1,n]:r.length===2&&r[0]<=t&&r[1]
2022-11-18 17:13:29 +01:00
bool isnan_custom(float val) {
uint floatToUint = floatBitsToUint(val);
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
`:"",p="",u=`
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`):(r="",e="attribute",t="varying",o="varying",n="texture2D",s="gl_FragColor",a="",i=`
2022-11-18 17:13:29 +01:00
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`,p=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,u=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`),{version:r,attribute:e,varyingVs:t,varyingFs:o,texture2D:n,output:s,defineOutput:a,defineSpecialNaN:i,defineSpecialInf:p,defineRound:u}}function Qs(r,e,t="index"){let o=y.computeStrides(e);return o.map((n,s)=>{let a=`int ${r[s]} = ${t} / ${n}`,i=s===o.length-1?`int ${r[s+1]} = ${t} - ${r[s]} * ${n}`:`index -= ${r[s]} * ${n}`;return`${a}; ${i};`}).join("")}function Ip(r,e,t="index"){let o=y.computeStrides(e);return o.map((n,s)=>{let a=`int ${r[s]} = ${t} / outShapeStrides[${s}]`,i=s===o.length-1?`int ${r[s+1]} = ${t} - ${r[s]} * outShapeStrides[${s}]`:`index -= ${r[s]} * outShapeStrides[${s}]`;return`${a}; ${i};`}).join("")}function A9(r,e){let t=r.length,o=r.map(s=>`${e}[${s}]`),n=new Array(t-1);n[t-2]=o[t-1];for(let s=t-3;s>=0;--s)n[s]=`(${n[s+1]} * ${o[s+1]})`;return n}function fD(r,e,t="index"){let o=r.map((s,a)=>a),n=A9(o,e);return n.map((s,a)=>{let i=`int ${r[a]} = ${t} / ${n[a]}`,p=a===n.length-1?`int ${r[a+1]} = ${t} - ${r[a]} * ${n[a]}`:`index -= ${r[a]} * ${n[a]}`;return`${i}; ${p};`}).join("")}function Pl(r){let e=y.computeStrides(r).map(t=>t.toString());return`
2022-11-18 17:13:29 +01:00
int getFlatIndex(ivec3 coords) {
return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z;
2022-11-18 17:13:29 +01:00
}
`}function Ol(){return`
2022-11-18 17:13:29 +01:00
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
`}var uh=`
2022-11-18 17:13:29 +01:00
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
`;var{getBroadcastDims:hD}=C;function gD(r,e,t){let o=[];if(r.forEach(d=>{let f=y.sizeFromShape(d.shapeInfo.logicalShape);if(d.shapeInfo.isUniform?o.push(`uniform float ${d.name}${f>1?`[${f}]`:""};`):(o.push(`uniform sampler2D ${d.name};`),o.push(`uniform int offset${d.name};`)),t.enableShapeUniforms){let{uniformShape:h}=ph(t.packedInputs,d.shapeInfo.logicalShape,d.shapeInfo.texShape);switch(h.length){case 1:o.push(`uniform int ${d.name}Shape;`);break;case 2:o.push(`uniform ivec2 ${d.name}Shape;`);break;case 3:o.push(`uniform ivec3 ${d.name}Shape;`);break;case 4:o.push(`uniform ivec4 ${d.name}Shape;`);break;default:break}o.push(`uniform ivec2 ${d.name}TexShape;`)}}),t.enableShapeUniforms){switch(e.logicalShape.length){case 1:o.push("uniform int outShape;");break;case 2:o.push("uniform ivec2 outShape;"),o.push("uniform int outShapeStrides;");break;case 3:o.push("uniform ivec3 outShape;"),o.push("uniform ivec2 outShapeStrides;");break;case 4:o.push("uniform ivec4 outShape;"),o.push("uniform ivec3 outShapeStrides;");break;default:break}o.push("uniform ivec2 outTexShape;")}t.customUniforms&&t.customUniforms.forEach(d=>{o.push(`uniform ${d.type} ${d.name}${d.arrayIndex?`[${d.arrayIndex}]`:""};`)});let n=o.join(`
`),s=r.map(d=>F9(d,e,t.packedInputs,t.enableShapeUniforms)).join(`
`),a=e.texShape,i=kt(),p=M9(i),u,l,c=z9(i);return e.isPacked?(u=P9(e.logicalShape,a,t.enableShapeUniforms),l=B9(i)):(u=O9(e.logicalShape,a,t.enableShapeUniforms),l=L9(i)),t.packedInputs&&(c+=G9),[c,p,l,n,u,s,t.userCode].join(`
`)}function Ll(r,e=!1){let t=r.shapeInfo.logicalShape;switch(t.length){case 0:return rJ(r,e);case 1:return nJ(r,e);case 2:return aJ(r,e);case 3:return uJ(r,e);case 4:return lJ(r,e);case 5:return cJ(r);case 6:return mJ(r);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function xD(r,e){switch(r.shapeInfo.logicalShape.length){case 0:return tJ(r);case 1:return oJ(r,e);case 2:return sJ(r,e);case 3:return iJ(r,e);default:return pJ(r,e)}}function F9(r,e,t=!1,o){let n="";t?n+=xD(r,o):n+=Ll(r,o);let s=r.shapeInfo.logicalShape,a=e.logicalShape;return s.length<=a.length&&(t?n+=dJ(r,e):n+=fJ(r,e)),n}function P9(r,e,t){switch(r.length){case 0:return yD();case 1:return H9(r,e,t);case 2:return J9(r,e,t);case 3:return q9(r,e,t);default:return X9(r,e,t)}}function O9(r,e,t){switch(r.length){case 0:return yD();case 1:return K9(r,e,t);case 2:return eJ(r,e,t);case 3:return j9(r,e,t);case 4:return Y9(r,e,t);case 5:return Q9(r,e);case 6:return Z9(r,e);default:throw new Error(`${r.length}-D output sampling is not yet supported`)}}function M9(r){return`
2022-11-18 17:13:29 +01:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${r.texture2D}(textureSampler, uv).r;
}
`}function L9(r){return`
2022-11-18 17:13:29 +01:00
void setOutput(float val) {
${r.output} = vec4(val, 0, 0, 0);
}
`}function B9(r){return`
2022-11-18 17:13:29 +01:00
void setOutput(vec4 val) {
${r.output} = val;
}
`}function z9(r){return`${r.version}
2022-11-18 17:13:29 +01:00
precision highp float;
precision highp int;
precision highp sampler2D;
${r.varyingFs} vec2 resultUV;
${r.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${r.defineSpecialNaN}
${r.defineSpecialInf}
${r.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
}
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
${V9}
${W9}
${U9}
`}var V9=`
2022-11-18 17:13:29 +01:00
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,W9=`
2022-11-18 17:13:29 +01:00
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,U9=`
2022-11-18 17:13:29 +01:00
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,G9=`
2022-11-18 17:13:29 +01:00
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
`;function yD(){return`
2022-11-18 17:13:29 +01:00
int getOutputCoords() {
return 0;
}
`}function H9(r,e,t){let o=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return o[0]===1?t?`
2022-11-18 17:13:29 +01:00
int getOutputCoords() {
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.x * ${o[1]}.0);
}
`:o[1]===1?t?`
2022-11-18 17:13:29 +01:00
int getOutputCoords() {
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.y * ${o[0]}.0);
}
`:t?`
2022-11-18 17:13:29 +01:00
int getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${o[0]}, ${o[1]}));
return 2 * (resTexRC.x * ${o[1]} + resTexRC.y);
}
`}function K9(r,e,t){return e[0]===1?t?`
2022-11-18 17:13:29 +01:00
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
}
`:`
int getOutputCoords() {
return int(resultUV.x * ${e[1]}.0);
2022-11-18 17:13:29 +01:00
}
`:e[1]===1?t?`
2022-11-18 17:13:29 +01:00
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
}
`:`
int getOutputCoords() {
return int(resultUV.y * ${e[0]}.0);
2022-11-18 17:13:29 +01:00
}
`:t?`
2022-11-18 17:13:29 +01:00
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
return resTexRC.x * outTexShape[1] + resTexRC.y;
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
return resTexRC.x * ${e[1]} + resTexRC.y;
2022-11-18 17:13:29 +01:00
}
`}function q9(r,e,t){if(t)return`
2022-11-18 17:13:29 +01:00
ivec3 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec3(b, r, c);
}
`;let o=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],n=Math.ceil(r[2]/2),s=n*Math.ceil(r[1]/2);return`
2022-11-18 17:13:29 +01:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${o[0]}, ${o[1]}));
int index = resTexRC.x * ${o[1]} + resTexRC.y;
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec3(b, r, c);
}
`}function j9(r,e,t){if(t)return`
2022-11-18 17:13:29 +01:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${Ip(["r","c","d"],r)}
2022-11-18 17:13:29 +01:00
return ivec3(r, c, d);
}
`;let o=Qs(["r","c","d"],r);return`
2022-11-18 17:13:29 +01:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
2022-11-18 17:13:29 +01:00
${o}
return ivec3(r, c, d);
}
`}function X9(r,e,t){if(t)return`
2022-11-18 17:13:29 +01:00
ivec4 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
int texelsInBatchN = texelsInBatch * outShape[1];
int b2 = index / texelsInBatchN;
index -= b2 * texelsInBatchN;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec4(b2, b, r, c);
}
`;let o=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],n=Math.ceil(r[r.length-1]/2),s=n*Math.ceil(r[r.length-2]/2),a=s,i="",p="b, r, c";for(let u=2;u<r.length-1;u++)a*=r[r.length-u-1],i=`
2022-11-18 17:13:29 +01:00
int b${u} = index / ${a};
index -= b${u} * ${a};
`+i,p=`b${u}, `+p;return`
ivec${r.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${o[0]}, ${o[1]}));
int index = resTexRC.x * ${o[1]} + resTexRC.y;
${i}
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec${r.length}(${p});
}
`}function Y9(r,e,t){if(t)return`
2022-11-18 17:13:29 +01:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${Ip(["r","c","d","d2"],r)}
2022-11-18 17:13:29 +01:00
return ivec4(r, c, d, d2);
}
`;let o=Qs(["r","c","d","d2"],r);return`
2022-11-18 17:13:29 +01:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
2022-11-18 17:13:29 +01:00
${o}
return ivec4(r, c, d, d2);
}
`}function Q9(r,e){let t=Qs(["r","c","d","d2","d3"],r);return`
2022-11-18 17:13:29 +01:00
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${e[0]},
${e[1]}));
2022-11-18 17:13:29 +01:00
int index = resTexRC.x * ${e[1]} + resTexRC.y;
2022-11-18 17:13:29 +01:00
${t}
2022-11-18 17:13:29 +01:00
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`}function Z9(r,e){let t=Qs(["r","c","d","d2","d3","d4"],r);return`
2022-11-18 17:13:29 +01:00
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
2022-11-18 17:13:29 +01:00
${t}
2022-11-18 17:13:29 +01:00
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function J9(r,e,t){let o=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(y.arraysEqual(r,e))return t?`
2022-11-18 17:13:29 +01:00
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
}
`:`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${o[0]}, ${o[1]}));
}
`;let n=Math.ceil(r[1]/2);return t?`
2022-11-18 17:13:29 +01:00
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec2(r, c);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${o[0]}, ${o[1]}));
int index = resTexRC.x * ${o[1]} + resTexRC.y;
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec2(r, c);
}
`}function eJ(r,e,t){return y.arraysEqual(r,e)?t?`
2022-11-18 17:13:29 +01:00
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
}
`:`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${e[0]}, ${e[1]}));
2022-11-18 17:13:29 +01:00
}
`:r[1]===1?t?`
2022-11-18 17:13:29 +01:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
2022-11-18 17:13:29 +01:00
return ivec2(index, 0);
}
`:r[0]===1?t?`
2022-11-18 17:13:29 +01:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
2022-11-18 17:13:29 +01:00
return ivec2(0, index);
}
`:t?`
2022-11-18 17:13:29 +01:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
int r = index / outShape[1];
int c = index - r * outShape[1];
return ivec2(r, c);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
2022-11-18 17:13:29 +01:00
int r = index / ${r[1]};
int c = index - r * ${r[1]};
return ivec2(r, c);
}
`}function vp(r){return`offset${r}`}function tJ(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),o=kt();return`
vec4 ${t}() {
return ${o.texture2D}(${e}, halfCR);
2022-11-18 17:13:29 +01:00
}
`}function rJ(r,e){let t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1);if(r.shapeInfo.isUniform)return`float ${o}() {return ${t};}`;let[n,s]=r.shapeInfo.texShape;if(n===1&&s===1)return`
2022-11-18 17:13:29 +01:00
float ${o}() {
return sampleTexture(${t}, halfCR);
2022-11-18 17:13:29 +01:00
}
`;let a=vp(t);if(e)return`
2022-11-18 17:13:29 +01:00
float ${o}() {
vec2 uv = uvFromFlat(${t}TexShape[0], ${t}TexShape[1], ${a});
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`;let[i,p]=r.shapeInfo.texShape;return`
float ${o}() {
vec2 uv = uvFromFlat(${i}, ${p}, ${a});
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`}function oJ(r,e){let t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape,s=kt();if(e)return`
2022-11-18 17:13:29 +01:00
vec4 ${o}(int index) {
ivec2 packedTexShape = ivec2(ceil(float(${t}TexShape[0]) / 2.0), ceil(float(${t}TexShape[1]) / 2.0));
2022-11-18 17:13:29 +01:00
vec2 uv = packedUVfrom1D(
packedTexShape[0], packedTexShape[1], index);
return ${s.texture2D}(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`;let a=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)];return`
vec4 ${o}(int index) {
vec2 uv = packedUVfrom1D(
${a[0]}, ${a[1]}, index);
return ${s.texture2D}(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`}function nJ(r,e){let t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1);if(r.shapeInfo.isUniform)return`
2022-11-18 17:13:29 +01:00
float ${o}(int index) {
${Bl(r)}
2022-11-18 17:13:29 +01:00
}
`;let n=r.shapeInfo.texShape,s=n[0],a=n[1];if(a===1&&s===1)return`
float ${o}(int index) {
return sampleTexture(${t}, halfCR);
2022-11-18 17:13:29 +01:00
}
`;let i=vp(t);return a===1?e?`
2022-11-18 17:13:29 +01:00
float ${o}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${t}TexShape[0]));
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`:`
float ${o}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${s}.0);
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`:s===1?e?`
2022-11-18 17:13:29 +01:00
float ${o}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${t}TexShape[1]), 0.5);
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`:`
float ${o}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${a}.0, 0.5);
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`:e?`
2022-11-18 17:13:29 +01:00
float ${o}(int index) {
vec2 uv = uvFromFlat(${t}TexShape[0], ${t}TexShape[1], index + ${i});
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`:`
float ${o}(int index) {
vec2 uv = uvFromFlat(${s}, ${a}, index + ${i});
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`}function sJ(r,e){let t=r.shapeInfo.logicalShape,o=r.name,n="get"+o.charAt(0).toUpperCase()+o.slice(1),s=r.shapeInfo.texShape,a=s[0],i=s[1],p=kt();if(s!=null&&y.arraysEqual(t,s))return e?`
2022-11-18 17:13:29 +01:00
vec4 ${n}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}TexShape[1], ${o}TexShape[0]);
return ${p.texture2D}(${o}, uv);
}
`:`
vec4 ${n}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${a}.0);
return ${p.texture2D}(${o}, uv);
}
`;if(e)return`
2022-11-18 17:13:29 +01:00
vec4 ${n}(int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${o}TexShape[0]) / 2.0), ceil(float(${o}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${o}Shape[1]) / 2.0));
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
return ${p.texture2D}(${o}, uv);
}
`;let u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],l=Math.ceil(t[1]/2);return`
2022-11-18 17:13:29 +01:00
vec4 ${n}(int row, int col) {
vec2 uv = packedUVfrom2D(${l}, ${u[0]}, ${u[1]}, row, col);
2022-11-18 17:13:29 +01:00
return ${p.texture2D}(${o}, uv);
}
`}function aJ(r,e){let t=r.shapeInfo.logicalShape,o=r.name,n="get"+o.charAt(0).toUpperCase()+o.slice(1),s=r.shapeInfo.texShape;if(s!=null&&y.arraysEqual(t,s)){if(e)return`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}TexShape[1], ${o}TexShape[0]);
return sampleTexture(${o}, uv);
}
2022-11-20 22:20:02 +01:00
`;let m=s[0],d=s[1];return`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col) {
2022-11-20 22:20:02 +01:00
vec2 uv = (vec2(col, row) + halfCR) / vec2(${d}.0, ${m}.0);
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`}let{newShape:a,keptDims:i}=y.squeezeShape(t),p=a;if(p.length<t.length){let m=zl(r,p),d=["row","col"];return`
${Ll(m,e)}
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col) {
return ${n}(${Vl(d,i)});
2022-11-18 17:13:29 +01:00
}
`}if(r.shapeInfo.isUniform)return`
float ${n}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
${Bl(r)}
2022-11-18 17:13:29 +01:00
}
`;let u=s[0],l=s[1],c=vp(o);return l===1?e?`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${c}), vec3(${o}Shape[1], 1, 1));
2022-11-18 17:13:29 +01:00
vec2 uv = vec2(0.5, (index + 0.5) / float(${o}TexShape[0]));
return sampleTexture(${o}, uv);
}
`:`
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${c}), vec3(${t[1]}, 1, 1));
2022-11-18 17:13:29 +01:00
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
return sampleTexture(${o}, uv);
}
`:u===1?e?`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${c}), vec3(${o}Shape[1], 1, 1));
2022-11-18 17:13:29 +01:00
vec2 uv = vec2((index + 0.5) / float(${o}TexShape[1]), 0.5);
return sampleTexture(${o}, uv);
}
`:`
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${c}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${l}.0, 0.5);
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`:e?`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${o}Shape[1] + col + ${c};
2022-11-18 17:13:29 +01:00
vec2 uv = uvFromFlat(${o}TexShape[0], ${o}TexShape[1], index);
return sampleTexture(${o}, uv);
}
`:`
float ${n}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${t[1]} + col + ${c};
vec2 uv = uvFromFlat(${u}, ${l}, index);
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`}function iJ(r,e){let t=r.shapeInfo.logicalShape,o=r.name,n="get"+o.charAt(0).toUpperCase()+o.slice(1),s=r.shapeInfo.texShape,a=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(t[0]===1){let m=t.slice(1),d=[1,2],f=zl(r,m),h=["b","row","col"];return`
${xD(f,e)}
2022-11-18 17:13:29 +01:00
vec4 ${n}(int b, int row, int col) {
return ${n}(${Vl(h,d)});
2022-11-18 17:13:29 +01:00
}
`}let i=kt();if(e)return`
2022-11-18 17:13:29 +01:00
vec4 ${n}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${o}TexShape[0]) / 2.0), ceil(float(${o}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${o}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${o}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${i.texture2D}(${o}, uv);
}
`;let p=a[0],u=a[1],l=Math.ceil(t[2]/2),c=l*Math.ceil(t[1]/2);return`
2022-11-18 17:13:29 +01:00
vec4 ${n}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${p}, ${u}, ${c}, ${l}, b, row, col);
2022-11-18 17:13:29 +01:00
return ${i.texture2D}(${o}, uv);
}
`}function uJ(r,e){let t=r.shapeInfo.logicalShape,o=r.name,n="get"+o.charAt(0).toUpperCase()+o.slice(1),s=t[1]*t[2],a=t[2],{newShape:i,keptDims:p}=y.squeezeShape(t),u=i;if(u.length<t.length){let h=zl(r,u),g=["row","col","depth"];return`
${Ll(h,e)}
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col, int depth) {
return ${n}(${Vl(g,p)});
2022-11-18 17:13:29 +01:00
}
`}if(r.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${s}, ${a}, 1)));
${Bl(r)}
2022-11-18 17:13:29 +01:00
}
`;let l=r.shapeInfo.texShape,c=l[0],m=l[1],d=r.shapeInfo.flatOffset;if(m===s&&d==null)return e?`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col, int depth) {
int stride1 = ${o}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${o}TexShape[1], ${o}TexShape[0]);
return sampleTexture(${o}, uv);
}
`:`
float ${n}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${a}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${m}.0, ${c}.0);
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`;if(m===a&&d==null)return e?`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${o}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${o}TexShape[1], ${o}TexShape[0]);
return sampleTexture(${o}, uv);
}
`:`
float ${n}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
2022-11-18 17:13:29 +01:00
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${m}.0, ${c}.0);
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`;let f=vp(o);return e?`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = ${o}Shape[1] * ${o}Shape[2];
int stride1 = ${o}Shape[2];
2022-11-20 22:20:02 +01:00
int index = row * stride0 + col * stride1 + depth + ${f};
2022-11-18 17:13:29 +01:00
vec2 uv = uvFromFlat(${o}TexShape[0], ${o}TexShape[1], index);
return sampleTexture(${o}, uv);
}
`:`
float ${n}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
2022-11-20 22:20:02 +01:00
int index = row * ${s} + col * ${a} + depth + ${f};
vec2 uv = uvFromFlat(${c}, ${m}, index);
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`}function pJ(r,e){let t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=kt();if(e)return`
2022-11-18 17:13:29 +01:00
vec4 ${o}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${t}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${t}Shape[2]) / 2.0));
2022-11-18 17:13:29 +01:00
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${t}Shape[1];
2022-11-18 17:13:29 +01:00
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${t}TexShape[0]) / 2.0), ceil(float(${t}TexShape[1]) / 2.0));
2022-11-18 17:13:29 +01:00
int texR = index / packedTexShape[1];
int texC = index - texR * packedTexShape[1];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${n.texture2D}(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`;let s=r.shapeInfo.logicalShape,a=s.length,i=r.shapeInfo.texShape,p=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],u=p[0],l=p[1],c=Math.ceil(s[a-1]/2),m=c*Math.ceil(s[a-2]/2),d="int b, int row, int col",f=`b * ${m} + (row / 2) * ${c} + (col / 2)`;for(let h=2;h<a-1;h++)d=`int b${h}, `+d,m*=s[a-h-1],f=`b${h} * ${m} + `+f;return`
2022-11-20 22:20:02 +01:00
vec4 ${o}(${d}) {
int index = ${f};
int texR = index / ${l};
int texC = index - texR * ${l};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${u});
return ${n.texture2D}(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`}function lJ(r,e){let t=r.shapeInfo.logicalShape,o=r.name,n="get"+o.charAt(0).toUpperCase()+o.slice(1),s=t[3],a=t[2]*s,i=t[1]*a,{newShape:p,keptDims:u}=y.squeezeShape(t);if(p.length<t.length){let b=zl(r,p),w=["row","col","depth","depth2"];return`
${Ll(b,e)}
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col, int depth, int depth2) {
return ${n}(${Vl(w,u)});
2022-11-18 17:13:29 +01:00
}
`}if(r.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${i}, ${a}, ${s}, 1)));
${Bl(r)}
2022-11-18 17:13:29 +01:00
}
`;let l=r.shapeInfo.flatOffset,c=r.shapeInfo.texShape,m=c[0],d=c[1],f=`int stride2 = ${o}Shape[3];`,h=`int stride1 = ${o}Shape[2] * stride2;`,g=`int stride0 = ${o}Shape[1] * stride1;`;if(d===i&&l==null)return e?`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col, int depth, int depth2) {
2022-11-20 22:20:02 +01:00
${f}
2022-11-18 17:13:29 +01:00
${h}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${o}TexShape[1], ${o}TexShape[0]);
return sampleTexture(${o}, uv);
}
`:`
float ${n}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${a}, ${s}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
2022-11-20 22:20:02 +01:00
vec2(${d}.0, ${m}.0);
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`;if(d===s&&l==null)return e?`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${o}Shape[1] * ${o}Shape[2], ${o}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${o}TexShape[1], ${o}TexShape[0]);
return sampleTexture(${o}, uv);
}
`:`
float ${n}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${t[1]*t[2]}, ${t[2]}, 1));
2022-11-18 17:13:29 +01:00
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
2022-11-20 22:20:02 +01:00
vec2(${d}.0, ${m}.0);
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`;let x=vp(o);return e?`
2022-11-18 17:13:29 +01:00
float ${n}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
2022-11-20 22:20:02 +01:00
${f}
2022-11-18 17:13:29 +01:00
${h}
${g}
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2;
2022-11-20 22:20:02 +01:00
vec2 uv = uvFromFlat(${o}TexShape[0], ${o}TexShape[1], index + ${x});
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`:`
float ${n}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${a} +
depth * ${s} + depth2;
2022-11-20 22:20:02 +01:00
vec2 uv = uvFromFlat(${m}, ${d}, index + ${x});
2022-11-18 17:13:29 +01:00
return sampleTexture(${o}, uv);
}
`}function cJ(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[4],s=e[3]*n,a=e[2]*s,i=e[1]*a,{newShape:p,keptDims:u}=y.squeezeShape(e);if(p.length<e.length){let h=zl(r,p),g=["row","col","depth","depth2","depth3"];return`
${Ll(h)}
2022-11-18 17:13:29 +01:00
float ${o}(int row, int col, int depth, int depth2, int depth3) {
return ${o}(${Vl(g,u)});
2022-11-18 17:13:29 +01:00
}
`}if(r.shapeInfo.isUniform)return`
float ${o}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${i}, ${a}, ${s}, ${n})) +
depth3;
${Bl(r)}
2022-11-18 17:13:29 +01:00
}
`;let l=r.shapeInfo.flatOffset,c=r.shapeInfo.texShape,m=c[0],d=c[1];if(d===i&&l==null)return`
2022-11-18 17:13:29 +01:00
float ${o}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${a}, ${s}, ${n}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
2022-11-20 22:20:02 +01:00
vec2(${d}.0, ${m}.0);
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`;if(d===n&&l==null)return`
2022-11-18 17:13:29 +01:00
float ${o}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${e[1]*e[2]*e[3]},
${e[2]*e[3]}, ${e[3]}, 1));
2022-11-18 17:13:29 +01:00
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
2022-11-20 22:20:02 +01:00
vec2(${d}.0, ${m}.0);
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`;let f=vp(t);return`
2022-11-18 17:13:29 +01:00
float ${o}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${a} + depth * ${s} +
2022-11-20 22:20:02 +01:00
depth2 * ${n} + depth3 + ${f};
vec2 uv = uvFromFlat(${m}, ${d}, index);
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`}function mJ(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),{newShape:n,keptDims:s}=y.squeezeShape(e);if(n.length<e.length){let g=zl(r,n),x=["row","col","depth","depth2","depth3","depth4"];return`
${Ll(g)}
2022-11-18 17:13:29 +01:00
float ${o}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${o}(${Vl(x,s)});
2022-11-18 17:13:29 +01:00
}
`}let a=e[5],i=e[4]*a,p=e[3]*i,u=e[2]*p,l=e[1]*u;if(r.shapeInfo.isUniform)return`
2022-11-18 17:13:29 +01:00
float ${o}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${l}, ${u}, ${p}, ${i})) +
2022-11-18 17:13:29 +01:00
dot(
vec2(depth3, depth4),
vec2(${a}, 1)));
${Bl(r)}
2022-11-18 17:13:29 +01:00
}
`;let c=r.shapeInfo.flatOffset,m=r.shapeInfo.texShape,d=m[0],f=m[1];if(f===l&&c==null)return`
2022-11-18 17:13:29 +01:00
float ${o}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${u}, ${p}, ${i}, ${a})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
2022-11-20 22:20:02 +01:00
vec2(${f}.0, ${d}.0);
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`;if(f===a&&c==null)return`
2022-11-18 17:13:29 +01:00
float ${o}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${e[1]*e[2]*e[3]*e[4]},
${e[2]*e[3]*e[4]},
${e[3]*e[4]},
${e[4]})) + float(depth3);
2022-11-18 17:13:29 +01:00
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
2022-11-20 22:20:02 +01:00
vec2(${f}.0, ${d}.0);
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`;let h=vp(t);return`
2022-11-18 17:13:29 +01:00
float ${o}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${l} + col * ${u} + depth * ${p} +
2022-11-18 17:13:29 +01:00
depth2 * ${i} + depth3 * ${a} + depth4 + ${h};
2022-11-20 22:20:02 +01:00
vec2 uv = uvFromFlat(${d}, ${f}, index);
return sampleTexture(${t}, uv);
2022-11-18 17:13:29 +01:00
}
`}function Bl(r){let e=r.name,t=y.sizeFromShape(r.shapeInfo.logicalShape);return t<2?`return ${e};`:`
for (int i = 0; i < ${t}; i++) {
2022-11-18 17:13:29 +01:00
if (i == index) {
return ${e}[i];
2022-11-18 17:13:29 +01:00
}
}
`}function dJ(r,e){let t=r.name,o=t.charAt(0).toUpperCase()+t.slice(1),n="get"+o+"AtOutCoords",s=r.shapeInfo.logicalShape.length,a=e.logicalShape.length,i=hD(r.shapeInfo.logicalShape,e.logicalShape),p=Re(a),u=a-s,l,c=["x","y","z","w","u","v"];s===0?l="":a<2&&i.length>=1?l="coords = 0;":l=i.map(b=>`coords.${c[b+u]} = 0;`).join(`
`);let m="";a<2&&s>0?m="coords":m=r.shapeInfo.logicalShape.map((b,w)=>`coords.${c[w+u]}`).join(", ");let d="return outputValue;",h=y.sizeFromShape(r.shapeInfo.logicalShape)===1,x=y.sizeFromShape(e.logicalShape)===1;if(s===1&&!h&&!x)d=`
2022-11-18 17:13:29 +01:00
return vec4(outputValue.xy, outputValue.xy);
2022-11-20 22:20:02 +01:00
`;else if(h&&!x)a===1?d=`
2022-11-18 17:13:29 +01:00
return vec4(outputValue.x, outputValue.x, 0., 0.);
2022-11-20 22:20:02 +01:00
`:d=`
2022-11-18 17:13:29 +01:00
return vec4(outputValue.x);
`;else if(i.length){let b=s-2,w=s-1;i.indexOf(b)>-1&&i.indexOf(w)>-1?d="return vec4(outputValue.x);":i.indexOf(b)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(w)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}return`
2022-11-18 17:13:29 +01:00
vec4 ${n}() {
${p} coords = getOutputCoords();
${l}
2022-11-18 17:13:29 +01:00
vec4 outputValue = get${o}(${m});
2022-11-20 22:20:02 +01:00
${d}
2022-11-18 17:13:29 +01:00
}
`}function fJ(r,e){let t=r.name,o=t.charAt(0).toUpperCase()+t.slice(1),n="get"+o+"AtOutCoords",s=e.texShape,a=r.shapeInfo.texShape,i=r.shapeInfo.logicalShape.length,p=e.logicalShape.length;if(!r.shapeInfo.isUniform&&i===p&&r.shapeInfo.flatOffset==null&&y.arraysEqual(a,s))return`
2022-11-18 17:13:29 +01:00
float ${n}() {
return sampleTexture(${t}, resultUV);
2022-11-18 17:13:29 +01:00
}
`;let u=Re(p),l=hD(r.shapeInfo.logicalShape,e.logicalShape),c=p-i,m,d=["x","y","z","w","u","v"];i===0?m="":p<2&&l.length>=1?m="coords = 0;":m=l.map(h=>`coords.${d[h+c]} = 0;`).join(`
`);let f="";return p<2&&i>0?f="coords":f=r.shapeInfo.logicalShape.map((h,g)=>`coords.${d[g+c]}`).join(", "),`
2022-11-18 17:13:29 +01:00
float ${n}() {
${u} coords = getOutputCoords();
${m}
2022-11-20 22:20:02 +01:00
return get${o}(${f});
2022-11-18 17:13:29 +01:00
}
`}function Re(r){if(r<=1)return"int";if(r===2)return"ivec2";if(r===3)return"ivec3";if(r===4)return"ivec4";if(r===5)return"ivec5";if(r===6)return"ivec6";throw Error(`GPU for rank ${r} is not yet supported`)}function ph(r,e,t){let{newShape:o,keptDims:n}=y.squeezeShape(e),s=e.length,a=r&&s===3&&e[0]===1,i=a?e.slice(1):o,p=!r&&s>1&&!y.arraysEqual(e,t)&&o.length<s||a;return{useSqueezeShape:p,uniformShape:p?i:e,keptDims:n}}function zl(r,e){let t=JSON.parse(JSON.stringify(r));return t.shapeInfo.logicalShape=e,t}function Vl(r,e){return e.map(t=>r[t]).join(", ")}function CD(r,e,t,o){let n=t.map((l,c)=>{let m={logicalShape:l.shape,texShape:l.isUniform?null:l.texData.texShape,isUniform:l.isUniform,isPacked:l.isUniform?!1:l.texData.isPacked,flatOffset:null};return l.texData!=null&&l.texData.slice!=null&&l.texData.slice.flatOffset>0&&(m.flatOffset=l.texData.slice.flatOffset),{name:e.variableNames[c],shapeInfo:m}}),s=n.map(l=>l.shapeInfo),a={logicalShape:o.shape,texShape:o.texData.texShape,isUniform:!1,isPacked:o.texData.isPacked,flatOffset:null},i=gD(n,a,e),p=GI(r.gl,i),u=r.createProgram(p);return A().get("ENGINE_COMPILE_ONLY")?{program:e,fragmentShader:p,source:i,webGLProgram:u,inShapeInfos:s,outShapeInfo:a,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(r.buildVao(u),Object.assign({program:e,fragmentShader:p,source:i,webGLProgram:u,inShapeInfos:s,outShapeInfo:a},u0(r,e,u)))}function u0(r,e,t){let o=[],n=[],s,a,i,p=null,u=null;u=r.getUniformLocation(t,"NAN",!1),A().getNumber("WEBGL_VERSION")===1&&(p=r.getUniformLocation(t,"INFINITY",!1));let l=!1;for(let c of e.variableNames){let m={name:c,uniform:r.getUniformLocation(t,c,l),offset:r.getUniformLocation(t,`offset${c}`,l)};e.enableShapeUniforms&&(m.shape=r.getUniformLocation(t,`${c}Shape`,l),m.texShape=r.getUniformLocation(t,`${c}TexShape`,l)),o.push(m)}if(e.enableShapeUniforms&&(s=r.getUniformLocation(t,"outShape",l),i=r.getUniformLocation(t,"outShapeStrides",l),a=r.getUniformLocation(t,"outTexShape",l)),e.customUniforms)for(let c of e.customUniforms)n.push(r.getUniformLocation(t,c.name,l));return{variablesLocations:o,customUniformLocations:n,infLoc:p,nanLoc:u,outShapeLocation:s,outShapeStridesLocation:i,outTexShapeLocation:a}}function bD(r,e){if(r.length!==e.length)throw Error(`Binary was compiled with ${r.length} inputs, but was executed with ${e.length} inputs`);r.forEach((t,o)=>{let n=t.logicalShape,s=e[o],a=s.shape;if(!y.arraysEqual(n,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${n} and ${a} must match`);if(t.isUniform&&s.isUniform)return;let i=t.texShape,p=s.isUniform?null:s.texData.texShape;if(!y.arraysEqual(i,p))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${p} must match`)})}function wD(r,e,t,o,n){e.program.enableShapeUniforms||(bD(e.inShapeInfos,t),bD([e.outShapeInfo],[o]));let s=o.texData.texture,a=o.texData.texShape;o.texData.isPacked?r.setOutputPackedMatrixTexture(s.texture,a[0],a[1]):r.setOutputMatrixTexture(s.texture,a[0],a[1]),r.setProgram(e.webGLProgram),r.bindVertexArray(e.webGLProgram.vao),A().getNumber("WEBGL_VERSION")===1&&e.infLoc!==null&&r.gl.uniform1f(e.infLoc,1/0),e.nanLoc!==null&&r.gl.uniform1f(e.nanLoc,NaN);for(let p=0;p<t.length;++p){let u=t[p],{uniform:l,offset:c,shape:m,texShape:d}=e.variablesLocations[p];if(m){let{uniformShape:f}=ph(e.program.packedInputs,u.shape,u.texData.texShape);switch(f.length){case 1:r.gl.uniform1iv(m,new Int32Array(f));break;case 2:r.gl.uniform2iv(m,new Int32Array(f));break;case 3:r.gl.uniform3iv(m,new Int32Array(f));break;case 4:r.gl.uniform4iv(m,new Int32Array(f));break;default:break}}if(d&&r.gl.uniform2i(d,u.texData.texShape[0],u.texData.texShape[1]),l!=null){if(u.isUniform){if(y.sizeFromShape(u.shape)<2)r.gl.uniform1f(l,u.uniformValues[0]);else{let f=u.uniformValues;f instanceof Float32Array||(f=new Float32Array(f)),r.gl.uniform1fv(l,f)}continue}u.texData.slice!=null&&c!=null&&r.gl.uniform1i(c,u.texData.slice.flatOffset)
2022-11-18 17:13:29 +01:00
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?Ip(["r","c","d"],e):Qs(["r","c","d"],e)}
2022-11-18 17:13:29 +01:00
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
${t.output} = result;
2022-11-18 17:13:29 +01:00
}
`}};var ch=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Iu.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=kt();this.outputShape=e,this.enableShapeUniforms=lt(this.outputShape.length),this.userCode=`
2022-11-18 17:13:29 +01:00
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?Ip(["r","c","d"],e):Qs(["r","c","d"],e)}
2022-11-18 17:13:29 +01:00
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
${t.output} = result;
2022-11-18 17:13:29 +01:00
}
`}};var mh=class{constructor(e){this.variableNames=["A"],this.outTexUsage=hr.DOWNLOAD;let t=kt();this.outputShape=e,this.userCode=`
${uh}
2022-11-18 17:13:29 +01:00
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
2022-11-18 17:13:29 +01:00
}
`}};var dh=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=hr.DOWNLOAD;let t=kt();this.outputShape=e,this.userCode=`
${uh}
2022-11-18 17:13:29 +01:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
2022-11-18 17:13:29 +01:00
}
`}};var xJ={R:0,G:1,B:2,A:3},sm=class{constructor(e,t=!1,o="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=kt();this.outputShape=e,this.enableShapeUniforms=lt(this.outputShape.length);let s="result";t&&(s="floor(result * 255. + 0.5)");let a="";for(let i=0;i<o.length;i++){let p=o[i];a+=`
2022-11-18 17:13:29 +01:00
if(offset == ${i}) {
result = values[${xJ[p]}];
2022-11-18 17:13:29 +01:00
}`}this.userCode=`
${this.enableShapeUniforms?Ol():Pl(e)}
2022-11-18 17:13:29 +01:00
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
float result = 0.;
int offset = imod(flatIndex, ${o.length});
flatIndex = idiv(flatIndex, ${o.length}, 1.);
int r = flatIndex / texShape[1];
if (r < texShape[0]) {
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
vec4 values = ${n.texture2D}(A, uv);
${a}
}
${n.output} = vec4(${s}, 0., 0., 0.);
}
`}};var fh=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let o=kt();this.outputShape=e,this.enableShapeUniforms=lt(this.outputShape.length);let n="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let a=0;a<=1;a++)for(let i=0;i<=1;i++){let p=a*2+i;n+=`
2022-11-18 17:13:29 +01:00
localCoords = coords;
if(localCoords[2] + ${i} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
2022-11-18 17:13:29 +01:00
localCoords[2] += ${i};
if (localCoords[1] + ${a} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
2022-11-18 17:13:29 +01:00
localCoords[1] += ${a};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
values = ${o.texture2D}(A, uv);
if (offset == 0) {
result[${p}] = values[0];
} else if (offset == 1) {
result[${p}] = values[1];
} else if (offset == 2) {
result[${p}] = values[2];
} else {
result[${p}] = values[3];
}
}
}
`}this.userCode=`
${this.enableShapeUniforms?Ol():Pl(e)}
2022-11-18 17:13:29 +01:00
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${n}
${o.output} = ${s};
}
`}};var k0={};qe(k0,{bindVertexProgramAttributeStreams:()=>x0,createBufferFromOutputTexture:()=>C0,createFloat16MatrixTexture:()=>d0,createFloat16PackedMatrixTexture:()=>g0,createFloat32MatrixTexture:()=>m0,createIndexBuffer:()=>c0,createPackedMatrixTexture:()=>h0,createUnsignedBytesMatrixTexture:()=>f0,createVertexBuffer:()=>l0,createVertexShader:()=>p0,downloadByteEncodedFloatMatrixFromOutputTexture:()=>S0,downloadFloat32MatrixFromBuffer:()=>w0,downloadMatrixFromPackedOutputTexture:()=>v0,downloadPackedMatrixFromBuffer:()=>I0,getInternalFormatForFloat16MatrixTexture:()=>gh,getInternalFormatForFloat16PackedMatrixTexture:()=>bh,getInternalFormatForFloat32MatrixTexture:()=>hh,getInternalFormatForPackedMatrixTexture:()=>yh,getInternalFormatForUnsignedBytesMatrixTexture:()=>xh,uploadDenseMatrixToTexture:()=>y0,uploadPixelDataToTexture:()=>b0});function p0(r){let e=kt(),t=`${e.version}
2022-11-18 17:13:29 +01:00
precision highp float;
${e.attribute} vec3 clipSpacePos;
${e.attribute} vec2 uv;
${e.varyingVs} vec2 resultUV;
2022-11-18 17:13:29 +01:00
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;return UI(r,t)}function l0(r){let e=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return qI(r,e)}function c0(r){let e=new Uint16Array([0,1,2,2,1,3]);return jI(r,e)}function am(r,e,t,o,n,s){YI(e,t);let a=XI(r),i=r.TEXTURE_2D;return ce(r,()=>r.bindTexture(i,a)),ce(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)),ce(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)),ce(r,()=>r.texParameteri(i,r.TEXTURE_MIN_FILTER,r.NEAREST)),ce(r,()=>r.texParameteri(i,r.TEXTURE_MAG_FILTER,r.NEAREST)),A().getNumber("WEBGL_VERSION")===1?ce(r,()=>r.texImage2D(i,0,o,e,t,0,n,s,null)):ce(r,()=>r.texStorage2D(i,1,o,e,t)),ce(r,()=>r.bindTexture(r.TEXTURE_2D,null)),{texture:a,texShape:[t,e]}}function hh(r){return r.internalFormatFloat}function m0(r,e,t,o){let[n,s]=Sp(e,t);return am(r,n,s,hh(o),o.textureFormatFloat,r.FLOAT)}function gh(r){return r.internalFormatHalfFloat}function d0(r,e,t,o){let[n,s]=Sp(e,t);return am(r,n,s,gh(o),o.textureFormatFloat,o.textureTypeHalfFloat)}function xh(r){return r.downloadTextureFormat}function f0(r,e,t,o){let[n,s]=Sp(e,t);return am(r,n,s,xh(o),r.RGBA,r.UNSIGNED_BYTE)}function yh(r){return r.internalFormatPackedFloat}function h0(r,e,t,o){let[n,s]=Ga(e,t);return am(r,n,s,yh(o),r.RGBA,r.FLOAT)}function bh(r){return r.internalFormatPackedHalfFloat}function g0(r,e,t,o){let[n,s]=Ga(e,t);return am(r,n,s,bh(o),r.RGBA,o.textureTypeHalfFloat)}function x0(r,e,t){return ce(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),sh(r,e,"clipSpacePos",t,3,20,0)&&sh(r,e,"uv",t,2,20,12)}function y0(r,e,t,o,n,s){ce(r,()=>r.bindTexture(r.TEXTURE_2D,e));let a,i,p;n instanceof Uint8Array?(a=new Uint8Array(t*o*4),i=r.UNSIGNED_BYTE,p=r.RGBA):(a=new Float32Array(t*o*4),i=r.FLOAT,p=s.internalFormatPackedFloat),a.set(n),A().getNumber("WEBGL_VERSION")===2?ce(r,()=>r.texSubImage2D(r.TEXTURE_2D,0,0,0,t,o,r.RGBA,i,a)):ce(r,()=>r.texImage2D(r.TEXTURE_2D,0,p,t,o,0,r.RGBA,i,a)),ce(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function b0(r,e,t){ce(r,()=>r.bindTexture(r.TEXTURE_2D,e)),t.data instanceof Uint8Array?A().getNumber("WEBGL_VERSION")===2?ce(r,()=>r.texSubImage2D(r.TEXTURE_2D,0,0,0,t.width,t.height,r.RGBA,r.UNSIGNED_BYTE,t.data)):ce(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,t.width,t.height,0,r.RGBA,r.UNSIGNED_BYTE,t.data)):A().getNumber("WEBGL_VERSION")===2?ce(r,()=>r.texSubImage2D(r.TEXTURE_2D,0,0,0,r.RGBA,r.UNSIGNED_BYTE,t)):ce(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t)),ce(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function C0(r,e,t,o){let n=r.createBuffer();ce(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,n));let i=4*4*e*t;return ce(r,()=>r.bufferData(r.PIXEL_PACK_BUFFER,i,r.STREAM_READ)),ce(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,0)),ce(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,null)),n}function w0(r,e,t){let o=r,n=new Float32Array(t);return o.bindBuffer(o.PIXEL_PACK_BUFFER,e),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,n),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),n}function S0(r,e,t,o){let[n,s]=Sp(e,t),a=4,i=new Uint8Array(uD(e*t,a));return ce(r,()=>r.readPixels(0,0,n,s,o.downloadTextureFormat,r.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function I0(r,e,t,o,n,s,a,i){let p=r,u=new Float32Array(pD(s,a));return p.bindBuffer(p.PIXEL_PACK_BUFFER,e),p.getBufferSubData(p.PIXEL_PACK_BUFFER,0,u),p.bindBuffer(p.PIXEL_PACK_BUFFER,null),u}function v0(r,e,t){let o=new Float32Array(e*t*4);return ce(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,o)),o}var kp=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];let t=A().getNumber("WEBGL_VERSION");if(e!=null?(this.gl=e,BI(t,e)):this.gl=Zr(t),e=this.gl,A().getNumber("WEBGL_VERSION")===2){let s=e;this.createVertexArray=()=>ce(s,()=>s.createVertexArray()),this.bindVertexArray=a=>ce(s,()=>s.bindVertexArray(a)),this.deleteVertexArray=a=>ce(s,()=>s.deleteVertexArray(a)),this.getVertexArray=()=>ce(s,()=>s.getParameter(s.VERTEX_ARRAY_BINDING))}else if(e!=null){let s=e.getExtension("OES_vertex_array_object");if(s==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>c
2022-11-18 17:13:29 +01:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{let t=At("rc",this.rank),o=Re(this.rank),n=this.getOutOfBoundsCondition(t),s=this.getSetup(t),a=this.getOutput(t);this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${o} rc = getOutputCoords();
if(${n}) {
setOutput(vec4(0));
} else {
${s}
setOutput(vec4(${a}));
}
}
`}}getSourceCoordsArr(e){let t=[];for(let o=0;o<=1;o++)for(let n=0;n<=1;n++){let s=`${o===0?"r":"rp1"}, ${n===0?"c":"cp1"}`;for(let a=2;a<this.rank;a++)s=`${e[e.length-1-a]},`+s;t.push(s)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let o=this.rank-2;o<this.rank;o++)t+=`${e[o]} >= ${this.enableShapeUniforms?`outShape[${o}]`:this.outputShape[o]}`,o<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),o=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],n=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
int r = ${t[0]};
int c = ${t[1]};
2022-11-18 17:13:29 +01:00
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${o};
bool rEdge = rp1 >= ${n};
`}getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),
cEdge ? 0. : getA(${t[1]}),
rEdge ? 0. : getA(${t[2]}),
rEdge || cEdge ? 0. : getA(${t[3]})`}};var Wl=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=lt(this.outputShape.length);let o="";for(let n=0;n<4;n++){let s="thisRC = rc;";n%2===1&&(s+="thisRC.z += 1;"),n>1&&(s+="thisRC.y += 1;"),o+=`
2022-11-18 17:13:29 +01:00
${s}
${n>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${n}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${n>0?"}":""}
`}this.userCode=`
${bJ(t,this.enableShapeUniforms)}
${this.enableShapeUniforms?Ol():Pl(e)}
2022-11-18 17:13:29 +01:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};
int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};
2022-11-18 17:13:29 +01:00
${o}
setOutput(result);
}
`}};function bJ(r,e){return`
2022-11-18 17:13:29 +01:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${e?fD(["r","c","d"],"inputShape"):Qs(["r","c","d"],r)}
2022-11-18 17:13:29 +01:00
return ivec3(r, c, d);
}
`}var vh=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,o){let n=gA(t,o),s=xA(e,n,o);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=hA(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,o);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let p=this.freeTextures[s].pop();return this.usedTextures[s].push(p),p}let i;return n===or.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===or.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===or.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===or.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===or.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,o,n){if(this.freeTextures==null)return;let s=gA(o,n),a=xA(t,s,n);a in this.freeTextures||(this.freeTextures[a]=[]);let i=hA(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,n),p=A().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");p!==-1&&this._numBytesAllocated>p?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let u=this.usedTextures[a],l=u&&u.indexOf(e);if(l==null||l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u[l]=u[u.length-1],u.pop(),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function CJ(r,e){let t=r;if(e===t.R32F)return 4;if(e===t.R16F)return 2;if(e===t.RGBA32F)return 16;if(e===r.RGBA)return 16;if(e===t.RGBA16F)return 8;if(e===t.RGBA8)return 4;throw new Error(`Unknown internal format ${e}`)}function hA(r,e,t,o,n){let s=wJ(e,o),a;if(n){let[p,u]=Ga(r[0],r[1]);a=p*u}else{let[p,u]=Sp(r[0],r[1]);a=p*u}let i=CJ(t,s);return a*i}function wJ(r,e){switch(r){case or.PACKED_2X2_FLOAT32:return yh(e);case or.PACKED_2X2_FLOAT16:return bh(e);case or.UNPACKED_FLOAT32:return hh(e);case or.UNPACKED_FLOAT16:return gh(e);case or.PACKED_4X1_UNSIGNED_BYTE:return xh(e);default:throw new Error(`Unknown physical texture type ${r}`)}}function SJ(r){return A().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?or.PACKED_2X2_FLOAT32:or.UNPACKED_FLOAT32:r?or.PACKED_2X2_FLOAT16:or.UNPACKED_FLOAT16}function gA(r,e){if(r===hr.UPLOAD)return or.PACKED_2X2_FLOAT32;if(r===hr.RENDER||r==null)return SJ(e);if(r===hr.DOWNLOAD||r===hr.PIXELS)return or.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${r}`)}function xA(r,e,t){return`${r[0]}_${r[1]}_${e}_${t}`}var nr=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=lt(this.outputShape.length),this.userCode=`
2022-11-18 17:13:29 +01:00
float unaryOperation(float x) {
${t}
2022-11-18 17:13:29 +01:00
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`}},Gt="if (isnan(x)) return x;",yA="return x;",T0="return abs(x);";var bA="return (x >= 0.0) ? x : (exp(x) - 1.0);",CA=Gt+`
2022-11-18 17:13:29 +01:00
return (x < 0.0) ? 0.0 : x;
`,wA=Gt+`
2022-11-18 17:13:29 +01:00
return (x < 0.0) ? 0.0 : min(6.0, x);
`,Ha="return x;",SA="return 1.0 / (1.0 + exp(-1.0 * x));";var vA="return x;",kA=`
2022-11-18 17:13:29 +01:00
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`,NA=`
2022-11-18 17:13:29 +01:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,TA=`
2022-11-18 17:13:29 +01:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,_A="return 1.0 / (1.0 + exp(-1.0 * x));",Lr=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=lt(this.outputShape.length),this.userCode=`
2022-11-18 17:13:29 +01:00
vec4 unaryOperation(vec4 x) {
${t}
2022-11-18 17:13:29 +01:00
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`}};var kh=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=lt(this.outputShape.length);let t=e.length,o=At("rc",t),n=Re(t),s=fA(t,o),a=o.slice(-2),i=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${n} rc = getOutputCoords();
vec4 packedInput = getA(${s});
setOutput(getChannel(packedInput, ${i}));
}
`}};var vJ=Ut.whereImpl,kJ=1e-7,NJ=1e-4,Nh={};function TJ(r){return r in Nh||(Nh[r]={}),Nh[r]}var _J=A().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),EJ=600;function $J(){return A().global.screen==null?1024:A().global.screen.height*A().global.screen.width*window.devicePixelRatio*EJ/1024/1024}var Ul=class r extends mo{nextDataId(){return r.nextDataId++}constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!A().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof kp)t=e;else{let o=Zr(A().getNumber("WEBGL_VERSION"),e);t=new kp(o)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let o=Zr(A().getNumber("WEBGL_VERSION"));t=new kp(o),this.binaryCache=TJ(A().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new vh(this.gpgpu),this.numMBBeforeWarning=$J(),this.texData=new mn(this,cr())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,o,n,s,a){let i=this.makeTensorInfo(t,o),p=this.texData.get(i.dataId);p.isPacked=!1,p.texture={texture:e,texShape:[n,s]},p.texShape=[n,s];let u=Al(t),l=new sm(u,!1,a),c=this.runWebGLProgram(l,[i],o,[[n,s]]);return c.shape=t,p.texture=null,this.disposeIntermediateTensorInfo(i),c.dataId}write(e,t,o){if((A().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||A().getBool("DEBUG"))&&this.checkNumericalProblems(e),o==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let n={id:this.nextDataId()};return this.texData.set(n,{shape:t,dtype:o,values:e,usage:hr.UPLOAD,refCount:1}),n}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,o,n,s){if(A().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:o,dtype:n,values:t,usage:hr.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:o,dtype:n,complexTensorInfos:s,slice:a,shape:i,isPacked:p}=t;if(a!=null){let m;p?m=new Lr(i,Ha):m=new nr(i,Ha);let d=this.runWebGLProgram(m,[{dataId:e,shape:i,dtype:n}],n),f=this.readSync(d.dataId);return this.disposeIntermediateTensorInfo(d),f}if(o!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return o;let u=this.activeTimers!=null,l;u&&(l=y.now());let c;if(n==="complex64"){let m=this.readSync(s.real.dataId),d=this.readSync(s.imag.dataId);c=C.mergeRealAndImagArrays(m,d)}else c=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=y.now()-l),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){let f=this.pendingRead.get(e);return new Promise(h=>f.push(h))}let t=this.texData.get(e),{values:o,shape:n,slice:s,dtype:a,complexTensorInfos:i,isPacked:p}=t;if(s!=null){let f;p?f=new Lr(n,Ha):f=new nr(n,Ha);let h=this.runWebGLProgram(f,[{dataId:e,shape:n,dtype:a}],a),g=this.read(h.dataId);return this.disposeIntermediateTensorInfo(h),g}if(o!=null)return this.convertAndCacheOnCPU(e);if(A().getBool("DEBUG")&&!A().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&A().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,l;if(a!=="complex64"&&A().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);let f=this.texData.get(l.dataId);u=this.gpgpu.createBufferFromTexture(f.texture.texture,...tm(n))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let c;if(a==="complex64"){let f=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),h=f[0],g=f[1];c=C.mergeRealAndImagArrays(h,g)}else if(u==null)c=this.getValuesFrom
2022-11-18 17:13:29 +01:00
if (isnan(a)) return a;
if (isnan(b)) return b;
`;var Br=class{constructor(e,t,o){this.variableNames=["A","B"],this.outputShape=C.assertAndGetBroadcastShape(t,o),this.enableShapeUniforms=lt(this.outputShape.length),this.userCode=`
2022-11-18 17:13:29 +01:00
float binaryOperation(float a, float b) {
${e}
2022-11-18 17:13:29 +01:00
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}};var to=`
2022-11-18 17:13:29 +01:00
result.r = isNaN.r ? NAN : result.r;
result.g = isNaN.g ? NAN : result.g;
result.b = isNaN.b ? NAN : result.b;
result.a = isNaN.a ? NAN : result.a;
`;var eo=class{constructor(e,t,o,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=C.assertAndGetBroadcastShape(t,o);let s=this.outputShape.length;this.enableShapeUniforms=lt(s);let a="";if(n)if(s===0||y.sizeFromShape(this.outputShape)===1)a=`
2022-11-18 17:13:29 +01:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else if(a=`
2023-05-08 15:12:41 +02:00
${Re(s)} coords = getOutputCoords();
2022-11-18 17:13:29 +01:00
`,s===1)this.enableShapeUniforms?a+=`
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`:a+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{let p=At("coords",s);this.enableShapeUniforms?a+=`
2022-11-18 17:13:29 +01:00
bool nextRowOutOfBounds =
(${p[s-2]} + 1) >= outShape[${s} - 2];
bool nextColOutOfBounds =
(${p[s-1]} + 1) >= outShape[${s} - 1];
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`:a+=`
bool nextRowOutOfBounds =
(${p[s-2]} + 1) >= ${this.outputShape[s-2]};
bool nextColOutOfBounds =
(${p[s-1]} + 1) >= ${this.outputShape[s-1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
2022-11-18 17:13:29 +01:00
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${a}
setOutput(result);
}
`}};function Ft(r){let{inputs:e,backend:t}=r,{x:o}=e;return t.incRef(o.dataId),{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}var $A={kernelName:vo,backendName:"webgl",kernelFunc:Ft};function zr(r){let{inputs:e,backend:t}=r,{real:o,imag:n}=e,s=t.makeTensorInfo(o.shape,"complex64"),a=t.texData.get(s.dataId),i=Ft({inputs:{x:o},backend:t}),p=Ft({inputs:{x:n},backend:t});return a.complexTensorInfos={real:i,imag:p},s}var RA={kernelName:ei,backendName:"webgl",kernelFunc:zr};var _0="return (a < 0.) ? b * a : a;",E0=`
2022-11-18 17:13:29 +01:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function AJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o,a=t.makeTensorInfo([],"float32",y.createScalarValue(s,"float32")),i=A().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new eo(E0,n.shape,a.shape):new Br(_0,n.shape,a.shape),p=t.runWebGLProgram(i,[n,a],"float32");return t.disposeIntermediateTensorInfo(a),p}var DA={kernelName:Yn,backendName:"webgl",kernelFunc:AJ};var $0="return (a < 0.) ? b * a : a;",R0=`
2022-11-18 17:13:29 +01:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function FJ(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e,s=A().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new eo(R0,o.shape,n.shape):new Br($0,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],"float32")}var AA={kernelName:gs,backendName:"webgl",kernelFunc:FJ};var sn="if (isnan(x)) return x;";function xe({opSnippet:r,packedOpSnippet:e,cpuKernelImpl:t,dtype:o}){return({inputs:n,backend:s})=>{let{x:a}=n,i=s,p=o||a.dtype;if(i.shouldExecuteOnCPU([a])&&t!=null){let c=i.texData.get(a.dataId),m=t(c.values,p);return i.makeTensorInfo(a.shape,p,m)}let u=A().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&e!=null,l;return u?l=new Lr(a.shape,e):l=new nr(a.shape,r),i.runWebGLProgram(l,[a],p)}}function st({opSnippet:r,packedOpSnippet:e,checkOutOfBounds:t=!1,supportsComplex:o=!1,cpuKernelImpl:n,dtype:s}){return({inputs:a,backend:i})=>{let{a:p,b:u}=a,l=i;if(o&&p.dtype==="complex64"){let f=l.texData.get(p.dataId),h=l.texData.get(u.dataId),[g,x]=[[f.complexTensorInfos.real,h.complexTensorInfos.real],[f.complexTensorInfos.imag,h.complexTensorInfos.imag]].map(w=>{let[S,k]=w,T={dataId:S.dataId,dtype:S.dtype,shape:p.shape},E={dataId:k.dataId,dtype:k.dtype,shape:u.shape},R=new Br(r,p.shape,u.shape);return l.runWebGLProgram(R,[T,E],pt(S.dtype,k.dtype))}),b=zr({inputs:{real:g,imag:x},backend:l});return l.disposeIntermediateTensorInfo(g),l.disposeIntermediateTensorInfo(x),b}let c=s||pt(p.dtype,u.dtype);if((p.dtype==="string"||u.dtype==="string"||l.shouldExecuteOnCPU([p,u]))&&n!=null){let f=l.texData.get(p.dataId).values,h=l.texData.get(u.dataId).values,g=p.dtype==="string"?C.fromUint8ToStringArray(f):f,x=p.dtype==="string"?C.fromUint8ToStringArray(h):h,[b,w]=n(p.shape,u.shape,g,x,c),S=l.makeTensorInfo(w,c),k=l.texData.get(S.dataId);return k.values=b,S}let m=A().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null,d;return m?d=new eo(e,p.shape,u.shape,t):d=new Br(r,p.shape,u.shape),l.runWebGLProgram(d,[p,u],c)}}function Ti(r,e=!1){if(r==="linear")return e?vA:yA;if(r==="relu")return e?NA:CA;if(r==="elu")return e?kA:bA;if(r==="relu6")return e?TA:wA;if(r==="prelu")return e?R0:$0;if(r==="leakyrelu")return e?E0:_0;if(r==="sigmoid")return e?_A:SA;throw new Error(`Activation ${r} has not been implemented for the WebGL backend.`)}var Hl=class{constructor(e,t,o,n=!1,s=!1,a=!1,i=null,p=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=o,this.enableShapeUniforms=lt(this.outputShape.length);let l=n?e[1]:e[2],c=Math.ceil(l/2),m=n?"i * 2, rc.y":"rc.y, i * 2",d=s?"rc.z, i * 2":"i * 2, rc.z",f=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],g="",x="";i&&(p?g=`vec4 activation(vec4 a) {
2022-11-18 17:13:29 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords();
${i}
}`:u?g=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${i}
}`:g=`vec4 activation(vec4 x) {
${i}
}`,x="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),p&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let w="rc.x",S="rc.x";e[0]<t[0]?w=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(S=`imod(rc.x, ${t[0]})`),this.userCode=`
2022-11-18 17:13:29 +01:00
${g}
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = ${c}.0;
2022-11-18 17:13:29 +01:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
int batchA = ${w};
2023-05-08 15:12:41 +02:00
int batchB = ${S};
for (int i = 0; i < ${c}; i++) {
2022-11-18 17:13:29 +01:00
vec4 a = getMatrixA(batchA, ${m});
2022-11-20 22:20:02 +01:00
vec4 b = getMatrixB(batchB, ${d});
2022-11-18 17:13:29 +01:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
2022-11-20 22:20:02 +01:00
result += (${f[0]} * ${h[0]});
result += (${f[1]} * ${h[1]});
2022-11-18 17:13:29 +01:00
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${b}
2022-11-20 22:20:02 +01:00
${x}
2022-11-18 17:13:29 +01:00
setOutput(result);
}
`}};var D0={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},im=class{constructor(e,t,o){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=C.assertAndGetBroadcastShape(t,o),this.userCode=`
2022-11-18 17:13:29 +01:00
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
2022-11-18 17:13:29 +01:00
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}};var FA="return a * b;";function um(r){let{inputs:e,backend:t}=r,{a:o,b:n}=e,s=C.upcastType(o.dtype,n.dtype);if(o.dtype==="complex64"){let i=t.texData.get(o.dataId),p=t.texData.get(n.dataId),u=new im(D0.REAL,o.shape,n.shape),l=new im(D0.IMAG,o.shape,n.shape),c=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:o.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:n.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:n.shape}],m=t.runWebGLProgram(u,c,"float32"),d=t.runWebGLProgram(l,c,"float32"),f=zr({inputs:{real:m,imag:d},backend:t});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(d),f}if(t.shouldExecuteOnCPU([o,n])){let i=t.texData.get(o.dataId),p=t.texData.get(n.dataId),[u,l]=GD(o.shape,n.shape,i.values,p.values,s),c=t.makeTensorInfo(l,s),m=t.texData.get(c.dataId);return m.values=u,c}let a;return A().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new eo(FA,o.shape,n.shape):a=new Br(FA,o.shape,n.shape),t.runWebGLProgram(a,[o,n],s)}var PA={kernelName:$o,backendName:"webgl",kernelFunc:um};function OA(r,e,t){let o=[ki(r.shape),...Ni(r.shape)],n={dtype:r.dtype,shape:o,dataId:r.dataId},s=[ki(e),...Ni(e)],a=new Wl(s,o),i=!0,p=[o],u=t.runWebGLProgram(a,[n],r.dtype,p,i);return{dataId:u.dataId,shape:e,dtype:u.dtype}}function te(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{shape:s}=o,a=t,i=y.sizeFromShape(n.shape),p=y.inferFromImplicitShape(s,i),u=y.sizeFromShape(p);y.assert(i===u,()=>`The new shape (${p}) has ${u} elements and the old shape (${n.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let l=a.texData.get(n.dataId);return l.isPacked&&!vu(n.shape,p)&&!(l.texture!==null&&vu(l.shape,p))?OA(n,p,a):(a.incRef(n.dataId),{dataId:n.dataId,shape:p,dtype:n.dtype})}var MA={kernelName:Ca,backendName:"webgl",kernelFunc:te};var pm=class{constructor(e,t){this.variableNames=["x"];let{windowSize:o,batchSize:n,inSize:s,outSize:a}=e;this.outputShape=[n,a];let i=Math.floor(o/4)*4,p=o%4,u="sumValue += dot(values, ones);";if(t!=null){let c=1/t;u=`sumValue += dot(values * ${y.isInt(c)?c.toPrecision(2):c}, ones);`}let l="";s%o>0&&(l=`
2022-11-18 17:13:29 +01:00
if (inIdx < 0 || inIdx >= ${s}) {
return 0.0;
}
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${l}
2022-11-18 17:13:29 +01:00
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${o};
float sumValue = 0.0;
for (int i = 0; i < ${i}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${u}
}
int inIdx = inOffset + ${i};
if (${p===1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
${u}
} else if (${p===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
${u}
} else if (${p===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
${u}
}
setOutput(sumValue);
}
`}};var Th=class{constructor(e,t){this.variableNames=["x"];let{windowSize:o,batchSize:n,inSize:s,outSize:a}=e;this.outputShape=[n,a];let i="0.0",p="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",p="min"):t==="max"&&(i="-1.0 / 1e-20",p="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?u="sumValue":t==="prod"?u="prodValue":t==="all"?u="allValue":t==="any"&&(u="anyValue");let l=Math.floor(o/4)*4,c=o%4,m=`
if (${t==="sum"}) {
2022-11-18 17:13:29 +01:00
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
2022-11-18 17:13:29 +01:00
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${p}(values, minMaxValue);
if (${t==="min"} || ${t==="max"}) {
2022-11-18 17:13:29 +01:00
minMaxValue = ${p}(values, minMaxValue);
bvec4 isNaN = isnan(values);
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
minMaxValue = vec4(NAN);
}
}
}
`,d="vec4";t==="all"?(i="1.0",m=`
2022-11-18 17:13:29 +01:00
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,d="bvec4"):t==="any"&&(i="0.0",m=`
2022-11-18 17:13:29 +01:00
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
2022-11-20 22:20:02 +01:00
`,d="bvec4");let f="";s%o>0&&(f=`
2022-11-18 17:13:29 +01:00
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${i};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
2022-11-20 22:20:02 +01:00
${f}
2022-11-18 17:13:29 +01:00
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${o};
vec4 minMaxValue = vec4(${i});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${l}; i += 4) {
2022-11-18 17:13:29 +01:00
int inIdx = inOffset + i;
2022-11-20 22:20:02 +01:00
${d} values = ${d}(
2022-11-18 17:13:29 +01:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${m}
}
int inIdx = inOffset + ${l};
if (${c===1}) {
2022-11-20 22:20:02 +01:00
${d} values = ${d}(
2022-11-18 17:13:29 +01:00
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${m}
} else if (${c===2}) {
2022-11-20 22:20:02 +01:00
${d} values = ${d}(
2022-11-18 17:13:29 +01:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${m}
} else if (${c===3}) {
2022-11-20 22:20:02 +01:00
${d} values = ${d}(
2022-11-18 17:13:29 +01:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${m}
}
setOutput(${u});
}
`}};function OJ(r){let e=[];for(;e.length===0||e[e.length-1].outSize!==1;){let t=e.length?e[e.length-1].outSize:r[1],o=C.computeOptimalWindowSize(t);e.push({inSize:t,windowSize:o,outSize:Math.ceil(t/o)})}return e}function ro(r,e,t,o){let n=OJ(r.shape),s=r;for(let a=0;a<n.length;a++){let{inSize:i,windowSize:p,outSize:u}=n[a],l,c;t==="mean"?l=a===0?new pm({windowSize:p,inSize:i,batchSize:r.shape[0],outSize:u},i):new pm({windowSize:p,inSize:i,batchSize:r.shape[0],outSize:u}):l=new Th({windowSize:p,inSize:i,batchSize:r.shape[0],outSize:u},t),c=s,s=o.runWebGLProgram(l,[s],e),c.dataId!==r.dataId&&o.disposeIntermediateTensorInfo(c)}return s}var _h=class{constructor(e,t){this.variableNames=["A"];let o=new Array(e.length);for(let a=0;a<o.length;a++)o[a]=e[t[a]];this.outputShape=o,this.rank=o.length;let n=Re(this.rank),s=MJ(t);this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${s}));
}
`}};function MJ(r){let e=r.length;if(e>6)throw Error(`Transpose for rank ${e} is not yet supported`);let t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],o=new Array(e);for(let n=0;n<r.length;n++)o[r[n]]=t[n];return o.join()}var Eh=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let o=new Array(e.length);for(let l=0;l<o.length;l++)o[l]=e[t[l]];if(this.outputShape=o,this.rank=o.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let n=Re(this.rank),s=N0("rc",this.rank),a=new Array(this.rank);for(let l=0;l<t.length;l++)a[t[l]]=s[l];let i=`vec2(${a.slice(-2).join()})`,p=`++${s[this.rank-1]} < ${o[this.rank-1]}`,u=`getChannel(getA(${a.join()}), ${i})`;this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${n} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${u};
if(${p}) {
result[1] = ${u};
}
--${s[this.rank-1]};
if(++${s[this.rank-2]} < ${o[this.rank-2]}) {
result[2] = ${u};
if(${p}) {
result[3] = ${u};
}
}
setOutput(result);
}
`}};function ku(r,e,t){let o=A().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Eh(r.shape,e):new _h(r.shape,e);return t.runWebGLProgram(o,[r],r.dtype)}function LA(r,e,t,o){let n=e,s=r.shape.length,a=y.parseAxisParam(n,r.shape),i=a,p=C.getAxesPermutation(i,s),u=p!=null,l=r;u&&(l=ku(r,p,o),i=C.getInnerMostAxes(i.length,s)),C.assertAxesAreInnerMostDims("sum",i,s);let[c,m]=C.computeOutAndReduceShapes(l.shape,i),d=c;t&&(d=C.expandShapeToKeepDim(c,a));let f=y.sizeFromShape(m),g=y.sizeFromShape(r.shape)/f,x=te({inputs:{x:l},attrs:{shape:[g,f]},backend:o}),b=mi(r.dtype),w=ro(x,b,"sum",o),S=te({inputs:{x:w},attrs:{shape:d},backend:o});return o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(w),u&&o.disposeIntermediateTensorInfo(l),S}function Tp(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;return LA(n,s,a,t)}var BA={kernelName:As,backendName:"webgl",kernelFunc:Tp};function Ct(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{perm:s}=o,a=t,i=n.shape.length,p=new Array(i);for(let l=0;l<p.length;l++)p[l]=n.shape[s[l]];let u;if(a.shouldExecuteOnCPU([n])){let c=a.texData.get(n.dataId).values,m=Np(c,n.shape,n.dtype,s,p);u=a.makeTensorInfo(p,n.dtype);let d=a.texData.get(u.dataId);d.values=m}else u=ku(n,s,a);return u}var zA={kernelName:Kr,backendName:"webgl",kernelFunc:Ct};var A0=1e3;function _p({a:r,b:e,transposeA:t,transposeB:o,backend:n,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:p=null}){let u=r.shape.length,l=e.shape.length,c=t?r.shape[u-2]:r.shape[u-1],m=o?e.shape[l-1]:e.shape[l-2],d=t?r.shape[u-1]:r.shape[u-2],f=o?e.shape[l-2]:e.shape[l-1],h=r.shape.slice(0,-2),g=e.shape.slice(0,-2),x=y.sizeFromShape(h),b=y.sizeFromShape(g),S=kr.assertAndGetBroadcastShape(r.shape.slice(0,-2),e.shape.slice(0,-2)).concat([d,f]);y.assert(c===m,()=>`Error in matMul: inner shapes (${c}) and (${m}) of Tensors with shapes ${r.shape} and ${e.shape} and transposeA=${t} and transposeB=${o} must match.`);let k=t?[x,c,d]:[x,d,c],T=o?[b,f,m]:[b,m,f],E=te({inputs:{x:r},backend:n,attrs:{shape:k}}),R=te({inputs:{x:e},backend:n,attrs:{shape:T}}),D=[E,R],F=Math.max(x,b),O=t?E.shape[1]:E.shape[2],M=s!=null,L=a!=null,B=p==="leakyrelu",z=p!=null?Ti(p,!0):null,U=M||L||B||z!=null,j;if((d===1||f===1)&&O>A0&&U===!1){let Y=E,J=R;t&&(Y=Ct({inputs:{x:E},backend:n,attrs:{perm:[0,2,1]}}),D.push(Y)),o&&(J=Ct({inputs:{x:R},backend:n,attrs:{perm:[0,2,1]}}),D.push(J));let re=f!==1,ne=f===1,ee=Y;re&&(ee=te({inputs:{x:Y},backend:n,attrs:{shape:[F,O,1]}}),D.push(ee));let oe=f===1?2:1,ue=J;ne&&(ue=te({inputs:{x:J},backend:n,attrs:{shape:[F,1,O]}}),D.push(ue));let me=um({inputs:{a:ee,b:ue},backend:n});j=Tp({inputs:{x:me},backend:n,attrs:{axis:oe,keepDims:!0}}),D.push(me)}else{let Y=pt(r.dtype,e.dtype),J=new Hl(k,T,[F,d,f],t,o,M,z,L,B),re=[E,R];if(s!=null&&re.push(s),L&&re.push(a),B){let ne=n.makeTensorInfo([],"float32",y.createScalarValue(i,"float32"));re.push(ne),D.push(ne)}j=n.runWebGLProgram(J,re,Y)}let q=te({inputs:{x:j},backend:n,attrs:{shape:S}});D.push(j);for(let Y of D)n.disposeIntermediateTensorInfo(Y);return q}function LJ(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e,{transposeA:p,transposeB:u,activation:l,leakyreluAlpha:c}=o;return _p({a:n,b:s,transposeA:p,transposeB:u,backend:t,bias:a,preluActivationWeights:i,leakyreluAlpha:c,activation:l})}var VA={kernelName:qo,backendName:"webgl",kernelFunc:LJ};var WA="return abs(x);";function BJ(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])&&o.dtype!=="complex64"){let s=t.texData.get(o.dataId),a=wh(s.values);return t.makeTensorInfo(o.shape,o.dtype,a)}let n;return A().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new Lr(o.shape,WA):n=new nr(o.shape,WA),t.runWebGLProgram(n,[o],o.dtype)}var UA={kernelName:fn,backendName:"webgl",kernelFunc:BJ};var zJ=Gt+`
2022-11-18 17:13:29 +01:00
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,VJ=xe({opSnippet:zJ}),GA={kernelName:hn,backendName:"webgl",kernelFunc:VJ};var WJ=Gt+`
2022-11-18 17:13:29 +01:00
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,UJ=xe({opSnippet:WJ}),HA={kernelName:gn,backendName:"webgl",kernelFunc:UJ};var KA="return a + b;",GJ=st({opSnippet:KA,packedOpSnippet:KA,supportsComplex:!0,cpuKernelImpl:ID}),qA={kernelName:Rr,backendName:"webgl",kernelFunc:GJ};var $h=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let o=[];this.variableNames.forEach(s=>{o.push(`float v${s} = get${s}AtOutCoords();`)});let n=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${o.join(`
`)}
float result = ${n};
setOutput(result);
}
`}};var Rh=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let o=[];this.variableNames.forEach(s=>{o.push(`vec4 v${s} = get${s}AtOutCoords();`)});let n=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${o.join(`
`)}
vec4 result = ${n};
setOutput(result);
}
`}};function Dh(r){let{inputs:e,backend:t}=r,o=e;if(o.length===1)return Ft({inputs:{x:o[0]},backend:t});if(o.length>A().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let p=Math.floor(o.length/2),u=Dh({inputs:o.slice(0,p),backend:t}),l=Dh({inputs:o.slice(p),backend:t});return Dh({inputs:[u,l],backend:t})}let n=o.map(p=>p.dtype).reduce((p,u)=>pt(p,u)),s=o.map(p=>p.shape),i=A().getBool("WEBGL_PACK")?new Rh(o[0].shape,s):new $h(o[0].shape,s);return t.runWebGLProgram(i,o,n)}var jA={kernelName:xn,backendName:"webgl",kernelFunc:Dh};function HJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,p=y.parseAxisParam(s,n.shape),u=p,l=C.getAxesPermutation(u,i),c=n;l!=null&&(c=Ct({inputs:{x:n},backend:t,attrs:{perm:l}}),u=C.getInnerMostAxes(u.length,i)),C.assertAxesAreInnerMostDims("all",u,i);let[m,d]=C.computeOutAndReduceShapes(c.shape,u),f=y.sizeFromShape(d),h=te({inputs:{x:c},backend:t,attrs:{shape:[-1,f]}}),g=ro(h,h.dtype,"all",t),x;if(a){let b=C.expandShapeToKeepDim(m,p);x=te({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=te({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),l!=null&&t.disposeIntermediateTensorInfo(c),x}var XA={kernelName:yn,backendName:"webgl",kernelFunc:HJ};function KJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,p=y.parseAxisParam(s,n.shape),u=p,l=C.getAxesPermutation(u,i),c=n;l!=null&&(c=Ct({inputs:{x:n},backend:t,attrs:{perm:l}}),u=C.getInnerMostAxes(u.length,i)),C.assertAxesAreInnerMostDims("any",u,i);let[m,d]=C.computeOutAndReduceShapes(c.shape,u),f=y.sizeFromShape(d),h=te({inputs:{x:c},backend:t,attrs:{shape:[-1,f]}}),g=ro(h,h.dtype,"any",t),x;if(a){let b=C.expandShapeToKeepDim(m,p);x=te({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=te({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),l!=null&&t.disposeIntermediateTensorInfo(c),x}var YA={kernelName:bn,backendName:"webgl",kernelFunc:KJ};var Ah=class{constructor(e,t,o){this.variableNames=["A"];let{windowSize:n,batchSize:s,outSize:a}=e;o||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let i=t==="max"?">":"<",p=o?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${n}; i++) {
int inIdx = ${p};
float candidate = getA(batch, inIdx);
if (candidate ${i} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}};var Fh=class{constructor(e,t,o,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,y.assert(e.length>2,()=>`Packed arg${o.charAt(0).toUpperCase()+o.slice(1)} supports only inputs with rank above 2.`);let s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),n||this.variableNames.push("bestIndicesA");let i=this.outputShape,p=i.length,u=Re(p),l=At("coords",p),c,m;if(a===1){m=p+1;let R=Re(m);c=`
${R} sourceLocR = ${R}(${l.join()}, 0);
++${l[p-1]};
${R} sourceLocG = ${R}(${l.join()}, 0);
++${l[p-2]};
${R} sourceLocA = ${R}(${l.join()}, 0);
--${l[p-1]};
${R} sourceLocB = ${R}(${l.join()}, 0);
--${l[p-2]};`}else m=p,c=`
2022-11-18 17:13:29 +01:00
${u} sourceLocR = coords;
++${l[p-1]};
2022-11-18 17:13:29 +01:00
${u} sourceLocG = coords;
++${l[p-2]};
2022-11-18 17:13:29 +01:00
${u} sourceLocA = coords;
--${l[p-1]};
2022-11-18 17:13:29 +01:00
${u} sourceLocB = coords;
--${l[p-2]};`;let d=["x","y","z","w","u","v"].slice(0,m),f="."+d[m-1],h=d.map(R=>"int "+R),g=At("sourceLocR",m-1).concat("inIdx.r"),x=At("sourceLocG",m-1).concat("inIdx.g"),b=At("sourceLocB",m-1).concat("inIdx.b"),w=At("sourceLocA",m-1).concat("inIdx.a"),S=o==="max"?"greaterThan":"lessThan",k=n?"":`
2022-11-18 17:13:29 +01:00
inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
2022-11-20 22:20:02 +01:00
getBestIndicesAChannel(${x.join()}),
2022-11-18 17:13:29 +01:00
getBestIndicesAChannel(${b.join()}),
getBestIndicesAChannel(${w.join()})));`,T=`vec4(
2022-11-18 17:13:29 +01:00
getAChannel(${g.join()}),
2022-11-20 22:20:02 +01:00
hasNextCol ? getAChannel(${x.join()}) : 0.,
2022-11-18 17:13:29 +01:00
hasNextRow ? getAChannel(${b.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,E=n?"":`
2022-11-18 17:13:29 +01:00
float getBestIndicesAChannel(${h.join()}) {
2022-11-20 22:20:02 +01:00
return getChannel(getBestIndicesA(${d.join()}),
vec2(${d.slice(-2).join()}));
2022-11-18 17:13:29 +01:00
}`;this.userCode=`
float getAChannel(${h.join()}) {
2022-11-20 22:20:02 +01:00
return getChannel(getA(${d.join()}),
vec2(${d.slice(-2).join()}));
2022-11-18 17:13:29 +01:00
}
2023-01-06 19:23:06 +01:00
${E}
2022-11-18 17:13:29 +01:00
void main() {
${u} coords = getOutputCoords();
bool hasNextCol = ${l[p-1]} < ${i[p-1]-1};
bool hasNextRow = ${l[p-2]} < ${i[p-2]-1};
${c}
2022-11-20 22:20:02 +01:00
ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f},
sourceLocB${f}, sourceLocA${f}) * ${t};
2022-11-18 17:13:29 +01:00
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${T};
2022-11-18 17:13:29 +01:00
for (int i = 0; i < ${t}; i++) {
2022-11-18 17:13:29 +01:00
inIdx = srcIdx;
${k}
vec4 candidate = ${T};
2022-11-18 17:13:29 +01:00
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
2023-05-08 15:12:41 +02:00
vec4(${S}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
2022-11-18 17:13:29 +01:00
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`}};function QA(r,e,t,o=null){let n=e.shape[0],s=e.shape[1];o!=null&&(n=o.shape[0],s=o.shape[1]);let a=C.computeOptimalWindowSize(s),i={windowSize:a,inSize:s,batchSize:n,outSize:Math.ceil(s/a)},p=new Ah(i,t,o==null),u=[e];o!=null&&u.push(o);let l=r.runWebGLProgram(p,u,"int32");if(l.shape[1]===1)return l;let c=QA(r,e,t,l);return r.disposeIntermediateTensorInfo(l),c}function ZA(r,e,t,o=null){let n=o!=null?o.shape:e.shape,s=n[n.length-1],a=C.computeOptimalWindowSize(s),i=new Fh(n,a,t,o==null),p=o==null?[e]:[e,o],u=r.runWebGLProgram(i,p,"int32");if(u.shape.length===e.shape.length){let l=ZA(r,e,t,u);return r.disposeIntermediateTensorInfo(u),l}return u}function Ph(r,e,t,o){let n=[t];if(C.assertAxesAreInnerMostDims("arg"+o.charAt(0).toUpperCase()+o.slice(1),n,e.shape.length),!A().getBool("WEBGL_PACK_REDUCE")||e.shape.length<=2){let s=[],a=r.texData.get(e.dataId),i=a!==null&&a.isPacked,p=e;i&&(p=r.unpackTensor(e),s.push(p));let[u,l]=C.computeOutAndReduceShapes(p.shape,n),c=y.sizeFromShape(l),m=te({inputs:{x:p},backend:r,attrs:{shape:[-1,c]}});s.push(m);let d=QA(r,m,o);s.push(d);let f=te({inputs:{x:d},backend:r,attrs:{shape:u}});return s.forEach(h=>r.disposeIntermediateTensorInfo(h)),f}return ZA(r,e,o)}function qJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=y.parseAxisParam(s,n.shape),i=C.getAxesPermutation(a,n.shape.length),p=n,u=[];i!=null&&(p=Ct({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(p),a=C.getInnerMostAxes(a.length,p.shape.length)),C.assertAxesAreInnerMostDims("argMax",[a[0]],p.shape.length);let l=Ph(t,p,a[0],"max");return u.forEach(c=>t.disposeIntermediateTensorInfo(c)),l}var JA={kernelName:na,backendName:"webgl",kernelFunc:qJ};function jJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=y.parseAxisParam(s,n.shape),i=C.getAxesPermutation(a,n.shape.length),p=n,u=[];i!=null&&(p=Ct({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(p),a=C.getInnerMostAxes(a.length,p.shape.length)),C.assertAxesAreInnerMostDims("argMin",[a[0]],p.shape.length);let l=Ph(t,p,a[0],"min");return u.forEach(c=>t.disposeIntermediateTensorInfo(c)),l}var eF={kernelName:sa,backendName:"webgl",kernelFunc:jJ};var XJ=Gt+`
2022-11-18 17:13:29 +01:00
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,YJ=xe({opSnippet:XJ}),tF={kernelName:Cn,backendName:"webgl",kernelFunc:YJ};var QJ=Gt+"return log(x + sqrt(x * x + 1.0));",ZJ=xe({opSnippet:QJ}),rF={kernelName:wn,backendName:"webgl",kernelFunc:ZJ};var JJ=Gt+`
2022-11-18 17:13:29 +01:00
return atan(x);
`,eee=xe({opSnippet:JJ}),oF={kernelName:Sn,backendName:"webgl",kernelFunc:eee};var tee=Gl+`
2022-11-18 17:13:29 +01:00
return atan(a, b);
`,ree=`
2022-11-18 17:13:29 +01:00
vec4 result = atan(a, b);
bvec4 isNaNA = isnan(a);
bvec4 isNaNB = isnan(b);
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
`+to+`
2022-11-18 17:13:29 +01:00
return result;
`,oee=st({opSnippet:tee,packedOpSnippet:ree}),nF={kernelName:vn,backendName:"webgl",kernelFunc:oee};var nee=Gt+`
2022-11-18 17:13:29 +01:00
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,see=xe({opSnippet:nee}),sF={kernelName:In,backendName:"webgl",kernelFunc:see};var Zs=class{constructor(e,t,o,n=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&o)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,i=e.strideHeight,p=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterHeight,m=e.effectiveFilterWidth,d=e.padInfo.top,f=e.padInfo.left;this.outputShape=e.outShape;let h=t==="avg",g=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,x=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,b="0.0";if(h||(b="-1.0 / 1e-20"),o){let R=">=";this.userCode=`
2022-11-18 17:13:29 +01:00
const ivec2 strides = ivec2(${i}, ${p});
2022-11-20 22:20:02 +01:00
const ivec2 pads = ivec2(${d}, ${f});
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < ${c};
2022-11-18 17:13:29 +01:00
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
2022-11-18 17:13:29 +01:00
continue;
}
for (int wC = 0; wC < ${m};
wC += ${l}) {
2022-11-18 17:13:29 +01:00
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
2022-11-18 17:13:29 +01:00
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
2023-05-08 15:12:41 +02:00
if (value ${R} currMinMaxValue) {
2022-11-18 17:13:29 +01:00
minMaxValue = value;
minMaxValueFound = 1.0;
2022-11-20 22:20:02 +01:00
minMaxPosition = ${n?s?g:x:`wR * ${m} + wC`};
2022-11-18 17:13:29 +01:00
}
}
}
setOutput(float(minMaxPosition));
}
`;return}let w="max",S=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(S="avgValue / max(count, 1.0)");let k=Math.floor(a/4)*4,T=a%4,E=`
2022-11-18 17:13:29 +01:00
if (${h}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${w}(values, minMaxValue);
2022-11-18 17:13:29 +01:00
}
`;this.userCode=`
const ivec2 strides = ivec2(${i}, ${p});
2022-11-20 22:20:02 +01:00
const ivec2 pads = ivec2(${d}, ${f});
2022-11-18 17:13:29 +01:00
const float initializationValue = ${b};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${e.inWidth}) {
2022-11-18 17:13:29 +01:00
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${b});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${c};
2022-11-18 17:13:29 +01:00
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
2022-11-18 17:13:29 +01:00
continue;
}
for (int wC = 0; wC < ${k}; wC += 4) {
int xC = xCCorner + wC * ${l};
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${l}, d),
getValue(batch, xR, xC + 2 * ${l}, d),
getValue(batch, xR, xC + 3 * ${l}, d)
2022-11-18 17:13:29 +01:00
);
2023-01-06 19:23:06 +01:00
${E}
2022-11-18 17:13:29 +01:00
}
int xC = xCCorner + ${k};
if (${T===1}) {
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
2023-01-06 19:23:06 +01:00
${E}
} else if (${T===2}) {
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${l}, d),
2022-11-18 17:13:29 +01:00
initializationValue,
initializationValue
);
2023-01-06 19:23:06 +01:00
${E}
} else if (${T===3}) {
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${l}, d),
getValue(batch, xR, xC + 2 * ${l}, d),
2022-11-18 17:13:29 +01:00
initializationValue
);
2023-01-06 19:23:06 +01:00
${E}
2022-11-18 17:13:29 +01:00
}
}
2023-05-08 15:12:41 +02:00
setOutput(${S});
2022-11-18 17:13:29 +01:00
}
`}},Nu=class{constructor(e,t,o,n=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&o)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,i=e.strideDepth,p=e.strideHeight,u=e.strideWidth,l=e.dilationDepth,c=e.dilationHeight,m=e.dilationWidth,d=e.effectiveFilterDepth,f=e.effectiveFilterHeight,h=e.effectiveFilterWidth,g=e.padInfo.front,x=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let w=t==="avg",S="0.0";if(w||(S="-1.0 / 1e-20"),o){let F=">=";this.userCode=`
2022-11-18 17:13:29 +01:00
const ivec3 strides =
ivec3(${i}, ${p}, ${u});
2022-11-20 22:20:02 +01:00
const ivec3 pads = ivec3(${g}, ${x}, ${b});
2022-11-18 17:13:29 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
2022-11-20 22:20:02 +01:00
for (int wD = 0; wD < ${d};
wD += ${l}) {
2022-11-18 17:13:29 +01:00
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
2022-11-18 17:13:29 +01:00
continue;
}
2022-11-20 22:20:02 +01:00
for (int wR = 0; wR < ${f};
wR += ${c}) {
2022-11-18 17:13:29 +01:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
2022-11-18 17:13:29 +01:00
continue;
}
for (int wC = 0; wC < ${h};
wC += ${m}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
2022-11-18 17:13:29 +01:00
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${F} currMinMaxValue) {
2022-11-18 17:13:29 +01:00
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?s?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${f} * ${h} +
2022-11-18 17:13:29 +01:00
wR * ${h} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}let k="max",T=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(T="avgValue / max(count, 1.0)");let E=Math.floor(a/4)*4,R=a%4,D=`
if (${w}) {
2022-11-18 17:13:29 +01:00
avgValue += dot(values, ones);
} else {
minMaxValue = ${k}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${i}, ${p}, ${u});
2022-11-20 22:20:02 +01:00
const ivec3 pads = ivec3(${g}, ${x}, ${b});
2023-05-08 15:12:41 +02:00
const float initializationValue = ${S};
2022-11-18 17:13:29 +01:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
2022-11-18 17:13:29 +01:00
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2023-05-08 15:12:41 +02:00
vec4 minMaxValue = vec4(${S});
2022-11-18 17:13:29 +01:00
float avgValue = 0.0;
count = 0.0;
2022-11-20 22:20:02 +01:00
for (int wD = 0; wD < ${d};
wD += ${l}) {
2022-11-18 17:13:29 +01:00
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
2022-11-18 17:13:29 +01:00
continue;
}
2022-11-20 22:20:02 +01:00
for (int wR = 0; wR < ${f};
wR += ${c}) {
2022-11-18 17:13:29 +01:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
2022-11-18 17:13:29 +01:00
continue;
}
2023-01-06 19:23:06 +01:00
for (int wC = 0; wC < ${E}; wC += 4) {
2022-11-18 17:13:29 +01:00
int xC = xCCorner + wC * ${m};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${m}, ch),
getValue(batch, xD, xR, xC + 2 * ${m}, ch),
getValue(batch, xD, xR, xC + 3 * ${m}, ch)
);
2023-05-08 15:12:41 +02:00
${D}
2022-11-18 17:13:29 +01:00
}
2023-01-06 19:23:06 +01:00
int xC = xCCorner + ${E};
2023-05-08 15:12:41 +02:00
if (${R===1}) {
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
2023-05-08 15:12:41 +02:00
${D}
} else if (${R===2}) {
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${m}, ch),
initializationValue,
initializationValue
);
2023-05-08 15:12:41 +02:00
${D}
} else if (${R===3}) {
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${m}, ch),
getValue(batch, xD, xR, xC + 2 * ${m}, ch),
initializationValue
);
2023-05-08 15:12:41 +02:00
${D}
2022-11-18 17:13:29 +01:00
}
}
}
setOutput(${T});
2022-11-18 17:13:29 +01:00
}
`}};function aee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;Ys(n,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:p}=o,u=1;y.assert(C.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let l=C.computePool2DInfo(n.shape,s,a,u,i,p);if(l.filterWidth===1&&l.filterHeight===1&&y.arraysEqual(l.inShape,l.outShape))return Ft({inputs:{x:n},backend:t});let c=new Zs(l,"avg",!1);return t.runWebGLProgram(c,[n],"float32")}var aF={kernelName:kn,backendName:"webgl",kernelFunc:aee};function iee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:p,dataFormat:u}=o,l=[1,1,1],c=C.computePool3DInfo(n.shape,s,a,l,i,p,u),m=new Nu(c,"avg",!1);return t.runWebGLProgram(m,[n],"float32")}var iF={kernelName:aa,backendName:"webgl",kernelFunc:iee};var Oh=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,o=e.filterWidth,n=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,p=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=p-1-e.padInfo.top,c=u-1-e.padInfo.left,m=1/(t*o);this.userCode=`
const ivec2 pads = ivec2(${l}, ${c});
2022-11-18 17:13:29 +01:00
const float avgMultiplier = float(${m});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${p};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2022-11-18 17:13:29 +01:00
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${u};
wC+= ${i}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`}},Mh=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,o=e.filterHeight,n=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,p=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterDepth,m=e.effectiveFilterHeight,d=e.effectiveFilterWidth,f=c-1-e.padInfo.front,h=m-1-e.padInfo.top,g=d-1-e.padInfo.left,x=1/(t*o*n);this.userCode=`
2022-11-20 22:20:02 +01:00
const ivec3 pads = ivec3(${f}, ${h}, ${g});
const float avgMultiplier = float(${x});
2022-11-18 17:13:29 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${c};
2022-11-18 17:13:29 +01:00
wD += ${p}) {
float dyD = float(dyDCorner + wD) / ${s}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
2022-11-18 17:13:29 +01:00
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${m};
wR += ${u}) {
float dyR = float(dyRCorner + wR) / ${a}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2022-11-20 22:20:02 +01:00
for (int wC = 0; wC < ${d};
wC += ${l}) {
2022-11-18 17:13:29 +01:00
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`}};function uee(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:p,pad:u,dimRoundingMode:l}=o,c=[1,1,1],m=C.computePool3DInfo(a.shape,i,p,c,u,l),d=new Mh(m);return t.runWebGLProgram(d,[n],a.dtype)}var uF={kernelName:Vi,backendName:"webgl",kernelFunc:uee};function pee(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s;Ys([n,s],"avgPoolGrad");let{filterSize:i,strides:p,pad:u}=o,l=C.computePool2DInfo(a.shape,i,p,1,u),c=new Oh(l);return t.runWebGLProgram(c,[n],a.dtype)}var pF={kernelName:zi,backendName:"webgl",kernelFunc:pee};function lee(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;return _p({a:n,b:s,transposeA:a,transposeB:i,backend:t})}var lF={kernelName:Nn,backendName:"webgl",kernelFunc:lee};var Lh=class{constructor(e,t,o,n,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,o);let i="0.0";n!=null&&(C.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let p="1.0";s!=null&&(C.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),p="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${i};
float scale = ${p};
float inv = scale * inversesqrt(variance + float(${a}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`}};var Bh=class{constructor(e,t,o,n,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,o);let i="vec4(0.0)";n!=null&&(C.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let p="vec4(1.0)";s!=null&&(C.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),p="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
vec4 offset = ${i};
vec4 scale = ${p};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
setOutput((x - mean) * inv + offset);
}
`}};var cee=({inputs:r,backend:e,attrs:t})=>{let{x:o,mean:n,variance:s,offset:a,scale:i}=r;y.assert(n.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),y.assert(a==null||n.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),y.assert(i==null||n.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:p}=t;p==null&&(p=.001);let u=[o,n,s],l=null;a!=null&&(l=a.shape,u.push(a));let c=null;i!=null&&(c=i.shape,u.push(i));let m=A().getBool("WEBGL_PACK_NORMALIZATION")?new Bh(o.shape,n.shape,s.shape,l,c,p):new Lh(o.shape,n.shape,s.shape,l,c,p);return e.runWebGLProgram(m,u,u[0].dtype)},cF={kernelName:Hn,backendName:"webgl",kernelFunc:cee};var zh=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=Re(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let o=mee(this.rank),n,s=e.map((a,i)=>`sourceLoc.${F0[i]} = start[${i}] + coords.${F0[i]};`);n=`
${t} sourceLoc;
${t} coords = getOutputCoords();
2022-11-18 17:13:29 +01:00
${s.join(`
`)}
`,this.userCode=`
void main() {
${n}
setOutput(getSource(${o}));
}
`}},F0=["x","y","z","w","u","v"];function mee(r){if(r===1)return"sourceLoc";if(r<=6)return F0.slice(0,r).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}var Vh=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=Re(this.rank),o=At("coords",this.rank),n=At("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${n.slice(-2).join()})`,a=`getChannel(getSource(${n.join()}), ${s})`,i=`
2022-11-18 17:13:29 +01:00
result.x = ${a};
if (++${o[this.rank-1]} < ${e[this.rank-1]}) {
2022-11-18 17:13:29 +01:00
++${n[this.rank-1]};
result.y = ${a};
--${n[this.rank-1]};
}
`,p=this.rank===1?"":`
--${o[this.rank-1]};
if (++${o[this.rank-2]} < ${e[this.rank-2]}) {
2022-11-18 17:13:29 +01:00
++${n[this.rank-2]};
result.z = ${a};
if (++${o[this.rank-1]} < ${e[this.rank-1]}) {
2022-11-18 17:13:29 +01:00
++${n[this.rank-1]};
result.w = ${a};
}
}
`,u=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((l,c)=>`start[${c}]`).join()});`:e.map((l,c)=>`${n[c]} = ${o[c]} + start[${c}];`).join(`
2022-11-18 17:13:29 +01:00
`);this.userCode=`
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
2022-11-18 17:13:29 +01:00
${u}
vec4 result = vec4(0.);
${i}
${p}
setOutput(result);
}
`}};function dee(r,e,t,o){let n=o.texData.get(r.dataId),s=o.makeTensorInfo(t,r.dtype),a=o.texData.get(s.dataId);Object.assign(a,n),a.refCount=1,a.shape=t,a.dtype=r.dtype;let i=nt.computeFlatOffset(e,y.computeStrides(r.shape));n.slice&&(i+=n.slice.flatOffset),a.slice={flatOffset:i,origDataId:n.slice&&n.slice.origDataId||r.dataId};let p=o.dataRefCount.get(a.slice.origDataId)||1;return o.dataRefCount.set(a.slice.origDataId,p+1),s}function Js(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o,[i,p]=nt.parseSliceParams(n,s,a);if(nt.assertParamsValid(n,i,p),y.sizeFromShape(p)===0)return t.makeTensorInfo(p,n.dtype,[]);if(t.shouldExecuteOnCPU([n])||n.dtype==="string"){let c=t.texData.get(n.dataId),m=tA(c.values,i,p,n.shape,n.dtype);return t.makeTensorInfo(p,n.dtype,m)}let{isPacked:u}=t.texData.get(n.dataId),l=nt.isSliceContinous(n.shape,i,p);if(u||!l){let c=A().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Vh(p):new zh(p),m=[i];return t.runWebGLProgram(c,[n],n.dtype,m)}return t.uploadToGPU(n.dataId),dee(n,i,p,t)}var mF={kernelName:_s,backendName:"webgl",kernelFunc:Js};var fee=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;y.assert(n.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((b,w)=>b*w),p=C.getReshaped(n.shape,s,i),u=C.getPermuted(p.length,s.length),l=C.getReshapedPermuted(n.shape,s,i),c=C.getSliceBeginCoords(a,s.length),m=C.getSliceSize(l,a,s.length),d=[],f=te({inputs:{x:n},backend:t,attrs:{shape:p}}),h=Ct({inputs:{x:f},backend:t,attrs:{perm:u}}),g=te({inputs:{x:h},backend:t,attrs:{shape:l}}),x=Js({inputs:{x:g},backend:t,attrs:{begin:c,size:m}});return d.push(f),d.push(h),d.push(g),d.forEach(b=>t.disposeIntermediateTensorInfo(b)),x},dF={kernelName:ia,backendName:"webgl",kernelFunc:fee};function hee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a}=o,i=t.readSync(n.dataId),p=t.readSync(s.dataId),u=Ch(i,p,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var fF={kernelName:Tn,backendName:"webgl",kernelFunc:hee};var gee=`
int r = int(a.r) & int(b.r);
int g = int(a.g) & int(b.g);
int rb = int(a.b) & int(b.b);
int ra = int(a.a) & int(b.a);
return vec4(r, g, rb, ra);
`,xee=`
return float(int(a.r) & int(b.r));
`;function yee(r){let{inputs:e,backend:t}=r,{a:o,b:n}=e,s=A().getBool("WEBGL_PACK_BINARY_OPERATIONS"),a=A().getNumber("WEBGL_VERSION");if(t.shouldExecuteOnCPU([o,n])||a===1){let p=t.texData.get(o.dataId).values,u=t.texData.get(n.dataId).values,[l,c]=kD(o.shape,n.shape,p,u,o.dtype),m=t.makeTensorInfo(c,o.dtype),d=t.texData.get(m.dataId);return d.values=l,m}let i;return s?i=new eo(gee,o.shape,n.shape,!1):i=new Br(xee,o.shape,n.shape),t.runWebGLProgram(i,[o,n],o.dtype)}var hF={kernelName:_n,backendName:"webgl",kernelFunc:yee};function bee(r){let{inputs:e,backend:t}=r,{s0:o,s1:n}=e,s=t.readSync(o.dataId),a=t.readSync(n.dataId),i=C.assertAndGetBroadcastShape(Array.from(s),Array.from(a));return t.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var gF={kernelName:ua,backendName:"webgl",kernelFunc:bee};var Cee="return float(a != b);",P0=st({opSnippet:Cee,cpuKernelImpl:KD,dtype:"bool"}),xF={kernelName:Ro,backendName:"webgl",kernelFunc:P0};function _i(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return Ft({inputs:{x:n.complexTensorInfos.real},backend:t})}var yF={kernelName:si,backendName:"webgl",kernelFunc:_i};var wee="return float(int(x));";function bF(r,e){let t=new nr(r.shape,wee),o=e.runWebGLProgram(t,[r],"int32");return{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}function O0(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dtype:s}=o;if(s==="complex64"){if(n.dtype==="complex64")return Ft({inputs:{x:n},backend:t});let a=Yr(n.shape),i=O0({inputs:{x:n},backend:t,attrs:{dtype:"float32"}}),p=zr({inputs:{real:i,imag:a},backend:t});return a.dispose(),t.disposeIntermediateTensorInfo(i),p}if(n.dtype==="complex64"){let a=_i({inputs:{input:n},backend:t}),i=O0({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!y.hasEncodingLoss(n.dtype,s)){let a=Ft({inputs:{x:n},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(t.shouldExecuteOnCPU([n])){let a=t.texData.get(n.dataId).values,[i,p,u]=ND(a,n.shape,n.dtype,s);return t.makeTensorInfo(i,p,u)}if(s==="int32")return bF(n,t);if(s==="bool"){let a=t.makeTensorInfo([],"bool",y.getTypedArrayFromDType("bool",1)),p=P0({inputs:{a:n,b:a},backend:t});return t.disposeIntermediateTensorInfo(a),p}throw new Error(`Error in Cast: failed to cast ${n.dtype} to ${s}`)}var CF={kernelName:ho,backendName:"webgl",kernelFunc:O0};var wF="return ceil(x);",See=xe({opSnippet:wF,packedOpSnippet:wF,cpuKernelImpl:TD}),SF={kernelName:go,backendName:"webgl",kernelFunc:See};var Wh=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`}};var Uh=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`}};function Iee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{clipValueMin:s,clipValueMax:a}=o,i;A().getBool("WEBGL_PACK_CLIP")?i=new Uh(n.shape):i=new Wh(n.shape);let p=[[s],[a]];return t.runWebGLProgram(i,[n],n.dtype,p)}var IF={kernelName:Go,backendName:"webgl",kernelFunc:Iee};var Gh=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
`}};function vF(r,e){return{dataId:e.dataId,dtype:e.dtype,shape:r.shape}}function vee(r){let{inputs:e,backend:t}=r,{x:o}=e,n=t.texData.get(o.dataId),s=new Gh(o.shape),a=[vF(o,n.complexTensorInfos.real),vF(o,n.complexTensorInfos.imag)];return t.runWebGLProgram(s,a,a[0].dtype)}var kF={kernelName:Wi,backendName:"webgl",kernelFunc:vee};var Hh=class{constructor(e){this.outputShape=[],this.outputShape=C.computeOutShape(e,1),this.variableNames=e.map((a,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let o=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let i=t[a-1];o.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${i}));`)}let n=t.length,s=t[t.length-1];o.push(`else setOutput(getT${n}(yR, yC-${s}));`),this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${o.join(`
`)}
}
`}};var qh=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=C.computeOutShape(e,t);let o=this.outputShape,n=o.length,s=Re(n),a=At("coords",n),i=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((h,g)=>`T${g}`);let p=new Array(e.length-1);p[0]=e[0][t];for(let h=1;h<p.length;h++)p[h]=p[h-1]+e[h][t];let u=i[t],l=i.slice(-2),c=i.join(),m=`if (${u} < ${p[0]}) {
2022-11-18 17:13:29 +01:00
return getChannel(
getT0(${c}), vec2(${l.join()}));
2022-11-18 17:13:29 +01:00
}`;for(let h=1;h<p.length;h++){let g=p[h-1];m+=`
if (${u} < ${p[h]} && ${u} >= ${p[h-1]}) {
return getChannel(
getT${h}(${Kh(i,u,g)}),
vec2(${Kh(l,u,g)}));
2022-11-20 22:20:02 +01:00
}`}let d=p.length,f=p[p.length-1];m+=`
2022-11-18 17:13:29 +01:00
return getChannel(
getT${d}(${Kh(i,u,f)}),
vec2(${Kh(l,u,f)}));`,this.userCode=`
2022-11-18 17:13:29 +01:00
float getValue(${i.map(h=>"int "+h)}) {
${m}
}
void main() {
${s} coords = getOutputCoords();
vec4 result = vec4(getValue(${a}), 0., 0., 0.);
${a[n-1]} = ${a[n-1]} + 1;
if (${a[n-1]} < ${o[n-1]}) {
result.g = getValue(${a});
}
${a[n-2]} = ${a[n-2]} + 1;
if (${a[n-2]} < ${o[n-2]}) {
result.a = getValue(${a});
}
${a[n-1]} = ${a[n-1]} - 1;
if (${a[n-2]} < ${o[n-2]} &&
${a[n-1]} < ${o[n-1]}) {
result.b = getValue(${a});
}
setOutput(result);
}
`}};function Kh(r,e,t){let o=r.indexOf(e);return r.map((s,a)=>a===o?`${s} - ${t}`:s).join()}function Ep(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return Ft({inputs:{x:n.complexTensorInfos.imag},backend:t})}var NF={kernelName:Qi,backendName:"webgl",kernelFunc:Ep};function Kl(r,e,t){let o=r[0].dtype;if(o==="complex64"){let d=r.map(b=>_i({inputs:{input:b},backend:t})),f=r.map(b=>Ep({inputs:{input:b},backend:t})),h=Kl(d,e,t),g=Kl(f,e,t),x=zr({inputs:{real:h,imag:g},backend:t});return d.forEach(b=>t.disposeIntermediateTensorInfo(b)),f.forEach(b=>t.disposeIntermediateTensorInfo(b)),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),x}let n=t.shouldExecuteOnCPU(r);if(o==="string"&&(n=!0),n){let d=r.map(S=>{let T=[-1,y.sizeFromShape(S.shape.slice(e))];return te({inputs:{x:S},backend:t,attrs:{shape:T}})}),f=d.map(S=>({vals:t.readSync(S.dataId),shape:S.shape})),h=C.computeOutShape(d.map(S=>S.shape),1),g=d[0].shape[0]===1,x=_D(f,h,o,g),b=C.computeOutShape(r.map(S=>S.shape),e),w=t.makeTensorInfo(b,o,x);return d.forEach(S=>t.disposeIntermediateTensorInfo(S)),w}let s=r.filter(d=>y.sizeFromShape(d.shape)>0),a=A().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(s.length===1){let d=a?new nr(r[0].shape,Ha):new Lr(r[0].shape,Ha);return t.runWebGLProgram(d,r,o)}let i=A().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>i){let d=[];for(let h=0;h<s.length;h+=i){let g=s.slice(h,h+i);d.push(Kl(g,e,t))}let f=Kl(d,e,t);for(let h of d)t.disposeIntermediateTensorInfo(h);return f}if(a){let d=new qh(s.map(f=>f.shape),e);return t.runWebGLProgram(d,s,o)}let{tensors2D:p,outShape:u}=kee(s,e,t),l=new Hh(p.map(d=>d.shape)),c=t.runWebGLProgram(l,p,o);p.forEach(d=>t.disposeIntermediateTensorInfo(d));let m=te({inputs:{x:c},attrs:{shape:u},backend:t});return t.disposeIntermediateTensorInfo(c),m}function kee(r,e,t){let o=C.computeOutShape(r.map(s=>s.shape),e);return{tensors2D:r.map(s=>te({inputs:{x:s},attrs:{shape:[-1,y.sizeFromShape(s.shape.slice(e))]},backend:t})),outShape:o}}function M0(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=y.parseAxisParam(n,e[0].shape)[0],a=e.map(u=>u.shape);C.assertParamsConsistent(a,s);let i=C.computeOutShape(e.map(u=>u.shape),s);if(y.sizeFromShape(i)===0)return t.makeTensorInfo(i,e[0].dtype,[]);let p=e.filter(u=>y.sizeFromShape(u.shape)>0);return p.length===1?Ft({inputs:{x:p[0]},backend:t}):Kl(p,s,t)}var TF={kernelName:pa,backendName:"webgl",kernelFunc:M0};var ql=class{constructor(e,t=!1,o=null,n=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,i=e.padInfo.left,p=e.strideHeight,u=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,m=e.filterHeight,d=e.filterWidth,f=Math.floor(e.inChannels/4)*4,h=e.inChannels%4,g=e.dataFormat==="channelsLast",x=g?1:2,b=g?2:3,w=g?3:1,S="",k="";o&&(n?S=`float activation(float a) {
2022-11-18 17:13:29 +01:00
float b = getPreluActivationWeightsAtOutCoords();
${o}
2023-05-08 15:12:41 +02:00
}`:s?S=`float activation(float a) {
2022-11-18 17:13:29 +01:00
float b = getLeakyreluAlphaAtOutCoords();
${o}
2023-05-08 15:12:41 +02:00
}`:S=`
2022-11-18 17:13:29 +01:00
float activation(float x) {
${o}
}
`,k="result = activation(result);");let T=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
2023-05-08 15:12:41 +02:00
${S}
2022-11-18 17:13:29 +01:00
const ivec2 strides = ivec2(${p}, ${u});
const ivec2 pads = ivec2(${a}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${w}];
2022-11-18 17:13:29 +01:00
ivec2 xRCCorner =
2022-11-20 22:20:02 +01:00
ivec2(coords[${x}], coords[${b}]) * strides - pads;
2022-11-18 17:13:29 +01:00
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${l};
2022-11-18 17:13:29 +01:00
if (xR < 0 || xR >= ${e.inHeight}) {
2022-11-18 17:13:29 +01:00
continue;
}
2022-11-20 22:20:02 +01:00
for (int wC = 0; wC < ${d}; wC++) {
int xC = xCCorner + wC * ${c};
2022-11-18 17:13:29 +01:00
if (xC < 0 || xC >= ${e.inWidth}) {
2022-11-18 17:13:29 +01:00
continue;
}
2022-11-20 22:20:02 +01:00
for (int d1 = 0; d1 < ${f}; d1 += 4) {
2022-11-18 17:13:29 +01:00
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (${g}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (${h===1}) {
if (${g}) {
dotProd +=
2022-11-20 22:20:02 +01:00
getX(batch, xR, xC, ${f}) *
getW(wR, wC, ${f}, d2);
2022-11-18 17:13:29 +01:00
} else {
dotProd +=
2022-11-20 22:20:02 +01:00
getX(batch, ${f}, xR, xC) *
getW(wR, wC, ${f}, d2);
2022-11-18 17:13:29 +01:00
}
} else if (${h===2}) {
vec2 wValues = vec2(
2022-11-20 22:20:02 +01:00
getW(wR, wC, ${f}, d2),
getW(wR, wC, ${f} + 1, d2)
2022-11-18 17:13:29 +01:00
);
if (${g}) {
vec2 xValues = vec2(
2022-11-20 22:20:02 +01:00
getX(batch, xR, xC, ${f}),
getX(batch, xR, xC, ${f} + 1)
2022-11-18 17:13:29 +01:00
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
2022-11-20 22:20:02 +01:00
getX(batch, ${f}, xR, xC),
getX(batch, ${f} + 1, xR, xC)
2022-11-18 17:13:29 +01:00
);
dotProd += dot(xValues, wValues);
}
} else if (${h===3}) {
vec3 wValues = vec3(
2022-11-20 22:20:02 +01:00
getW(wR, wC, ${f}, d2),
getW(wR, wC, ${f} + 1, d2),
getW(wR, wC, ${f} + 2, d2)
2022-11-18 17:13:29 +01:00
);
if (${g}) {
vec3 xValues = vec3(
2022-11-20 22:20:02 +01:00
getX(batch, xR, xC, ${f}),
getX(batch, xR, xC, ${f} + 1),
getX(batch, xR, xC, ${f} + 2)
2022-11-18 17:13:29 +01:00
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
2022-11-20 22:20:02 +01:00
getX(batch, ${f}, xR, xC),
getX(batch, ${f} + 1, xR, xC),
getX(batch, ${f} + 2, xR, xC)
2022-11-18 17:13:29 +01:00
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${T}
2022-11-18 17:13:29 +01:00
${k}
setOutput(result);
}
`}},jh=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,o=e.padInfo.top,n=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,p=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.filterDepth,m=e.filterHeight,d=e.filterWidth,f=Math.floor(e.inChannels/4)*4,h=e.inChannels%4;this.userCode=`
2022-11-18 17:13:29 +01:00
const ivec3 strides = ivec3(${s}, ${a}, ${i});
const ivec3 pads = ivec3(${t}, ${o}, ${n});
2022-11-18 17:13:29 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${c}; wF++) {
2022-11-18 17:13:29 +01:00
int xF = xFCorner + wF * ${p};
if (xF < 0 || xF >= ${e.inDepth}) {
2022-11-18 17:13:29 +01:00
continue;
}
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${u};
if (xR < 0 || xR >= ${e.inHeight}) {
2022-11-18 17:13:29 +01:00
continue;
}
2022-11-20 22:20:02 +01:00
for (int wC = 0; wC < ${d}; wC++) {
int xC = xCCorner + wC * ${l};
2022-11-18 17:13:29 +01:00
if (xC < 0 || xC >= ${e.inWidth}) {
2022-11-18 17:13:29 +01:00
continue;
}
2022-11-20 22:20:02 +01:00
for (int d1 = 0; d1 < ${f}; d1 += 4) {
2022-11-18 17:13:29 +01:00
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (${h===1}) {
dotProd +=
2022-11-20 22:20:02 +01:00
getX(batch, xF, xR, xC, ${f}) *
getW(wF, wR, wC, ${f}, d2);
2022-11-18 17:13:29 +01:00
} else if (${h===2}) {
vec2 xValues = vec2(
2022-11-20 22:20:02 +01:00
getX(batch, xF, xR, xC, ${f}),
getX(batch, xF, xR, xC, ${f} + 1)
2022-11-18 17:13:29 +01:00
);
vec2 wValues = vec2(
2022-11-20 22:20:02 +01:00
getW(wF, wR, wC, ${f}, d2),
getW(wF, wR, wC, ${f} + 1, d2)
2022-11-18 17:13:29 +01:00
);
dotProd += dot(xValues, wValues);
} else if (${h===3}) {
vec3 xValues = vec3(
2022-11-20 22:20:02 +01:00
getX(batch, xF, xR, xC, ${f}),
getX(batch, xF, xR, xC, ${f} + 1),
getX(batch, xF, xR, xC, ${f} + 2)
2022-11-18 17:13:29 +01:00
);
vec3 wValues = vec3(
2022-11-20 22:20:02 +01:00
getW(wF, wR, wC, ${f}, d2),
getW(wF, wR, wC, ${f} + 1, d2),
getW(wF, wR, wC, ${f} + 2, d2)
2022-11-18 17:13:29 +01:00
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`}};var jl=class{constructor(e,t=!1,o=null,n=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=lt(this.outputShape.length);let a=e.padInfo.left,i=e.strideWidth,p=e.dilationWidth,u=e.filterHeight,l=e.filterWidth,c=l,m=`
2022-11-18 17:13:29 +01:00
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<l;g++)m+=`
2022-11-18 17:13:29 +01:00
vec4 xTexelC${g*2};
int xTexelC${g*2}Ready;
vec4 xTexelC${g*2+1};
int xTexelC${g*2+1}Ready;
vec4 xC${g};`;m+=`
for (int r = 0; r < ${u}; r++) {
for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {
`;for(let g=0;g<l;g++)m+=`
2022-11-18 17:13:29 +01:00
xTexelC${g*2} = vec4(0.0);
xTexelC${g*2}Ready = 0;
xTexelC${g*2+1} = vec4(0.0);
xTexelC${g*2+1}Ready = 0;
xC${g} = vec4(0.0);`;m+=`
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;for(let g=0;g<(c+1)/2;g++){let x=g*2;if(m+=`
2022-11-20 22:20:02 +01:00
xC = xCCorner + ${x*p};
`,i===1){if(x<l&&(a%2===1?(m+=`
2022-11-18 17:13:29 +01:00
xCOffset = xC + 1;
2022-11-20 22:20:02 +01:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = getX(batch, xR, xCOffset, d1);
2022-11-18 17:13:29 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
2022-11-20 22:20:02 +01:00
xTexelC${x}.zw = vec2(0.0);
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xTexelC${x}Ready = 1;
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
`,p===1&&x>0?m+=`
xC${x} = vec4(xTexelC${x-2}.zw, xTexelC${x}.xy);
2022-11-18 17:13:29 +01:00
`:m+=`
xCOffset = xC + 1 - 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
2022-11-20 22:20:02 +01:00
xC${x} = vec4(previous.zw, xTexelC${x}.xy);
2022-11-18 17:13:29 +01:00
} else {
2022-11-20 22:20:02 +01:00
xC${x} = vec4(0.0, 0.0, xTexelC${x}.xy);
2022-11-18 17:13:29 +01:00
}
`):m+=`
2022-11-20 22:20:02 +01:00
if (xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = getX(batch, xR, xC, d1);
2022-11-18 17:13:29 +01:00
if (xC + 1 >= inDims[1]) {
2022-11-20 22:20:02 +01:00
xTexelC${x}.zw = vec2(0.0);
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xTexelC${x}Ready = 1;
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xC${x} = xTexelC${x};
`,x+1<l)){let b=a%2===0?y.nearestLargerEven(p):p;p%2===0&&a%2===1||p%2!==0&&a%2!==1?(m+=`
2022-11-18 17:13:29 +01:00
xCOffset = xC + imod(pads[1], 2) + ${b};
2022-11-20 22:20:02 +01:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
2022-11-18 17:13:29 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
2022-11-20 22:20:02 +01:00
xTexelC${x+1}.zw = vec2(0.0);
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xTexelC${x+1}Ready = 1;
2022-11-18 17:13:29 +01:00
}
`,p>1?m+=`
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
2022-11-20 22:20:02 +01:00
xC${x+1} = vec4(previous.zw, xTexelC${x+1}.xy);
2022-11-18 17:13:29 +01:00
} else {
2022-11-20 22:20:02 +01:00
xC${x+1} = vec4(0.0, 0.0, xTexelC${x+1}.xy);
2022-11-18 17:13:29 +01:00
}
`:m+=`
2022-11-20 22:20:02 +01:00
xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.xy);
2022-11-18 17:13:29 +01:00
`):b===1?m+=`
2022-11-20 22:20:02 +01:00
xC${x+1} = xTexelC${x};
2022-11-18 17:13:29 +01:00
`:m+=`
xCOffset = xC + ${b};
2022-11-20 22:20:02 +01:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
2022-11-18 17:13:29 +01:00
if (xCOffset + 1 >= inDims[1]) {
2022-11-20 22:20:02 +01:00
xTexelC${x+1}.zw = vec2(0.0);
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xTexelC${x+1}Ready = 1;
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xC${x+1} = xTexelC${x+1};
`}}else x<l&&(a%2===1?(m+=`
2022-11-18 17:13:29 +01:00
xCOffset = xC + 1 - strides[1];
2022-11-20 22:20:02 +01:00
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = getX(batch, xR, xCOffset, d1);
2022-11-18 17:13:29 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
2022-11-20 22:20:02 +01:00
xTexelC${x}.zw = vec2(0.0);
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xTexelC${x}Ready = 1;
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${x+1}Ready == 0) {
xTexelC${x+1} = getX(batch, xR, xC + 1, d1);
2022-11-18 17:13:29 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
2022-11-20 22:20:02 +01:00
xTexelC${x+1}.zw = vec2(0.0);
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xTexelC${x+1}Ready = 1;
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xC${x} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw);
`,x+1<l&&(m+=`
2022-11-18 17:13:29 +01:00
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
2022-11-20 22:20:02 +01:00
xC${x+1} = vec4(xTexelC${x+1}.xy, final.xy);
2022-11-18 17:13:29 +01:00
`)):(m+=`
2022-11-20 22:20:02 +01:00
if(xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = getX(batch, xR, xC, d1);
2022-11-18 17:13:29 +01:00
if (xC + 1 >= inDims[1]) {
2022-11-20 22:20:02 +01:00
xTexelC${x}.zw = vec2(0.0);
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xTexelC${x}Ready = 1;
2022-11-18 17:13:29 +01:00
}
xCOffset = xC + strides[1];
2022-11-20 22:20:02 +01:00
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
2022-11-18 17:13:29 +01:00
if (xCOffset + 1 >= inDims[1]) {
2022-11-20 22:20:02 +01:00
xTexelC${x+1}.zw = vec2(0.);
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xTexelC${x+1}Ready = 1;
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
xC${x} = vec4(
xTexelC${x}.xy, xTexelC${x+1}.xy);
`,x+1<l&&(m+=`
2022-11-20 22:20:02 +01:00
xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw);
`)));x<l&&(m+=`
2022-11-20 22:20:02 +01:00
wTexel = getW(r, ${x}, d1, d2);
dotProd += xC${x}.xxzz * vec4(wTexel.xy, wTexel.xy);
if(d1 + 1 < ${e.inChannels}) {
2022-11-20 22:20:02 +01:00
dotProd += xC${x}.yyww * vec4(wTexel.zw, wTexel.zw);
2022-11-18 17:13:29 +01:00
}
`,x+1<l&&(m+=`
2022-11-20 22:20:02 +01:00
wTexel = getW(r, ${x+1}, d1, d2);
dotProd += xC${x+1}.xxzz * vec4(wTexel.xy, wTexel.xy);
if(d1 + 1 < ${e.inChannels}) {
2022-11-20 22:20:02 +01:00
dotProd += xC${x+1}.yyww * vec4(wTexel.zw, wTexel.zw);
2022-11-18 17:13:29 +01:00
}
`))}m+=`
}
`,m+=`
}
`,m+=`
}
2022-11-20 22:20:02 +01:00
`;let d="",f="";o&&(n?d=`vec4 activation(vec4 a) {
2022-11-18 17:13:29 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
2022-11-20 22:20:02 +01:00
}`:s?d=`vec4 activation(vec4 a) {
2022-11-18 17:13:29 +01:00
vec4 b = getLeakyreluAlphaAtOutCoords();
${o}
2022-11-20 22:20:02 +01:00
}`:d=`vec4 activation(vec4 x) {
2022-11-18 17:13:29 +01:00
${o}
}`,f="result = activation(result);");let h=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
2022-11-20 22:20:02 +01:00
${d}
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${m}
vec4 result = dotProd - vec4(0.000000000000001);
${h}
2022-11-20 22:20:02 +01:00
${f}
2022-11-18 17:13:29 +01:00
setOutput(result);
}
`}};var Xh=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=lt(this.outputShape.length);let{dataFormat:o}=t,n=kt(),s=o==="channelsLast",a=s?1:2,i=s?2:3,p=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`,u="";for(let l=0;l<=1;l++)for(let c=0;c<=1;c++)u+=`
blockIndex = rc.z + ${c};
pos = rc.y + ${l};
2022-11-18 17:13:29 +01:00
${p}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
if(d0 < inputShape[${a}] && d0 >= 0) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
inChannels);
if(d1 < inputShape[${i}] && d1 >= 0) {
ch = imod(pos, inChannels);
if (${s}) {
innerDims = vec2(d1, ch);
result[${l*2+c}] = getChannel(
2022-11-18 17:13:29 +01:00
getA(rc.x, d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${l*2+c}] = getChannel(
2022-11-18 17:13:29 +01:00
getA(rc.x, ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${u}
${n.output} = result;
}
`}};function Yh(r,e){let t=r.length;return t>=3?e?[...r.slice(0,-3),r[t-3]*r[t-2],r[t-1]]:[...r.slice(0,-3),r[t-3],r[t-2]*r[t-1]]:!e&&t===1&&r[0]>1?[r[0],1]:null}function Qh({x:r,filter:e,convInfo:t,backend:o,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let p=r.shape,u=o.texData.get(r.dataId),l=t.inChannels,c=p[0]*p[1]*p[2],m=t.outChannels,d=t.dataFormat==="channelsLast",f=!1,h=!1,g,x=[];if(s!=null){let S=Yh(s.shape,d);S!=null&&(s=te({inputs:{x:s},backend:o,attrs:{shape:S}}),x.push(s))}if(n!=null){let S=Yh(n.shape,d);S!=null&&(n=te({inputs:{x:n},backend:o,attrs:{shape:S}}),x.push(n))}if(!((c===1||m===1)&&l>A0)&&u.isPacked&&d&&u.texture!=null&&p[2]%2!==0&&y.arraysEqual(u.shape.slice(-3),p.slice(-3))){let S=p[0]*p[1]*(p[2]+1),k={dataId:r.dataId,shape:[1,S,t.inChannels],dtype:r.dtype},T=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,y.assert(vu(u.shape,k.shape),()=>`packed reshape ${u.shape} to ${k.shape} isn't free`);let E=te({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}});x.push(E);let R=_p({a:k,b:E,backend:o,transposeA:f,transposeB:h,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a}),D=o.texData.get(R.dataId);y.assert(D.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=T,D.shape=t.outShape,g=Ft({inputs:{x:R},backend:o}),g.shape=t.outShape,x.push(R)}else{let S=t.outHeight*t.outWidth,k=te({inputs:{x:r},backend:o,attrs:{shape:d?[t.batchSize,S,t.inChannels]:[t.batchSize,t.inChannels,S]}}),T=te({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}}),E=_p({a:d?k:T,b:d?T:k,transposeA:!d,transposeB:h,backend:o,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a});g=te({inputs:{x:E},backend:o,attrs:{shape:t.outShape}}),x.push(k),x.push(T),x.push(E)}for(let S of x)o.disposeIntermediateTensorInfo(S);return g}function Zh({x:r,filter:e,convInfo:t,backend:o,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let{filterWidth:p,filterHeight:u,inChannels:l,outWidth:c,outHeight:m,dataFormat:d}=t,f=d==="channelsLast",h=p*u*l,g=m*c,x=[t.batchSize,h,g],b=!0,w=!1,S=[];if(s!=null){let q=Yh(s.shape,f);q!=null&&(s=te({inputs:{x:s},backend:o,attrs:{shape:q}}),S.push(s))}if(n!=null){let q=Yh(n.shape,f);q!=null&&(n=te({inputs:{x:n},backend:o,attrs:{shape:q}}),S.push(n))}let k=te({inputs:{x:e},backend:o,attrs:{shape:[1,h,y.sizeFromShape(e.shape)/h]}});S.push(k);let T=new Xh(x,t),E=[r.shape,[t.padInfo.top,t.padInfo.left],[t.strideHeight,t.strideWidth],[t.dilationHeight,t.dilationWidth],[t.inChannels],[t.filterWidth*t.inChannels],[t.outWidth]],R=o.runWebGLProgram(T,[r],"float32",E),D=te({inputs:{x:R},backend:o,attrs:{shape:x}});S.push(R),S.push(D);let F=n!=null,O=s!=null,M=i==="leakyrelu",L=i?Ti(i,!0):null,B=new Hl(f?D.shape:k.shape,f?k.shape:D.shape,f?[t.batchSize,g,t.outChannels]:[t.batchSize,t.outChannels,g],b,w,F,L,O,M),z=f?[D,k]:[k,D];if(n&&z.push(n),O&&z.push(s),M){let q=o.makeTensorInfo([],"float32",y.createScalarValue(a,"float32"));z.push(q),S.push(q)}let U=o.runWebGLProgram(B,z,"float32"),j=te({inputs:{x:U},backend:o,attrs:{shape:t.outShape}});S.push(U);for(let q of S)o.disposeIntermediateTensorInfo(q);return j}function Nee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dataFormat:p,dilations:u,dimRoundingMode:l}=o,c=C.convertConv2DDataFormat(p),m=C.computeConv2DInfo(n.shape,s.shape,a,u,i,l,!1,c),d;if(m.filterHeight===1&&m.filterWidth===1&&m.dilationHeight===1&&m.dilationWidth===1&&m.strideHeight===1&&m.strideWidth===1&&(m.padInfo.type==="SAME"||m.padInfo.type==="VALID"))d=Qh({x:n,filter:s,convInfo:m,backend:t});else if(m.strideWidth<=2&&c==="channelsLast"&&A().getBool("WEBGL_EXP_CONV")){let h=new jl(m),g=[[m.padInfo.top,m.padInfo.left],[m.strideHeight,m.strideWidth],[m.dilationHeight,m.dilationWidth],[m.inHeight,m.inWidth]];d=t.runWebGLProgram(h,[n,s],"float32",g)}else if(A().getBool("WEBGL_CONV_IM2COL"))d=Zh({x:n,filter:s,convInfo:m,backend:t});else{let h=new ql(m);d=t.runWebGLProgram(h,[n,s],"float32")}let f=te({inputs:{x:d},backend:t,attrs:{shape:m.outShap
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${n};
2022-11-18 17:13:29 +01:00
if (xR < 0 || xR >= ${e.inHeight}) {
2022-11-18 17:13:29 +01:00
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
2022-11-18 17:13:29 +01:00
int xC = wC + yC * ${o} - ${s};
if (xC < 0 || xC >= ${e.inWidth}) {
2022-11-18 17:13:29 +01:00
continue;
}
2023-05-08 15:12:41 +02:00
${a?`float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);`}
2022-11-18 17:13:29 +01:00
}
}
}
setOutput(dotProd);
}
`}},eg=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,o=e.filterWidth,n=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,p=o-1-e.padInfo.left,u=a?1:2,l=a?2:3,c=a?3:1;this.userCode=`
2022-11-18 17:13:29 +01:00
const ivec2 pads = ivec2(${i}, ${p});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${c}];
2022-11-18 17:13:29 +01:00
ivec2 dyCorner = ivec2(coords[${u}], coords[${l}]) - pads;
2022-11-18 17:13:29 +01:00
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
2022-11-18 17:13:29 +01:00
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2022-11-18 17:13:29 +01:00
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
2022-11-18 17:13:29 +01:00
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${o} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
2022-11-18 17:13:29 +01:00
if (${a}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}},tg=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,o=e.strideHeight,n=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,i=e.padInfo.left;this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${s};
2022-11-18 17:13:29 +01:00
if (xF < 0 || xF >= ${e.inDepth}) {
2022-11-18 17:13:29 +01:00
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
2022-11-18 17:13:29 +01:00
int xR = wR + yR * ${o} - ${a};
if (xR < 0 || xR >= ${e.inHeight}) {
2022-11-18 17:13:29 +01:00
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
2022-11-18 17:13:29 +01:00
int xC = wC + yC * ${n} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
2022-11-18 17:13:29 +01:00
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}},rg=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,o=e.filterHeight,n=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,p=t-1-e.padInfo.front,u=o-1-e.padInfo.top,l=n-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${p}, ${u}, ${l});
2022-11-18 17:13:29 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
2022-11-18 17:13:29 +01:00
float dyF = float(dyFCorner + wF) / ${s}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
2022-11-18 17:13:29 +01:00
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
2022-11-18 17:13:29 +01:00
for (int wR = 0; wR < ${o}; wR++) {
float dyR = float(dyRCorner + wR) / ${a}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${o} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
2022-11-18 17:13:29 +01:00
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}};function Tee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,dataFormat:p,dimRoundingMode:u,filterShape:l}=o,c=C.convertConv2DDataFormat(p),m=C.computeConv2DInfo(n.shape,l,a,1,i,u,!1,c),d=new Jh(m);return t.runWebGLProgram(d,[n,s],"float32")}var EF={kernelName:Ui,backendName:"webgl",kernelFunc:Tee};var og=class{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=lt(this.outputShape.length);let t=e.filterHeight,o=e.filterWidth,n=t-1-e.padInfo.top,s=o-1-e.padInfo.left;this.userCode=`
2023-05-08 15:12:41 +02:00
const ivec2 pads = ivec2(${n}, ${s});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
vec4 result = vec4(0.);
for (int wR = 0; wR < ${t}; wR++) {
2023-05-08 15:12:41 +02:00
float dyR = float(dyRCorner + wR) / strides[0];
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2023-05-08 15:12:41 +02:00
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
2023-05-08 15:12:41 +02:00
for (int wC = 0; wC < ${o}; wC++) {
int wCPerm = ${o} - 1 - wC;
float dyC = float(dyCCorner + wC) / strides[1];
bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)
2023-05-08 15:12:41 +02:00
&& (fract(dyC) == 0.0);
int idyC = int(dyC);
float dyC2 = float(dyCCorner + wC + 1) / strides[1];
bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)
2023-05-08 15:12:41 +02:00
&& (fract(dyC2) == 0.0);
int idyC2 = int(dyC2);
if (idyCVal && idyCVal2) {
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
2023-05-08 15:12:41 +02:00
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
vec4 dySample = getDy(batch, idyR, idyC, d2);
vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?
dySample : getDy(batch, idyR, idyC2, d2);
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
dySample.xy : dySample.zw;
result.xy += vec2(dot(dyValue, wValue.xy),
dot(dyValue, wValue.zw));
dyValue = mod(float(idyC2), 2.) == 0. ?
dySample2.xy : dySample2.zw;
result.zw += vec2(dot(dyValue, wValue.xy),
dot(dyValue, wValue.zw));
}
} else if (idyCVal) {
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
2023-05-08 15:12:41 +02:00
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
vec4 dySample = getDy(batch, idyR, idyC, d2);
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
dySample.xy : dySample.zw;
result.xy += vec2(dot(dyValue, wValue.xy),
dot(dyValue, wValue.zw));
}
} else if (idyCVal2) {
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
2023-05-08 15:12:41 +02:00
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
vec4 dySample = getDy(batch, idyR, idyC2, d2);
vec2 dyValue = mod(float(idyC2), 2.) == 0. ?
dySample.xy : dySample.zw;
result.zw += vec2(dot(dyValue, wValue.xy),
dot(dyValue, wValue.zw));
}
}
}
}
setOutput(result);
}
`}};function _ee(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{inputShape:a,strides:i,pad:p,dataFormat:u,dimRoundingMode:l}=o,c=C.convertConv2DDataFormat(u),m=C.computeConv2DInfo(a,s.shape,i,1,p,l,!1,c);if(A().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&c==="channelsLast"){let d=[[m.strideHeight,m.strideWidth]],f=new og(m);return t.runWebGLProgram(f,[n,s],"float32",d)}else{let d=new eg(m);return t.runWebGLProgram(d,[n,s],"float32")}}var $F={kernelName:$n,backendName:"webgl",kernelFunc:_ee};function Eee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:p}=o,u=C.computeConv3DInfo(n.shape,s.shape,a,p,i),l=new jh(u);return t.runWebGLProgram(l,[n,s],"float32")}var RF={kernelName:Rn,backendName:"webgl",kernelFunc:Eee};function $ee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,filterShape:p}=o,u=C.computeConv3DInfo(n.shape,p,a,1,i),l=new tg(u);return t.runWebGLProgram(l,[n,s],"float32")}var DF={kernelName:ti,backendName:"webgl",kernelFunc:$ee};function Ree(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{pad:a,strides:i,inputShape:p}=o,u=C.computeConv3DInfo(p,s.shape,i,1,a),l=new rg(u);return t.runWebGLProgram(l,[n,s],"float32")}var AF={kernelName:Dn,backendName:"webgl",kernelFunc:Ree};var Dee=sn+`
2022-11-18 17:13:29 +01:00
return cos(x);
`,Aee=`
2023-05-08 15:12:41 +02:00
vec4 result = cos(x);
bvec4 isNaN = isnan(x);
${to}
2023-05-08 15:12:41 +02:00
return result;
`,Fee=xe({opSnippet:Dee,packedOpSnippet:Aee}),FF={kernelName:An,backendName:"webgl",kernelFunc:Fee};var Pee=`
2022-11-18 17:13:29 +01:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,Oee=xe({opSnippet:Pee}),PF={kernelName:Fn,backendName:"webgl",kernelFunc:Oee};var ng=class{constructor(e,t,o,n,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,i,p,u]=e,[l]=t,[c,m]=o;this.outputShape=[l,c,m,u];let d=n==="bilinear"?1:0,[f,h]=[`${i-1}.0`,`${p-1}.0`],[g,x,b]=c>1?[`${(i-1)/(c-1)}`,"(y2-y1) * height_ratio",`y1*${f} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${f}`],[w,S,k]=m>1?[`${(p-1)/(m-1)}`,"(x2-x1) * width_ratio",`x1*${h} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${h}`];this.userCode=`
2022-11-18 17:13:29 +01:00
const float height_ratio = float(${g});
const float width_ratio = float(${w});
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${a}) {
return;
}
2022-11-20 22:20:02 +01:00
float height_scale = ${x};
2023-05-08 15:12:41 +02:00
float width_scale = ${S};
2022-11-18 17:13:29 +01:00
float in_y = ${b};
2022-11-20 22:20:02 +01:00
if( in_y < 0.0 || in_y > ${f} ) {
2022-11-18 17:13:29 +01:00
setOutput(float(${s}));
return;
}
float in_x = ${k};
if( in_x < 0.0 || in_x > ${h} ) {
setOutput(float(${s}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
2022-11-20 22:20:02 +01:00
if(${d} == 1) {
2022-11-18 17:13:29 +01:00
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
`}};var Mee=r=>{let{inputs:e,backend:t,attrs:o}=r,{image:n,boxes:s,boxInd:a}=e,{cropSize:i,method:p,extrapolationValue:u}=o,l=new ng(n.shape,s.shape,i,p,u);return t.runWebGLProgram(l,[n,s,a],"float32")},OF={kernelName:Mn,backendName:"webgl",kernelFunc:Mee};var $p;(function(r){r.Prod="*",r.Sum="+"})($p||($p={}));var lm=class{constructor(e,t,o,n){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let s=this.outputShape.length,a=this.op===$p.Prod?"1.0":"0.0",i=o?a:`getX(${MF(s,"coords",this.op)})`,p=this.outputShape[this.outputShape.length-1],u="",l="";o?(u=n?`end != ${p-1}`:"end != 0",l=n?"end + 1":"end - 1"):(u=n?`end + pow2 < ${p}`:"end >= pow2",l=n?"end + pow2":"end - pow2"),this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
2023-05-08 15:12:41 +02:00
${Re(s)} coords = getOutputCoords();
int end = ${LF(s,"coords",this.op)};
2022-11-18 17:13:29 +01:00
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${u}) {
int idx = ${l};
${LF(s,"coords",this.op)} = idx;
val ${this.op}= getX(${MF(s,"coords",this.op)});
2022-11-18 17:13:29 +01:00
}
setOutput(val);
}
`}};function MF(r,e,t){if(r===1)return`${e}`;if(r===2)return`${e}.x, ${e}.y`;if(r===3)return`${e}.x, ${e}.y, ${e}.z`;if(r===4)return`${e}.x, ${e}.y, ${e}.z, ${e}.w`;throw new Error(`Cumulative ${t} for rank ${r} is not yet supported`)}function LF(r,e,t){if(r===1)return`${e}`;if(r===2)return`${e}.y`;if(r===3)return`${e}.z`;if(r===4)return`${e}.w`;throw new Error(`Cumulative ${t} for rank ${r} is not yet supported`)}function sg(r,e,t,o,n,s){let a=e.shape.length,i=C.getAxesPermutation([o],a),p=e;i!=null&&(p=Ct({inputs:{x:e},backend:t,attrs:{perm:i}}));let u=C.getInnerMostAxes(1,a)[0];if(u!==a-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${e.shape.length-1} but got axis=${o}`);let l=p.shape[u],c=Ft({inputs:{x:p},backend:t});for(let m=0;m<=Math.ceil(Math.log2(l))-1;m++){let d=new lm(r,p.shape,!1,s),f=[[m]],h=c;c=t.runWebGLProgram(d,[c],c.dtype,f),t.disposeIntermediateTensorInfo(h)}if(n){let m=new lm(r,p.shape,n,s),d=c;c=t.runWebGLProgram(m,[c],c.dtype),t.disposeIntermediateTensorInfo(d)}if(i!=null){let m=C.getUndoAxesPermutation(i),d=Ct({inputs:{x:c},backend:t,attrs:{perm:m}});return t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(p),d}return c}function Lee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o;return sg($p.Prod,n,t,s,a,i)}var BF={kernelName:Pn,backendName:"webgl",kernelFunc:Lee};function Bee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o;return sg($p.Sum,n,t,s,a,i)}var zF={kernelName:On,backendName:"webgl",kernelFunc:Bee};function zee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a,binaryOutput:i}=o;if(n.shape.length===1){let p=t.readSync(n.dataId),u=t.readSync(s.dataId),l=Ch(p,u,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,l)}else if(n.shape.length===2){let p=t.bufferSync(n),u=t.bufferSync(s),l=vD(p,u,a,i);return t.makeTensorInfo(l.shape,s.dtype,l.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${n.shape.length}.`)}var VF={kernelName:la,backendName:"webgl",kernelFunc:zee};var ag=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=o,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
2022-11-18 17:13:29 +01:00
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function Vee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockSize:s,dataFormat:a}=o,i=n.shape[0],p=a==="NHWC"?n.shape[1]:n.shape[2],u=a==="NHWC"?n.shape[2]:n.shape[3],l=a==="NHWC"?n.shape[3]:n.shape[1],c=p*s,m=u*s,d=l/(s*s),f=a==="NHWC"?[i,c,m,d]:[i,d,c,m],h=new ag(f,s,a);return t.runWebGLProgram(h,[n],n.dtype)}var WF={kernelName:Ln,backendName:"webgl",kernelFunc:Vee};var Xl=class{constructor(e,t=!1,o=null,n=!1,s=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=lt(this.outputShape.length);let a=e.filterHeight,i=e.filterWidth,p=e.outChannels/e.inChannels,u="",l="";o&&(n?u=`float activation(float a) {
2022-11-18 17:13:29 +01:00
float b = getPreluActivationWeightsAtOutCoords();
${o}
}`:s?u=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${o}
}`:u=`
float activation(float x) {
${o}
}
`,l="result = activation(result);");let c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
2022-11-18 17:13:29 +01:00
${u}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${p};
int q = d2 - d1 * ${p};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${a}; wR++) {
int xR = xRCorner + wR * dilations[0];
if (xR < 0 || xR >= inDims[0]) {
continue;
}
for (int wC = 0; wC < ${i}; wC++) {
int xC = xCCorner + wC * dilations[1];
if (xC < 0 || xC >= inDims[1]) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${c}
${l}
2022-11-18 17:13:29 +01:00
setOutput(result);
}
`}};var Yl=class{constructor(e,t=!1,o=null,n=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=lt(this.outputShape.length);let a=e.outChannels/e.inChannels,i=e.padInfo.left,p=e.strideWidth,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,m=c,d=`
2022-11-18 17:13:29 +01:00
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;for(let x=0;x<c;x++)d+=`
2022-11-20 22:20:02 +01:00
vec4 xTexelC${x*2};
int xTexelC${x*2}Ready;
vec4 xTexelC${x*2+1};
int xTexelC${x*2+1}Ready;
vec4 xC${x};`;d+=`
for (int r = 0; r < ${l}; r++) {
`;for(let x=0;x<c;x++)d+=`
2022-11-20 22:20:02 +01:00
xTexelC${x*2} = vec4(0.0);
xTexelC${x*2}Ready = 0;
xTexelC${x*2+1} = vec4(0.0);
xTexelC${x*2+1}Ready = 0;
xC${x} = vec4(0.0);`;d+=`
2022-11-18 17:13:29 +01:00
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
2022-11-20 22:20:02 +01:00
`;for(let x=0;x<(m+1)/2;x++){let b=x*2;if(d+=`
2022-11-18 17:13:29 +01:00
xC = xCCorner + ${b*u};
`,p===1){if(b<c&&(i%2===1?(d+=`
2022-11-18 17:13:29 +01:00
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
2022-11-20 22:20:02 +01:00
`,u===1&&b>0?d+=`
2022-11-18 17:13:29 +01:00
xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy);
2022-11-20 22:20:02 +01:00
`:d+=`
2022-11-18 17:13:29 +01:00
xCOffset = xC + 1 - 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
xC${b} = vec4(previous.zw, xTexelC${b}.xy);
} else {
xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
}
2022-11-20 22:20:02 +01:00
`):d+=`
2022-11-18 17:13:29 +01:00
if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
xC${b} = xTexelC${b};
`,b+1<c)){let w=i%2===0?y.nearestLargerEven(u):u;u%2===0&&i%2===1||u%2!==0&&i%2!==1?(d+=`
xCOffset = xC + imod(pads[1], 2) + ${w};
2022-11-18 17:13:29 +01:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b+1}.zw = vec2(0.0);
}
xTexelC${b+1}Ready = 1;
}
2022-11-20 22:20:02 +01:00
`,u>1?d+=`
2022-11-18 17:13:29 +01:00
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
xC${b+1} = vec4(previous.zw, xTexelC${b+1}.xy);
} else {
xC${b+1} = vec4(0.0, 0.0, xTexelC${b+1}.xy);
}
2022-11-20 22:20:02 +01:00
`:d+=`
2022-11-18 17:13:29 +01:00
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy);
`):w===1?d+=`
2022-11-18 17:13:29 +01:00
xC${b+1} = xTexelC${b};
2022-11-20 22:20:02 +01:00
`:d+=`
xCOffset = xC + ${w};
2022-11-18 17:13:29 +01:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b+1}.zw = vec2(0.0);
}
xTexelC${b+1}Ready = 1;
}
xC${b+1} = xTexelC${b+1};
`}}else b<c&&(i%2===1?(d+=`
2022-11-18 17:13:29 +01:00
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xC + 1, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
xTexelC${b+1}.zw = vec2(0.0);
}
xTexelC${b+1}Ready = 1;
}
xC${b} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
`,b+1<c&&(d+=`
2022-11-18 17:13:29 +01:00
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${b+1} = vec4(xTexelC${b+1}.xy, final.xy);
2022-11-20 22:20:02 +01:00
`)):(d+=`
2022-11-18 17:13:29 +01:00
if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${b}.zw = vec2(0.0);
}
xTexelC${b}Ready = 1;
}
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${b+1}.zw = vec2(0.);
}
xTexelC${b+1}Ready = 1;
}
xC${b} = vec4(
xTexelC${b}.xy, xTexelC${b+1}.xy);
`,b+1<c&&(d+=`
2022-11-18 17:13:29 +01:00
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
`)));b<c&&(d+=`
2022-11-18 17:13:29 +01:00
wTexel = getW(r, ${b}, d1, q);
dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
`,b+1<c&&(d+=`
2022-11-18 17:13:29 +01:00
wTexel = getW(r, ${b+1}, d1, q);
dotProd += xC${b+1} * vec4(wTexel.xz, wTexel.xz);
2022-11-20 22:20:02 +01:00
`))}d+=`
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
`,d+=`
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
`;let f="",h="";o&&(n?f=`vec4 activation(vec4 a) {
2022-11-18 17:13:29 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
2022-11-20 22:20:02 +01:00
}`:s?f=`vec4 activation(vec4 a) {
2022-11-18 17:13:29 +01:00
vec4 b = getLeakyreluAlphaAtOutCoords();
${o}
2022-11-20 22:20:02 +01:00
}`:f=`vec4 activation(vec4 x) {
2022-11-18 17:13:29 +01:00
${o}
}`,h="result = activation(result);");let g=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
2022-11-20 22:20:02 +01:00
${f}
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${a};
int q = d2 - d1 * ${a};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
2022-11-20 22:20:02 +01:00
${d}
2022-11-18 17:13:29 +01:00
vec4 result = dotProd - vec4(0.000000000000001);
${g}
${h}
setOutput(result);
}
`}};function Wee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:p,dimRoundingMode:u}=o,l=p;l==null&&(l=[1,1]),y.assert(C.eitherStridesOrDilationsAreOne(a,l),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${l}'`);let c=C.computeConv2DInfo(n.shape,s.shape,a,l,i,u,!0),m;A().getBool("WEBGL_PACK_DEPTHWISECONV")&&c.strideWidth<=2&&c.outChannels/c.inChannels===1?m=new Yl(c):m=new Xl(c);let d=[[c.padInfo.top,c.padInfo.left],[c.strideHeight,c.strideWidth],[c.dilationHeight,c.dilationWidth],[c.inHeight,c.inWidth]];return t.runWebGLProgram(m,[n,s],"float32",d)}var UF={kernelName:Bn,backendName:"webgl",kernelFunc:Wee};var ig=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,o=e.strideWidth,n=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${a} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${n};
2022-11-18 17:13:29 +01:00
if (xR < 0 || xR >= ${e.inHeight}) {
2022-11-18 17:13:29 +01:00
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
2022-11-18 17:13:29 +01:00
int xC = wC + yC * ${o} - ${s};
if (xC < 0 || xC >= ${e.inWidth}) {
2022-11-18 17:13:29 +01:00
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`}},ug=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,o=e.filterWidth,n=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,i=o-1-e.padInfo.left,p=e.outChannels/e.inChannels;this.userCode=`
2022-11-18 17:13:29 +01:00
const ivec2 pads = ivec2(${a}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
2022-11-18 17:13:29 +01:00
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2022-11-18 17:13:29 +01:00
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
2022-11-18 17:13:29 +01:00
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${o} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${p}; dm++) {
int d2 = d1 * ${p} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}};function Uee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,dilations:i,pad:p,dimRoundingMode:u,filterShape:l}=o,c=C.computeConv2DInfo(n.shape,l,a,i,p,u,!0),m=new ig(c);return t.runWebGLProgram(m,[n,s],"float32")}var GF={kernelName:Gi,backendName:"webgl",kernelFunc:Uee};function Gee(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{strides:a,dilations:i,pad:p,dimRoundingMode:u,inputShape:l}=o,c=C.computeConv2DInfo(l,s.shape,a,i,p,u,!0),m=new ug(c);return t.runWebGLProgram(m,[n,s],"float32")}var HF={kernelName:Hi,backendName:"webgl",kernelFunc:Gee};var pg=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`}};function Hee(r){let{inputs:e,backend:t}=r,{x:o}=e,n=[...o.shape,...o.shape],s=y.sizeFromShape(o.shape),a=te({inputs:{x:o},backend:t,attrs:{shape:[s]}}),i=new pg(s),p=t.runWebGLProgram(i,[a],a.dtype),u=te({inputs:{x:p},backend:t,attrs:{shape:n}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(p),u}var KF={kernelName:ca,backendName:"webgl",kernelFunc:Hee};var lg=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:o,padInfo:n,strideHeight:s,strideWidth:a,filterHeight:i,filterWidth:p,dilationHeight:u,dilationWidth:l}=e,{top:c,left:m}=n;this.userCode=`
2022-11-18 17:13:29 +01:00
const ivec2 strides = ivec2(${s}, ${a});
const ivec2 pads = ivec2(${c}, ${m});
2022-11-18 17:13:29 +01:00
const float neg_infinity = -3.4e38;
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.w;
ivec2 outTopLeftCorner =
coords.yz * strides - pads;
int hBeg = outTopLeftCorner.x;
int wBeg = outTopLeftCorner.y;
float curVal = neg_infinity;
for (int h = 0; h < ${i}; h++) {
int hIn = hBeg + h * ${u};
if (hIn >= 0 && hIn < ${t}) {
2022-11-18 17:13:29 +01:00
for (int w = 0; w < ${p}; w++) {
int wIn = wBeg + w * ${l};
2022-11-18 17:13:29 +01:00
if (wIn >= 0 && wIn < ${o}) {
float xVal = getX(batch, hIn, wIn, d1);
float wVal = getW(h, w, d1);
float val = xVal + wVal;
if (val > curVal) {
curVal = val;
}
}
}
}
}
float result = curVal;
setOutput(result);
}
`}};function Kee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:p}=o,u=C.computeDilation2DInfo(n.shape,s.shape,a,i,"NHWC",p),l,c=new lg(u);l=t.runWebGLProgram(c,[n,s],"float32");let m=te({inputs:{x:l},backend:t,attrs:{shape:u.outShape}});return t.disposeIntermediateTensorInfo(l),m}var qF={kernelName:zn,backendName:"webgl",kernelFunc:Kee};function qee(r){let{inputs:e,backend:t,attrs:o}=r,{equation:n}=o,s=e,{allDims:a,summedDims:i,idDims:p}=C.decodeEinsumEquation(n,s.length);C.checkEinsumDimSizes(a.length,p,s);let{path:u,steps:l}=C.getEinsumComputePath(i,p),c=l.length,m=null,d=a.length,f=[];for(let h=0;h<c;++h){for(let g of l[h]){let{permutationIndices:x,expandDims:b}=C.getEinsumPermutation(d,p[g]),w;C.isIdentityPermutation(x)?w=s[g]:(w=Ct({inputs:{x:s[g]},backend:t,attrs:{perm:x}}),f.push(w));let S=w.shape.slice();for(let k=0;k<b.length;++k)S.splice(b[k],0,1);y.arraysEqual(w.shape,S)||(w=te({inputs:{x:w},backend:t,attrs:{shape:S}}),f.push(w)),m===null?m=w:(m=um({inputs:{a:w,b:m},backend:t}),f.push(m))}h<c-1&&(u[h]>=0&&(m=Tp({inputs:{x:m},backend:t,attrs:{axis:u[h]-(a.length-d),keepDims:!1}}),f.push(m)),d--)}for(let h of f)h!==m&&t.disposeIntermediateTensorInfo(h);return m}var jF={kernelName:ji,backendName:"webgl",kernelFunc:qee};var jee="return (x >= 0.0) ? x : (exp(x) - 1.0);",Xee=`
2022-11-18 17:13:29 +01:00
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`,Yee=xe({opSnippet:jee,packedOpSnippet:Xee}),XF={kernelName:Wn,backendName:"webgl",kernelFunc:Yee};var Qee="return (b >= 0.0) ? a : a * (b + 1.0);",Zee=`
2022-11-18 17:13:29 +01:00
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,Jee=r=>{let{inputs:e,backend:t}=r,{dy:o,y:n}=e,s=A().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new eo(Zee,o.shape,n.shape):new Br(Qee,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)},YF={kernelName:ri,backendName:"webgl",kernelFunc:Jee};var ete=`
2022-11-18 17:13:29 +01:00
return vec4(equal(a, b));
`,tte="return float(a == b);",rte=st({opSnippet:tte,packedOpSnippet:ete,dtype:"bool",cpuKernelImpl:ED}),QF={kernelName:xo,backendName:"webgl",kernelFunc:rte};var ote=`
2022-11-18 17:13:29 +01:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${C.ERF_P};
float a1 = ${C.ERF_A1};
float a2 = ${C.ERF_A2};
float a3 = ${C.ERF_A3};
float a4 = ${C.ERF_A4};
float a5 = ${C.ERF_A5};
2022-11-18 17:13:29 +01:00
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
`,nte=xe({opSnippet:ote}),ZF={kernelName:Un,backendName:"webgl",kernelFunc:nte};var ste=sn+`
2022-11-18 17:13:29 +01:00
return exp(x);
`,ate=`
2022-11-18 17:13:29 +01:00
vec4 result = exp(x);
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,L0=xe({opSnippet:ste,packedOpSnippet:ate,cpuKernelImpl:$D,dtype:"float32"}),JF={kernelName:yo,backendName:"webgl",kernelFunc:L0};function cg(r){let{inputs:e,attrs:t,backend:o}=r,{dim:n}=t,{input:s}=e,a=s.shape.length,i=s.shape.slice(),p=n;return n<0&&(y.assert(-(a+1)<=n,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),p=a+n+1),i.splice(p,0,1),te({inputs:{x:s},backend:o,attrs:{shape:i}})}var e3={kernelName:ma,backendName:"webgl",kernelFunc:cg};var t3="return exp(x) - 1.0;",ite=xe({opSnippet:t3,packedOpSnippet:t3,cpuKernelImpl:RD}),r3={kernelName:bo,backendName:"webgl",kernelFunc:ite};var cm=class{constructor(e,t,o){this.variableNames=["real","imag"];let n=t[1];this.outputShape=t;let s=o?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=o?`${n}.0`:"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
2022-11-18 17:13:29 +01:00
const float exponentMultiplier = ${s};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${i}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${n});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${n}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${a};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}};function mg(r,e,t){let o=t.texData.get(r.dataId),n=y.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],a=n/s,i=te({inputs:{x:r},backend:t,attrs:{shape:[a,s]}}),p=i.shape,u=new cm("real",p,e),l=new cm("imag",p,e),c=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:p},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:p}],m=t.runWebGLProgram(u,c,"float32"),d=t.runWebGLProgram(l,c,"float32"),f=zr({inputs:{real:m,imag:d},backend:t});t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(d);let h=te({inputs:{x:f},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(f),h}function ute(r){let{inputs:e,backend:t}=r,{input:o}=e;return mg(o,!1,t)}var o3={kernelName:Xi,backendName:"webgl",kernelFunc:ute};var dg=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`}};function Ei(r){let{backend:e,attrs:t}=r,{shape:o,value:n}=t,{dtype:s}=t;if(s=s||y.inferDtype(n),s==="string"){let a=y.getArrayFromDType(s,y.sizeFromShape(o));return a.fill(n),e.makeTensorInfo(o,s,a)}else{let a=new dg(o,n),i=[[n]];return e.runWebGLProgram(a,[],s,i)}}var n3={kernelName:da,backendName:"webgl",kernelFunc:Ei};var fg=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x - 1;
2022-11-18 17:13:29 +01:00
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
2022-11-18 17:13:29 +01:00
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
`}};var s3={kernelName:Gn,backendName:"webgl",kernelFunc:({inputs:r,backend:e})=>{let{image:t}=r,o=e,n=new fg(t.shape);return o.runWebGLProgram(n,[t],t.dtype)}};var a3="return floor(x);",pte=xe({opSnippet:a3,packedOpSnippet:a3,cpuKernelImpl:DD}),i3={kernelName:Co,backendName:"webgl",kernelFunc:pte};var lte=`
2022-11-18 17:13:29 +01:00
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
`,cte=`
2022-11-18 17:13:29 +01:00
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
`,mte=st({opSnippet:lte,packedOpSnippet:cte,dtype:"int32"}),u3={kernelName:wo,backendName:"webgl",kernelFunc:mte};var hg=class{constructor(e){this.variableNames=["A"];let t=kt(),[o,n]=e;this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}.0, ${o}.0);
vec4 values = ${t.texture2D}(A, uv);
2022-11-18 17:13:29 +01:00
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
`}};var gg=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=kt(),[o,n]=e;this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}.0, ${o}.0);
vec4 values = ${t.texture2D}(A, uv);
2022-11-18 17:13:29 +01:00
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${t.output} = result;
2022-11-18 17:13:29 +01:00
}
`}};var p3={kernelName:Lu,backendName:"webgl",kernelFunc:dte},Ql,B0=A().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function dte(r){let{inputs:e,backend:t,attrs:o}=r,{pixels:n}=e,{numChannels:s}=o,a=typeof HTMLVideoElement!="undefined"&&n instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement,[p,u]=a?[n.videoWidth,n.videoHeight]:[n.width,n.height],l=[u,p],c=[u,p,s];if(i||a){let h=A().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Ql==null||h!==B0)&&(B0=h,Ql=document.createElement("canvas").getContext("2d",{willReadFrequently:B0})),Ql.canvas.width=p,Ql.canvas.height=u,Ql.drawImage(n,0,0,p,u),n=Ql.canvas}let m=t.makeTensorInfo(l,"int32");t.texData.get(m.dataId).usage=hr.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(m.dataId),n);let d=A().getBool("WEBGL_PACK")?new gg(c):new hg(c),f=t.runWebGLProgram(d,[m],"int32");return t.disposeData(m.dataId),f}function fte(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:p,pad:u,dataFormat:l,dilations:c,dimRoundingMode:m,activation:d,leakyreluAlpha:f}=o,h=C.convertConv2DDataFormat(l),g=C.computeConv2DInfo(n.shape,s.shape,p,c,u,m,!1,h),x,b=[],w=a!=null,S=i!=null,k=d==="leakyrelu",T=()=>{let R=[n,s],D=(F,O)=>{if(O==="NCHW"&&F.shape.length===1&&F.shape[0]!==1){let M=te({inputs:{x:F},backend:t,attrs:{shape:[F.shape[0],1,1]}});return b.push(M),M}return F};if(w&&R.push(D(a,l)),S&&R.push(D(i,l)),k){let F=t.makeTensorInfo([],"float32",y.createScalarValue(f,"float32"));R.push(F),b.push(F)}return R};if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))x=Qh({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:d,preluActivationWeights:i,leakyreluAlpha:f});else if(g.strideWidth<=2&&h==="channelsLast"&&A().getBool("WEBGL_EXP_CONV")){let R=d?Ti(d,!0):null,D=new jl(g,w,R,S,k),F=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],O=T();x=t.runWebGLProgram(D,O,"float32",F)}else if(A().getBool("WEBGL_CONV_IM2COL"))x=Zh({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:d,preluActivationWeights:i,leakyreluAlpha:f});else{let R=d?Ti(d,!1):null,D=new ql(g,w,R,S,k),F=T();x=t.runWebGLProgram(D,F,"float32")}let E=te({inputs:{x},backend:t,attrs:{shape:g.outShape}});return b.push(x),b.forEach(R=>t.disposeIntermediateTensorInfo(R)),E}var l3={kernelName:jo,backendName:"webgl",kernelFunc:fte};function hte(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:p,pad:u,dilations:l,dimRoundingMode:c,activation:m,leakyreluAlpha:d}=o,f=[],h=l;h==null&&(h=[1,1]),y.assert(C.eitherStridesOrDilationsAreOne(p,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${p} and dilations '${h}'`);let g=C.computeConv2DInfo(n.shape,s.shape,p,h,u,c,!0),x=A().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,b=m?Ti(m,x):null,w=[n,s],S=a!=null,k=i!=null,T=m==="leakyrelu";if(S&&w.push(a),k&&w.push(i),T){let F=t.makeTensorInfo([],"float32",y.createScalarValue(d,"float32"));w.push(F),f.push(F)}let E;x?E=new Yl(g,S,b,k,T):E=new Xl(g,S,b,k,T);let R=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],D=t.runWebGLProgram(E,w,"float32",R);return f.forEach(F=>t.disposeIntermediateTensorInfo(F)),D}var c3={kernelName:Xo,backendName:"webgl",kernelFunc:hte};var xg=class{constructor(e,t,o,n){this.sliceDim=e,this.strides=t,this.paramsShape=n,this.variableNames=["x","indices"],this.outputShape=o;let s=Re(o.length),a=`
2022-11-18 17:13:29 +01:00
int index;`;for(let i=0;i<this.sliceDim;i++)a+=`
index = round(getIndices(coords[0], ${i}));
out_of_bounds = out_of_bounds || index < 0;
out_of_bounds = out_of_bounds || index >= ${this.paramsShape[i]};
flattenIndex += index * ${this.strides[i]};`;this.userCode=`
void main() {
${s} coords = getOutputCoords();
int flattenIndex = 0;
bool out_of_bounds = false;
${a}
setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
}
`}};function gte(r){let{inputs:e,backend:t}=r,{params:o,indices:n}=e,s=n.shape,a=s[s.length-1],i=y.sizeFromShape(o.shape),[p,u,l,c]=C.prepareAndValidate(o,n),m=te({inputs:{x:n},backend:t,attrs:{shape:[u,a]}}),d=te({inputs:{x:o},backend:t,attrs:{shape:[y.sizeFromShape(o.shape)/l,l]}});if(t.shouldExecuteOnCPU([o,n])||o.dtype==="string"){let x=t.readSync(n.dataId),b=t.bufferSync(o),w=AD(x,b,o.dtype,u,a,l,c,o.shape,i);return t.makeTensorInfo(p,o.dtype,w.values)}let f=new xg(a,c,[u,l],o.shape),h=t.runWebGLProgram(f,[d,m],d.dtype),g=te({inputs:{x:h},backend:t,attrs:{shape:p}});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(h),g}var m3={kernelName:Kn,backendName:"webgl",kernelFunc:gte};var yg=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let o=Re(this.rank),n=xte(e,2);this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${o} resRC = getOutputCoords();
int index = int(getIndices(resRC.x, resRC.z));
float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
2022-11-18 17:13:29 +01:00
setOutput(inBounds * getA(${n}));
}
`}};function xte(r,e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[];for(let n=0;n<r.length;n++)n===2?o.push("index"):o.push(`${t[n]}`);return o.join()}function z0(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,indices:s}=e,{axis:a,batchDims:i}=o,p=y.parseAxisParam(a,n.shape)[0];if(A().get("DEBUG")){let b=t.readSync(s.dataId),w=n.shape[p];for(let S=0;S<b.length;++S){let k=b[S];y.assert(k<=w-1&&k>=0,()=>`GatherV2: the index value ${k} is not in [0, ${w-1}]`)}}let u=C.segment_util.collectGatherOpShapeInfo(n,s,p,i),l=y.sizeFromShape(s.shape),c=[],m=te({inputs:{x:n},backend:t,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),d=te({inputs:{x:s},backend:t,attrs:{shape:[u.batchSize,l/u.batchSize]}});c.push(m),c.push(d);let f=[u.batchSize,u.outerSize,l/u.batchSize,u.sliceSize];if(t.shouldExecuteOnCPU([n,s])||n.dtype==="string"){let b=t.bufferSync(d),w=t.bufferSync(m),S=FD(w,b,f);return c.forEach(k=>t.disposeIntermediateTensorInfo(k)),t.makeTensorInfo(u.outputShape,S.dtype,S.values)}let h=new yg(m.shape,f),g=t.runWebGLProgram(h,[m,d],m.dtype);c.push(g);let x=te({inputs:{x:g},backend:t,attrs:{shape:u.outputShape}});return c.forEach(b=>t.disposeIntermediateTensorInfo(b)),x}var d3={kernelName:fa,backendName:"webgl",kernelFunc:z0};var yte="return float(a > b);",bte=`
2022-11-18 17:13:29 +01:00
return vec4(greaterThan(a, b));
`,Cte=st({opSnippet:yte,packedOpSnippet:bte,cpuKernelImpl:PD,dtype:"bool"}),f3={kernelName:So,backendName:"webgl",kernelFunc:Cte};var wte="return float(a >= b);",Ste=`
2022-11-18 17:13:29 +01:00
return vec4(greaterThanEqual(a, b));
`,Ite=st({opSnippet:wte,packedOpSnippet:Ste,dtype:"bool",cpuKernelImpl:OD}),h3={kernelName:Io,backendName:"webgl",kernelFunc:Ite};function vte(r){let{inputs:e,backend:t}=r,{input:o}=e;return mg(o,!0,t)}var g3={kernelName:Yi,backendName:"webgl",kernelFunc:vte};var kte="return float(!isnan(x) && !isinf(x));",Nte=xe({opSnippet:kte,dtype:"bool"}),x3={kernelName:qn,backendName:"webgl",kernelFunc:Nte};var Tte="return float(isinf(x));",_te=xe({opSnippet:Tte,dtype:"bool"}),y3={kernelName:jn,backendName:"webgl",kernelFunc:_te};var Ete="return float(isnan(x));",$te=xe({opSnippet:Ete,dtype:"bool"}),b3={kernelName:Xn,backendName:"webgl",kernelFunc:$te};var Rte="return float(a < b);",Dte=`
2022-11-18 17:13:29 +01:00
return vec4(lessThan(a, b));
`,Ate=st({opSnippet:Rte,packedOpSnippet:Dte,cpuKernelImpl:MD,dtype:"bool"}),C3={kernelName:ko,backendName:"webgl",kernelFunc:Ate};var Fte="return float(a <= b);",Pte=`
2022-11-18 17:13:29 +01:00
return vec4(lessThanEqual(a, b));
`,Ote=st({opSnippet:Fte,packedOpSnippet:Pte,cpuKernelImpl:LD,dtype:"bool"}),w3={kernelName:No,backendName:"webgl",kernelFunc:Ote};function Mte(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=BD(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var S3={kernelName:Qn,backendName:"webgl",kernelFunc:Mte};var Lte=sn+`
2022-11-18 17:13:29 +01:00
return x < 0.0 ? 0./0. : log(x);
`,Bte=`
2022-11-18 17:13:29 +01:00
vec4 result = log(x);
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
return result;
`,zte=xe({opSnippet:Lte,packedOpSnippet:Bte,cpuKernelImpl:zD}),I3={kernelName:To,backendName:"webgl",kernelFunc:zte};var Vte=sn+`
2022-11-18 17:13:29 +01:00
return log(1.0 + x);
`,Wte=xe({opSnippet:Vte}),v3={kernelName:Zn,backendName:"webgl",kernelFunc:Wte};var Ute="return float(a >= 1.0 && b >= 1.0);",Gte=`
2022-11-18 17:13:29 +01:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,Hte=st({opSnippet:Ute,packedOpSnippet:Gte,dtype:"bool"}),k3={kernelName:Jn,backendName:"webgl",kernelFunc:Hte};var Kte="return float(!(x >= 1.0));",qte=xe({opSnippet:Kte}),N3={kernelName:es,backendName:"webgl",kernelFunc:qte};var jte="return float(a >= 1.0 || b >= 1.0);",Xte=`
2022-11-18 17:13:29 +01:00
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,Yte=st({opSnippet:jte,packedOpSnippet:Xte,dtype:"bool"}),T3={kernelName:ts,backendName:"webgl",kernelFunc:Yte};var bg=class{constructor(e,t,o,n,s){this.variableNames=["x"],this.outputShape=[];let a=t,i=e[3]-1;this.outputShape=e;let p,u=`float(${o}) + float(${n}) * sum`;s===.5?p=`inversesqrt(${u})`:s===1?p=`1.0/(${u})`:p=`exp(log(${u}) * float(-${s}));`,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${a}; j <= ${a}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${i}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${p};
setOutput(val);
}
`}};var Cg=class{constructor(e,t,o,n,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,i=e[3]-1;this.outputShape=e;let p,u=`float(${o}) + float(${n}) * sum`;s===.5?p=`inversesqrt(${u})`:s===1?p=`1.0/(${u})`:p=`exp(log(${u}) * float(-${s}));`,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${a};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${a}; j <= ${a}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * ${p};
setOutput(result);
}
`}};var Qte=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{depthRadius:s,bias:a,alpha:i,beta:p}=o,u=A().getBool("WEBGL_PACK_NORMALIZATION")?new Cg(n.shape,s,a,i,p):new bg(n.shape,s,a,i,p);return t.runWebGLProgram(u,[n],n.dtype)},_3={kernelName:rs,backendName:"webgl",kernelFunc:Qte};var wg=class{constructor(e,t,o,n,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=o,this.alpha=n,this.beta=s,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
2022-11-18 17:13:29 +01:00
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
2022-11-18 17:13:29 +01:00
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${n}) * norm + float(${o});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${n})
* float(${s})
2023-01-06 19:23:06 +01:00
* getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)
2022-11-18 17:13:29 +01:00
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${s});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`}};var Zte=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n,y:s,dy:a}=e,{depthRadius:i,bias:p,alpha:u,beta:l}=o,c=new wg(n.shape,i,p,u,l);return t.runWebGLProgram(c,[n,s,a],n.dtype)},E3={kernelName:oi,backendName:"webgl",kernelFunc:Zte};function $3(r,e,t,o){let n=y.sizeFromShape(e),a=y.sizeFromShape(r.shape)/n,i=te({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),p=ro(i,r.dtype,"max",o),u=te({inputs:{x:p},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(p),u}function V0(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reductionIndices:s,keepDims:a}=o,i=n.shape.length,p=y.parseAxisParam(s,n.shape),u=p,l=C.getAxesPermutation(u,i),c=l!=null,m=t.shouldExecuteOnCPU([n]),d=n;if(c){if(m){let w=t.texData.get(d.dataId).values,S=new Array(i);for(let E=0;E<S.length;E++)S[E]=n.shape[l[E]];let k=Np(w,n.shape,n.dtype,l,S);d=t.makeTensorInfo(S,n.dtype);let T=t.texData.get(d.dataId);T.values=k}else d=ku(n,l,t);u=C.getInnerMostAxes(u.length,i)}C.assertAxesAreInnerMostDims("max",u,i);let[f,h]=C.computeOutAndReduceShapes(d.shape,u),g=f;a&&(g=C.expandShapeToKeepDim(f,p));let x;if(m){let w=t.texData.get(d.dataId).values,S=VD(w,y.sizeFromShape(h),g,n.dtype);x=t.makeTensorInfo(g,n.dtype);let k=t.texData.get(x.dataId);k.values=S}else x=$3(d,h,g,t);return c&&t.disposeIntermediateTensorInfo(d),x}var R3={kernelName:os,backendName:"webgl",kernelFunc:V0};var Jte=Gl+`
2022-11-18 17:13:29 +01:00
return max(a, b);
`,ere=`
2022-11-18 17:13:29 +01:00
vec4 result = vec4(max(a, b));
bvec4 isNaNA = isnan(a);
bvec4 isNaNB = isnan(b);
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
`+to+`
2022-11-18 17:13:29 +01:00
return result;
`,tre=st({opSnippet:Jte,packedOpSnippet:ere,cpuKernelImpl:WD}),D3={kernelName:_o,backendName:"webgl",kernelFunc:tre};function rre(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;Ys(n,"maxPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:p}=o,u=1;y.assert(C.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let l=C.computePool2DInfo(n.shape,s,a,u,i,p);if(l.filterWidth===1&&l.filterHeight===1&&y.arraysEqual(l.inShape,l.outShape))return Ft({inputs:{x:n},backend:t});let c=new Zs(l,"max",!1);return t.runWebGLProgram(c,[n],n.dtype)}var A3={kernelName:ns,backendName:"webgl",kernelFunc:rre};function ore(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dataFormat:p,dimRoundingMode:u}=o,l=[1,1,1],c=C.computePool3DInfo(n.shape,s,a,l,i,u,p),m=new Nu(c,"max",!1);return t.runWebGLProgram(m,[n],n.dtype)}var F3={kernelName:ha,backendName:"webgl",kernelFunc:ore};var Sg=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,o=e.strideWidth,n=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=s-1-e.padInfo.top,p=a-1-e.padInfo.left,u=s*a-1;this.userCode=`
2022-11-18 17:13:29 +01:00
const ivec2 pads = ivec2(${i}, ${p});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${s};
wR += ${n}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
2022-11-18 17:13:29 +01:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2022-11-18 17:13:29 +01:00
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${a}; wC++) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${a} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}},Ig=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,o=e.strideHeight,n=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,p=e.effectiveFilterDepth,u=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=p-1-e.padInfo.front,m=u-1-e.padInfo.top,d=l-1-e.padInfo.left,f=p*u*l-1;this.userCode=`
const ivec3 pads = ivec3(${c}, ${m}, ${d});
2022-11-18 17:13:29 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${p};
wD += ${s}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
2022-11-18 17:13:29 +01:00
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
2022-11-18 17:13:29 +01:00
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${u};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${l};
2022-11-18 17:13:29 +01:00
wC += ${i}) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2022-11-18 17:13:29 +01:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
2022-11-20 22:20:02 +01:00
int maxPosValue = ${f} -
2022-11-18 17:13:29 +01:00
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${u} * ${l} +
wR * ${l} + wC;
2022-11-18 17:13:29 +01:00
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}};function nre(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:p,pad:u,dimRoundingMode:l}=o,c=[1,1,1],m=C.computePool3DInfo(a.shape,i,p,c,u,l),d=new Nu(m,"max",!0),f=t.runWebGLProgram(d,[a],a.dtype),h=new Ig(m),g=t.runWebGLProgram(h,[n,f],a.dtype);return t.disposeIntermediateTensorInfo(f),g}var P3={kernelName:Ji,backendName:"webgl",kernelFunc:nre};function sre(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s,output:a}=e,i=s;Ys([s,a],"maxPoolGrad");let{filterSize:p,strides:u,pad:l,dimRoundingMode:c}=o,m=C.computePool2DInfo(i.shape,p,u,1,l,c),d=!0,f=new Zs(m,"max",d),h=t.runWebGLProgram(f,[i],i.dtype),g=new Sg(m),x=t.runWebGLProgram(g,[n,h],i.dtype);return t.disposeIntermediateTensorInfo(h),x}var O3={kernelName:Zi,backendName:"webgl",kernelFunc:sre};function M3(r,e,t,o){let n=new Zs(t,"max",!1),s=o.runWebGLProgram(n,[r],"float32");n=new Zs(t,"max",!0,!0,e);let a=o.runWebGLProgram(n,[r],"float32");return[s,a]}var L3={kernelName:ga,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{filterSize:n,strides:s,pad:a,includeBatchInIndex:i}=e,p=t;y.assert(o.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.shape.length}.`);let u=[1,1];y.assert(C.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let l=C.computePool2DInfo(o.shape,n,s,u,a),[c,m]=M3(o,i,l,p);return[c,m]}};function B3(r,e,t,o){let n=y.sizeFromShape(e),a=y.sizeFromShape(r.shape)/n,i=te({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),p=ro(i,"float32","mean",o),u=te({inputs:{x:p},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(p),u}var z3={kernelName:ss,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{keepDims:n,axis:s}=e,a=t,i=o.shape.length,p=y.parseAxisParam(s,o.shape),u=p,l=C.getAxesPermutation(u,i),c=l!=null,m=a.shouldExecuteOnCPU([o]),d=[],f=o;if(c){if(m){let S=a.texData.get(f.dataId).values,k=new Array(i);for(let R=0;R<k.length;R++)k[R]=o.shape[l[R]];let T=Np(S,o.shape,o.dtype,l,k);f=a.makeTensorInfo(k,o.dtype);let E=a.texData.get(f.dataId);E.values=T}else f=ku(o,l,a);d.push(f),u=C.getInnerMostAxes(u.length,i)}C.assertAxesAreInnerMostDims("sum",u,i);let[h,g]=C.computeOutAndReduceShapes(f.shape,u),x=h;n&&(x=C.expandShapeToKeepDim(h,p));let b=B3(f,g,x,a);for(let w of d)a.disposeIntermediateTensorInfo(w);return b}};function are(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,p=y.parseAxisParam(s,n.shape),u=p,l=C.getAxesPermutation(u,i),c=n;l!=null&&(c=Ct({inputs:{x:n},backend:t,attrs:{perm:l}}),u=C.getInnerMostAxes(u.length,n.shape.length)),C.assertAxesAreInnerMostDims("min",u,i);let[m,d]=C.computeOutAndReduceShapes(c.shape,u),f=y.sizeFromShape(d),h=te({inputs:{x:c},backend:t,attrs:{shape:[-1,f]}}),g=ro(h,h.dtype,"min",t),x;if(a){let b=C.expandShapeToKeepDim(m,p);x=te({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=te({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),l!=null&&t.disposeIntermediateTensorInfo(c),x}var V3={kernelName:as,backendName:"webgl",kernelFunc:are};var ire=Gl+`
2022-11-18 17:13:29 +01:00
return min(a, b);
`,ure=`
2022-11-18 17:13:29 +01:00
vec4 result = vec4(min(a, b));
bvec4 isNaNA = isnan(a);
bvec4 isNaNB = isnan(b);
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
`+to+`
2022-11-18 17:13:29 +01:00
return result;
`,pre=st({opSnippet:ire,packedOpSnippet:ure,cpuKernelImpl:UD}),W3={kernelName:Eo,backendName:"webgl",kernelFunc:pre};var vg=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=t.map((l,c)=>l[0]+e[c]+l[1]);let n=e.length,s=Re(n),a=t.map(l=>l[0]).join(","),i=t.map((l,c)=>l[0]+e[c]).join(","),p=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n),u=o==="reflect"?0:1;if(n===1){this.userCode=`
2022-11-18 17:13:29 +01:00
int start = ${a};
int end = ${i};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${u};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${u};
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${s} start = ${s}(${a});
${s} end = ${s}(${i});
void main() {
${s} outC = getOutputCoords();
for (int i = 0; i < ${n}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${u};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};
}
}
${s} coords = outC - start;
setOutput(getX(${p}));
}
`}};var kg=class{constructor(e,t,o){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((f,h)=>f[0]+e[h]+f[1]);let n=e.length,s=Re(n),a=t.map(f=>f[0]).join(","),i=t.map((f,h)=>f[0]+e[h]).join(","),p=At("rc",n),u=At("source",n),l=`${p[n-1]} < ${this.outputShape[n-1]}`,c=n===1?"source":`vec2(${u.slice(-2).join()})`,m=o==="reflect"?0:1,d="";if(n===1){let f=`
2022-11-18 17:13:29 +01:00
${s} source = rc;
if (source < start) {
source = start * 2 - source - ${m};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${m};
}
source -= start;
2022-11-20 22:20:02 +01:00
`;d=`
2022-11-18 17:13:29 +01:00
${s} rc = outputLoc;
2022-11-20 22:20:02 +01:00
${f}
result[0] = getChannel(getX(${u.join()}), ${c});
2022-11-18 17:13:29 +01:00
${p[n-1]} += 1;
if(${l}) {
2022-11-20 22:20:02 +01:00
${f}
result[1] = getChannel(getX(${u.join()}), ${c});
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
`}else{let f=`
2022-11-18 17:13:29 +01:00
${s} source = rc;
${s} lt = ${s}(lessThan(source, start));
${s} gte = ${s}(greaterThanEqual(source, end));
${s} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${m}) +
gte * ((end - 1) * 2 - source + ${m});
source -= start;
2022-11-20 22:20:02 +01:00
`;d=`
2022-11-18 17:13:29 +01:00
${s} rc = outputLoc;
2022-11-20 22:20:02 +01:00
${f}
result[0] = getChannel(getX(${u.join()}), ${c});
2022-11-18 17:13:29 +01:00
${p[n-1]} += 1;
if(${l}) {
2022-11-20 22:20:02 +01:00
${f}
result[1] = getChannel(getX(${u.join()}), ${c});
2022-11-18 17:13:29 +01:00
}
rc = outputLoc;
${p[n-2]} += 1;
if(${p[n-2]} < ${this.outputShape[n-2]}) {
2022-11-20 22:20:02 +01:00
${f}
result[2] = getChannel(getX(${u.join()}), ${c});
2022-11-18 17:13:29 +01:00
${p[n-1]} += 1;
if(${l}) {
2022-11-20 22:20:02 +01:00
${f}
result[3] = getChannel(getX(${u.join()}), ${c});
2022-11-18 17:13:29 +01:00
}
}
`}this.userCode=`
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${i});
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
2022-11-20 22:20:02 +01:00
${d}
2022-11-18 17:13:29 +01:00
setOutput(result);
}
`}};var lre=({inputs:r,backend:e,attrs:t})=>{let{x:o}=r,{paddings:n,mode:s}=t,a=A().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new kg(o.shape,n,s):new vg(o.shape,n,s);return e.runWebGLProgram(a,[o],o.dtype)},U3={kernelName:is,backendName:"webgl",kernelFunc:lre};var cre=`if (b == 0.0) return NAN;
return mod(a, b);`,mre=`
2022-11-18 17:13:29 +01:00
vec4 result = mod(a, b);
bvec4 isNaN = equal(b, vec4(0.0));
`+to+`
2022-11-18 17:13:29 +01:00
return result;
`,dre=st({opSnippet:cre,packedOpSnippet:mre}),G3={kernelName:us,backendName:"webgl",kernelFunc:dre};var Ng=class{constructor(e,t,o){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,o],this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t-1}; i++) {
2022-11-18 17:13:29 +01:00
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
setOutput(float(${t-1}));
2022-11-18 17:13:29 +01:00
}
`}};var fre=`
2022-11-18 17:13:29 +01:00
if (a == b) {
return 1.0;
};
return a / b;`,hre=`
2022-11-18 17:13:29 +01:00
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
`,W0=st({opSnippet:fre,packedOpSnippet:hre,checkOutOfBounds:!0}),H3={kernelName:Vn,backendName:"webgl",kernelFunc:W0};var K3="return a - b;",U0=st({opSnippet:K3,packedOpSnippet:K3,supportsComplex:!0,cpuKernelImpl:lA}),q3={kernelName:Oo,backendName:"webgl",kernelFunc:U0};function G0(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{dim:s}=o,a=y.parseAxisParam([s],n.shape),i=V0({inputs:{x:n},backend:t,attrs:{reductionIndices:a,keepDims:!1}}),p=C.expandShapeToKeepDim(i.shape,a),u=te({inputs:{x:i},backend:t,attrs:{shape:p}}),l=U0({inputs:{a:n,b:u},backend:t}),c=L0({inputs:{x:l},backend:t}),m=Tp({inputs:{x:c},backend:t,attrs:{axis:a,keepDims:!1}}),d=te({inputs:{x:m},backend:t,attrs:{shape:p}}),f=W0({inputs:{a:c,b:d},backend:t});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(l),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(d),f}var j3={kernelName:Fs,backendName:"webgl",kernelFunc:G0};function gre(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o,p=i?n:G0({inputs:{logits:n},backend:t,attrs:{dim:n.shape.length-1}}),u=p.shape[0],l=p.shape[1],c=new Ng(u,l,s),m=[[a]],d=t.runWebGLProgram(c,[p],"int32",m);return i||t.disposeIntermediateTensorInfo(p),d}var X3={kernelName:ps,backendName:"webgl",kernelFunc:gre};var xre=Gt+`
2022-11-18 17:13:29 +01:00
return -x;
`,yre=`
2022-11-18 17:13:29 +01:00
vec4 result = -x;
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;function bre(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])){let s=t.texData.get(o.dataId),[a,i]=HD(s.values,o.shape,o.dtype);return t.makeTensorInfo(i,o.dtype,a)}let n;return A().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new Lr(o.shape,yre):n=new nr(o.shape,xre),t.runWebGLProgram(n,[o],o.dtype)}var Y3={kernelName:ls,backendName:"webgl",kernelFunc:bre};var Cre=Ut.nonMaxSuppressionV3Impl;function wre(r){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:p}=o,u=t.readSync(n.dataId),l=t.readSync(s.dataId),{selectedIndices:c}=Cre(u,l,a,i,p);return t.makeTensorInfo([c.length],"int32",new Int32Array(c))}var Q3={kernelName:cs,backendName:"webgl",kernelFunc:wre};var Sre=Ut.nonMaxSuppressionV4Impl;function Ire(r){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:p,padToMaxOutputSize:u}=o,l=t.readSync(n.dataId),c=t.readSync(s.dataId),{selectedIndices:m,validOutputs:d}=Sre(l,c,a,i,p,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([d]))]}var Z3={kernelName:ni,backendName:"webgl",kernelFunc:Ire};var vre=Ut.nonMaxSuppressionV5Impl;function kre(r){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:p,softNmsSigma:u}=o,l=t.readSync(n.dataId),c=t.readSync(s.dataId),m=a,d=i,f=p,h=u,{selectedIndices:g,selectedScores:x}=vre(l,c,m,d,f,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var J3={kernelName:ms,backendName:"webgl",kernelFunc:kre};var Tg=class{constructor(e,t,o,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${n}), float(${o}),
float(index == coords.y)));
}
`}};var Nre=r=>{let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{dtype:s,depth:a,onValue:i,offValue:p}=o,u=y.sizeFromShape(n.shape),l=new Tg(u,a,i,p),c=te({inputs:{x:n},backend:t,attrs:{shape:[u]}}),m=t.runWebGLProgram(l,[c],s);t.disposeIntermediateTensorInfo(c);let d=[...n.shape,a],f=te({inputs:{x:m},backend:t,attrs:{shape:d}});return t.disposeIntermediateTensorInfo(m),f},eP={kernelName:ds,backendName:"webgl",kernelFunc:Nre};function mm(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="complex64"){let n=_i({inputs:{input:o},backend:t}),s=mm({inputs:{x:n},backend:t}),a=Ep({inputs:{input:o},backend:t}),i=mm({inputs:{x:a},backend:t}),p=zr({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),p}else return Ei({attrs:{shape:o.shape,dtype:o.dtype,value:o.dtype==="string"?"":0},backend:t})}var tP={kernelName:_a,backendName:"webgl",kernelFunc:mm};function rP(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(o.dtype==="complex64"){let n=_i({inputs:{input:o},backend:t}),s=rP({inputs:{x:n},backend:t}),a=Ep({inputs:{input:o},backend:t}),i=mm({inputs:{x:a},backend:t}),p=zr({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),p}else return Ei({attrs:{shape:o.shape,dtype:o.dtype,value:1},backend:t})}var oP={kernelName:xa,backendName:"webgl",kernelFunc:rP};function Tre(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return cg({inputs:{input:e[0]},backend:t,attrs:{dim:n}});let s=e[0].shape,a=e[0].dtype;e.forEach(l=>{y.assertShapesMatch(s,l.shape,"All tensors passed to stack must have matching shapes"),y.assert(a===l.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],p=e.map(l=>{let c=cg({inputs:{input:l},backend:t,attrs:{dim:n}});return i.push(c),c}),u=M0({inputs:p,backend:t,attrs:{axis:n}});return i.forEach(l=>t.disposeIntermediateTensorInfo(l)),u}var nP={kernelName:ya,backendName:"webgl",kernelFunc:Tre};var _g=class{constructor(e,t,o){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((u,l)=>u[0]+e[l]+u[1]);let n=e.length,s=Re(n),a=t.map(u=>u[0]).join(","),i=t.map((u,l)=>u[0]+e[l]).join(","),p=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode=`
2022-11-18 17:13:29 +01:00
int start = ${a};
int end = ${i};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${s} start = ${s}(${a});
${s} end = ${s}(${i});
void main() {
${s} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${s} coords = outC - start;
setOutput(getX(${p}));
}
}
`}};var Eg=class{constructor(e,t,o){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((h,g)=>h[0]+e[g]+h[1]);let n=e.length,s=Re(n),a=t.map(h=>h[0]).join(","),i=t.map((h,g)=>h[0]+e[g]).join(","),p=At("rc",n),u=At("source",n),l=`${p[n-1]} < ${this.outputShape[n-1]}`,c=n===1?"source":`vec2(${u.slice(-2).join()})`,m=[`${s} rc = outputLoc;`,`${p[n-1]} += 1;
if(${l}) {
2022-11-18 17:13:29 +01:00
`,n===1?"":`}
rc = outputLoc;
${p[n-2]} += 1;
if(${p[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${p[n-1]} += 1;
if(${l}) {`],d=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="";for(let h=0,g=n===1?2:4;h<g;h++)f+=`
2022-11-18 17:13:29 +01:00
${m[h]}
2022-11-20 22:20:02 +01:00
if (${d}) {
2022-11-18 17:13:29 +01:00
result[${h}] = float(value);
} else {
${s} source = rc - start;
result[${h}] = getChannel(getX(${u.join()}), ${c});
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
`;f+=n===1?"} ":"}}",this.userCode=`
2022-11-18 17:13:29 +01:00
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${i});
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
2022-11-20 22:20:02 +01:00
${f}
2022-11-18 17:13:29 +01:00
setOutput(result);
}
`}};var H0=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,constantValue:a}=o;if(y.sizeFromShape(n.shape)===0){let u=s.map((l,c)=>l[0]+n.shape[c]+l[1]);return Ei({backend:t,attrs:{shape:u,value:a,dtype:n.dtype}})}let i=A().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Eg(n.shape,s,a):new _g(n.shape,s,a),p=[[a]];return t.runWebGLProgram(i,[n],n.dtype,p)},sP={kernelName:fs,backendName:"webgl",kernelFunc:H0};var _re=`
2022-11-18 17:13:29 +01:00
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
`,Ere=`
2022-11-18 17:13:29 +01:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
bvec4 isNaN1 = lessThan(a, vec4(0.0));
bvec4 isNaN2 = lessThan(floor(b), b);
bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);
`+to+`
2022-11-18 17:13:29 +01:00
return result;
`,$re=st({opSnippet:_re,packedOpSnippet:Ere}),aP={kernelName:hs,backendName:"webgl",kernelFunc:$re};function Rre(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,p=[],u=y.parseAxisParam(s,n.shape),l=u,c=C.getAxesPermutation(l,i),m=n;c!=null&&(m=Ct({inputs:{x:n},backend:t,attrs:{perm:c}}),l=C.getInnerMostAxes(l.length,i),p.push(m)),C.assertAxesAreInnerMostDims("prod",l,i);let d;if(t.shouldExecuteOnCPU([m])){let f=t.texData.get(m.dataId).values,{outVals:h,outShape:g,outDtype:x}=qD(m.shape,m.dtype,f,l);d=t.makeTensorInfo(g,x,h)}else{let[f,h]=C.computeOutAndReduceShapes(m.shape,l),g=y.sizeFromShape(h),x=te({inputs:{x:m},backend:t,attrs:{shape:[-1,g]}}),b=mi(n.dtype),w=ro(x,b,"prod",t);d=te({inputs:{x:w},backend:t,attrs:{shape:f}}),p.push(x),p.push(w)}if(a){p.push(d);let f=C.expandShapeToKeepDim(d.shape,u);d=te({inputs:{x:d},backend:t,attrs:{shape:f}})}return p.forEach(f=>t.disposeIntermediateTensorInfo(f)),d}var iP={kernelName:Ho,backendName:"webgl",kernelFunc:Rre};function Dre(r){let{inputs:e,backend:t,attrs:o}=r,{paramsNestedSplits:n,paramsDenseValues:s,indices:a}=e,{outputRaggedRank:i}=o,p=n.map(x=>t.readSync(x.dataId)),u=n.map(x=>x.shape),l=t.readSync(s.dataId),c=t.readSync(a.dataId),[m,d,f]=jD(p,u,l,s.shape,s.dtype,c,a.shape,i),h=m.map(x=>t.makeTensorInfo([x.length],"int32",x)),g=t.makeTensorInfo(f,s.dtype,d);return h.concat([g])}var uP={kernelName:Qp,backendName:"webgl",kernelFunc:Dre};function Are(r){let{inputs:e,backend:t}=r,{starts:o,limits:n,deltas:s}=e,a=t.readSync(o.dataId),i=t.readSync(n.dataId),p=t.readSync(s.dataId),[u,l]=XD(a,o.shape,o.dtype,i,n.shape,p,s.shape),c=t.makeTensorInfo([u.length],"int32",u),m=t.makeTensorInfo([l.length],o.dtype,l);return[c,m]}var pP={kernelName:Zp,backendName:"webgl",kernelFunc:Are};function Fre(r){let{inputs:e,backend:t,attrs:o}=r,{shape:n,values:s,defaultValue:a,rowPartitionTensors:i}=e,{rowPartitionTypes:p}=o,u=t.readSync(n.dataId),l=t.readSync(s.dataId),c=t.readSync(a.dataId),m=i.map(g=>t.readSync(g.dataId)),d=i.map(g=>g.shape),[f,h]=YD(u,n.shape,l,s.shape,s.dtype,c,a.shape,m,d,p);return t.makeTensorInfo(f,s.dtype,h)}var lP={kernelName:Jp,backendName:"webgl",kernelFunc:Fre};var K0=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=QD(o,n,s,a);return e.makeTensorInfo([i.length],a,i)},cP={kernelName:ba,backendName:"webgl",kernelFunc:K0};var Pre="return 1.0 / x;",Ore=xe({opSnippet:Pre}),mP={kernelName:xs,backendName:"webgl",kernelFunc:Ore};var Mre=Gt+`
2022-11-18 17:13:29 +01:00
return (x < 0.0) ? 0.0 : x;
`,Lre=`
2022-11-18 17:13:29 +01:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,Bre=xe({opSnippet:Mre,packedOpSnippet:Lre}),dP={kernelName:ys,backendName:"webgl",kernelFunc:Bre};var zre=Gt+`
2022-11-18 17:13:29 +01:00
return (x < 0.0) ? 0.0 : min(6.0, x);
`,Vre=`
2022-11-18 17:13:29 +01:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,Wre=xe({opSnippet:zre,packedOpSnippet:Vre}),fP={kernelName:ws,backendName:"webgl",kernelFunc:Wre};var $g=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.outputShape=[];let[a,i,p,u]=e;this.outputShape=[a,t,o,u];let l=[n&&t>1?i-1:i,n&&o>1?p-1:p],c=[n&&t>1?t-1:t,n&&o>1?o-1:o],m;s?m="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":m="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2022-11-18 17:13:29 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0]/c[0]},
${l[1]/c[1]});
2022-11-18 17:13:29 +01:00
const vec2 inputShapeRC = vec2(${i}.0, ${p}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${m};
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
`}};var Rg=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,i,p,u]=e;this.outputShape=[a,t,o,u];let l=[n&&t>1?i-1:i,n&&o>1?p-1:p],c=[n&&t>1?t-1:t,n&&o>1?o-1:o],m;s?m="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":m="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2022-11-18 17:13:29 +01:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
${l[0]/c[0]},
${l[1]/c[1]},
${l[1]/c[1]});
2022-11-18 17:13:29 +01:00
const vec3 inputShapeRC = vec3(${i}.0, ${p}.0,
${p}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = ${m};
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${u-1};
bool hasNextRow = coords.z < ${o-1};
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
`}};function Ure(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[p,u]=i,l=A().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Rg(n.shape,p,u,s,a):new $g(n.shape,p,u,s,a);return t.runWebGLProgram(l,[n],"float32")}var hP={kernelName:Cs,backendName:"webgl",kernelFunc:Ure};var Dg=class{constructor(e,t,o){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,s]=t,[,a,i]=e,p=[o&&a>1?n-1:n,o&&i>1?s-1:s],u=[o&&a>1?a-1:a,o&&i>1?i-1:i],l=p[0]/u[0],c=p[1]/u[1],m=1/l,d=1/c,f=Math.ceil(m)*2+2,h=Math.ceil(d)*2+2;this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${l});
const float widthScale = float(${c});
2022-11-18 17:13:29 +01:00
const float invHeightScale = float(${m});
2022-11-20 22:20:02 +01:00
const float invWidthScale = float(${d});
2022-11-18 17:13:29 +01:00
2022-11-20 22:20:02 +01:00
const int winHeight = int(${f});
2022-11-18 17:13:29 +01:00
const int winWidth = int(${h});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${i}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${n-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${s-1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}};function Gre(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new Dg(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var gP={kernelName:ii,backendName:"webgl",kernelFunc:Gre};var Ag=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.outputShape=[];let[a,i,p,u]=e;this.outputShape=[a,t,o,u];let l=[n&&t>1?i-1:i,n&&o>1?p-1:p],c=[n&&t>1?t-1:t,n&&o>1?o-1:o],m=n?"0.5":"0.0",d;s?d="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2022-11-18 17:13:29 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0]/c[0]},
${l[1]/c[1]});
2022-11-18 17:13:29 +01:00
const vec2 inputShapeRC = vec2(${i}.0, ${p}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
2022-11-20 22:20:02 +01:00
vec2 sourceFracIndexRC = ${d};
2022-11-18 17:13:29 +01:00
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`}};var Fg=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,i,p,u]=e;this.outputShape=[a,t,o,u];let l=[n&&t>1?i-1:i,n&&o>1?p-1:p],c=[n&&t>1?t-1:t,n&&o>1?o-1:o],m=n?"0.5":"0.0",d;s?d="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2022-11-18 17:13:29 +01:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
${l[0]/c[0]},
${l[1]/c[1]},
${l[1]/c[1]});
2022-11-18 17:13:29 +01:00
const vec3 inputShapeRC = vec3(${i}.0, ${p}.0,
${p}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
2022-11-20 22:20:02 +01:00
vec3 sourceFracIndexRC = ${d};
2022-11-18 17:13:29 +01:00
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${u-1};
bool hasNextRow = coords.z < ${o-1};
vec4 newValue = vec4(
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
setOutput(newValue);
}
`}};function Hre(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[p,u]=i,l=A().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Fg(n.shape,p,u,s,a):new Ag(n.shape,p,u,s,a);return t.runWebGLProgram(l,[n],n.dtype)}var xP={kernelName:bs,backendName:"webgl",kernelFunc:Hre};var Pg=class{constructor(e,t,o){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,s]=t,[,a,i]=e,p=[o&&a>1?n-1:n,o&&i>1?s-1:s],u=[o&&a>1?a-1:a,o&&i>1?i-1:i],l=p[0]/u[0],c=p[1]/u[1],m=1/l,d=1/c,f=Math.ceil(m)*2+2,h=Math.ceil(d)*2+2;this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${l});
const float widthScale = float(${c});
2022-11-18 17:13:29 +01:00
const float invHeightScale = float(${m});
2022-11-20 22:20:02 +01:00
const float invWidthScale = float(${d});
2022-11-18 17:13:29 +01:00
2022-11-20 22:20:02 +01:00
const int winHeight = int(${f});
2022-11-18 17:13:29 +01:00
const int winWidth = int(${h});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${i}) {
continue;
}
float sourceFracRow =
float(${p[0]}) *
(float(dyR) / float(${u[0]}));
float sourceFracCol =
float(${p[1]}) *
(float(dyC) / float(${u[1]}));
int sourceNearestRow = int(min(
float(int(${n}) - 1),
${o} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${s}) - 1),
${o} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}};function Kre(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new Pg(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var yP={kernelName:ai,backendName:"webgl",kernelFunc:Kre};var Og=class{constructor(e,t){this.variableNames=["x"];let o=e.length;if(o>4)throw new Error(`WebGL backend: Reverse of rank-${o} tensor is not yet supported`);if(this.outputShape=e,o===1){this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
2022-11-18 17:13:29 +01:00
}
`;return}let n=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,s=e.map((i,p)=>n(p)).join(","),a=Re(o);this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${s}));
}
`}};var Mg=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let o=e.length;if(o>4)throw new Error(`WebGL backend: Reverse of rank-${o} tensor is not yet supported`);this.outputShape=e;let n=At("rc",o),s=`${n[o-1]} + 1 < ${this.outputShape[o-1]}`,a=`${n[o-2]} + 1 < ${this.outputShape[o-2]}`,i=Re(o);o===1?this.userCode=`
2022-11-18 17:13:29 +01:00
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
2022-11-18 17:13:29 +01:00
if(${s}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
2022-11-18 17:13:29 +01:00
}
setOutput(result);
}
`:this.userCode=`
void main() {
${i} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${p(n.slice())};
if(${s}){
result.g = ${u(n.slice())};
}
if(${a}) {
result.b = ${l(n.slice())};
2022-11-18 17:13:29 +01:00
if(${s}) {
result.a = ${c(n.slice())};
2022-11-18 17:13:29 +01:00
}
}
setOutput(result);
}
`;function p(f){return m(f)}function u(f){return f[o-1]="("+f[o-1]+" + 1)",m(f)}function l(f){return f[o-2]="("+f[o-2]+" + 1)",m(f)}function c(f){return f[o-1]="("+f[o-1]+" + 1)",f[o-2]="("+f[o-2]+" + 1)",m(f)}function m(f){let h=e.map((b,w)=>d(w,f)),g=h.join(","),x=h.slice(-2).join(",");return`getChannel(getX(${g}), vec2(${x}))`}function d(f,h){return t.indexOf(f)!==-1&&e[f]!==1?`${e[f]} - ${h[f]} - 1`:`${h[f]}`}}};function qre(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o,a=n.shape.length,i=y.parseAxisParam(s,n.shape);if(a===0)return Ft({inputs:{x:n},backend:t});let p=A().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Mg(n.shape,i):new Og(n.shape,i);return t.runWebGLProgram(p,[n],n.dtype)}var bP={kernelName:Ss,backendName:"webgl",kernelFunc:qre};var Lg=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let o=e[1],n=e[2];this.outputShape=e;let s="";typeof t=="number"?s=`float outputValue = ${t.toFixed(2)};`:s=`
vec3 fill = vec3(${t.join(",")});
2022-11-18 17:13:29 +01:00
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - params[0]) * params[3] -
(float(y) - params[1]) * params[2];
float coordYFloat = (float(x) - params[0]) * params[2] +
(float(y) - params[1]) * params[3];
int coordX = int(round(coordXFloat + params[0]));
int coordY = int(round(coordYFloat + params[1]));
${s}
if(coordX >= 0 && coordX < ${n} && coordY >= 0 && coordY < ${o}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}};var CP={kernelName:Vs,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:o}=r,{radians:n,fillValue:s,center:a}=e,i=t,p=new Lg(o.shape,s),[u,l]=C.getImageCenter(a,o.shape[1],o.shape[2]),c=[[u,l,Math.sin(n),Math.cos(n)]];return i.runWebGLProgram(p,[o],o.dtype,c)}};var jre=`
2022-11-18 17:13:29 +01:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
`,Xre=xe({opSnippet:jre}),wP={kernelName:Is,backendName:"webgl",kernelFunc:Xre};var Yre="return inversesqrt(x);",Qre=xe({opSnippet:Yre,cpuKernelImpl:ZD}),SP={kernelName:Do,backendName:"webgl",kernelFunc:Qre};var Tu=class{constructor(e,t,o,n,s,a,i=!0,p=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let u=Re(s.length),l=Re(a.length),c="";o===1?c="i":o===2&&(c="i, j");let m=`getIndices(${c})`,d="";n===1?d="i":n===2&&(d="i, coords[1]");let f=`getUpdates(${d})`,h="";p&&(h="coords[0], coords[1]");let g=`getDefaultValue(${h})`,x=t>1?"strides[j]":"strides";this.userCode=`
2023-05-08 15:12:41 +02:00
${u} strides = ${u}(${s});
2022-11-18 17:13:29 +01:00
void main() {
${l} coords = getOutputCoords();
2022-11-18 17:13:29 +01:00
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
2022-11-18 17:13:29 +01:00
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
2023-05-08 15:12:41 +02:00
int index = round(${m});
flattenedIndex += index * ${x};
2022-11-18 17:13:29 +01:00
}
if (flattenedIndex == coords[0]) {
2023-05-08 15:12:41 +02:00
sum += ${f};
2022-11-18 17:13:29 +01:00
found = true;
}
}
2023-05-08 15:12:41 +02:00
setOutput(mix(${g}, sum, float(found)));
}
`}};var Bg=class{constructor(e,t,o,n,s,a,i=!0,p=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=a;let u=Re(s.length),l=Re(a.length),c="";o===1?c="i":o===2&&(c="i, j");let m=`getIndices(${c})`,d="";n===1?d="i":n===2&&(d="i, coords[1]");let f=`getUpdates(${d})`,h="";p&&(h="coords[0], coords[1]");let g=`getDefaultValue(${h})`,x=t>1?"strides[j]":"strides",b=t>1?"strides[j + 1]":"strides";this.userCode=`
2023-05-08 15:12:41 +02:00
${u} strides = ${u}(${s});
void main() {
${l} coords = getOutputCoords();
2023-05-08 15:12:41 +02:00
vec4 sum = vec4(0.);
vec4 found = vec4(0.);
for (int i = 0; i < ${e}; i+=2) {
2023-05-08 15:12:41 +02:00
ivec2 flattenedIndex = ivec2(0);
for (int j = 0; j < ${t}; j+=2) {
2023-05-08 15:12:41 +02:00
ivec4 index = round(${m});
flattenedIndex += index.xz * ${x};
if (j + 1 < ${t}) {
2023-05-08 15:12:41 +02:00
flattenedIndex += index.yw * ${b};
}
}
if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
vec4 updVals = ${f};
if (flattenedIndex[0] == coords[0]) {
sum.xy += updVals.xy;
found.xy = vec2(1.);
} else if (flattenedIndex[0] == coords[0] + 1) {
sum.zw += updVals.xy;
found.zw = vec2(1.);
}
if (flattenedIndex[1] == coords[0]) {
sum.xy += updVals.zw;
found.xy = vec2(1.);
} else if (flattenedIndex[1] == coords[0] + 1) {
sum.zw += updVals.zw;
found.zw = vec2(1.);
}
}
}
setOutput(mix(${g}, sum, found));
2022-11-18 17:13:29 +01:00
}
`}};function Zre(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n,updates:s}=e,{shape:a}=o,{sliceRank:i,numUpdates:p,sliceSize:u,strides:l,outputSize:c}=C.calculateShapes(s,n,a),m=[c/u,u];if(c===0)return t.makeTensorInfo(a,n.dtype);let d=te({inputs:{x:n},backend:t,attrs:{shape:[p,i]}}),f=te({inputs:{x:s},backend:t,attrs:{shape:[p,u]}}),h=t.makeTensorInfo([],"float32",new Float32Array([0])),g;A().getBool("WEBGL_PACK")?g=new Bg(p,i,d.shape.length,f.shape.length,l,m):g=new Tu(p,i,d.shape.length,f.shape.length,l,m);let x=t.runWebGLProgram(g,[f,d,h],f.dtype),b=te({inputs:{x},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(h),b}var IP={kernelName:vs,backendName:"webgl",kernelFunc:Zre};var zg=class{constructor(e,t,o,n){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,o];let s="while (left < right) {",a=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,i=A().getNumber("WEBGL_VERSION")===2?s:a,p=n==="left"?"<":"<=";this.userCode=`
2022-11-18 17:13:29 +01:00
int findBound(int batch, float value) {
int left = 0;
int right = numInputs;
int mid;
${i}
mid = (left + right) / 2;
if (getSortedSequence(batch, mid) ${p} value) {
left = mid + 1;
} else {
right = mid;
}
}
return right;
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int valueIndex = coords[1];
float value = getValues(batch, valueIndex);
setOutput(float(findBound(batch, value)));
}
`}};function Jre(r){let{inputs:e,backend:t,attrs:o}=r,{sortedSequence:n,values:s}=e,{side:a}=o,i=new zg(n.shape[0],n.shape[1],s.shape[1],a),p=[[n.shape[1]]];return t.runWebGLProgram(i,[n,s],"int32",p)}var vP={kernelName:Ns,backendName:"webgl",kernelFunc:Jre};var Vg=class{constructor(e,t,o){this.variableNames=["c","a","b"],this.outputShape=t;let n,s;if(o>4)throw Error(`Where for rank ${o} is not yet supported`);if(o===1)s="resRC",n="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],p=[],u=[];for(let l=0;l<t.length;l++)u.push(`${i[l]}`),l<e&&p.push(`${i[l]}`);n=p.join(),s=u.join()}let a=Re(o);this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${a} resRC = getOutputCoords();
float cVal = getC(${n});
if (cVal >= 1.0) {
setOutput(getA(${s}));
} else {
setOutput(getB(${s}));
}
}
`}};function eoe(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e,a=new Vg(o.shape.length,n.shape,n.shape.length);return t.runWebGLProgram(a,[o,n,s],pt(n.dtype,s.dtype))}var kP={kernelName:wa,backendName:"webgl",kernelFunc:eoe};var toe=`
2022-11-18 17:13:29 +01:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${C.SELU_SCALEALPHA};
float scale = ${C.SELU_SCALE};
2022-11-18 17:13:29 +01:00
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`,roe=xe({opSnippet:toe}),NP={kernelName:Ts,backendName:"webgl",kernelFunc:roe};var ooe=sn+`
2022-11-18 17:13:29 +01:00
return 1.0 / (1.0 + exp(-1.0 * x));
`,noe=`
2022-11-18 17:13:29 +01:00
vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,soe=xe({opSnippet:ooe,packedOpSnippet:noe,cpuKernelImpl:eA}),TP={kernelName:Ao,backendName:"webgl",kernelFunc:soe};var aoe=`
2022-11-18 17:13:29 +01:00
if (isnan(x)) { return 0.0; }
return sign(x);
`,ioe=xe({opSnippet:aoe}),_P={kernelName:Rs,backendName:"webgl",kernelFunc:ioe};var uoe=sn+`
2022-11-18 17:13:29 +01:00
return sin(x);
`,poe=`
2023-05-08 15:12:41 +02:00
vec4 result = sin(x);
bvec4 isNaN = isnan(x);
${to}
2023-05-08 15:12:41 +02:00
return result;
`,loe=xe({opSnippet:uoe,packedOpSnippet:poe}),EP={kernelName:Es,backendName:"webgl",kernelFunc:loe};var coe=`
2022-11-18 17:13:29 +01:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,moe=xe({opSnippet:coe}),$P={kernelName:$s,backendName:"webgl",kernelFunc:moe};var doe=`
2022-11-18 17:13:29 +01:00
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
`,foe=xe({opSnippet:doe}),RP={kernelName:Ds,backendName:"webgl",kernelFunc:foe};var hoe=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,paddings:a}=o;y.assert(n.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((x,b)=>x*b),p=[[0,0]];p.push(...a);for(let x=1+s.length;x<n.shape.length;++x)p.push([0,0]);let u=[],l=H0({inputs:{x:n},backend:t,attrs:{paddings:p,constantValue:0}}),c=C.getReshaped(l.shape,s,i,!1),m=C.getPermuted(c.length,s.length,!1),d=C.getReshapedPermuted(l.shape,s,i,!1),f=te({inputs:{x:l},backend:t,attrs:{shape:c}}),h=Ct({inputs:{x:f},backend:t,attrs:{perm:m}}),g=te({inputs:{x:h},backend:t,attrs:{shape:d}});return u.push(l),u.push(f),u.push(h),u.forEach(x=>t.disposeIntermediateTensorInfo(x)),g},DP={kernelName:Sa,backendName:"webgl",kernelFunc:hoe};function goe(r){let{inputs:e,backend:t}=r,{indices:o,values:n,denseShape:s,defaultValue:a}=e;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
2022-11-18 17:13:29 +01:00
${s.shape}`);if(o.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${o.shape}`);if(n.shape.length!==1)throw new Error(`Values must be a vector, saw:
${n.shape}`);if(a.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${a.shape}`);let i=t.readSync(o.dataId),p=t.readSync(n.dataId),u=t.readSync(s.dataId),l=t.readSync(a.dataId)[0],[c,m,d,f,h]=rA(i,o.shape,o.dtype,p,n.dtype,u,l);return[t.makeTensorInfo(m,o.dtype,c),t.makeTensorInfo([m[0]],n.dtype,d),t.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),t.makeTensorInfo([h.length],o.dtype,new Int32Array(h))]}var AP={kernelName:eu,backendName:"webgl",kernelFunc:goe};function xoe(r){let{inputs:e,backend:t}=r,{inputIndices:o,inputShape:n,newShape:s}=e;if(o.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${o.shape}`);if(n.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${n.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let a=Array.from(t.readSync(n.dataId)),i=t.readSync(o.dataId),p=Array.from(t.readSync(s.dataId)),[u,l,c]=oA(i,o.shape,o.dtype,a,p);return[t.makeTensorInfo(l,o.dtype,u),t.makeTensorInfo([c.length],s.dtype,new Int32Array(c))]}var FP={kernelName:ui,backendName:"webgl",kernelFunc:xoe};function yoe(r){let{inputs:e,backend:t}=r,{data:o,indices:n,segmentIds:s}=e;if(o.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2022-11-18 17:13:29 +01:00
${n.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);let a=t.readSync(o.dataId),i=t.readSync(n.dataId),p=t.readSync(s.dataId),[u,l]=Sh(a,o.shape,o.dtype,i,p,!0);return t.makeTensorInfo(l,o.dtype,u)}var PP={kernelName:va,backendName:"webgl",kernelFunc:yoe};function boe(r){let{inputs:e,backend:t}=r,{data:o,indices:n,segmentIds:s}=e;if(o.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2022-11-18 17:13:29 +01:00
${n.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);let a=t.readSync(o.dataId),i=t.readSync(n.dataId),p=t.readSync(s.dataId),[u,l]=Sh(a,o.shape,o.dtype,i,p);return t.makeTensorInfo(l,o.dtype,u)}var OP={kernelName:ka,backendName:"webgl",kernelFunc:boe};function Coe(r){let{inputs:e,backend:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=e,{outputShape:i}=o,{sliceRank:p,numUpdates:u,sliceSize:l,strides:c,outputSize:m}=C.calculateShapes(s,n,i),d=!1;if(s.dtype==="string"){let x=t.bufferSync(n),b=t.bufferSync(s),w=y.decodeString(t.readSync(a.dataId)[0]),S=JD(x,b,i,m,l,u,p,c,w,d);return t.makeTensorInfo(i,S.dtype,S.values)}let f=new Tu(u,p,n.shape.length,s.shape.length,c,[m,1],d),h=t.runWebGLProgram(f,[s,n,a],s.dtype),g=te({inputs:{x:h},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(h),g}var MP={kernelName:Ps,backendName:"webgl",kernelFunc:Coe};function woe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=o,i=y.parseAxisParam(a,n.shape)[0],p=C.prepareSplitSize(n,s,i),u=n.shape.length,l=new Array(u).fill(0),c=n.shape.slice();return p.map(m=>{let d=[...c];d[i]=m;let f=Js({inputs:{x:n},backend:t,attrs:{begin:l,size:d}});return l[i]+=m,f})}var LP={kernelName:Ia,backendName:"webgl",kernelFunc:woe};var BP="return sqrt(x);",Soe=xe({opSnippet:BP,packedOpSnippet:BP,cpuKernelImpl:nA}),zP={kernelName:Fo,backendName:"webgl",kernelFunc:Soe};var Ioe="return x * x;",voe=xe({opSnippet:Ioe}),VP={kernelName:tu,backendName:"webgl",kernelFunc:voe};var WP="return (a - b) * (a - b);",koe=st({opSnippet:WP,packedOpSnippet:WP}),UP={kernelName:Po,backendName:"webgl",kernelFunc:koe};function Noe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;if(n.dtype!=="string")throw new Error("Input must be of datatype string");let s=t.readSync(n.dataId),a=C.fromUint8ToStringArray(s),i=sA(a,"string",o);return t.makeTensorInfo(n.shape,"string",i)}var GP={kernelName:pi,backendName:"webgl",kernelFunc:Noe};function Toe({inputs:r,attrs:e,backend:t}){let{x:o}=r,n=Gt+`
return x > 0.0 ? 1.0 : float(${e.alpha});
`,s=new nr(o.shape,n);return t.runWebGLProgram(s,[o],o.dtype)}var HP={kernelName:Ko,backendName:"webgl",kernelFunc:Toe};var Wg=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=o;let n=o.length,s=Re(o.length),a=Re(o.length),i="";if(n===1)i="coords * strides + begin";else{let p=0;i=o.map((u,l)=>(p++,o.length===1?`coords * strides[${l}] + begin[${l}]`:`coords[${p-1}] * strides[${l}] + begin[${l}]`)).join(",")}this.userCode=`
${s} begin = ${s}(${e});
${s} strides = ${s}(${t});
2022-11-18 17:13:29 +01:00
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}};function _oe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,end:a,strides:i,beginMask:p,endMask:u,ellipsisMask:l,newAxisMask:c,shrinkAxisMask:m}=o,{finalShapeSparse:d,finalShape:f,isIdentity:h,sliceDim0:g,isSimpleSlice:x,begin:b,end:w,strides:S}=nt.sliceInfo(n.shape,s,a,i,p,u,l,c,m),k;if(h)k=te({inputs:{x:n},backend:t,attrs:{shape:f}});else if(g||x){y.assert(n.shape.length>=1,()=>`Input must have rank at least 1, got: ${n.shape.length}`);let E=nt.computeOutShape(b,w,S),R=Js({inputs:{x:n},backend:t,attrs:{begin:b,size:E}});k=te({inputs:{x:R},backend:t,attrs:{shape:f}}),t.disposeIntermediateTensorInfo(R)}else if(t.shouldExecuteOnCPU([n])){let R=t.readSync(n.dataId),D=ie(n.shape,n.dtype,R),F=aA(d,D,S,b);k=t.makeTensorInfo(f,n.dtype,F.values)}else{let R=new Wg(b,S,d);k=t.runWebGLProgram(R,[n],n.dtype)}let T=te({inputs:{x:k},backend:t,attrs:{shape:f}});return t.disposeIntermediateTensorInfo(k),T}var KP={kernelName:Os,backendName:"webgl",kernelFunc:_oe};function Eoe(r){let{inputs:e,backend:t,attrs:o}=r,{separator:n,nGramWidths:s,leftPad:a,rightPad:i,padWidth:p,preserveShortSequences:u}=o,{data:l,dataSplits:c}=e,m=t.readSync(l.dataId),d=t.readSync(c.dataId),[f,h]=iA(m,d,n,s,a,i,p,u);return[t.makeTensorInfo([f.length],"string",f),t.makeTensorInfo(c.shape,"int32",h)]}var qP={kernelName:Na,backendName:"webgl",kernelFunc:Eoe};function $oe(r){let{inputs:e,backend:t,attrs:o}=r,{skipEmpty:n}=o,{input:s,delimiter:a}=e;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(a.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${a.shape}`);let i=t.readSync(s.dataId),p=t.readSync(a.dataId)[0],[u,l,c]=uA(i,p,n),m=l.length;return[t.makeTensorInfo([m,2],"int32",u),t.makeTensorInfo([m],"string",l),t.makeTensorInfo([2],"int32",new Int32Array(c))]}var jP={kernelName:ru,backendName:"webgl",kernelFunc:$oe};function Roe(r){let{inputs:e,backend:t,attrs:o}=r,{numBuckets:n}=o,{input:s}=e;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(n<=0)throw new Error("Number of buckets must be at least 1");let a=t.readSync(s.dataId),i=pA(a,n);return t.makeTensorInfo(s.shape,"int32",i)}var XP={kernelName:ou,backendName:"webgl",kernelFunc:Roe};var Doe="return tan(x);",Aoe=xe({opSnippet:Doe}),YP={kernelName:Ms,backendName:"webgl",kernelFunc:Aoe};var Foe=`
2022-11-18 17:13:29 +01:00
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,Poe=xe({opSnippet:Foe}),QP={kernelName:Ls,backendName:"webgl",kernelFunc:Poe};function Ooe(r){let{inputs:e,backend:t,attrs:o}=r,{tensor:n,indices:s,updates:a}=e,{}=o,{sliceRank:i,numUpdates:p,sliceSize:u,strides:l,outputSize:c}=C.calculateShapes(a,s,n.shape),m=[c/u,u];if(c===0)return t.makeTensorInfo(n.shape,s.dtype);let d=te({inputs:{x:s},backend:t,attrs:{shape:[p,i]}}),f=te({inputs:{x:a},backend:t,attrs:{shape:[p,u]}}),h=te({inputs:{x:n},backend:t,attrs:{shape:m}}),g=new Tu(p,i,d.shape.length,f.shape.length,l,m,!1,!0),x=t.runWebGLProgram(g,[f,d,h],h.dtype),b=te({inputs:{x},backend:t,attrs:{shape:n.shape}});return t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(x),b}var ZP={kernelName:ks,backendName:"webgl",kernelFunc:Ooe};var Ug=class{constructor(e,t){this.variableNames=["A"];let o=new Array(e.length);for(let a=0;a<o.length;a++)o[a]=e[a]*t[a];this.outputShape=o,this.rank=o.length;let n=Re(this.rank),s=Moe(e);this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${s}));
}
`}};function Moe(r){let e=r.length;if(e>5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`imod(resRC, ${r[0]})`;let t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],o=[];for(let n=0;n<r.length;n++)o.push(`imod(${t[n]}, ${r[n]})`);return o.join()}function q0(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;if(n.dtype==="string"||n.shape.length>5){let p=t.readSync(n.dataId),u=n.dtype==="string"?p.map(m=>y.decodeString(m)):p,l=ie(n.shape,n.dtype,u),c=cA(l,s);return t.makeTensorInfo(c.shape,c.dtype,c.values)}let a=new Ug(n.shape,s);return t.runWebGLProgram(a,[n],n.dtype)}var JP={kernelName:Mo,backendName:"webgl",kernelFunc:q0};var Gg=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced above,
// Figure5(a) shows that element[1] is in the
// second half of the group when group size is 2, but it is in the
// first half of the group when group size is 4.
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
int i = isFirstInPair ? elemIdx : elemIdx - inc;
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
// Denotes which direction indices are in (ascending or descending).
bool reverse = imod(elemIdx, 2 * dir) >= dir;
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
if (reverse == isGreater) { // Elements in opposite order of direction
int iTemp = i0;
i0 = i1;
i1 = iTemp;
}
if (isFirstInPair) {
setOutput(float(i0));
} else {
setOutput(float(i1));
}
}
`}},Hg=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=`
2022-11-18 17:13:29 +01:00
void main() {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
// we only need to output the indices at positions |, the indices at
// positions _ can be thrown away, see Figure5(b) After Phase 2
// (Merge phase) in the Bitonic Top K paper referenced above.
// For example, the paper shows we only need to output the orange bars.
// The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back
// to the previous sequence to find the corresponding value,
// we need to double the index. When we double the index,
// we basically interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
// of each 2k positions by - elemIdx % k. E.g. for output at
// index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
float x0 = getX(batch, i0);
float x1 = i1 < n ? getX(batch, i1) : x0;
setOutput(x0 >= x1 ? float(i0) : float(i1));
}
`}};function Rp(r,e){e!==null&&r.disposeIntermediateTensorInfo(e)}function eO(r){let e=1;for(;e<r;)e*=2;return e}function Loe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o,i=A().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),p=A().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=n.shape,l=u[u.length-1];if(t.shouldExecuteOnCPU([n])||l<i||s>p){let F=t.readSync(n.dataId),[O,M]=mA(F,u,n.dtype,s,a);return[t.makeTensorInfo(O.shape,O.dtype,O.values),t.makeTensorInfo(M.shape,M.dtype,M.values)]}if(s===0)return u[u.length-1]=0,[t.makeTensorInfo(u,n.dtype,[]),t.makeTensorInfo(u,"int32",[])];if(l===1)return[n,Ei({attrs:{shape:u,dtype:"int32",value:0},backend:t})];let c=t.texData.get(n.dataId),m=c!==null&&c.isPacked,d=m?t.unpackTensor(n):n,h=y.sizeFromShape(u)/l,g=te({inputs:{x:d},attrs:{shape:[h,l]},backend:t});m&&Rp(t,d);let x=eO(s),b=eO(l),w=null,S=()=>w===null?[g,g]:[g,w],k=(F,O,M)=>{let L=S(),B=new Gg(M),U=[[l],[w===null?1:0],[Number.NEGATIVE_INFINITY],[F],[O]],j=w;w=t.runWebGLProgram(B,L,"int32",U),Rp(t,j)};for(let F=1;F<x;F*=2){let O=F*2;for(let M=F;M>=1;M/=2)k(O,M,[h,b])}for(let F=b;F>x;F/=2){let O=S(),M=new Hg([h,F/2]),B=[[l],[w===null?1:0],[x]],z=w;w=t.runWebGLProgram(M,O,"int32",B),Rp(t,z);let U=x/2,j=U*2;for(let q=U;q>=1;q/=2)k(j,q,w.shape)}let T=w;w=Js({inputs:{x:w},backend:t,attrs:{begin:0,size:[h,s]}}),Rp(t,T);let E=z0({inputs:{x:g,indices:w},backend:t,attrs:{axis:1,batchDims:1}});Rp(t,g);let R=u.slice(0,-1);R.push(s),T=w,w=te({inputs:{x:w},attrs:{shape:R},backend:t}),Rp(t,T);let D=E;return E=te({inputs:{x:E},attrs:{shape:R},backend:t}),Rp(t,D),[E,w]}var tO={kernelName:Bs,backendName:"webgl",kernelFunc:Loe};var Kg=class{constructor(e,t,o,n,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let i=o==="nearest"?1:2,p;switch(n){case"constant":p=1;break;case"reflect":p=2;break;case"wrap":p=3;break;case"nearest":p=4;break;default:p=1;break}this.userCode=`
2022-11-18 17:13:29 +01:00
float mapCoord(float outCoord, float len) {
float inCoord = outCoord;
if(${p} == 2) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
if (inCoord < sz2) {
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
inCoord;
}
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
inCoord -= sz2 * float(int(float(inCoord / sz2)));
if (inCoord >= len) {
inCoord = sz2 - inCoord - 1.0;
}
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${p} == 3) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord -= len * float(int(float(inCoord / sz)));
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${p} == 4) {
return clamp(outCoord, 0.0, len - 1.0);
} else {
return outCoord;
}
}
float readWithFillValue(int batch, int coordY, int coordX,
int channel) {
float outputValue;
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
2022-11-18 17:13:29 +01:00
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = float(${s});
}
return outputValue;
}
void main() {
ivec4 coords = getOutputCoords();
float outputValue;
int batch = coords[0];
int x = coords[2];
int y = coords[1];
int channel = coords[3];
float xf = float(x);
float yf = float(y);
float a1 = getTransforms(batch, 0);
float a2 = getTransforms(batch, 1);
float a3 = getTransforms(batch, 2);
float b1 = getTransforms(batch, 3);
float b2 = getTransforms(batch, 4);
float b3 = getTransforms(batch, 5);
float c1 = getTransforms(batch, 6);
float c2 = getTransforms(batch, 7);
float projection = c1 * xf + c2 * yf + 1.0;
if (projection == 0.0) {
outputValue = float(${s});
} else {
float inX = (a1 * xf + a2 * yf + a3) / projection;
float inY = (b1 * xf + b2 * yf + b3) / projection;
float mapX = mapCoord(inX, float(${t}));
float mapY = mapCoord(inY, float(${e}));
2022-11-18 17:13:29 +01:00
if (${i} == 1) {
int coordY = int(round(mapY));
int coordX = int(round(mapX));
outputValue = readWithFillValue(batch, coordY, coordX,
channel);
} else {
float yFloor = floor(mapY);
float xFloor = floor(mapX);
float yCeil = yFloor + 1.0;
float xCeil = xFloor + 1.0;
float valueYFloor = (xCeil - mapX) *
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
float valueYCeil = (xCeil - mapX) *
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
outputValue = (yCeil - mapY) * valueYFloor +
(mapY - yFloor) * valueYCeil;
}
}
setOutput(outputValue);
}
`}};function Boe(r){let{inputs:e,backend:t,attrs:o}=r,{image:n,transforms:s}=e,{interpolation:a,fillMode:i,fillValue:p,outputShape:u}=o,[l,c,m,d]=n.shape,[f,h]=u!=null?u:[c,m],g=[l,f,h,d],x=new Kg(c,m,a,i,p,g);return t.runWebGLProgram(x,[n,s],"float32")}var rO={kernelName:zs,backendName:"webgl",kernelFunc:Boe};function zoe(r){let{inputs:e,attrs:t,backend:o}=r,{axis:n}=t,{x:s}=e;Ys(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let a=o.readSync(s.dataId),{outputValues:i,outputShape:p,indices:u}=dA(a,n,s.shape,s.dtype);return[o.makeTensorInfo(p,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var oO={kernelName:nu,backendName:"webgl",kernelFunc:zoe};function Voe(r){let{inputs:e,backend:t,attrs:o}=r,{value:n}=e,{axis:s}=o;s<0&&(s+=n.shape.length);let a=n,i=a.shape.length,p=n.shape[s],u=new Array(i-1),l=0;for(let h=0;h<i;h++)h!==s&&(u[l++]=a.shape[h]);let c=[],m=new Array(i).fill(0),d=a.shape.slice();d[s]=1;let f=new Array(p);for(let h=0;h<f.length;h++){m[s]=h;let g=Js({inputs:{x:a},backend:t,attrs:{begin:m,size:d}}),x=te({inputs:{x:g},backend:t,attrs:{shape:u}});f[h]=x,c.push(g)}return c.forEach(h=>t.disposeIntermediateTensorInfo(h)),f}var nO={kernelName:Ta,backendName:"webgl",kernelFunc:Voe};var qg=class{constructor(e,t){this.variableNames=["x","segmentIds"];let o=e.windowSize,n=e.batchSize,s=e.inSize,a=e.numSegments,i=a*Math.ceil(s/o);this.outputShape=[n,i];let p="0.0",u="sumValue",l=Math.floor(o/4)*4,c=o%4,m=`
2022-11-18 17:13:29 +01:00
sumValue += dot(values, segFilter);
2022-11-20 22:20:02 +01:00
`,d="";s%o>0&&(d=`
2022-11-18 17:13:29 +01:00
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
2022-11-20 22:20:02 +01:00
`);let f="";s%o>0&&(f=`
2022-11-18 17:13:29 +01:00
if (inIdx < 0 || inIdx >= ${s}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${p};
float getValue(int batch, int inIdx) {
2022-11-20 22:20:02 +01:00
${d}
2022-11-18 17:13:29 +01:00
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
2022-11-20 22:20:02 +01:00
${f}
2022-11-18 17:13:29 +01:00
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${a})) * float(${o}));
int currentSeg = int(mod(float(outIdx), float(${a})));
float sumValue = 0.0;
for (int i = 0; i < ${l}; i += 4) {
2022-11-18 17:13:29 +01:00
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${m}
}
int inIdx = inOffset + ${l};
if (${c===1}) {
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
${m}
} else if (${c===2}) {
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
${m}
} else if (${c===3}) {
2022-11-18 17:13:29 +01:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
${m}
}
setOutput(${u});
}
`}};function Woe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,segmentIds:s}=e,{numSegments:a}=o,i=n.shape.length,p=[],u=0,l=C.getAxesPermutation([u],i),c=n;l!=null&&(c=Ct({inputs:{x:n},backend:t,attrs:{perm:l}}),p.push(c),u=C.getInnerMostAxes(1,i)[0]);let m=C.segment_util.computeOutShape(c.shape,u,a),d=y.sizeFromShape([c.shape[u]]),f=te({inputs:{x:c},backend:t,attrs:{shape:[-1,d]}});p.push(f);let h=mi(n.dtype),g=(S,k,T,E,R)=>{let D=S.shape[0],F=S.shape[1],O=C.segment_util.segOpComputeOptimalWindowSize(F,R),M={windowSize:O,inSize:F,batchSize:D,numSegments:R},L=new qg(M,k),B=t.compileAndRun(L,[S,T],E);if(p.push(B),B.shape[1]===R)return B;let z=K0({backend:t,attrs:{start:0,stop:R,step:1,dtype:"float32"}}),U=q0({inputs:{x:z},backend:t,attrs:{reps:[F/O]}});return p.push(z),p.push(U),g(B,k,U,E,R)},x=g(f,"unsortedSegmentSum",s,h,a),b=te({inputs:{x},backend:t,attrs:{shape:m}}),w=b;if(l!=null){p.push(b);let S=C.getUndoAxesPermutation(l);w=Ct({inputs:{x:w},backend:t,attrs:{perm:S}})}return p.forEach(S=>t.disposeIntermediateTensorInfo(S)),w}var sO={kernelName:su,backendName:"webgl",kernelFunc:Woe};var Uoe=[VA,UA,GA,HA,qA,jA,XA,YA,JA,eF,tF,rF,oF,nF,sF,aF,iF,uF,pF,lF,cF,dF,fF,hF,gF,CF,SF,IF,RA,kF,TF,_F,EF,$F,RF,DF,AF,FF,PF,OF,BF,zF,VF,WF,UF,GF,HF,KF,qF,jF,XF,YF,QF,ZF,JF,e3,r3,o3,n3,s3,i3,u3,p3,l3,c3,m3,d3,f3,h3,$A,g3,NF,x3,y3,b3,DA,C3,w3,S3,I3,v3,k3,N3,T3,_3,E3,R3,D3,A3,F3,P3,O3,L3,z3,V3,W3,U3,G3,X3,PA,Y3,Q3,Z3,J3,xF,eP,oP,nP,sP,aP,AA,iP,uP,pP,lP,cP,yF,H3,mP,dP,fP,MA,hP,gP,xP,yP,bP,CP,wP,SP,IP,vP,kP,NP,TP,_P,EP,$P,mF,j3,RP,DP,AP,FP,PP,OP,MP,LP,zP,VP,UP,GP,HP,KP,qP,jP,XP,q3,BA,YP,QP,ZP,JP,tO,rO,zA,oO,nO,sO,tP];for(let r of Uoe)li(r);var we;(function(r){r[r.float32=0]="float32",r[r.int32=1]="int32",r[r.bool=2]="bool",r[r.string=3]="string",r[r.complex64=4]="complex64"})(we||(we={}));var _u;(function(r){r[r.linear=0]="linear",r[r.relu=1]="relu",r[r.relu6=2]="relu6",r[r.prelu=3]="prelu",r[r.leakyrelu=4]="leakyrelu",r[r.sigmoid=5]="sigmoid",r[r.elu=6]="elu"})(_u||(_u={}));var aO;function Goe(r){aO=r.wasm.cwrap(qo,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Hoe(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e;if(n.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:p,transposeB:u,activation:l,leakyreluAlpha:c}=o,m=t.dataIdMap.get(n.dataId).id,d=t.dataIdMap.get(s.dataId).id,f=0;if(a!=null){let R=t.dataIdMap.get(a.dataId);if(R.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${R.shape.length}.`);f=R.id}let h=i==null?0:t.dataIdMap.get(i.dataId).id,g=_u[l];if(g==null)throw new Error(`${l} activation not yet supported for FusedConv2D in the wasm backend.`);let x=p?n.shape[2]:n.shape[1],b=u?s.shape[1]:s.shape[2],w=kr.assertAndGetBroadcastShape(n.shape.slice(0,-2),s.shape.slice(0,-2)),S=t.makeOutput([...w,x,b],n.dtype),k=t.dataIdMap.get(S.dataId).id,T=new Uint8Array(new Int32Array(n.shape).buffer),E=new Uint8Array(new Int32Array(s.shape).buffer);return aO(m,T,n.shape.length,d,E,s.shape.length,p,u,g,f,h,c||0,k),S}var iO={kernelName:qo,backendName:"wasm",setupFunc:Goe,kernelFunc:Hoe};function he(r,e){let t;function o(s){t=s.wasm.cwrap(r,null,["number","number","number"])}function n(s){let{backend:a,inputs:{x:i}}=s,p=a.dataIdMap.get(i.dataId).id,u=a.makeOutput(i.shape,e||i.dtype),l=a.dataIdMap.get(u.dataId).id;return y.sizeFromShape(u.shape)===0||t(p,we[i.dtype],l),u}return{kernelName:r,backendName:"wasm",setupFunc:o,kernelFunc:n}}var uO=he(fn);var pO=he(hn);var lO=he(gn);function He(r,e,t){let o;function n(a){o=a.wasm.cwrap(r,null,["number","array","number","number","array","number","number","number"])}function s(a){let{backend:i,inputs:p}=a,{a:u,b:l}=p,c=i.dataIdMap.get(u.dataId).id,m=i.dataIdMap.get(l.dataId).id,d=t!=null?t:u.dtype,f=C.assertAndGetBroadcastShape(u.shape,l.shape),h=i.makeOutput(f,d);if(y.sizeFromShape(f)===0)return h;let g=new Uint8Array(new Int32Array(u.shape).buffer),x=new Uint8Array(new Int32
2022-11-18 17:13:29 +01:00
${o.shape}`);if(n.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
${n.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let a=e.dataIdMap.get(o.dataId).id,i=e.dataIdMap.get(n.dataId).id,p=e.dataIdMap.get(s.dataId).id,u=o.shape[0],l=y.sizeFromShape(s.shape),c=e.makeOutput([u,l],o.dtype),m=e.dataIdMap.get(c.dataId).id,d=e.makeOutput([l],s.dtype),f=e.dataIdMap.get(d.dataId).id,h=e.makeOutput([3],"int32"),g=e.dataIdMap.get(h.dataId).id;UB(a,i,p,u,m,f,g);let x=e.readSync(h.dataId),b;switch(x[0]){case 0:{b=C.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(x[1],x[2]);break}case 1:{b=C.getSparseReshapeNegativeOutputDimErrorMessage(x[1],x[2]);break}case 2:b=C.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let w=Array.from(e.readSync(n.dataId)),S=Array.from(e.readSync(d.dataId));b=C.getSparseReshapeInputOutputMultipleErrorMessage(w,S);break}case 4:{let w=Array.from(e.readSync(n.dataId)),S=Array.from(e.readSync(d.dataId));b=C.getSparseReshapeInputOutputMismatchErrorMessage(w,S);break}default:b=""}if(e.disposeData(h.dataId),b)throw e.disposeData(c.dataId),e.disposeData(d.dataId),new Error(b);return[c,d]}var GB={kernelName:ui,backendName:"wasm",setupFunc:Wae,kernelFunc:Uae};var HB;function Qg(r){HB=r.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function Zg(r,e){let{backend:t,inputs:o}=r,{data:n,indices:s,segmentIds:a}=o,i=s.shape[0],p=t.readSync(a.dataId,i-1,i)[0],l=i>0?p+1:0;if(l<0)throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let c=n.shape.slice();c[0]=l;let m=t.dataIdMap.get(n.dataId).id,d=t.dataIdMap.get(s.dataId).id,f=t.dataIdMap.get(a.dataId).id,h=t.makeOutput(c,n.dtype),g=t.dataIdMap.get(h.dataId).id,x=t.makeOutput([4],"int32"),b=t.dataIdMap.get(x.dataId).id;HB(m,we[n.dtype],n.shape[0],d,f,g,b,e,0);let w=t.readSync(x.dataId),S;switch(w[0]){case 0:{S=C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{S=C.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:S=C.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(w[1],w[2]);break;case 3:S=C.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(w[1],w[2],w[3]);break;default:S=""}if(t.disposeData(x.dataId),S)throw t.disposeData(h.dataId),new Error(S);return h}function Gae(r){return Zg(r,!0)}var KB={kernelName:va,backendName:"wasm",setupFunc:Qg,kernelFunc:Gae};function Hae(r){return Zg(r,!1)}var qB={kernelName:ka,backendName:"wasm",setupFunc:Qg,kernelFunc:Hae};var jB;function Kae(r){jB=r.wasm.cwrap(Ps,null,["number","number","number","number","number","number","number","number","array","number","number"])}function qae(r){let{backend:e,inputs:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=t,{outputShape:i}=o,p=e.makeOutput(i,a.dtype);if(y.sizeFromShape(i)===0)return p;let{sliceRank:u,numUpdates:l,sliceSize:c,strides:m,outputSize:d}=C.calculateShapes(s,n,i),f=e.dataIdMap.get(n.dataId).id,h=e.dataIdMap.get(s.dataId).id,g=e.dataIdMap.get(a.dataId).id,x=new Uint8Array(new Int32Array(m).buffer),b=e.dataIdMap.get(p.dataId).id;return jB(f,h,s.shape.length,g,we[a.dtype],u,l,c,x,d,b),p}var XB={kernelName:Ps,backendName:"wasm",setupFunc:Kae,kernelFunc:qae};function jae(r){let{inputs:e,attrs:t,backend:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=t,i=y.parseAxisParam(a,n.shape)[0],p=C.prepareSplitSize(n,s,i),u=new Array(n.shape.length).fill(0),l=n.shape.slice();return p.map(c=>{let m=[...l];m[i]=c;let d=an({inputs:{x:n},attrs:{begin:u,size:m},backend:o});return u[i]+=c,d})}var YB={kernelName:Ia,backendName:"wasm",kernelFunc:jae};var QB=he(Fo);var ZB=he(tu);var Xae=!0,JB=He(Po,Xae);var ez;function Yae(r){ez=r.wasm.cwrap(Ko,null,["number","number","number","number"])}function Qae(r){let{backend:e,inputs:t,attrs:o}=r,{alpha:n}=o,{x:s}=t,a=e.dataIdMap.get(s.dataId).id,i=e.makeOutput(s.shape,s.dtype),p=e.dataIdMap.get(i.dataId).id;return ez(a,n,we[s.dtype],p),i}var tz={kernelName:Ko,backendName:"wasm",setupFunc:Yae,kernelFunc:Qae};var rz;function Zae(r){rz=r.wasm.cwrap(Os,null,["number","array","
2023-01-06 19:23:06 +01:00
{
var oldValue = 0;
loop {
let newValueF32 = bitcast<f32>(oldValue) + (${e});
2023-01-06 19:23:06 +01:00
let newValue = bitcast<i32>(newValueF32);
let res = atomicCompareExchangeWeak(${r}, oldValue, newValue);
if res.exchanged {
break;
}
oldValue = res.old_value;
}
}`;var $i;(function(r){r[r.FROM_PIXELS=0]="FROM_PIXELS",r[r.DRAW=1]="DRAW"})($i||($i={}));var Wz=(r,e,t,o,n)=>{let s={dtype:o.dtype,shape:o.shape},a=Eie(t,s,e),i=r.createShaderModule({code:a,label:e.constructor.name}),p=A().get("WEBGPU_PRINT_SHADER");if(p!==""){p=p.toLowerCase();let u=p.split(",");(p==="all"||u.some(l=>e.shaderKey.toLowerCase().includes(l)))&&(console.group(e.shaderKey),console.debug(a),console.groupEnd())}return n?r.createComputePipelineAsync({compute:{module:i,entryPoint:"_start"},label:e.constructor.name,layout:"auto"}):r.createComputePipeline({compute:{module:i,entryPoint:"_start"},label:e.constructor.name,layout:"auto"})},Ae=(r,e="f32")=>{switch(r){case 1:return`${e}`;case 2:return`vec2<${e}>`;case 3:return`vec3<${e}>`;case 4:return`vec4<${e}>`;default:throw new Error(`${r}-component ${e} is not supported.`)}};function ft(r){if(r<=1)return"i32";if(r===2)return"vec2<i32>";if(r===3)return"vec3<i32>";if(r===4)return"vec4<i32>";if(r===5)return"vec5";if(r===6)return"vec6";throw Error(`GPU for rank ${r} is not yet supported`)}function un(r){if(r===0)return"x";if(r===1)return"y";if(r===2)return"z";if(r===3)return"w";if(r===4)return"u";if(r===5)return"v";throw Error(`Index ${r} is not yet supported`)}function G(...r){let e;switch(r.length){case 0:e=`
2022-11-18 17:13:29 +01:00
fn main()
`;break;case 1:e=`
2022-11-18 17:13:29 +01:00
fn main(${r[0]} : i32)
`;break;default:throw Error("Unreachable")}return e}function Bz(r,e){let t;return t=`
${_ie(e)}
2022-11-20 22:20:02 +01:00
fn _start(@builtin(local_invocation_id) LocalId : vec3<u32>,
@builtin(global_invocation_id) GlobalId : vec3<u32>,
@builtin(local_invocation_index) LocalIndex: u32,
@builtin(workgroup_id) WorkgroupId : vec3<u32>,
@builtin(num_workgroups) NumWorkgroups : vec3<u32>) {
localId = LocalId;
localIndex = LocalIndex;
globalId = GlobalId;
numWorkgroups = NumWorkgroups;
workgroupId = WorkgroupId;
${r?"main(getGlobalIndex());":"main();"};
}
`,t}function _ie(r){return`
2023-01-06 19:23:06 +01:00
@compute @workgroup_size(${r.workgroupSize[0]}, ${r.workgroupSize[1]}, ${r.workgroupSize[2]})
`}function Eie(r,e,t){let o=[],n=t.workgroupSize[0]*t.workgroupSize[1]*t.workgroupSize[2];if(t.outputComponent=t.outputComponent?t.outputComponent:1,o.push(`
2022-11-18 17:13:29 +01:00
var<private> localId: vec3<u32>;
2022-11-20 22:20:02 +01:00
var<private> localIndex: u32;
2022-11-18 17:13:29 +01:00
var<private> globalId: vec3<u32>;
var<private> numWorkgroups: vec3<u32>;
2022-11-20 22:20:02 +01:00
var<private> workgroupId: vec3<u32>;
2022-11-18 17:13:29 +01:00
// Only used when the y/z dimension of workgroup size is 1.
fn getGlobalIndex() -> i32 {
${Gz(t)?" return i32(globalId.x);":` return i32((workgroupId.z * numWorkgroups.x * numWorkgroups.y +
2023-01-06 19:23:06 +01:00
workgroupId.y * numWorkgroups.x + workgroupId.x) * ${n}u +
2022-11-20 22:20:02 +01:00
localIndex);
2022-11-18 17:13:29 +01:00
`}
}
`),t.pixelsOpType!=null){let f=t.pixelsOpType===$i.FROM_PIXELS?`@group(0) @binding(0) var<storage, read_write> result: array<${Eu(e.dtype,t.outputComponent)}>;`:`@group(0) @binding(1) var<storage, read> inBuf : array<${Eu(r[0].dtype,t.outputComponent)}>;`,h=e.shape.length===3?"vec2<i32>":"i32";o.push(`
2022-11-18 17:13:29 +01:00
struct Uniform {
2023-08-05 15:03:11 +02:00
outShapeStrides : ${h},
2022-11-18 17:13:29 +01:00
size : i32,
numChannels : i32,
2023-08-05 15:03:11 +02:00
alpha : f32,
2022-11-18 17:13:29 +01:00
};
2023-08-05 15:03:11 +02:00
${f}
2022-11-18 17:13:29 +01:00
@group(0) @binding(2) var<uniform> uniforms: Uniform;
`);let g=Vz(t);return[zz,o.join(`
`),xm(e.shape),t.getUserCode(),Bz(g,t)].join(`
`)}let s,a,i="struct Uniforms { NAN : f32, INFINITY : f32, ";t.variableNames.forEach((f,h)=>{let g=ft(r[h].shape.length);i+=`${f.charAt(0).toLowerCase()+f.slice(1)}Shape : ${g}, `,s=r[h].shape.length-1,a=ft(s),i+=`${f.charAt(0).toLowerCase()+f.slice(1)}ShapeStrides: ${a}, `});let p=ft(e.shape.length);i+=`outShape : ${p}, `,s=e.shape.length-1,a=ft(s),i+=`
outShapeStrides: ${a}, `,t.size&&(i+="size : i32, "),t.uniforms&&(i+=t.uniforms),i+="};",i=Mie(i),o.push(i),t.atomic?o.push(`
2022-11-18 17:13:29 +01:00
@group(0) @binding(0) var<storage, read_write> result: array<atomic<i32>>;
`):o.push(`
@group(0) @binding(0) var<storage, read_write> result: array<${Eu(e.dtype,t.outputComponent)}>;
`),t.variableNames.forEach((f,h)=>{o.push(`
@group(0) @binding(${1+h}) var<storage, read> ${f}: array<${t.variableComponents?Eu(r[h].dtype,t.variableComponents[h]):Eu(r[h].dtype,t.outputComponent)}>;
2023-05-08 15:12:41 +02:00
`)}),i!==""&&o.push(`
@group(0) @binding(${1+t.variableNames.length}) var<uniform> uniforms: Uniforms;
`);let u=Fie(e.shape,t.dispatchLayout),l=[zz,o.join(`
`)+$ie,xm(e.shape),u,Pie(e.shape.length)];t.atomic||l.push(Oie(e.shape,e.dtype,t.outputComponent)),t.variableNames.forEach((f,h)=>{l.push(`${xm(r[h].shape,f)}`)});let c=r.map((f,h)=>Aie(f,e.shape,t.variableComponents?t.variableComponents[h]:t.outputComponent,t.dispatchLayout.x.length===e.shape.length)).join(`
`);l.push(c),l.push(t.getUserCode());let m=Vz(t);return l.push(Bz(m,t)),l.join(`
`)}function Uz(r,e,t){let o=r.shaderKey;if(r.pixelsOpType!=null)return o;let n=[],s=[];e.forEach(l=>{n.push(l.shape),s.push(l.dtype)}),n.push(t.shape),s.push(t.dtype);let a=e.map(l=>C.getBroadcastDims(l.shape,t.shape)),i=e.map(l=>y.arraysEqual(l.shape,t.shape)).join("_"),p=a.map(l=>l.join("_")).join(";"),u=Gz(r)?"flatDispatch":"";return o+="_"+(r.workgroupSize?r.workgroupSize.join(","):"")+n.map(l=>l.length).join(",")+s.join(",")+r.variableNames.join(",")+p+i+u,o}var zz=`
2022-11-18 17:13:29 +01:00
struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32};
struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32};
// Checks whether coordinates lie within the bounds of the shape.
fn coordsInBounds2D(coord : vec2<i32>, shape : vec2<i32>) -> bool {
return all(coord >= vec2<i32>(0)) && all(coord < shape);
}
fn coordsInBounds3D(coord : vec3<i32>, shape : vec3<i32>) -> bool {
return all(coord >= vec3<i32>(0)) && all(coord < shape);
}
fn coordsInBounds4D(coord : vec4<i32>, shape : vec4<i32>) -> bool {
return all(coord >= vec4<i32>(0)) && all(coord < shape);
}
fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 {
return coord;
}
fn getIndexFromCoords2D(coords : vec2<i32>, shape : vec2<i32>) -> i32 {
return dot(coords, vec2<i32>(shape.y, 1));
}
fn getIndexFromCoords3D(coords : vec3<i32>, shape : vec3<i32>) -> i32 {
return dot(coords, vec3<i32>(shape.y * shape.z, shape.z, 1));
}
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
return dot(coords, vec4<i32>(
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
}
fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 {
let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1);
return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u;
}
fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 {
let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1);
return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v;
}
// NaN defination in IEEE 754-1985 is :
// - sign = either 0 or 1.
// - biased exponent = all 1 bits.
// - fraction = anything except all 0 bits (since all 0 bits represents infinity).
// https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers
fn isnan(val: f32) -> bool {
let floatToUint: u32 = bitcast<u32>(val);
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
}
fn isnanVec4(val : vec4<f32>) -> vec4<bool> {
2023-01-06 19:23:06 +01:00
let floatToUint: vec4<u32> = bitcast<vec4<u32>>(val);
return (floatToUint & vec4<u32>(0x7fffffffu)) > vec4<u32>(0x7f800000u);
2022-11-18 17:13:29 +01:00
}
`,$ie=`
2022-11-20 22:20:02 +01:00
fn isinf(val: f32) -> bool {
return abs(val) == uniforms.INFINITY;
}
`;function xm(r,e=""){let t=r.length,o=e!==""?`get${e.charAt(0).toUpperCase()+e.slice(1)}CoordsFromIndex`:"getCoordsFromIndex",n=e!==""?`${e.charAt(0).toLowerCase()+e.slice(1)}ShapeStrides`:"outShapeStrides";if(t<=1)return`fn ${o}(index : i32) -> i32 { return index; }`;let s=y.computeStrides(r),a=ft(t),i=[];for(let u=0;u<t;u++)i.push(`d${u}`);if(s.length===1)return` fn ${o}(index : i32) -> vec2<i32> {
2023-05-08 15:12:41 +02:00
let d0 = index / uniforms.${n}; let d1 = index - d0 * uniforms.${n};
2022-11-18 17:13:29 +01:00
return vec2<i32>(d0, d1);
}`;let p;return p="var index2 = index;"+s.map((u,l)=>{let c=`let ${i[l]} = index2 / uniforms.${n}.${un(l)}`,m=l===s.length-1?`let ${i[l+1]} = index2 - ${i[l]} * uniforms.${n}.${un(l)}`:`index2 = index2 - ${i[l]} * uniforms.${n}.${un(l)}`;return`${c}; ${m};`}).join(""),`
2023-05-08 15:12:41 +02:00
fn ${o}(index : i32) -> ${a} {
${p}
return ${a}(${i.join(",")});
2022-11-18 17:13:29 +01:00
}
`}function Rie(r,e){let t=r.name,o=r.shape.length,n=ft(o),s="get"+t.charAt(0).toUpperCase()+t.slice(1),a=["d0","d1","d2","d3","d4","d5"].slice(0,o),i=a.map(l=>`${l} : i32`).join(", ");if(o<1)return`
fn ${s}() -> ${Ae(e)} {
return ${Ae(e)}(${t}[0]);
}
`;let p=`uniforms.${t.charAt(0).toLowerCase()+t.slice(1)}Shape`,u=`${o}D`;return o===0&&(u="1D"),`
fn ${s}(${i}) -> ${Ae(e)} {
return ${Ae(e)}(${t}[getIndexFromCoords${u}(${n}(${a.join(",")}),
${p})${e===1?"":` / ${e}`}]);
2022-11-18 17:13:29 +01:00
}
`}function Die(r,e,t,o){let n=r.name,s=n.charAt(0).toUpperCase()+n.slice(1),a="get"+s+"ByOutput",i=r.shape.length,p=e.length,u=ft(p);if(y.arraysEqual(r.shape,e)&&o)return`
fn ${a}Index(globalIndex : i32) -> ${Ae(t)} {
return ${Ae(t)}(${n}[globalIndex]);
2022-11-18 17:13:29 +01:00
}
fn ${a}Coords(coords : ${u}) -> ${Ae(t)} {
return ${Ae(t)}(${n}[${p>1?"getOutputIndexFromCoords(coords)":"coords"}${t===1?"":` / ${t}`}]);
2022-11-18 17:13:29 +01:00
}
`;let l=C.getBroadcastDims(r.shape,e),c=p-i,m="";if(i===0)return`
fn ${a}Index(globalIndex : i32) -> ${Ae(t)}{
2022-11-18 17:13:29 +01:00
return get${s}();
}
fn ${a}Coords(coords : ${u}) -> ${Ae(t)}{
2022-11-18 17:13:29 +01:00
return get${s}();
}
`;p<2&&l.length>=1?m="coords = 0;":m=l.map(g=>`coords.${un(g+c)} = 0;`).join(`
`);let d="";if(p<2&&i>0)d="coords";else if(p>1){let g=ft(i),x=r.shape.map((b,w)=>`coords.${un(w+c)}`).join(", ");d=`${g}(${x})`}else d="coords";let f=`uniforms.${n.charAt(0).toLowerCase()+n.slice(1)}Shape`,h=`${i}D`;return`
fn ${a}Index(globalIndex : i32) -> ${Ae(t)} {
2022-11-18 17:13:29 +01:00
var coords = getCoordsFromIndex(globalIndex);
${m}
return ${Ae(t)}(${n}[getIndexFromCoords${h}(${d}, ${f})${t===1?"":` / ${t}`}]);
2022-11-18 17:13:29 +01:00
}
fn ${a}Coords(coordsIn : ${u}) -> ${Ae(t)} {
2022-11-18 17:13:29 +01:00
var coords = coordsIn;
${m}
return ${Ae(t)}(${n}[getIndexFromCoords${h}(${d}, ${f})${t===1?"":` / ${t}`}]);
2022-11-18 17:13:29 +01:00
}
`}function Aie(r,e,t,o){let n=Rie(r,t);return r.shape.length<=e.length&&(n+=Die(r,e,t,o)),n}function Fie(r,e){let{x:t,y:o=[],z:n=[]}=e,s=r.length,a=t.length+o.length+n.length;if(a!==s)return"";if(t.length===s)return`fn getOutputCoords() -> ${ft(s)}{
2022-11-18 17:13:29 +01:00
let globalIndex = getGlobalIndex();
return getCoordsFromIndex(globalIndex);
}
`;let i="",p=[t,o,n];for(let m=0;m<p.length;m++){let d=p[m];if(d.length!==0)if(d.length===1)i+=`let d${d[0]} = i32(globalId[${m}]);`;else{let f=Lz(d,"uniforms.outShape");i+=`var index${m} = i32(globalId[${m}]);`;for(let h=0;h<f.length;h++)i+=`let d${d[h]} = index${m} / ${f[h]};`,h===f.length-1?i+=`let d${d[h+1]} = index${m} - d${d[h]} * ${f[h]};`:i+=`index${m} = index${m} - d${d[h]} * ${f[h]};`}}let u=[];for(let m=0;m<a;m++)u.push(`d${m}`);let l=ft(a),c=`fn getOutputCoords() -> ${l} {
2022-11-18 17:13:29 +01:00
${i}
`;return u.length===0?c+=`return ${l}(0); }`:c+=`return ${l}(${u.join(",")}); }`,c}function Pie(r){let e="";switch(r){case 0:case 1:e+=`
2022-11-18 17:13:29 +01:00
fn getOutputIndexFromCoords(coords : i32) -> i32 {
return coords;
}
`;break;case 2:e+=`
2022-11-18 17:13:29 +01:00
fn getOutputIndexFromCoords(coords : vec2<i32>) -> i32 {
return dot(coords, vec2<i32>(uniforms.outShapeStrides, 1));
}
`;break;case 3:e+=`
2022-11-18 17:13:29 +01:00
fn getOutputIndexFromCoords(coords : vec3<i32>) -> i32 {
return dot(coords, vec3<i32>(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1));
}
`;break;case 4:e+=`
2022-11-18 17:13:29 +01:00
fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
return dot(coords, vec4<i32>(
uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1));
}
`;break;case 5:e+=`
2022-11-18 17:13:29 +01:00
fn getOutputIndexFromCoords(coords : vec5) -> i32 {
return coords.x * uniforms.outShapeStrides.x +
coords.y * uniforms.outShapeStrides.y +
coords.z * uniforms.outShapeStrides.z +
coords.w * uniforms.outShapeStrides.w +
coords.u;
}
`;break;case 6:e+=`
2022-11-18 17:13:29 +01:00
fn getOutputIndexFromCoords(coords : vec6) -> i32 {
return coords.x * uniforms.outShapeStrides.x +
coords.y * uniforms.outShapeStrides.y +
coords.z * uniforms.outShapeStrides.z +
coords.w * uniforms.outShapeStrides.w +
coords.u * uniforms.outShapeStrides.u +
coords.v;
}
`;break;default:y.assert(!1,()=>`Unsupported ${r}D shape`);break}return e}function Gz(r){return r.dispatch[1]===1&&r.dispatch[2]===1}function Eu(r,e=1){if(r==="float32")return Ae(e,"f32");if(r==="int32"||r==="bool")return Ae(e,"i32");throw new Error(`type ${r} is not supported.`)}function Oie(r,e,t){let o=r.length,n=Eu(e,t),s=`fn setOutputAtIndex(flatIndex : i32, value : ${Ae(t)}) {
2022-11-18 17:13:29 +01:00
result[flatIndex] = ${n}(value);
}
2023-05-08 15:12:41 +02:00
fn setOutputAtIndexI32(flatIndex : i32, value : ${Ae(t,"i32")}) {
2022-11-18 17:13:29 +01:00
result[flatIndex] = ${n}(value);
}
`;if(o>=2){let a=["d0","d1","d2","d3","d4","d5"].slice(0,o),i=ft(o);s+=`
fn setOutputAtCoords(${a.map(p=>`${p} : i32`).join(", ")}, value : ${Ae(t)}) {
2022-11-18 17:13:29 +01:00
let flatIndex = getOutputIndexFromCoords(${i}(${a.join(", ")}));
setOutputAtIndex(flatIndex${t===1?"":` / ${t}`}, value);
2022-11-18 17:13:29 +01:00
}
fn setOutputAtCoordsI32(${a.map(p=>`${p} : i32`).join(", ")}, value : ${Ae(t,"i32")}) {
2022-11-18 17:13:29 +01:00
let flatIndex = getOutputIndexFromCoords(${i}(${a.join(", ")}));
setOutputAtIndexI32(flatIndex${t===1?"":` / ${t}`}, value);
2023-08-05 15:03:11 +02:00
}
`}return s}function Mie(r){let e=/(\w+)\s*:\s*vec(5|6)/g;r=r.replace(e,o=>"@align(16) "+o);let t=/vec(5|6)\s*,\s*(\w+)/g;return r=r.replace(t,(o,n,s)=>`vec${n}, @align(16) ${s}`),r}function Vz(r){return!(r.dispatchLayout.hasOwnProperty("y")&&r.dispatchLayout.y.length!==0||r.dispatchLayout.hasOwnProperty("z")&&r.dispatchLayout.z.length!==0)}var cv={};qe(cv,{GPUBytesPerElement:()=>sx,MatMulProgramType:()=>pn,assertNotComplex:()=>wm,computeDispatch:()=>H,computeWorkPerThreadForConv2d:()=>bm,computeWorkgroupInfoForMatMul:()=>lv,computeWorkgroupSizeForConv2d:()=>ym,flatDispatchLayout:()=>X,isWebGPUSupported:()=>Cm,tilesFitEvenlyIntoShape:()=>Bie});var Ap=r=>{let e=1;for(let t=0;t<r.length;t++)e*=r[t];return e};function Bie(r,e){if(r.length!==e.length)throw new Error(`Cannot compute whether rank ${r.length} tiles fit evenly into rank ${e.length} shape - ranks must match.`);return e.every((t,o)=>t%r[o]===0)}function H(r,e,t=[1,1,1],o=[1,1,1]){let[n,s,a]=[Math.ceil(Ap(r.x.map(i=>e[i]))/(t[0]*o[0])),r.y?Math.ceil(Ap(r.y.map(i=>e[i]))/(t[1]*o[1])):1,r.z?Math.ceil(Ap(r.z.map(i=>e[i]))/(t[2]*o[2])):1];return[n,s,a]}function lv(r,e,t,o=!1){let n=[8,8,1],s=[4,4,1];return o||(r<=8&&(s[1]=1),e<=16&&t<=16&&(n[0]=4)),{workgroupSize:n,elementsPerThread:s}}function ym(r,e,t=!1){if(t)return[8,8,1];let o=Ap(r.x.map(s=>e[s])),n=Ap(r.y.map(s=>e[s]));return o<=4?[4,16,1]:n<=4?[16,4,1]:[16,16,1]}function bm(r,e,t=!1){if(t)return[4,4,1];let o=Ap(r.x.map(s=>e[s])),n=Ap(r.y.map(s=>e[s]));return o<=4?[1,2,1]:n<=4?[2,1,1]:[2,2,1]}function X(r){return{x:r.map((e,t)=>t)}}function sx(r){if(r==="float32"||r==="int32"||r==="bool"||r==="string")return 4;if(r==="complex64")return 8;throw new Error(`Unknown dtype ${r}`)}function Cm(){return!!(globalThis&&globalThis.navigator&&globalThis.navigator.gpu)}function wm(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&y.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGPU backend.`)})}var pn;(function(r){r[r.MatMulReduceProgram=0]="MatMulReduceProgram",r[r.MatMulSplitKProgram=1]="MatMulSplitKProgram",r[r.MatMulSmallOutputSizeProgram=2]="MatMulSmallOutputSizeProgram",r[r.MatMulPackedProgram=3]="MatMulPackedProgram",r[r.MatMulMax=4]="MatMulMax"})(pn||(pn={}));var zie=A().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),Vie=(r,e)=>{let t=r.limits.maxComputeWorkgroupsPerDimension,o=e.dispatchLayout,n=e.dispatch;if(n.every(a=>a<=t))return n;y.assert(n[0]>t&&o.y===void 0&&o.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let s=Math.ceil(Math.sqrt(n[0]));return s>t?(s=Math.ceil(Math.cbrt(n[0])),y.assert(s<=t,()=>"Total dispatch size exceeds WebGPU maximum."),[s,s,s]):[s,s,1]},Jl=class r extends mo{nextDataId(){return r.nextDataId++}constructor(e,t){if(super(),this.commandQueueOwnedIds=new WeakSet,this.dispatchCountInPass=0,this.disposed=!1,this.downloadWaitMs=0,this.tensorDataPendingDisposal=[],this.queryResolveBuffer=null,this.querySet=null,this.querySetCount=2,this.stagingPendingDisposal=[],this.uniformPendingDisposal=[],this.uploadWaitMs=0,this.hasReadSyncWarned=!1,this.hasTimestampQueryWarned=!1,!Cm())throw new Error("WebGPU is not supported on this device");this.pipelineCache={},this.device=e,this.queue=e.queue,this.commandEncoder=null,this.computePassEncoder=null,this.adapterInfo=new rx(t),this.supportTimestampQuery=this.device.features.has("timestamp-query"),this.thresholdToIncreaseWorkgroups=this.adapterInfo.intelGPUGeneration>=12?16:8,this.bufferManager=new ox(this.device),this.textureManager=new nx(this.device),this.tensorMap=new mn(this,cr()),A().getBool("WEBGPU_USE_PROFILE_TOOL")&&(this.dummyCanvas=document.createElement("canvas"),this.dummyCanvas.width=1,this.dummyCanvas.height=1,this.dummyContext=this.dummyCanvas.getContext("webgpu"),this.dummyContext.configure({device:e,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}floatPrecision(){return 32}disposeData(e,t=!1){if(!this.tensorMap.has(e))return!0;let o=this.tensorMap.get(e);return t?o.refCount=0:o.refCount--,o.refCount>0?!1:(o.complexTensorInfos!=null&&(this.disposeData
2023-08-05 15:03:11 +02:00
let zero = sign(a) * 0 + 0;
let one = sign(b) * 0 + 1;
let resultTemp = select(zero, one, a == b);
`,Xie=`
2023-08-05 15:03:11 +02:00
let remainder =
select(a % b, round(a % b), (round(a) == a) & (round(b) == b));
let quotient = (a - remainder) / b;
let resultTemp =
round(select(quotient, quotient - 1, sign(remainder) == -sign(b)));
`,Yie=`
2023-08-05 15:03:11 +02:00
let zero = sign(a) * 0 + 0;
let one = sign(b) * 0 + 1;
let resultTemp = select(zero, one, a > b);
`,Qie=`
2023-08-05 15:03:11 +02:00
let zero = sign(a) * 0 + 0;
let one = sign(b) * 0 + 1;
let resultTemp = select(zero, one, a >= b);
`,Zie=`
2023-08-05 15:03:11 +02:00
let zero = sign(a) * 0 + 0;
let one = sign(b) * 0 + 1;
let resultTemp = select(zero, one, a < b);
`,Jie=`
2023-08-05 15:03:11 +02:00
let zero = sign(a) * 0 + 0;
let one = sign(b) * 0 + 1;
let resultTemp = select(zero, one, a <= b);
`,eue="return f32(a >= 1.0 && b >= 1.0);",tue=`return (vec4<f32>(a >= vec4<f32>(1.0)) *
vec4<f32>(b >= vec4<f32>(1.0)));`,rue="return f32(a >= 1.0 || b >= 1.0);",oue=`return min(vec4<f32>(a >= vec4<f32>(1.0)) +
vec4<f32>(b >= vec4<f32>(1.0)), vec4<f32>(1.0));`,nue="let resultTemp = max(a, b);",sue="let resultTemp = min(a, b);",aue=`
2023-05-08 15:12:41 +02:00
let isNaN = b == 0.;
2022-11-20 22:20:02 +01:00
var resultTemp = a % b;
2023-05-08 15:12:41 +02:00
resultTemp = select((resultTemp + b) % b, resultTemp,
(a < 0. && b < 0.) || (a >= 0. && b > 0.));
`,iue=`
2023-01-06 19:23:06 +01:00
let isNaN = !vec4<bool>(b);
2022-11-20 22:20:02 +01:00
var resultTemp = vec4<f32>(a % b);
if (!((a[0] < 0. && b[0] < 0.) || (a[0] >= 0. && b[0] > 0.))) {
resultTemp[0] = (resultTemp[0] + b[0]) % b[0];
}
if (!((a[1] < 0. && b[1] < 0.) || (a[1] >= 0. && b[1] > 0.))) {
resultTemp[1] = (resultTemp[1] + b[1]) % b[1];
}
if (!((a[2] < 0. && b[2] < 0.) || (a[2] >= 0. && b[2] > 0.))) {
resultTemp[2] = (resultTemp[2] + b[2]) % b[2];
}
if (!((a[3] < 0. && b[3] < 0.) || (a[3] >= 0. && b[3] > 0.))) {
resultTemp[3] = (resultTemp[3] + b[3]) % b[3];
}
`,uue="let resultTemp = a * b;",pue=`
2023-05-08 15:12:41 +02:00
var resultTemp = f32(a != b);
let valueForNaN = 1.0;
`,lue=`
2022-11-18 17:13:29 +01:00
var resultTemp = vec4<f32>(a != b);
let valueForNaN = 1.0;
`,cue=`
2023-05-08 15:12:41 +02:00
let isNaN = a < 0.0 && floor(b) < b;
2022-11-18 17:13:29 +01:00
if (b == 0.0) {
return 1.0;
}
2023-05-08 15:12:41 +02:00
var resultTemp = select(sign(a) * pow(abs(a), b), pow(abs(a), b),
round(abs(b) % 2.0) != 1.0);
`,mue=`
2022-11-18 17:13:29 +01:00
let isModRound1Bool = vec4<i32>(round(abs(b) % vec4<f32>(2.0))) == vec4<i32>(1);
let isModRound1 = vec4<f32>(isModRound1Bool);
let multiplier = sign(a) * isModRound1 + (vec4<f32>(1.0) - isModRound1);
var resultTemp = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
let isExpZero = b == vec4<f32>(0.0);
if (isExpZero.r) {
resultTemp.r = 1.0;
}
if (isExpZero.g) {
resultTemp.g = 1.0;
}
if (isExpZero.b) {
resultTemp.b = 1.0;
}
if (isExpZero.a) {
resultTemp.a = 1.0;
}
let isNaN = (a < vec4<f32>(0.0)) & (floor(b) < b);
`,due="if (a < 0.0) { return b * a; } return a;",fue=`
2022-11-18 17:13:29 +01:00
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
`,hue="let resultTemp = (a - b) * (a - b);",gue="let resultTemp = a - b;";function ec(r,e){let t;do{switch(r){case fe.ATAN2:t=Uie;break;case fe.MAX:t=nue;break;case fe.MIN:t=sue;break;case fe.MOD:t=e?iue:aue;break;case fe.NOT_EQUAL:t=e?lue:pue;break;case fe.POW:t=e?mue:cue;break;default:continue}let o,n,s;return e?(o="isnanVec4",n="vec4<f32>",s="vec4<bool>"):(o="isnan",n="f32",s="bool"),`
let aIsNaN = ${o}(a);
let aPostLegalization = select(a, ${n}(42), aIsNaN);
let bIsNaN = ${o}(b);
let bPostLegalization = select(b, ${n}(42), bIsNaN);
2023-05-08 15:12:41 +02:00
let isNaN = false;
let valueForNaN = uniforms.NAN;
{
let a = aPostLegalization;
let b = bPostLegalization;
${t}
return select(
resultTemp, ${n}(valueForNaN),
${s}(isNaN) | aIsNaN | bIsNaN);
}
`}while(!1);switch(r){case fe.ADD:t=Wie;break;case fe.COMPLEX_MULTIPLY_IMAG:t=Hie;break;case fe.COMPLEX_MULTIPLY_REAL:t=Gie;break;case fe.DIV:t=Kie;break;case fe.ELU_DER:t=qie;break;case fe.EQUAL:t=jie;break;case fe.FLOOR_DIV:t=Xie;break;case fe.GREATER:t=Yie;break;case fe.GREATER_EQUAL:t=Qie;break;case fe.LESS:t=Zie;break;case fe.LESS_EQUAL:t=Jie;break;case fe.LOGICAL_AND:return e?tue:eue;case fe.LOGICAL_OR:return e?oue:rue;case fe.MUL:t=uue;break;case fe.PRELU:return e?fue:due;case fe.SQUARED_DIFFERENCE:t=hue;break;case fe.SUB:t=gue;break;default:}return`
${t}
return resultTemp;
`}var Z;(function(r){r[r.ABS=0]="ABS",r[r.ACOS=1]="ACOS",r[r.ACOSH=2]="ACOSH",r[r.ASIN=3]="ASIN",r[r.ASINH=4]="ASINH",r[r.ATAN=5]="ATAN",r[r.ATANH=6]="ATANH",r[r.CEIL=7]="CEIL",r[r.COS=8]="COS",r[r.COSH=9]="COSH",r[r.ELU=10]="ELU",r[r.ERF=11]="ERF",r[r.EXP=12]="EXP",r[r.EXPM1=13]="EXPM1",r[r.FLOOR=14]="FLOOR",r[r.IS_FINITE=15]="IS_FINITE",r[r.IS_INF=16]="IS_INF",r[r.IS_NAN=17]="IS_NAN",r[r.LINEAR=18]="LINEAR",r[r.LOG=19]="LOG",r[r.LOG1P=20]="LOG1P",r[r.LOGICAL_NOT=21]="LOGICAL_NOT",r[r.NEG=22]="NEG",r[r.RELU=23]="RELU",r[r.RELU6=24]="RELU6",r[r.LEAKYRELU=25]="LEAKYRELU",r[r.RECIPROCAL=26]="RECIPROCAL",r[r.ROUND=27]="ROUND",r[r.RSQRT=28]="RSQRT",r[r.SELU=29]="SELU",r[r.SIGMOID=30]="SIGMOID",r[r.SIGN=31]="SIGN",r[r.SIN=32]="SIN",r[r.SINH=33]="SINH",r[r.SOFTPLUS=34]="SOFTPLUS",r[r.SQRT=35]="SQRT",r[r.SQUARE=36]="SQUARE",r[r.STEP=37]="STEP",r[r.TAN=38]="TAN",r[r.TANH=39]="TANH",r[r.TO_INT=40]="TO_INT"})(Z||(Z={}));var xue="return abs(a);",yue=`
2022-11-20 22:20:02 +01:00
if (abs(a) > 1.) {
return uniforms.NAN;
}
return acos(a);
`,bue=`
2022-11-20 22:20:02 +01:00
if (a < 1.) {
return uniforms.NAN;
}
return acosh(a);
`,Cue=`
2022-11-20 22:20:02 +01:00
if (abs(a) > 1.) {
return uniforms.NAN;
}
return asin(a);
`,wue="return asinh(a);",Sue=`
2022-11-20 22:20:02 +01:00
if (isnan(a)) {
return uniforms.NAN;
}
return atan(a);
`,Iue=`
2022-11-20 22:20:02 +01:00
if (abs(a) > 1.) {
return uniforms.NAN;
}
if (a == 1.) {
return uniforms.INFINITY;
}
if (a == -1.) {
return -uniforms.INFINITY;
}
return atanh(a);
`,vue="return ceil(a);",kue="return cos(a);",Nue=`
2022-11-18 17:13:29 +01:00
let e2x = exp(-a);
return (e2x + 1.0 / e2x) / 2.0;
`,Tue="return exp(a) - 1.0;",_ue="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",Eue=`
2022-11-18 17:13:29 +01:00
var resFloat = exp(a) - vec4<f32>(1.0);
if (a.r >= 0.0) {
resFloat.r = a.r;
}
if (a.g >= 0.0) {
resFloat.g = a.g;
}
if (a.b >= 0.0) {
resFloat.b = a.b;
}
if (a.a >= 0.0) {
resFloat.a = a.a;
}
return resFloat;
`,$ue=`
2022-11-20 22:20:02 +01:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
let p = ${C.ERF_P};
let a1 = ${C.ERF_A1};
let a2 = ${C.ERF_A2};
let a3 = ${C.ERF_A3};
let a4 = ${C.ERF_A4};
let a5 = ${C.ERF_A5};
2022-11-20 22:20:02 +01:00
let sign = sign(a);
let absA = abs(a);
let t = 1.0 / (1.0 + p * absA);
return sign * (1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-absA * absA));
`,Rue="return exp(a);",Due="return floor(a);",Aue="return f32(!isnan(a) && !isinf(a));",Fue="return f32(isinf(a));",Pue="return f32(isnan(a));",Oue="return a;",Mue=`if (a < 0.0) { return uniforms.NAN; }
return log(a);`,Lue=`
2022-11-20 22:20:02 +01:00
if (isnan(a)) { return a; }
return log(1.0 + a);
`,Bue="return f32(!(a >= 1.0));",zue="return -a;",Vue="if (a < 0.0) { return uniforms.alpha * a; } return a;",Wue=`
2022-11-18 17:13:29 +01:00
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
return (aLessThanZero * (uniforms.alpha * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
`,Uue="return 1.0 / a;",Gue="return select(a, 0.0, a < 0.0);",Hue="return clamp(a, 0.0, 6.0);",Kue="return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));",que=`
2022-11-18 17:13:29 +01:00
return select(a, vec4<f32>(0.0), a < vec4<f32>(0.0));
`,jue="return round(a);",Xue="return inverseSqrt(a);",Yue=`
2023-01-06 19:23:06 +01:00
if (a >= 0.0) {
return ${C.SELU_SCALE} * a;
2023-01-06 19:23:06 +01:00
} else {
return ${C.SELU_SCALEALPHA} * (exp(a) - 1.0);
2023-01-06 19:23:06 +01:00
}
`,Que="return 1.0 / (1.0 + exp(-1.0 * a));",Zue="return sign(a);",Jue="return sin(a);",epe=`
2022-11-18 17:13:29 +01:00
let e2x = exp(a);
return (e2x - 1.0 / e2x) / 2.0;
`,tpe=`
2023-01-06 19:23:06 +01:00
let epsilon = 1.1920928955078125e-7;
let threshold = log(epsilon) + 2.0;
let too_large = a > -threshold;
let too_small = a < threshold;
let exp_a = exp(a);
if (too_large) {
return a;
} else if (too_small) {
return exp_a;
} else {
return log(exp_a + 1.0);
}
`,rpe="return sqrt(a);",ope="return a * a;",npe=`
2023-01-06 19:23:06 +01:00
if (isnan(a)) {
return a;
}
return select(uniforms.stepAlpha, 1.0, a > 0.0);
`,spe="return tan(a);",ape=`
2022-11-18 17:13:29 +01:00
let e2x = exp(-2.0 * abs(a));
return sign(a) * (1.0 - e2x) / (1.0 + e2x);
`,ipe="return f32(i32((a)));";function Ri(r,e){switch(r){case Z.ABS:return xue;case Z.ACOS:return yue;case Z.ACOSH:return bue;case Z.ASIN:return Cue;case Z.ASINH:return wue;case Z.ATAN:return Sue;case Z.ATANH:return Iue;case Z.COS:return kue;case Z.COSH:return Nue;case Z.CEIL:return vue;case Z.ELU:return e?Eue:_ue;case Z.ERF:return $ue;case Z.EXP:return Rue;case Z.EXPM1:return Tue;case Z.FLOOR:return Due;case Z.IS_FINITE:return Aue;case Z.IS_INF:return Fue;case Z.IS_NAN:return Pue;case Z.LINEAR:return Oue;case Z.LOG:return Mue;case Z.LOG1P:return Lue;case Z.LOGICAL_NOT:return Bue;case Z.NEG:return zue;case Z.LEAKYRELU:return e?Wue:Vue;case Z.RECIPROCAL:return Uue;case Z.RELU:return e?que:Gue;case Z.RELU6:return e?Kue:Hue;case Z.ROUND:return jue;case Z.RSQRT:return Xue;case Z.SELU:return Yue;case Z.SIGMOID:return Que;case Z.SIGN:return Zue;case Z.SIN:return Jue;case Z.SINH:return epe;case Z.SOFTPLUS:return tpe;case Z.SQRT:return rpe;case Z.SQUARE:return ope;case Z.STEP:return npe;case Z.TAN:return spe;case Z.TANH:return ape;case Z.TO_INT:return ipe;default:throw new Error(`BinaryType ${r} is not implemented!`)}}function gr(r,e=!1,t=!1,o=3){if(r===null)return"";let n="";if(r==="linear")n=Ri(Z.LINEAR);else if(r==="relu")n=Ri(Z.RELU,t);else if(r==="elu")n=Ri(Z.ELU,t);else if(r==="relu6")n=Ri(Z.RELU6,t);else if(r==="prelu")n=ec(fe.PRELU,t);else if(r==="sigmoid")n=Ri(Z.SIGMOID,t);else if(r==="leakyrelu")n=Ri(Z.LEAKYRELU,t);else throw new Error(`Activation ${r} has not been implemented for the WebGPU backend.`);let a=Ae(t?4:1),i="";return e?i=`
2022-11-18 17:13:29 +01:00
fn activation(a : ${a}, coords : vec${o}<i32>) -> ${a} {
let b = getPreluActivationWeightsByOutputCoords(coords);
${n}
}`:i=`
fn activation(a : ${a}, coords : vec${o}<i32>) -> ${a} {
${n}
}`,i}function no(r,e){return`
2022-11-18 17:13:29 +01:00
${r?"value = value + getBiasByOutputCoords(coords);":""}
${e?"value = activation(value, coords);":""}
`}function mv(r,e,t=!1,o=!1,n=!1,s=1){y.assert(r&&s===1||!r,()=>`transposeA ${r} is not compatible with component size ${s}`);let a=`
2023-01-06 19:23:06 +01:00
${r?"value = getA(batch, col, row);":"value = getA(batch, row, col);"}
`,i=e?"value = getB(batch, col, row);":"value = getB(batch, row, col);";return`
2023-08-05 15:03:11 +02:00
fn mm_readA(batch: i32, row: i32, col: i32) -> ${Ae(s)} {
2023-05-08 15:12:41 +02:00
var value = ${Ae(s)}(0.0);
${t&&n?a:`
2023-01-06 19:23:06 +01:00
${r?"if(row < uniforms.dimAOuter && col < uniforms.dimInner)":"if(row < uniforms.aShape[1] && col < uniforms.aShape[2])"}
2022-11-18 17:13:29 +01:00
{
2023-01-06 19:23:06 +01:00
${a}
2022-11-18 17:13:29 +01:00
}
`}
return value;
}
2023-08-05 15:03:11 +02:00
fn mm_readB(batch: i32, row: i32, col: i32) -> ${Ae(s)} {
2023-05-08 15:12:41 +02:00
var value = ${Ae(s)}(0.0);
2023-01-06 19:23:06 +01:00
${i}
2022-11-18 17:13:29 +01:00
return value;
}
`}function Sm(r,e,t,o,n=!1,s=!1,a=!1,i=1){return`
${mv(t,o,n,s,a,i)}
2023-08-05 15:03:11 +02:00
fn mm_write(batch: i32, row: i32, col: i32, valueIn: ${Ae(i)}) {
2023-01-06 19:23:06 +01:00
${n&&s?"":"if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)"}
2022-11-18 17:13:29 +01:00
{
var value = valueIn;
let coords = vec3<i32>(batch, row, col);
${no(r,e)}
2022-11-18 17:13:29 +01:00
setOutputAtCoords(coords[0], coords[1], coords[2], value);
}
}
`}var upe=(r,e)=>r?`
2023-01-06 19:23:06 +01:00
mm_Asub[inputRow][inputCol] = mm_readA(batchA,
2022-11-18 17:13:29 +01:00
kStart + inputRow,
globalRowStart + inputCol * ${e});
2022-11-18 17:13:29 +01:00
`:`
2023-01-06 19:23:06 +01:00
mm_Asub[inputRow][inputCol] = mm_readA(batchA,
2022-11-18 17:13:29 +01:00
globalRow + innerRow,
kStart + inputCol * ${e});
`,ppe=(r,e,t,o)=>{if(r)return`
2023-08-05 15:03:11 +02:00
for (var k = 0; k < ${o}; k++) {
let BCached0 = mm_Bsub[k][tileCol];
let ACached0 = mm_Asub[k][localRow];
for (var i = 0; i < ${t}; i++) {
2023-05-08 15:12:41 +02:00
acc[i] = fma(BCached0, vec4<f32>(ACached0[i]), acc[i]);
2023-08-05 15:03:11 +02:00
}
}`;{let n="",s="";for(let a=0;a<e;a++)n+=`let BCached${a} = mm_Bsub[k * ${e} + ${a}][tileCol];`,s+=`acc[i] = fma(BCached${a}, vec4<f32>(ACached[${a}]), acc[i]);`;return`
for (var k = 0; k < ${o/e}; k++) {
2023-08-05 15:03:11 +02:00
${n}
for (var i = 0; i < ${t}; i++) {
2022-11-18 17:13:29 +01:00
let ACached = mm_Asub[tileRow + i][k];
2023-08-05 15:03:11 +02:00
${s}
}
}`}};function Fp(r,e,t=!1,o=32,n=!1,s=32,a=!1){let i=e[1]*r[1],p=e[0]*r[0],u=t?i:o,l=t?o:i,c=u/e[0],m=o/e[1],d=r[1],f=r[0];return y.assert((t&&c===4&&r[1]===4||!t&&(c===3||c===4))&&u%e[0]===0&&o%e[1]===0&&r[0]===4,()=>`If transposeA ${t} is true, innerElementSize ${c} and workPerThread[1] ${r[1]} must be 4.
Otherwise, innerElementSize ${c} must be 3 or 4.
tileAWidth ${u} must be divisible by workgroupSize[0]${e[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${r[0]} must be 4.`),`
var<workgroup> mm_Asub : array<array<vec${c}<f32>, ${u/c}>, ${l}>;
2023-05-08 15:12:41 +02:00
var<workgroup> mm_Bsub : array<array<vec4<f32>, ${p/r[0]}>, ${o}>;
2023-08-05 15:03:11 +02:00
${G()} {
2022-11-18 17:13:29 +01:00
let localRow = i32(localId.y);
2023-05-08 15:12:41 +02:00
let tileRow = localRow * ${d};
2022-11-18 17:13:29 +01:00
let tileCol = i32(localId.x);
2023-05-08 15:12:41 +02:00
let globalRow = i32(globalId.y) * ${d};
2023-08-05 15:03:11 +02:00
let globalCol = i32(globalId.x) * ${f};
2022-11-18 17:13:29 +01:00
let batch = ${n?"0":"i32(globalId.z)"};
2023-05-08 15:12:41 +02:00
let batchA = ${n||!a?"batch":"batch % uniforms.aShape[0]"};
let batchB = ${n||!a?"batch":"batch % uniforms.bShape[0]"};
let globalRowStart = i32(workgroupId.y) * ${i};
2022-11-18 17:13:29 +01:00
2023-01-06 19:23:06 +01:00
let numTiles = ${n?`${Math.ceil(s/o)}`:`(uniforms.dimInner - 1) / ${o} + 1`};
2022-11-18 17:13:29 +01:00
var kStart = ${n?`i32(globalId.z) * ${s}`:"0"};
2023-05-08 15:12:41 +02:00
var acc: array<vec4<f32>, ${d}>;
2022-11-18 17:13:29 +01:00
// Loop over shared dimension.
2023-05-08 15:12:41 +02:00
let tileRowB = localRow * ${m};
2023-01-06 19:23:06 +01:00
for (var t = 0; t < numTiles; t++) {
2022-11-18 17:13:29 +01:00
// Load one tile of A into local memory.
2023-05-08 15:12:41 +02:00
for (var innerRow = 0; innerRow < ${d}; innerRow++) {
2022-11-18 17:13:29 +01:00
let inputRow = tileRow + innerRow;
let inputCol = tileCol;
${upe(t,c)}
2022-11-18 17:13:29 +01:00
}
// Load one tile of B into local memory.
2023-05-08 15:12:41 +02:00
for (var innerRow = 0; innerRow < ${m}; innerRow++) {
2022-11-18 17:13:29 +01:00
let inputRow = tileRowB + innerRow;
let inputCol = tileCol;
2023-01-06 19:23:06 +01:00
mm_Bsub[inputRow][inputCol] = mm_readB(batchB, kStart + inputRow, globalCol);
2022-11-18 17:13:29 +01:00
}
2023-01-06 19:23:06 +01:00
kStart = kStart + ${o};
2022-11-18 17:13:29 +01:00
workgroupBarrier();
// Compute acc values for a single thread.
${ppe(t,c,d,o)}
2022-11-18 17:13:29 +01:00
workgroupBarrier();
}
2023-05-08 15:12:41 +02:00
for (var innerRow = 0; innerRow < ${d}; innerRow++) {
2022-11-18 17:13:29 +01:00
mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
}
}`}var Hz=r=>r?`
2023-01-06 19:23:06 +01:00
mm_Asub[inputRow][inputCol] = mm_readA(batchA,
2022-11-18 17:13:29 +01:00
kStart + inputRow,
globalRowStart + inputCol);
`:`
2023-01-06 19:23:06 +01:00
mm_Asub[inputRow][inputCol] = mm_readA(batchA,
2022-11-18 17:13:29 +01:00
globalRowStart + inputRow,
kStart + inputCol);
`,lpe=r=>r?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];";function Pp(r,e,t=!1,o=32,n=!1,s=32,a=!1,i=!1){let p=r[1]*e[1],u=r[0]*e[0],l=t?p:o,c=t?o:p;y.assert(c%e[1]===0&&l%e[0]===0&&o%e[1]===0,()=>`tileAHight ${c} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${l} must be divisible by workgroupSize[0]${e[0]}, tileInner ${o} must be divisible by workgroupSize[1]${e[1]}`);let m=c/e[1],d=l/e[0],f=o/e[1],h=r[1],g=r[0],x=a?`
2022-11-18 17:13:29 +01:00
let localRow = i32(localId.y);
let localCol = i32(localId.x);
2023-01-06 19:23:06 +01:00
let globalRowStart = i32(workgroupId.y) * ${p};
let globalColStart = i32(workgroupId.x) * ${u};
2022-11-18 17:13:29 +01:00
// Loop over shared dimension.
2023-01-06 19:23:06 +01:00
for (var t = 0; t < numTiles; t++) {
2022-11-18 17:13:29 +01:00
// Load one tile of A into local memory.
for (var inputRow = localRow; inputRow < ${c}; inputRow = inputRow + ${e[1]}) {
for (var inputCol = localCol; inputCol < ${l}; inputCol = inputCol + ${e[0]}) {
${Hz(t)}
2022-11-18 17:13:29 +01:00
}
}
// Load one tile of B into local memory.
for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${e[1]}) {
for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${e[0]}) {
2023-01-06 19:23:06 +01:00
mm_Bsub[inputRow][inputCol] = mm_readB(batchB,
2022-11-18 17:13:29 +01:00
kStart + inputRow,
globalColStart + inputCol);
}
}
2023-01-06 19:23:06 +01:00
kStart = kStart + ${o};
2022-11-18 17:13:29 +01:00
workgroupBarrier();
// Compute acc values for a single thread.
2023-01-06 19:23:06 +01:00
var BCached : array<f32, ${g}>;
for (var k = 0; k < ${o}; k++) {
for (var inner = 0; inner < ${g}; inner++) {
BCached[inner] = mm_Bsub[k][localCol + inner * ${e[0]}];
2022-11-18 17:13:29 +01:00
}
2023-01-06 19:23:06 +01:00
for (var innerRow = 0; innerRow < ${h}; innerRow++) {
let ACached = ${t?`mm_Asub[k][localRow + innerRow * ${e[1]}];`:`mm_Asub[localRow + innerRow * ${e[1]}][k];`}
2023-01-06 19:23:06 +01:00
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
2023-05-08 15:12:41 +02:00
acc[innerRow][innerCol] =
fma(ACached, BCached[innerCol], acc[innerRow][innerCol]);
2022-11-18 17:13:29 +01:00
}
}
}
workgroupBarrier();
}
2023-01-06 19:23:06 +01:00
for (var innerRow = 0; innerRow < ${h}; innerRow++) {
let gRow = globalRowStart + localRow + innerRow * ${e[1]};
2023-01-06 19:23:06 +01:00
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
let gCol = globalColStart + localCol + innerCol * ${e[0]};
2022-11-18 17:13:29 +01:00
mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);
}
}
`:`
2023-01-06 19:23:06 +01:00
let tileRow = i32(localId.y) * ${h};
let tileCol = i32(localId.x) * ${g};
2022-11-18 17:13:29 +01:00
2023-01-06 19:23:06 +01:00
let globalRow = i32(globalId.y) * ${h};
let globalCol = i32(globalId.x) * ${g};
let globalRowStart = i32(workgroupId.y) * ${p};
2022-11-18 17:13:29 +01:00
2023-01-06 19:23:06 +01:00
let tileRowA = i32(localId.y) * ${m};
let tileColA = i32(localId.x) * ${d};
let tileRowB = i32(localId.y) * ${f};
2022-11-18 17:13:29 +01:00
// Loop over shared dimension.
2023-01-06 19:23:06 +01:00
for (var t = 0; t < numTiles; t++) {
2022-11-18 17:13:29 +01:00
// Load one tile of A into local memory.
2023-01-06 19:23:06 +01:00
for (var innerRow = 0; innerRow < ${m}; innerRow++) {
for (var innerCol = 0; innerCol < ${d}; innerCol++) {
2022-11-18 17:13:29 +01:00
let inputRow = tileRowA + innerRow;
let inputCol = tileColA + innerCol;
${Hz(t)}
2022-11-18 17:13:29 +01:00
}
}
// Load one tile of B into local memory.
2023-01-06 19:23:06 +01:00
for (var innerRow = 0; innerRow < ${f}; innerRow++) {
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
2022-11-18 17:13:29 +01:00
let inputRow = tileRowB + innerRow;
let inputCol = tileCol + innerCol;
2023-01-06 19:23:06 +01:00
mm_Bsub[inputRow][inputCol] = mm_readB(batchB,
2022-11-18 17:13:29 +01:00
kStart + inputRow,
globalCol + innerCol);
}
}
2023-01-06 19:23:06 +01:00
kStart = kStart + ${o};
2022-11-18 17:13:29 +01:00
workgroupBarrier();
// Compute acc values for a single thread.
2023-01-06 19:23:06 +01:00
var BCached : array<f32, ${g}>;
for (var k = 0; k < ${o}; k++) {
for (var inner = 0; inner < ${g}; inner++) {
2022-11-18 17:13:29 +01:00
BCached[inner] = mm_Bsub[k][tileCol + inner];
}
2023-01-06 19:23:06 +01:00
for (var innerRow = 0; innerRow < ${h}; innerRow++) {
${lpe(t)}
2023-01-06 19:23:06 +01:00
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
2023-05-08 15:12:41 +02:00
acc[innerRow][innerCol] =
fma(ACached, BCached[innerCol], acc[innerRow][innerCol]);
2022-11-18 17:13:29 +01:00
}
}
}
workgroupBarrier();
}
2023-01-06 19:23:06 +01:00
for (var innerRow = 0; innerRow < ${h}; innerRow++) {
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
2022-11-18 17:13:29 +01:00
mm_write(batch, globalRow + innerRow, globalCol + innerCol,
acc[innerRow][innerCol]);
}
}
`;return`
var<workgroup> mm_Asub : array<array<f32, ${l}>, ${c}>;
2023-01-06 19:23:06 +01:00
var<workgroup> mm_Bsub : array<array<f32, ${u}>, ${o}>;
2022-11-18 17:13:29 +01:00
2023-08-05 15:03:11 +02:00
${G()} {
2022-11-18 17:13:29 +01:00
let batch = ${n?"0":"i32(globalId.z)"};
2023-01-06 19:23:06 +01:00
let batchA = ${n||!i?"batch":"batch % uniforms.aShape[0]"};
let batchB = ${n||!i?"batch":"batch % uniforms.bShape[0]"};
let numTiles = ${n?`${Math.ceil(s/o)}`:`(uniforms.dimInner - 1) / ${o} + 1`};
2022-11-18 17:13:29 +01:00
var kStart = ${n?`i32(globalId.z) * ${s}`:"0"};
2023-01-06 19:23:06 +01:00
var acc : array<array<f32, ${g}>, ${h}>;
2022-11-18 17:13:29 +01:00
// Without this initialization strange values show up in acc.
2023-01-06 19:23:06 +01:00
for (var innerRow = 0; innerRow < ${h}; innerRow++) {
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
2022-11-18 17:13:29 +01:00
acc[innerRow][innerCol] = 0.0;
}
}
2023-01-06 19:23:06 +01:00
${x}
2022-11-18 17:13:29 +01:00
}
`}var cpe=r=>r?`
2023-01-06 19:23:06 +01:00
mm_readA(batchA, colA, globalRow),
mm_readA(batchA, colA + 1, globalRow),
mm_readA(batchA, colA + 2, globalRow),
mm_readA(batchA, colA + 3, globalRow)
2022-11-18 17:13:29 +01:00
`:`
2023-01-06 19:23:06 +01:00
mm_readA(batchA, globalRow, colA),
mm_readA(batchA, globalRow, colA + 1),
mm_readA(batchA, globalRow, colA + 2),
mm_readA(batchA, globalRow, colA + 3)
`;function mpe(r,e=!1){y.assert(r[1]===1&&r[2]===1,()=>`A linear work group size is required. But got ${r}.`);let t=r[0]*4;return`
2022-11-18 17:13:29 +01:00
var<workgroup> mm_Asub : array<vec4<f32>, ${r[0]}>;
2023-08-05 15:03:11 +02:00
${G()} {
2022-11-18 17:13:29 +01:00
let tileCol = i32(localId.x);
let globalCol = i32(globalId.x);
let globalRow = i32(globalId.y);
let numTiles = (uniforms.dimInner - 1) / ${t} + 1;
2022-11-18 17:13:29 +01:00
let batch = i32(globalId.z);
2023-01-06 19:23:06 +01:00
let batchA = batch % uniforms.aShape[0];
let batchB = batch % uniforms.bShape[0];
2022-11-18 17:13:29 +01:00
// Without this initialization strange values show up in acc.
var acc = 0.0;
// Loop over shared dimension.
2023-01-06 19:23:06 +01:00
for (var t = 0; t < numTiles; t++) {
2022-11-18 17:13:29 +01:00
// Load one tile of A into local memory.
let colA = t * ${t} + tileCol * 4;
mm_Asub[tileCol] = vec4<f32>(${cpe(e)});
2022-11-18 17:13:29 +01:00
workgroupBarrier();
// Compute acc values for a single thread.
for (var k = 0; k < ${t/4}; k++) {
let rowB = t * ${t} + k * 4;
2023-01-06 19:23:06 +01:00
let BCached = vec4<f32>(mm_readB(batchB, rowB, globalCol),
mm_readB(batchB, rowB + 1, globalCol),
mm_readB(batchB, rowB + 2, globalCol),
mm_readB(batchB, rowB + 3, globalCol));
2022-11-18 17:13:29 +01:00
let ACached = mm_Asub[k];
acc = acc + dot(ACached, BCached);
}
workgroupBarrier();
}
mm_write(batch, globalRow, globalCol, acc);
}
`}var ax=class{constructor(e,t,o=!1,n=!1,s=null,a=null,i=null,p=!1){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]};let u=o?e[1]:e[2];if(this.isVec4=(u%4===0&&!o||t[1]%4===0&&o)&&t[2]%4===0&&!n,this.outputComponent=this.isVec4?4:1,this.isVectorA=t[1]===1&&!o,!this.isVec4&&this.isVectorA)this.elementsPerThread=[1,1,1],this.workgroupSize=[32,1,1];else{let m=lv(t[1],u,t[2],o);this.workgroupSize=m.workgroupSize,this.elementsPerThread=m.elementsPerThread}this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread);let l=s!=null,c=i!=null;l&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights"),this.sequentialAccessByThreads=p,this.transposeA=o,this.transposeB=n,this.addBias=l,this.activation=a,this.hasPreluActivationWeights=c,[this.fitAOuter,this.fitBOuter,this.fitInner]=this.getShapeFit(t[1],t[2],u),this.shaderKey=`matMulPacked_${this.elementsPerThread}_${o}_${n}_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.isVectorA}_${this.sequentialAccessByThreads}`}getShapeFit(e,t,o){let n=this.workgroupSize[1]*this.elementsPerThread[1],s=this.workgroupSize[0]*this.elementsPerThread[0];!this.isVec4&&this.isVectorA?this.tileInner=this.workgroupSize[0]*4:this.tileInner=s;let a=e%n===0,i=t%s===0,p=o%this.tileInner===0;return[a,i,p]}getUserCode(){return`
${gr(this.activation,this.hasPreluActivationWeights,this.isVec4)}
${Sm(this.addBias,this.activation,!1,this.transposeB,this.fitAOuter,this.fitBOuter,this.fitInner,this.isVec4?4:1)}
${this.isVec4?Fp(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,!0):this.isVectorA?mpe(this.workgroupSize,this.transposeA):Pp(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,this.sequentialAccessByThreads,!0)}
`}};function dpe(r){return`
2023-01-06 19:23:06 +01:00
var<workgroup> sumValues : array<f32, ${r}>;
2023-08-05 15:03:11 +02:00
${G()} {
2022-11-18 17:13:29 +01:00
let coords = getOutputCoords();
let batch = coords[0];
2023-01-06 19:23:06 +01:00
let batchA = batch % uniforms.aShape[0];
let batchB = batch % uniforms.bShape[0];
2022-11-18 17:13:29 +01:00
let row = coords[1];
let col = coords[2];
var sum = 0.0;
let Length = uniforms.dimInner;
2023-01-06 19:23:06 +01:00
for (var k = i32(localId.x); k < Length; k = k + ${r}) {
let dataA = mm_readA(batchA, row, k);
let dataB = mm_readB(batchB, k, col);
2022-11-18 17:13:29 +01:00
sum = sum + dataA * dataB;
}
sumValues[localId.x] = sum;
workgroupBarrier();
2023-01-06 19:23:06 +01:00
for(var currentSize = ${r/2}u; currentSize > 1u;
2022-11-18 17:13:29 +01:00
currentSize = currentSize / 2u) {
if (localId.x < currentSize)
{
sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize];
}
workgroupBarrier();
}
if (localId.x == 0u) {
sum = sumValues[0] + sumValues[1];
mm_write(batch, row, col, sum);
}
}
`}var ix=class{constructor(e,t=!1,o=!1,n=null,s=null,a=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout={x:[],y:[1,2],z:[0]},this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize);let i=n!=null,p=a!=null;i&&this.variableNames.push("bias"),p&&this.variableNames.push("preluActivationWeights"),this.transposeA=t,this.transposeB=o,this.addBias=i,this.activation=s,this.hasPreluActivationWeights=p,this.shaderKey=`matMulReduce_${this.activation}_${t}_${o}`}getUserCode(){return`
${gr(this.activation,this.hasPreluActivationWeights)}
${Sm(this.addBias,this.activation,this.transposeA,this.transposeB)}
${dpe(this.workgroupSize[0])}
`}};function fpe(r){let e=r[1],t=r[0],o=e>t?e:t;return`
var<workgroup> mm_Asub : array<array<f32, ${o}>, ${e}>;
var<workgroup> mm_Bsub : array<array<f32, ${t}>, ${o}>;
2022-11-18 17:13:29 +01:00
// If the output size is small for matrix multiplication, avoid to use vec4
// and handle some elements per thread to optimally utilize the ALU.
// Read data from global memory to registers firstly, then store them into
// shared memory, so it is instruction-Level parallelism for arithmetic
// operations and others handle IO operations between barrier api, makes ALU
// and load/store units work simultaneously, could improves the performance.
2023-08-05 15:03:11 +02:00
${G()} {
2022-11-18 17:13:29 +01:00
let tileRow = i32(localId.y);
let tileCol = i32(localId.x);
let globalRow = i32(globalId.y);
let globalCol = i32(globalId.x);
let batch = i32(globalId.z);
2023-01-06 19:23:06 +01:00
let batchA = batch % uniforms.aShape[0];
let batchB = batch % uniforms.bShape[0];
2022-11-18 17:13:29 +01:00
// uniforms.dimInner should be greater than 0.
let numTiles = (uniforms.dimInner - 1) / ${o} + 1;
var acc = 0.0;
var globalColA = tileCol;
var globalRowB = 0;
2023-01-06 19:23:06 +01:00
var regA = mm_readA(batchA, globalRow, globalColA);
var regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol);
var regB1 = mm_readB(batchB, globalRowB + 2 * tileRow + 1, globalCol);
2022-11-18 17:13:29 +01:00
globalColA = globalColA + ${o};
globalRowB = globalRowB + ${o};
for (var t = 0; t < numTiles; t = t + 1) {
mm_Asub[tileRow][tileCol] = regA;
mm_Bsub[2 * tileRow][tileCol] = regB0;
mm_Bsub[2 * tileRow + 1][tileCol] = regB1;
workgroupBarrier();
2023-01-06 19:23:06 +01:00
regA = mm_readA(batchA, globalRow, globalColA);
regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol);
regB1 = mm_readB(batchB, globalRowB + 2 * tileRow + 1, globalCol);
2022-11-18 17:13:29 +01:00
globalColA = globalColA + ${o};
globalRowB = globalRowB + ${o};
for (var k = 0; k < ${o}; k = k + 1) {
acc = acc + mm_Asub[tileRow][k] * mm_Bsub[k][tileCol];
}
workgroupBarrier();
}
mm_write(batch, globalRow, globalCol, acc);
}
`}var ux=class{constructor(e,t,o,n=!1,s=!1,a=null,i=null,p=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[16,8,1],this.outputShape=o,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(o[2]/this.workgroupSize[0]),Math.ceil(o[1]/this.workgroupSize[1]),o[0]];let u=a!=null;u&&this.variableNames.push("bias");let l=p!=null;l&&this.variableNames.push("preluActivationWeights"),this.transposeA=n,this.transposeB=s,this.addBias=u,this.activation=i,this.hasPreluActivationWeights=l,this.shaderKey=`matMulSmallOutputSize_${this.activation}_${n}_${s}`}getUserCode(){return`
${gr(this.activation,this.hasPreluActivationWeights)}
${Sm(this.addBias,this.activation,this.transposeA,this.transposeB)}
${fpe(this.workgroupSize)}
`}};var px=class{constructor(e,t,o=!1,n=!1){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[8,8,1],this.atomic=!0,this.splitedDimInner=128,y.assert(e[0]===1,()=>"MatMulSplitKProgram only supports batch = 1."),this.outputShape=e,this.dispatchLayout={x:[2],y:[1],z:[0,3]};let s=(o&&this.outputShape[1]%4===0||!o&&t%4===0)&&this.outputShape[2]%4===0;this.elementsPerThread=[4,4,this.splitedDimInner],this.outputComponent=s?4:1,s||(this.outputShape[1]<16&&(this.elementsPerThread[1]=1),this.outputShape[2]<16&&(this.elementsPerThread[0]=1)),this.dispatch=H(this.dispatchLayout,[this.outputShape[0],this.outputShape[1],this.outputShape[2],t],this.workgroupSize,this.elementsPerThread),this.transposeA=o,this.transposeB=n,this.shaderKey=`matMulSplitK_${o}_${n}_${this.elementsPerThread}_${this.outputComponent}`}getUserCode(){let e=this.outputComponent;return`
${mv(!1,this.transposeB,!1,!1,!1,e)}
fn mm_write(batch: i32, row : i32, col : i32, value : ${Ae(e)}) {
2022-11-18 17:13:29 +01:00
if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {
let coords = vec3<i32>(batch, row, col);
let flatIndex = getOutputIndexFromCoords(coords);
// The problem is that we should initialize output to zero before using.
// Otherwise, the original value will be added to the result.
for (var i = 0; i < ${e}; i = i + 1) {
${oo("&result[flatIndex + i]",`${e>1?"value[i]":"value"}`,"float32")}
2023-01-06 19:23:06 +01:00
}
2022-11-18 17:13:29 +01:00
}
}
${e===4?Fp(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner):Pp(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner)}
`}},lx=class{constructor(e,t=null,o=null,n=null){this.uniforms="",this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.addBias=t!=null,this.hasPreluActivationWeights=n!=null,this.activation=o,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`biasActivation_${o}`}getUserCode(){return`
${gr(this.activation,this.hasPreluActivationWeights)}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
var value = getXByOutputIndex(index);
${no(this.addBias,this.activation)}
2022-11-18 17:13:29 +01:00
setOutputAtIndex(index, value);
}
}
`}};var cx=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="fill"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
setOutputAtIndex(index, uniforms.value);
}
}
`}};function Nt(r){let{backend:e,attrs:t}=r,{shape:o,value:n}=t,{dtype:s}=t;if(s=s||y.inferDtype(n),s==="string"){let a=y.getArrayFromDType(s,y.sizeFromShape(o));return a.fill(n),e.makeTensorInfo(o,s,a)}else{let a=new cx(o),i=[{type:"float32",data:[n]}];return e.runWebGPUProgram(a,[],s,i)}}var Kz={kernelName:da,backendName:"webgpu",kernelFunc:Nt};function le(r){let{inputs:e,attrs:t}=r,{x:o}=e,{shape:n}=t,s=y.sizeFromShape(o.shape),a=y.inferFromImplicitShape(n,s),i=y.sizeFromShape(a);return y.assert(s===i,()=>`The new shape (${a}) has ${i} elements and the old shape (${o.shape}) has ${s} elements. The new shape and old shape must have the same number of elements.`),r.backend.incRef(o.dataId),{dataId:o.dataId,shape:a,dtype:o.dtype}}var qz={kernelName:Ca,backendName:"webgpu",kernelFunc:le};function Op({a:r,b:e,transposeA:t,transposeB:o,backend:n,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:p=null}){let u=r.shape.length,l=e.shape.length,c=t?r.shape[u-2]:r.shape[u-1],m=o?e.shape[l-1]:e.shape[l-2],d=t?r.shape[u-1]:r.shape[u-2],f=o?e.shape[l-2]:e.shape[l-1],h=r.shape.slice(0,-2),g=e.shape.slice(0,-2),x=y.sizeFromShape(h),b=y.sizeFromShape(g),S=kr.assertAndGetBroadcastShape(r.shape.slice(0,-2),e.shape.slice(0,-2)).concat([d,f]);y.assert(c===m,()=>`Error in matMul: inner shapes (${c}) and (${m}) of Tensors with shapes ${r.shape} and ${e.shape} and transposeA=${t} and transposeB=${o} must match.`);let k=t?[x,c,d]:[x,d,c],T=o?[b,f,m]:[b,m,f],E=le({inputs:{x:r},backend:n,attrs:{shape:k}}),R=le({inputs:{x:e},backend:n,attrs:{shape:T}}),D=[E,R],F=Math.max(x,b),O=[E,R],M=[{type:"int32",data:[d]},{type:"int32",data:[f]},{type:"int32",data:[c]}],L,B,z=[F,d,f],U=A().get("WEBGPU_MATMUL_PROGRAM_TYPE");if(U<0){let q=A().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),Y=q>0?q:n.thresholdToIncreaseWorkgroups,J=F*Math.ceil(d/32)*Math.ceil(f/32);J<=Y||d<=8&&J<=Y*2?F*d*f<=128?U=pn.MatMulReduceProgram:F===1&&m>=2e3?U=pn.MatMulSplitKProgram:U=pn.MatMulSmallOutputSizeProgram:U=pn.MatMulPackedProgram}switch(U){case pn.MatMulReduceProgram:L=new ix(z,t,o,s,p,a);break;case pn.MatMulSplitKProgram:{if(B=Nt({backend:n,attrs:{shape:z,value:0,dtype:r.dtype}}),L=new px(z,m,t,o),s||p){B=n.runWebGPUProgram(L,O,r.dtype,M,B);let Y=new lx(B.shape,s,p,a),J=null,re=[B];s&&re.push(s),a&&re.push(a),p==="leakyrelu"&&(J=[{type:"float32",data:[i]}],Y.uniforms+=" alpha : f32,");let ne=n.runWebGPUProgram(Y,re,B.dtype,J);D.push(B);let ee=le({inputs:{x:ne},backend:n,attrs:{shape:S}});D.push(ne);for(let oe of D)n.disposeData(oe.dataId);return ee}break}case pn.MatMulSmallOutputSizeProgram:L=new ux(k,T,z,t,o,s,p,a);break;case pn.MatMulPackedProgram:let q=n.adapterInfo.isIntel();L=new ax(k,z,t,o,s,p,a,q);break;default:throw new Error(`Unsupported MatMulProgramType ${U}.`)}s&&O.push(s),a&&O.push(a),p==="leakyrelu"&&(M.push({type:"float32",data:[i]}),L.uniforms+=" alpha : f32,"),B=n.runWebGPUProgram(L,O,r.dtype,M,B);let j=le({inputs:{x:B},backend:n,attrs:{shape:S}});D.push(B);for(let q of D)n.disposeData(q.dataId);return j}function hpe(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e,{transposeA:p,transposeB:u,activation:l,leakyreluAlpha:c}=o;return Op({a:n,b:s,transposeA:p,transposeB:u,backend:t,bias:a,preluActivationWeights:i,leakyreluAlpha:c,activation:l})}var jz={kernelName:qo,backendName:"webgpu",kernelFunc:hpe};var Im=class{constructor(e,t,o){this.variableNames=["AReal","AImag","BReal","BImag"],this.workgroupSize=[128,1,1],this.size=!0,this.outputShape=C.assertAndGetBroadcastShape(t,o),this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`binaryOpComplex_${e}`,this.op=e}getUserCode(){return`
2022-11-18 17:13:29 +01:00
fn binaryOpComplex(
areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 {
${ec(this.op,!1)}
2022-11-18 17:13:29 +01:00
}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if(index < uniforms.size) {
let areal = getARealByOutputIndex(index);
let aimag = getAImagByOutputIndex(index);
let breal = getBRealByOutputIndex(index);
let bimag = getBImagByOutputIndex(index);
setOutputAtIndex(index, binaryOpComplex(areal, aimag, breal, bimag));
}
}
`}};var Di=class{constructor(e,t,o){if(this.size=!0,this.variableNames=["A","B"],this.outputShape=C.assertAndGetBroadcastShape(t,o),this.dispatchLayout=X(this.outputShape),this.op=e,this.useSharedMemoryWithA=t.length<=1&&o.length>1&&t[0]<128,this.useSharedMemoryWithB=o.length<=1&&t.length>1&&o[0]<128,this.useSharedMemoryWithA||this.useSharedMemoryWithB)this.outputComponent=1,this.variableComponents=[1,1],this.lastDimensionSize=this.useSharedMemoryWithB?o[0]:t[0],this.shaderKey=`binary_${e}_${this.lastDimensionSize}`,this.type="shared",this.workgroupSize=[256,1,1];else{let n=t.length>0&&t[t.length-1]%4===0,s=o.length>0&&o[o.length-1]%4===0;n&&s?(this.outputComponent=4,this.variableComponents=[4,4]):n&&(y.isScalarShape(o)||o[o.length-1]===1)||s&&(y.isScalarShape(t)||t[t.length-1]===1)?(this.outputComponent=4,this.variableComponents=n?[4,1]:[1,4]):(this.outputComponent=1,this.variableComponents=[1,1]),this.type="nonshared",this.shaderKey=`binary_${e}_${this.variableComponents}`,this.workgroupSize=[128,1,1]}this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.outputComponent,1,1])}getUserCode(){let e,t=this.outputComponent===4?"vec4<f32>":"f32",o=`
fn binaryOperation(a : ${t}, b : ${t}) -> ${t} {
${ec(this.op,this.outputComponent===4)}
2022-11-18 17:13:29 +01:00
};
`;if(this.type==="shared"){let n=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",s=this.useSharedMemoryWithB?`let a = getAByOutputIndex(index);
let b = sharedBuf[${n}];`:`let a = sharedBuf[${n}];
let b = getBByOutputIndex(index);`;e=`
2022-11-18 17:13:29 +01:00
${o}
var<workgroup> sharedBuf : array<f32, ${this.lastDimensionSize}>;
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
// Fill in the shared memory buffer.
let localIndex = i32(localId.x);
if(localIndex < ${this.lastDimensionSize}) {
sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB?"B":"A"}[localIndex]);
}
workgroupBarrier();
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
${s}
setOutputAtIndex(index, binaryOperation(a, b));
}
}
`}else e=`
2022-11-18 17:13:29 +01:00
${o}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
2023-05-08 15:12:41 +02:00
let coords = getCoordsFromIndex(index * ${this.outputComponent});
let a = ${t}(getAByOutputCoords(coords));
let b = ${t}(getBByOutputCoords(coords));
2022-11-18 17:13:29 +01:00
setOutputAtIndex(index, binaryOperation(a, b));
}
}
`;return e}};function Pt(r){let{inputs:e}=r,{x:t}=e;return r.backend.incRef(t.dataId),{dataId:t.dataId,shape:t.shape,dtype:t.dtype}}var Xz={kernelName:vo,backendName:"webgpu",kernelFunc:Pt};function Uo(r){let{inputs:e,backend:t}=r,{real:o,imag:n}=e,s=t.makeTensorInfo(o.shape,"complex64"),a=t.tensorMap.get(s.dataId),i=Pt({inputs:{x:o},backend:t}),p=Pt({inputs:{x:n},backend:t});return a.complexTensorInfos={real:i,imag:p},s}var Yz={kernelName:ei,backendName:"webgpu",kernelFunc:Uo};var so=class{constructor(e,t,o=""){this.variableNames=["A"],this.size=!0;let n=128;this.workgroupSize=[n,1,1],this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.op=t,o!==""&&(this.uniforms=o),this.shaderKey=`unary_${t}`}getUserCode(){return`
2022-11-18 17:13:29 +01:00
fn unaryOperation(a : f32) -> f32 {
${Ri(this.op,!1)}
2022-11-18 17:13:29 +01:00
}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let a = getAByOutputIndex(index);
setOutputAtIndex(index, unaryOperation(a));
}
}
`}};function ye({opType:r,cpuKernelImpl:e,dtype:t}){return({inputs:o,backend:n})=>{let{x:s}=o,a=n,i=t||s.dtype;if(a.shouldExecuteOnCPU([s])&&e!=null){let u=a.tensorMap.get(s.dataId),l=e(u.values,i);return a.makeTensorInfo(s.shape,i,l)}let p=new so(s.shape,r);return a.runWebGPUProgram(p,[s],i)}}function tt({opType:r,cpuKernelImpl:e,supportsComplex:t=!1,dtype:o}){return({inputs:n,backend:s})=>{let{a,b:i}=n,p=s;if(t&&a.dtype==="complex64"){let c=p.tensorMap.get(a.dataId),m=p.tensorMap.get(i.dataId),d,f;if(r!==fe.MUL)[d,f]=[[c.complexTensorInfos.real,m.complexTensorInfos.real],[c.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(g=>{let[x,b]=g,w={dataId:x.dataId,dtype:x.dtype,shape:a.shape},S={dataId:b.dataId,dtype:b.dtype,shape:i.shape},k=new Di(r,a.shape,i.shape);return p.runWebGPUProgram(k,[w,S],pt(x.dtype,b.dtype))});else{let g=new Im(fe.COMPLEX_MULTIPLY_REAL,a.shape,i.shape),x=new Im(fe.COMPLEX_MULTIPLY_IMAG,a.shape,i.shape),b=[{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:a.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:a.shape},{dataId:m.complexTensorInfos.real.dataId,dtype:m.complexTensorInfos.real.dtype,shape:i.shape},{dataId:m.complexTensorInfos.imag.dataId,dtype:m.complexTensorInfos.imag.dtype,shape:i.shape}];d=p.runWebGPUProgram(g,b,"float32"),f=p.runWebGPUProgram(x,b,"float32")}let h=Uo({inputs:{real:d,imag:f},backend:p});return p.disposeData(d.dataId),p.disposeData(f.dataId),h}let u=o||pt(a.dtype,i.dtype);if((a.dtype==="string"||i.dtype==="string"||p.shouldExecuteOnCPU([a,i]))&&e!=null){let c=p.tensorMap.get(a.dataId).values,m=p.tensorMap.get(i.dataId).values,d=a.dtype==="string"?C.fromUint8ToStringArray(c):c,f=a.dtype==="string"?C.fromUint8ToStringArray(m):m,[h,g]=e(a.shape,i.shape,d,f,u);return p.makeTensorInfo(g,u,h)}let l=new Di(r,a.shape,i.shape);return p.runWebGPUProgram(l,[a,i],u)}}var Lv={};qe(Lv,{addImpl:()=>hv,bincountImpl:()=>Jz,bincountReduceImpl:()=>eV,bitwiseAndImpl:()=>gv,castImpl:()=>fv,ceilImpl:()=>xv,concatImpl:()=>tV,equalImpl:()=>yv,expImpl:()=>bv,expm1Impl:()=>Cv,floorDivImpl:()=>Sv,floorImpl:()=>wv,gatherNdImpl:()=>rV,gatherV2Impl:()=>oV,greaterEqualImpl:()=>vv,greaterImpl:()=>Iv,lessEqualImpl:()=>Nv,lessImpl:()=>kv,linSpaceImpl:()=>nV,logImpl:()=>Tv,maxImpl:()=>sV,maximumImpl:()=>_v,minimumImpl:()=>Ev,multiplyImpl:()=>km,negImpl:()=>aV,notEqualImpl:()=>$v,prodImpl:()=>iV,raggedGatherImpl:()=>pV,raggedRangeImpl:()=>cV,raggedTensorToTensorImpl:()=>fV,rangeImpl:()=>hV,rsqrtImpl:()=>Av,scatterImpl:()=>gV,sigmoidImpl:()=>xV,simpleAbsImpl:()=>Qz,sliceImpl:()=>yV,sparseFillEmptyRowsImpl:()=>bV,sparseReshapeImpl:()=>CV,sparseSegmentReductionImpl:()=>wV,sqrtImpl:()=>SV,squaredDifferenceImpl:()=>Fv,staticRegexReplaceImpl:()=>Pv,stridedSliceImpl:()=>IV,stringNGramsImpl:()=>vV,stringSplitImpl:()=>kV,stringToHashBucketFastImpl:()=>NV,subImpl:()=>Mv,tileImpl:()=>TV,topKImpl:()=>EV,transposeImpl:()=>Rv,uniqueImpl:()=>$V});function Ai(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&y.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the CPU backend.`)})}function Qz(r){let e=new Float32Array(r.length);for(let t=0;t<r.length;++t)e[t]=Math.abs(r[t]);return e}function ht(r){return(e,t,o,n,s)=>{let a=C.assertAndGetBroadcastShape(e,t),i=a.length,p=y.computeStrides(a),u=y.sizeFromShape(a),l=y.getTypedArrayFromDType(s,u),c=e.length,m=t.length,d=y.computeStrides(e),f=y.computeStrides(t),h=C.getBroadcastDims(e,a),g=C.getBroadcastDims(t,a);if(h.length+g.length===0)for(let x=0;x<l.length;++x)l[x]=r(o[x%o.length],n[x%n.length]);else for(let x=0;x<l.length;++x){let b=y.indexToLoc(x,i,p),w=b.slice(-c);h.forEach(E=>w[E]=0);let S=y.locToIndex(w,c,d),k=b.slice(-m);g.forEach(E=>k[E]=0);let T=y.locToIndex(k,m,f);l[x]=r(o[S],n[T])}return[l,a]}}function tc(r){let{inputs:e,backend:t}=r,{real:o,imag:n}=e,s=t.data.get(o.dataId).values,a=t.data.get(n.dataId).values,i=t.makeTensorInfo(o.shape,"complex64"),p=t.data.get(i.dataId);return p.complexTensorInfos={real:t.makeTensorInfo(o.shape,"float32",s),imag
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
let flatIndex = index * ${this.workPerThread} + i;
if (flatIndex < uniforms.size) {
let coords = getCoordsFromIndex(flatIndex);
${e.join(`
2022-11-18 17:13:29 +01:00
`)}
setOutputAtIndex(flatIndex, ${t});
2022-11-18 17:13:29 +01:00
}
}
}
`}};function $pe(r){let{inputs:e,backend:t}=r,o=e;if(o.length===1)return Pt({inputs:{x:o[0]},backend:t});let n=o.map(i=>i.dtype).reduce((i,p)=>pt(i,p)),s=o.map(i=>i.shape),a=new fx(s);return t.runWebGPUProgram(a,o,n)}var hW={kernelName:xn,backendName:"webgpu",kernelFunc:$pe};var hx=class{constructor(e,t){this.variableNames=["A"],this.workgroupSize=[16,16,1];let o=new Array(e.length);for(let n=0;n<o.length;n++)o[n]=e[t[n]];this.outputShape=o,this.dispatchLayout={x:[0],y:[1]},this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,[1,1,1]),this.shaderKey="transposeShared"}getUserCode(){y.assert(this.workgroupSize[0]===this.workgroupSize[1],()=>`Must be a square tile, current tile shape is ${this.workgroupSize[0]} x ${this.workgroupSize[1]}`);let e=this.workgroupSize[0];return`
2022-11-20 22:20:02 +01:00
var<workgroup> tile : array<array<f32, ${this.workgroupSize[0]+1}>, ${this.workgroupSize[0]}>;
2023-08-05 15:03:11 +02:00
${G()} {
var x = i32(workgroupId.x) * ${e} + i32(localId.x);
var y = i32(workgroupId.y) * ${e} + i32(localId.y);
2022-11-20 22:20:02 +01:00
let width = uniforms.outShape[0];
let height = uniforms.outShape[1];
if (x < width && y < height) {
tile[localId.y][localId.x] = f32(A[y * width + x]);
}
workgroupBarrier();
x = i32(workgroupId.y) * ${e} + i32(localId.x);
y = i32(workgroupId.x) * ${e} + i32(localId.y);
2022-11-20 22:20:02 +01:00
if (x < height && y < width) {
setOutputAtIndex((y * height + x), tile[localId.x]
[localId.y]);
}
}
`}};var gx=class{constructor(e,t){this.variableNames=["A"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0;let o=new Array(e.length);for(let n=0;n<o.length;n++)o[n]=e[t[n]];this.outputShape=o,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.newDim=t,this.shaderKey=`transpose_${t}`}getUserCode(){let e=ft(this.outputShape.length),t=Bv(this.newDim);return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-20 22:20:02 +01:00
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
let flatIndex = index * ${this.workPerThread} + i;
if(flatIndex < uniforms.size) {
let coords = getCoordsFromIndex(flatIndex);
2022-11-20 22:20:02 +01:00
setOutputAtIndex(flatIndex, A[getIndexFromCoords${this.outputShape.length}D(
${e}(${t}), uniforms.aShape)]);
2022-11-20 22:20:02 +01:00
}
}
}
`}};function Bv(r){let e=r.length;if(e>6)throw Error(`Transpose for rank ${e} is not yet supported`);let t=new Array(e);for(let o=0;o<r.length;o++)t[r[o]]=`coords.${un(o)}`;return t.join()}function Cr(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{perm:s}=o,a=t,i=n.shape.length,p=new Array(i);for(let l=0;l<p.length;l++)p[l]=n.shape[s[l]];if(t.shouldExecuteOnCPU([n])){let c=a.tensorMap.get(n.dataId).values,m=lW(c,n.shape,n.dtype,s,p);return t.makeTensorInfo(p,n.dtype,m)}if(n.shape.length===2&&y.arraysEqual(s,[1,0])){let l=new hx(n.shape,s);return a.runWebGPUProgram(l,[n],n.dtype)}let u=new gx(n.shape,s);return a.runWebGPUProgram(u,[n],n.dtype)}var gW={kernelName:Kr,backendName:"webgpu",kernelFunc:Cr};var xx=class{constructor(e,t,o){this.variableNames=["x"],this.uniforms="reduceSize : i32,",this.size=!0,this.inputShape=[e.batchSize,e.inSize];let[n]=C.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=n.length===0?[1]:n,e.inSize>=32768&&o>=512?this.workgroupSize=[512,1,1]:e.inSize>=4096?this.workgroupSize=[256,1,1]:this.workgroupSize=[64,1,1],this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,[1,1,1]),this.reduceType=t,this.shaderKey=`reduce_${t}`}getUserCode(){let e="",t="0.0",o=this.workgroupSize[0];this.reduceType==="min"||this.reduceType==="max"?(e=`
2022-11-20 22:20:02 +01:00
if (isnan(candidate)) {
bestValue = uniforms.NAN;
} else if (!isnan(bestValue) && candidate ${this.reduceType==="min"?"<":">"} bestValue)
{ bestValue = candidate; }`,t="f32(x[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?e=" bestValue = bestValue + candidate; ":this.reduceType==="prod"?(e=" bestValue = bestValue * candidate; ",t="1.0"):this.reduceType==="all"?(e=" bestValue = f32(bestValue >= 1.0 && candidate >= 1.0); ",t="1.0"):this.reduceType==="any"&&(e=" bestValue = f32(bestValue >= 1.0 || candidate >= 1.0); ",t="0.0");let n=this.reduceType==="mean"?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return`
2022-11-20 22:20:02 +01:00
fn DIV_CEIL(a : u32, b : u32) -> u32 {
return ((a - 1u) / b + 1u);
}
${`
2023-01-06 19:23:06 +01:00
var<workgroup> xBestValues : array<f32, ${o}>;
2022-11-20 22:20:02 +01:00
`}
fn getOffset(outputIndex : i32) -> i32 {
let outputCoords = getCoordsFromIndex(outputIndex);
let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize;
return offset;
}
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-01-06 19:23:06 +01:00
let outputIndex = index / ${o};
2022-11-20 22:20:02 +01:00
let offset = getOffset(outputIndex);
var bestValue = ${t};
2022-11-20 22:20:02 +01:00
let Length = uniforms.reduceSize;
2023-01-06 19:23:06 +01:00
let WorkPerThread = DIV_CEIL(u32(Length), ${o}u);
2022-11-20 22:20:02 +01:00
for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;
2023-01-06 19:23:06 +01:00
k = k + ${o}) {
2022-11-20 22:20:02 +01:00
let candidate = f32(x[offset + k]);
${e}
2022-11-20 22:20:02 +01:00
}
xBestValues[localId.x] = bestValue;
workgroupBarrier();
2023-01-06 19:23:06 +01:00
var reduceSize = min(u32(Length), ${o}u);
2022-11-20 22:20:02 +01:00
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
currentSize = reduceSize / 2u) {
let interval = DIV_CEIL(reduceSize, 2u);
if (localId.x < currentSize) {
let candidate = xBestValues[localId.x + interval];
${e}
2022-11-20 22:20:02 +01:00
xBestValues[localId.x] = bestValue;
}
reduceSize = interval;
workgroupBarrier();
}
if (localId.x == 0u && outputIndex < uniforms.size) {
2023-01-06 19:23:06 +01:00
${n}
2022-11-20 22:20:02 +01:00
}
}
`}};var Rpe={mean:"float32",all:"bool",any:"bool"};function ao(r,e,t,o,n){let s=r.shape.length,a=[],i=y.parseAxisParam(e,r.shape),p=i,u=C.getAxesPermutation(p,s),l=r;u!=null&&(l=Cr({inputs:{x:r},attrs:{perm:u},backend:n}),p=C.getInnerMostAxes(p.length,s),a.push(l)),C.assertAxesAreInnerMostDims(o,p,s);let[c,m]=C.computeOutAndReduceShapes(l.shape,p),d=c;t&&(d=C.expandShapeToKeepDim(c,i));let f;if((o==="max"||o==="prod")&&n.shouldExecuteOnCPU([l])){let h=n.tensorMap.get(l.dataId).values;switch(o){case"max":let g=qV(h,y.sizeFromShape(m),d,r.dtype);f=n.makeTensorInfo(d,r.dtype,g);break;case"prod":let{outVals:x,outShape:b,outDtype:w}=JV(l.shape,l.dtype,h,p);f=n.makeTensorInfo(b,w,x);break;default:throw new Error(`${o} CPU implementation is not yet supported.`)}}else{let h=y.sizeFromShape(m),x=y.sizeFromShape(l.shape)/h,b={windowSize:h,inSize:h,batchSize:x,outSize:1},w=Rpe[o]||mi(r.dtype),S=[{type:"int32",data:[h]}],k=new xx(b,o,n.device.limits.maxComputeWorkgroupSizeX),T=n.runWebGPUProgram(k,[l],w,S);a.push(T),f=le({inputs:{x:T},attrs:{shape:d},backend:n})}return a.forEach(h=>n.disposeData(h.dataId)),f}function Dpe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{keepDims:s,axis:a}=o;return ao(n,a,s,"all",t)}var xW={kernelName:yn,backendName:"webgpu",kernelFunc:Dpe};function Ape(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{keepDims:s,axis:a}=o;return ao(n,a,s,"any",t)}var yW={kernelName:bn,backendName:"webgpu",kernelFunc:Ape};var oc=class{constructor(e,t,o){this.workgroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="infinityValue : f32,",this.size=!0;let n=[t];this.op=o==="min"?"<":">";let[s,a]=C.computeOutAndReduceShapes(e,n);this.outputShape=s.length===0?[1]:s,this.dispatchLayout=X(this.outputShape),y.sizeFromShape(a)<32?(this.type="plain",this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize)):(this.type="shared",this.dispatch=H(this.dispatchLayout,this.outputShape,[1,1,1])),this.inputShape=e,this.shaderKey=`argMinMax_${this.op}_${this.type}`}getUserCode(){let e=this.workgroupSize[0],t=()=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape.${un(this.inputShape.length-1)}`,o=()=>{let n="";if(this.outputShape.length===1)this.inputShape.length!==1&&(n+="outputCoords,");else for(let s=0;s<this.outputShape.length;s++)n+=`outputCoords.${un(s)},`;return n};return this.type==="shared"?`
2022-11-18 17:13:29 +01:00
fn DIV_CEIL(a : u32, b : u32) -> u32 {
return ((a - 1u) / b + 1u);
}
${`
var<workgroup> xBestIndices : array<i32, ${e}>;
var<workgroup> xBestValues : array<f32, ${e}>;
2022-11-18 17:13:29 +01:00
`}
2023-08-05 15:03:11 +02:00
${G("index")} {
let outputIndex = index / ${e};
let reduceLength = ${t()};
2022-11-18 17:13:29 +01:00
var bestIndex = i32(localId.x);
var bestValue = uniforms.infinityValue;
let outputCoords = getCoordsFromIndex(outputIndex);
for (var k = i32(localId.x); k < reduceLength && outputIndex < uniforms.size;
k = k + ${e}) {
2023-01-06 19:23:06 +01:00
let candidate = getX(${o()} k);
2022-11-18 17:13:29 +01:00
if (!isnan(candidate) && candidate ${this.op} bestValue) {
bestValue = candidate;
bestIndex = k;
}
}
xBestValues[localId.x] = bestValue;
xBestIndices[localId.x] = bestIndex;
workgroupBarrier();
var reduceSize = min(u32(reduceLength), ${e}u);
2022-11-18 17:13:29 +01:00
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
currentSize = reduceSize / 2u) {
let interval = DIV_CEIL(reduceSize, 2u);
if (localId.x < currentSize) {
let candidate = xBestValues[localId.x + interval];
if (candidate ${this.op} bestValue) {
bestValue = candidate;
xBestValues[localId.x] = bestValue;
xBestIndices[localId.x] = xBestIndices[localId.x + interval];
}
}
reduceSize = interval;
workgroupBarrier();
}
if (localId.x == 0u && outputIndex < uniforms.size) {
setOutputAtIndexI32(outputIndex, xBestIndices[localId.x]);
}
}
`:`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let outputCoords = getCoordsFromIndex(index);
var bestIndex = 0;
2023-01-06 19:23:06 +01:00
var bestValue = getX(${o()} 0);
let reduceLength = ${t()};
2022-11-18 17:13:29 +01:00
for (var i = 1; i < reduceLength; i++) {
2023-01-06 19:23:06 +01:00
let candidate = getX(${o()} i);
2022-11-18 17:13:29 +01:00
if (candidate ${this.op} bestValue) {
bestValue = candidate;
bestIndex = i;
}
}
setOutputAtIndexI32(index, bestIndex);
}
}
`}};function Fpe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=y.parseAxisParam(s,n.shape),i=C.getAxesPermutation(a,n.shape.length),p=n,u=[];i!=null&&(p=Cr({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(p),a=C.getInnerMostAxes(a.length,p.shape.length)),C.assertAxesAreInnerMostDims("argMax",[a[0]],p.shape.length);let l=new oc(p.shape,a[0],"max"),c=[{type:"float32",data:[Number.NEGATIVE_INFINITY]}],m=t.runWebGPUProgram(l,[p],"int32",c);return u.forEach(d=>t.disposeData(d.dataId)),m}var bW={kernelName:na,backendName:"webgpu",kernelFunc:Fpe};function Ppe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=y.parseAxisParam(s,n.shape),i=C.getAxesPermutation(a,n.shape.length),p=n,u=[];i!=null&&(p=Cr({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(p),a=C.getInnerMostAxes(a.length,p.shape.length)),C.assertAxesAreInnerMostDims("argMin",[a[0]],p.shape.length);let l=new oc(p.shape,a[0],"min"),c=[{type:"float32",data:[Number.POSITIVE_INFINITY]}],m=t.runWebGPUProgram(l,[p],"int32",c);return u.forEach(d=>t.disposeData(d.dataId)),m}var CW={kernelName:sa,backendName:"webgpu",kernelFunc:Ppe};var Ope=ye({opType:Z.ASIN}),wW={kernelName:Cn,backendName:"webgpu",kernelFunc:Ope};var Mpe=ye({opType:Z.ASINH}),SW={kernelName:wn,backendName:"webgpu",kernelFunc:Mpe};var Lpe=ye({opType:Z.ATAN}),IW={kernelName:Sn,backendName:"webgpu",kernelFunc:Lpe};var Bpe=tt({opType:fe.ATAN2}),vW={kernelName:vn,backendName:"webgpu",kernelFunc:Bpe};var zpe=ye({opType:Z.ATANH}),kW={kernelName:In,backendName:"webgpu",kernelFunc:zpe};var yx=class{constructor(e){this.variableNames=["x"],this.uniforms="strides : vec2<i32>,",this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let d = coords[3];
let xRCCorner = coords.yz * uniforms.strides;
let xRCorner = xRCCorner.x;
let xCCorner = xRCCorner.y;
let value = getX(batch, xRCorner, xCCorner, d);
setOutputAtIndex(index, value);
}
}
`}};var Ka=class{constructor(e,t,o=!1,n=!1,s=!1){if(this.variableNames=["x"],this.uniforms="strides : vec2<i32>, pads : vec2<i32>, dilations : vec2<i32>, convDims : vec2<i32>, filterDims : vec2<i32>,",this.workgroupSize=[128,1,1],this.size=!0,t==="avg"&&o)throw new Error("Cannot compute positions for average pool.");this.outputShape=e.outShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.poolType=t,this.computePositions=o,this.flattenPositions=n,this.includeBatchIndex=s,this.shaderKey=`pool2D_${t}_${o}_${n}_${s}`}getUserCode(){let e;this.poolType==="avg"?e="resultValue = resultValue + value; count = count + 1.0;":this.computePositions?e=`let currMaxValue = mix(value, maxValue, maxValueFound);
2023-05-08 15:12:41 +02:00
if (value >= currMaxValue) {
maxValue = value;
maxValueFound = 1.0;
maxPosition = ${this.flattenPositions?this.includeBatchIndex?"((batch * uniforms.xShape[1] + xR) * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d":"(xR * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d":"wR * uniforms.filterDims.y + wC"};
}`:e="resultValue = max(value, resultValue);";let t="resultValue";return this.poolType==="avg"&&(t="resultValue / max(count, 1.0)"),`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
2023-05-08 15:12:41 +02:00
let d = coords[3];
let xRCCorner = vec2<i32>(coords.yz) * uniforms.strides - uniforms.pads;
2022-11-18 17:13:29 +01:00
let xRCorner = xRCCorner.x;
let xCCorner = xRCCorner.y;
2023-05-08 15:12:41 +02:00
${this.computePositions?`var maxValue = 0.0;
var maxValueFound = 0.0;
var maxPosition = 0;`:`var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};`}
2022-11-18 17:13:29 +01:00
2023-05-08 15:12:41 +02:00
var count = 0.0;
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilations.x) {
2022-11-18 17:13:29 +01:00
let xR = xRCorner + wR;
if (xR < 0 || xR >= uniforms.convDims.x) {
continue;
}
2023-05-08 15:12:41 +02:00
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilations.y) {
2022-11-18 17:13:29 +01:00
let xC = xCCorner + wC;
if (xC < 0 || xC >= uniforms.convDims.y) {
continue;
}
2023-05-08 15:12:41 +02:00
let value = getX(batch, xR, xC, d);
${e}
2022-11-18 17:13:29 +01:00
}
}
${this.computePositions?"setOutputAtIndexI32(index, maxPosition);":`setOutputAtIndex(index, ${t});`}
2022-11-18 17:13:29 +01:00
}
}
`}},$u=class{constructor(e,t,o=!1,n=!1,s=!1){if(this.variableNames=["x"],this.uniforms="strides : vec3<i32>, pads : vec3<i32>, convDims : vec3<i32>, filterDims : vec3<i32>,",this.workgroupSize=[128,1,1],this.size=!0,t==="avg"&&o)throw new Error("Cannot compute positions for average pool.");this.outputShape=e.outShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.poolType=t,this.computePositions=o,this.flattenPositions=n,this.includeBatchIndex=s,this.shaderKey=`pool3D_${t}_${o}_${n}_${s}`}getUserCode(){let e;this.poolType==="avg"?e="resultValue += value; count += 1.0;":this.computePositions?e=`let currMaxValue = mix(value, maxValue, maxValueFound);
2023-05-08 15:12:41 +02:00
if (value >= currMaxValue) {
maxValue = value;
maxValueFound = 1.0;
maxPosition = ${this.flattenPositions?this.includeBatchIndex?"(((batch * uniforms.xShape.y + xD) * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch":"((xD * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch":"wD * uniforms.filterDims.y * uniforms.filterDims.y + wR * uniforms.filterDims.z + wC"};
}`:e="resultValue = max(value, resultValue);";let t="resultValue";return this.poolType==="avg"&&(t="resultValue / max(count, 1.0)"),`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
2023-05-08 15:12:41 +02:00
let batch = coords.x;
let ch = coords.u;
2022-11-18 17:13:29 +01:00
2023-05-08 15:12:41 +02:00
let xCorner = vec3<i32>(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads;
let xDCorner = xCorner.x;
let xRCorner = xCorner.y;
let xCCorner = xCorner.z;
2022-11-18 17:13:29 +01:00
2023-05-08 15:12:41 +02:00
${this.computePositions?`var maxValue = 0.0;
var maxValueFound = 0.0;
var maxPosition = 0;`:`var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};`}
var count = 0.0;
for (var wD = 0; wD < uniforms.filterDims.x; wD++) {
let xD = xDCorner + wD;
if (xD < 0 || xD >= uniforms.convDims.x) {
continue;
}
for (var wR = 0; wR < uniforms.filterDims.y; wR++) {
let xR = xRCorner + wR;
if (xR < 0 || xR >= uniforms.convDims.y) {
continue;
}
for (var wC = 0; wC < uniforms.filterDims.z; wC++) {
let xC = xCCorner + wC;
if (xC < 0 || xC >= uniforms.convDims.z) {
continue;
}
let value = getX(batch, xD, xR, xC, ch);
${e}
2023-05-08 15:12:41 +02:00
}
}
}
${this.computePositions?"setOutputAtIndexI32(index, maxPosition);":`setOutputAtIndex(index, ${t});`}
2022-11-18 17:13:29 +01:00
}
}
`}};function zv(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reductionIndices:s,keepDims:a}=o;return ao(n,s,a,"max",t)}var NW={kernelName:os,backendName:"webgpu",kernelFunc:zv};function Vv(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{keepDims:s,axis:a}=o;return ao(n,a,s,"mean",t)}var TW={kernelName:ss,backendName:"webgpu",kernelFunc:Vv};function bx(r,e,t,o){if(e.filterWidth===1&&e.filterHeight===1&&y.arraysEqual(e.inShape,e.outShape))return Pt({inputs:{x:r},backend:o});if(e.filterWidth===e.inWidth&&e.filterHeight===e.inHeight&&e.batchSize===1&&e.padInfo.type==="VALID"){let a=r.shape.length,i=le({inputs:{x:r},backend:o,attrs:{shape:[r.shape[a-3]*r.shape[a-2],r.shape[a-1]]}}),p;t==="avg"?p=Vv({inputs:{x:i},backend:o,attrs:{axis:0,keepDims:!1}}):(y.assert(t==="max",()=>`Invalid pool type ${t}`),p=zv({inputs:{x:i},backend:o,attrs:{reductionIndices:0,keepDims:!1}}));let u=le({inputs:{x:p},backend:o,attrs:{shape:e.outShape}});return o.disposeData(i.dataId),o.disposeData(p.dataId),u}let n,s=[{type:"int32",data:[e.strideHeight,e.strideWidth]}];return e.filterHeight===1&&e.filterWidth===1?n=new yx(e):(t==="avg"?n=new Ka(e,"avg"):(y.assert(t==="max",()=>`Invalid pool type ${t}`),n=new Ka(e,"max")),s.push({type:"int32",data:[e.padInfo.top,e.padInfo.left]},{type:"int32",data:[e.dilationHeight,e.dilationWidth]},{type:"int32",data:[e.inHeight,e.inWidth]},{type:"int32",data:[e.effectiveFilterHeight,e.effectiveFilterWidth]})),o.runWebGPUProgram(n,[r],r.dtype,s)}function Vpe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:p}=o,l=C.computePool2DInfo(n.shape,s,a,1,i,p);return bx(n,l,"avg",t)}var _W={kernelName:kn,backendName:"webgpu",kernelFunc:Vpe};function Wpe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dataFormat:p,dimRoundingMode:u}=o,l=[1,1,1],c=C.computePool3DInfo(n.shape,s,a,l,i,u,p),m=new $u(c,"avg"),d=[{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.padInfo.front,c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.inDepth,c.inHeight,c.inWidth]},{type:"int32",data:[c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth]}];return t.runWebGPUProgram(m,[n],n.dtype,d)}var EW={kernelName:aa,backendName:"webgpu",kernelFunc:Wpe};var Cx=class{constructor(e){this.variableNames=["dy"],this.uniforms=`strides : vec2<i32>, pads : vec2<i32>, dilations : vec2<i32>, filterDims : vec2<i32>,
outHeight : i32, outWidth : i32, avgMultiplier : f32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="avgPool2DBackprop"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-01-06 19:23:06 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let d = coords[3];
let dyRCCorner = vec2<i32>(coords.yz) - uniforms.pads;
let dyRCorner = dyRCCorner.x;
let dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
var dotProd = 0.0;
2023-05-08 15:12:41 +02:00
for (var wR = 0; wR < uniforms.filterDims[0]; wR = wR + uniforms.dilations[0]) {
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]);
2023-01-06 19:23:06 +01:00
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
continue;
}
let idyR = i32(dyR);
2023-05-08 15:12:41 +02:00
for (var wC = 0; wC < uniforms.filterDims[1]; wC = wC + uniforms.dilations[1]) {
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]);
2023-01-06 19:23:06 +01:00
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
continue;
}
let idyC = i32(dyC);
let dyValue = getDy(batch, idyR, idyC, d);
dotProd = dotProd + dyValue * uniforms.avgMultiplier;
}
}
setOutputAtIndex(index, dotProd);
}
}
`}},wx=class{constructor(e){this.variableNames=["dy"],this.uniforms=`strides : vec3<i32>, pads : vec3<i32>, filterDims : vec3<i32>,
outDepth : i32, outHeight : i32, outWidth : i32, avgMultiplier : f32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="avgPool3DBackprop"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords.x;
let ch = coords.u;
let dyCorner = vec3<i32>(coords.y, coords.z, coords.w) - uniforms.pads;
let dyDCorner = dyCorner.x;
let dyRCorner = dyCorner.y;
let dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
var dotProd = 0.0;
for (var wD = 0; wD < uniforms.filterDims[0]; wD++) {
let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]);
if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) {
continue;
}
let idyD = i32(dyD);
for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]);
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
continue;
}
let idyR = i32(dyR);
for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]);
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
continue;
}
let idyC = i32(dyC);
let dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * uniforms.avgMultiplier;
}
}
}
setOutputAtIndex(index, dotProd);
}
}
`}};function Upe(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:p,pad:u,dimRoundingMode:l}=o,c=C.computePool3DInfo(a.shape,i,p,1,u,l),m=new wx(c),d=1/(c.filterDepth*c.filterHeight*c.filterWidth),f=[{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.effectiveFilterDepth-1-c.padInfo.front,c.effectiveFilterHeight-1-c.padInfo.top,c.effectiveFilterWidth-1-c.padInfo.left]},{type:"int32",data:[c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth]},{type:"int32",data:[c.outDepth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"float32",data:[d]}];return t.runWebGPUProgram(m,[n],a.dtype,f)}var $W={kernelName:Vi,backendName:"webgpu",kernelFunc:Upe};function Gpe(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s;wm([n,s],"avgPoolGrad");let{filterSize:i,strides:p,pad:u}=o,l=C.computePool2DInfo(a.shape,i,p,1,u),c=new Cx(l),m=1/(l.filterHeight*l.filterWidth),d=[{type:"int32",data:[l.strideHeight,l.strideWidth]},{type:"int32",data:[l.effectiveFilterHeight-1-l.padInfo.top,l.effectiveFilterWidth-1-l.padInfo.left]},{type:"int32",data:[l.dilationHeight,l.dilationWidth]},{type:"int32",data:[l.effectiveFilterHeight,l.effectiveFilterWidth]},{type:"int32",data:[l.outHeight]},{type:"int32",data:[l.outWidth]},{type:"float32",data:[m]}];return t.runWebGPUProgram(c,[n],a.dtype,d)}var RW={kernelName:zi,backendName:"webgpu",kernelFunc:Gpe};function Hpe(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;return Op({a:n,b:s,transposeA:a,transposeB:i,backend:t})}var DW={kernelName:Nn,backendName:"webgpu",kernelFunc:Hpe};var Sx=class{constructor(e,t){this.variableNames=["source"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.rank=t.length,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${ft(e.length)}, `,this.shaderKey="slice"}getUserCode(){let e=ft(this.rank),t=Kpe(this.rank),o;return this.start.length===1?o=this.outputShape.map((s,a)=>"sourceLoc = uniforms.start + coords;"):o=this.outputShape.map((s,a)=>`sourceLoc.${Wv[a]} = uniforms.start.${un(a)} + coords.${Wv[a]};`),`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
var sourceLoc : ${e};
2022-11-18 17:13:29 +01:00
let coords = getCoordsFromIndex(index);
${o.join(`
`)}
setOutputAtIndex(index, getSource(${t}));
2022-11-18 17:13:29 +01:00
}
}
`}},Wv=["x","y","z","w","u","v"];function Kpe(r){if(r===1)return"sourceLoc";if(r<=6)return Wv.slice(0,r).map(e=>`sourceLoc.${e}`).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}function ea(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o,[i,p]=nt.parseSliceParams(n,s,a);if(nt.assertParamsValid(n,i,p),t.shouldExecuteOnCPU([n])||n.dtype==="string"){let c=t.tensorMap.get(n.dataId),m=nW(c.values,i,p,n.shape,n.dtype);return t.makeTensorInfo(p,n.dtype,m)}if(y.sizeFromShape(p)===0)return t.makeTensorInfo(p,n.dtype,[]);let u=new Sx(i,p),l=[{type:"int32",data:i}];return t.runWebGPUProgram(u,[n],n.dtype,l)}var AW={kernelName:_s,backendName:"webgpu",kernelFunc:ea};var qpe=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;y.assert(n.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");let i=s.reduce((b,w)=>b*w),p=C.getReshaped(n.shape,s,i),u=C.getPermuted(p.length,s.length),l=C.getReshapedPermuted(n.shape,s,i),c=C.getSliceBeginCoords(a,s.length),m=C.getSliceSize(l,a,s.length),d=[],f=le({inputs:{x:n},backend:t,attrs:{shape:p}}),h=Cr({inputs:{x:f},backend:t,attrs:{perm:u}}),g=le({inputs:{x:h},backend:t,attrs:{shape:l}}),x=ea({inputs:{x:g},backend:t,attrs:{begin:c,size:m}});return d.push(f),d.push(h),d.push(g),d.forEach(b=>t.disposeData(b.dataId)),x},FW={kernelName:ia,backendName:"webgpu",kernelFunc:qpe};var jpe=`
2022-11-20 22:20:02 +01:00
fn bincount_write(index: i32, value: f32) {
${oo("&result[index]","value","float32")}
2022-11-20 22:20:02 +01:00
}
`,Xpe=`
2022-11-20 22:20:02 +01:00
fn bincount_write(index: i32, value: f32) {
2023-01-06 19:23:06 +01:00
atomicStore(&result[index], bitcast<i32>(value));
2022-11-20 22:20:02 +01:00
}
`,nc=class{constructor(e,t,o=!1){this.outputShape=[],this.variableNames=["x"],this.uniforms="binCountSize : i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.hasWeights=!0,this.binaryOutput=!1,this.outputShape=e,this.rank=e.length,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.binaryOutput=o,o&&(this.atomic=!1),this.hasWeights=t,this.hasWeights&&this.variableNames.push("w"),this.shaderKey=`bincount_${this.hasWeights}_${this.binaryOutput}_${this.rank}`}getUserCode(){return`
${this.binaryOutput?Xpe:jpe}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-20 22:20:02 +01:00
${this.rank===1?`if (index < uniforms.xShape) {
let indexVal = i32(getX(index));
if (indexVal < uniforms.binCountSize) {
2023-01-06 19:23:06 +01:00
let value = ${this.binaryOutput?1:this.hasWeights?"getW(index)":"1."};
2022-11-20 22:20:02 +01:00
bincount_write(indexVal, value);
}
}`:`let coord = getCoordsFromIndex(index);
if (coordsInBounds2D(coord, uniforms.xShape)) {
let indexVal = i32(getX(coord[0], coord[1]));
if (indexVal < uniforms.binCountSize) {
2023-01-06 19:23:06 +01:00
let value = ${this.binaryOutput?1:this.hasWeights?"getW(coord[0], coord[1])":"1."};
2022-11-20 22:20:02 +01:00
bincount_write(coord.x * uniforms.binCountSize + indexVal, value);
}
}`}
}
`}};function Ype(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a}=o,i=y.sizeFromShape(n.shape),u=y.sizeFromShape(s.shape)>0,l=[a],c=s.dtype,m=Nt({backend:t,attrs:{shape:l,value:0,dtype:c}}),d=new nc([i],u),f=[{type:"int32",data:[a]}],h=u?[n,s]:[n];return t.runWebGPUProgram(d,h,c,f,m)}var PW={kernelName:Tn,backendName:"webgpu",kernelFunc:Ype};var Ix=class{constructor(e){this.outputShape=[],this.variableNames=["s0","s1"],this.uniforms="s0Size : i32, s1Size : i32, ",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e],this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="broadcastArgs"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
var s0 = 1.0;
var s1 = 1.0;
let indexS0 = index - uniforms.size + uniforms.s0Size;
let indexS1 = index - uniforms.size + uniforms.s1Size;
if (indexS0 >= 0) {
s0 = getS0(indexS0);
}
if (indexS1 >= 0) {
s1 = getS1(indexS1);
}
if (s0 == 1.0) {
setOutputAtIndex(index, s1);
} else if (s1 == 1.0) {
setOutputAtIndex(index, s0);
} else if (s0 != s1) {
setOutputAtIndex(index, uniforms.NAN);
} else {
setOutputAtIndex(index, s0);
}
}
}
`}};function Qpe(r){let{inputs:e,backend:t}=r,{s0:o,s1:n}=e;if(t.shouldExecuteOnCPU([o,n])){let l=t.tensorMap.get(o.dataId),c=t.tensorMap.get(n.dataId),m=l.values,d=c.values,f=C.assertAndGetBroadcastShape(Array.from(m),Array.from(d));return t.makeTensorInfo([f.length],"int32",Int32Array.from(f))}let s=y.sizeFromShape(o.shape),a=y.sizeFromShape(n.shape),i=Math.max(s,a),p=new Ix(i),u=[{type:"int32",data:[s]},{type:"int32",data:[a]}];return t.runWebGPUProgram(p,[o,n],"int32",u)}var OW={kernelName:ua,backendName:"webgpu",kernelFunc:Qpe};var Uv=tt({opType:fe.NOT_EQUAL,dtype:"bool",cpuKernelImpl:ZV}),MW={kernelName:Ro,backendName:"webgpu",kernelFunc:Uv};function Fi(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.tensorMap.get(o.dataId);return Pt({inputs:{x:n.complexTensorInfos.real},backend:t})}var LW={kernelName:si,backendName:"webgpu",kernelFunc:Fi};function BW(r,e){let t=new so(r.shape,Z.TO_INT),o=e.runWebGPUProgram(t,[r],"int32");return{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}function Gv(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dtype:s}=o;if(s==="complex64"){if(n.dtype==="complex64")return Pt({inputs:{x:n},backend:t});let a=Yr(n.shape),i=Gv({inputs:{x:n},backend:t,attrs:{dtype:"float32"}}),p=Uo({inputs:{real:i,imag:a},backend:t});return a.dispose(),t.disposeData(i.dataId),p}if(n.dtype==="complex64"){let a=Fi({inputs:{input:n},backend:t}),i=Gv({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeData(a.dataId),i}if(!y.hasEncodingLoss(n.dtype,s)){let a=Pt({inputs:{x:n},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(t.shouldExecuteOnCPU([n])){let a=t.tensorMap.get(n.dataId).values,[i,p,u]=DV(a,n.shape,n.dtype,s);return t.makeTensorInfo(i,p,u)}if(s==="int32")return BW(n,t);if(s==="bool"){let a=t.makeTensorInfo([],"bool",y.getTypedArrayFromDType("bool",1)),p=Uv({inputs:{a:n,b:a},backend:t});return t.disposeData(a.dataId),p}throw new Error(`Error in Cast: failed to cast ${n.dtype} to ${s}`)}var zW={kernelName:ho,backendName:"webgpu",kernelFunc:Gv};var Zpe=ye({opType:Z.CEIL,cpuKernelImpl:AV}),VW={kernelName:go,backendName:"webgpu",kernelFunc:Zpe};var vx=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workPerThread=4,this.workgroupSize=[64,1,1],this.outputComponent=4,this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if(index < uniforms.size) {
let value = getAByOutputIndex(index);
2023-01-06 19:23:06 +01:00
var clampedValue = clamp(
value, vec4<f32>(uniforms.minVal), vec4<f32>(uniforms.maxVal));
clampedValue = select(clampedValue, value, isnanVec4(value));
2022-11-18 17:13:29 +01:00
setOutputAtIndex(index, clampedValue);
}
}
`}};var kx=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="clip"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if(index < uniforms.size) {
let value = getAByOutputIndex(index);
if (isnan(value)) {
setOutputAtIndex(index, value);
return;
}
setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal));
}
}
`}};function Jpe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{clipValueMin:s,clipValueMax:a}=o,i,p=[{type:"float32",data:[s]},{type:"float32",data:[a]}];return y.sizeFromShape(n.shape)%4===0?i=new vx(n.shape):i=new kx(n.shape),t.runWebGPUProgram(i,[n],n.dtype,p)}var WW={kernelName:Go,backendName:"webgpu",kernelFunc:Jpe};var Nx=class{constructor(e){this.outputShape=[],this.variableNames=["real","imag"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="complexAbs"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let re = abs(getRealByOutputIndex(index));
let im = abs(getImagByOutputIndex(index));
let mx = max(re, im);
// The length function in wgsl may be not underflow-safe on some GPUs.
// So the safe solution is to ensure underflow-safety in all cases.
setOutputAtIndex(index, select(mx * length(vec2<f32>(1, min(re, im)/mx)), 0.0, mx == 0.0));
}
}
`}};function UW(r,e){return{dataId:e.dataId,dtype:e.dtype,shape:r.shape}}function ele(r){let{inputs:e,backend:t}=r,{x:o}=e,n=t.tensorMap.get(o.dataId),s=new Nx(o.shape),a=[UW(o,n.complexTensorInfos.real),UW(o,n.complexTensorInfos.imag)];return t.runWebGPUProgram(s,a,a[0].dtype)}var GW={kernelName:Wi,backendName:"webgpu",kernelFunc:ele};var Tx=class{constructor(e){this.uniforms="",this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=C.computeOutShape(e,1),this.variableNames=e.map((t,o)=>`T${o}`),this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.offsetLength=e.length-1;for(let t=0;t<this.offsetLength;t++)this.uniforms+=`offset${t} : i32,`;this.shaderKey="concat"}getUserCode(){let e=[];if(this.offsetLength>0){e.push("if (yC < uniforms.offset0){ setOutputAtCoords(coords.x, coords.y, getT0(yR, yC)); }");for(let s=1;s<this.offsetLength;s++)e.push(`else if (yC < uniforms.offset${[s]}){ setOutputAtCoords(coords.x, coords.y, getT${s}(yR, yC - uniforms.offset${s-1})); }`);let o=this.offsetLength,n=this.offsetLength-1;e.push(`else { setOutputAtCoords(coords.x, coords.y, getT${o}(yR, yC - uniforms.offset${n})); }`)}else e.push("setOutputAtCoords(coords.x, coords.y, getT0(yR, yC));");return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
let flatIndex = index * ${this.workPerThread} + i;
if(flatIndex < uniforms.size) {
let coords = getCoordsFromIndex(flatIndex);
let yR = coords.x;
let yC = coords.y;
${e.join(`
2022-11-18 17:13:29 +01:00
`)}
}
}
}
`}};function Mp(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.tensorMap.get(o.dataId);return Pt({inputs:{x:n.complexTensorInfos.imag},backend:t})}var HW={kernelName:Qi,backendName:"webgpu",kernelFunc:Mp};function sc(r,e,t){let o=r[0].dtype;if(o==="complex64"){let f=r.map(w=>Fi({inputs:{input:w},backend:t})),h=r.map(w=>Mp({inputs:{input:w},backend:t})),g=sc(f,e,t),x=sc(h,e,t),b=Uo({inputs:{real:g,imag:x},backend:t});return f.forEach(w=>t.disposeData(w.dataId)),h.forEach(w=>t.disposeData(w.dataId)),t.disposeData(g.dataId),t.disposeData(x.dataId),b}let n=t.shouldExecuteOnCPU(r);if(o==="string"&&(n=!0),n){let f=r.map(k=>{let E=[-1,y.sizeFromShape(k.shape.slice(e))];return le({inputs:{x:k},backend:t,attrs:{shape:E}})}),h=f.map(k=>({vals:t.readSync(k.dataId),shape:k.shape})),g=C.computeOutShape(f.map(k=>k.shape),1),x=f[0].shape[0]===1,b=FV(h,g,o,x),w=C.computeOutShape(r.map(k=>k.shape),e),S=t.makeTensorInfo(w,o,b);return f.forEach(k=>t.disposeData(k.dataId)),S}let s=t.device.limits.maxStorageBuffersPerShaderStage-1;if(r.length>s){let f=[];for(let g=0;g<r.length;g+=s){let x=r.slice(g,g+s);f.push(sc(x,e,t))}let h=sc(f,e,t);for(let g of f)t.disposeData(g.dataId);return h}let{tensors2D:a,outShape:i}=tle(r,e,t),p=a.map(f=>f.shape),u=new Tx(p),l=[],c=new Array(p.length-1);if(c.length>0){c[0]=p[0][1],l.push({type:"int32",data:[c[0]]});for(let f=1;f<c.length;f++)c[f]=c[f-1]+p[f][1],l.push({type:"int32",data:[c[f]]})}let m=t.runWebGPUProgram(u,a,a[0].dtype,l);a.forEach(f=>t.disposeData(f.dataId));let d=le({inputs:{x:m},backend:t,attrs:{shape:i}});return t.disposeData(m.dataId),d}function tle(r,e,t){let o=C.computeOutShape(r.map(s=>s.shape),e);return{tensors2D:r.map(s=>le({inputs:{x:s},backend:t,attrs:{shape:[y.sizeFromShape(s.shape.slice(0,e)),y.sizeFromShape(s.shape.slice(e))]}})),outShape:o}}function Hv(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=y.parseAxisParam(n,e[0].shape)[0],a=e.map(u=>u.shape);C.assertParamsConsistent(a,s);let i=C.computeOutShape(e.map(u=>u.shape),s);if(y.sizeFromShape(i)===0)return t.makeTensorInfo(i,e[0].dtype,[]);let p=e.filter(u=>y.sizeFromShape(u.shape)>0);return p.length===1?Pt({inputs:{x:p[0]},backend:t}):sc(p,s,t)}var KW={kernelName:pa,backendName:"webgpu",kernelFunc:Hv};function rle(r,e,t,o,n=!1,s=null,a=!1,i=4,p=4,u=4){let l=D=>{switch(D){case 1:return"resData = f32(x[xIndex]);";case 3:return"resData = vec3<f32>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";case 4:return"resData = vec4<f32>(x[xIndex / 4]);";default:throw new Error(`innerElementSize ${D} is not supported.`)}},c=D=>{switch(D){case 1:return"return f32(W[row * uniforms.wShape[3] + col]);";case 4:return"return vec4<f32>(W[(row * uniforms.wShape[3] + col) / 4]);";default:throw new Error(`innerElementSize ${D} is not supported.`)}},m=r?`
2022-11-18 17:13:29 +01:00
let coord = vec4<i32>(batch, xRow, xCol, xCh);
`:`
let coord = vec4<i32>(batch, xCh, xRow, xCol);
2022-11-20 22:20:02 +01:00
`,d=r?`
2022-11-18 17:13:29 +01:00
let coords = vec4<i32>(
batch,
row / outWidth,
row % outWidth,
col);
`:`
let coords = vec4<i32>(
batch,
row,
col / outWidth,
col % outWidth);
2022-11-20 22:20:02 +01:00
`,f=r?"uniforms.xShape[1]":"uniforms.xShape[2]",h=r?"uniforms.xShape[2]":"uniforms.xShape[3]",g=r?"row":"col",x=r?"col":"row",b=`
2022-11-18 17:13:29 +01:00
let inChannels = uniforms.wShape[2];
let outWidth = ${r?"uniforms.outShape[2]":"uniforms.outShape[3]"};
let outRow = ${g} / outWidth;
let outCol = ${g} % outWidth;
2022-11-20 22:20:02 +01:00
let WRow = ${x} / (uniforms.filterDims[1] * inChannels);
let WCol = ${x} / inChannels % uniforms.filterDims[1];
2023-05-08 15:12:41 +02:00
let xRow = outRow * uniforms.strides[0] + uniforms.dilations[0] * WRow - uniforms.pads[0];
let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * WCol - uniforms.pads[1];
2022-11-20 22:20:02 +01:00
let xCh = ${x} % inChannels;
2023-05-08 15:12:41 +02:00
var resData = ${Ae(i)}(0.0);
2022-11-18 17:13:29 +01:00
// The bounds checking is always needed since we use it to pad zero for
// the 'same' padding type.
2022-11-20 22:20:02 +01:00
if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${h}) {
2022-11-18 17:13:29 +01:00
${m}
let xIndex = getIndexFromCoords4D(coord, uniforms.xShape);
${l(i)}
2022-11-18 17:13:29 +01:00
}
return resData;`,w=r?e&&o?`
2022-11-18 17:13:29 +01:00
${b}`:`
if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
${b}
}
return ${Ae(i)}(0.0);`:o&&t?`
2022-11-18 17:13:29 +01:00
${b}`:`
if (row < uniforms.dimInner && col < uniforms.dimBOuter) {
${b}
}
return ${Ae(i)}(0.0);`,S=`${c(p)}`,k=Ae(u),T=r?Ae(i):Ae(p),E=r?Ae(p):Ae(i);return`
${gr(s,a,u===4,4)}
fn mm_readA(batch: i32, row : i32, col : i32) -> ${T} {
${r?w:S}
2022-11-18 17:13:29 +01:00
}
2023-08-05 15:03:11 +02:00
fn mm_readB(batch: i32, row : i32, col : i32) -> ${E} {
${r?S:w}
2022-11-18 17:13:29 +01:00
}
2023-08-05 15:03:11 +02:00
fn mm_write(batch: i32, row : i32, col : i32, valueIn : ${k}) {
2022-11-18 17:13:29 +01:00
if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)
{
var value = valueIn;
let outWidth = ${r?"uniforms.outShape[2]":"uniforms.outShape[3]"};
2022-11-20 22:20:02 +01:00
${d}
${no(n,s)}
2022-11-18 17:13:29 +01:00
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}`}var _x=class{constructor(e,t,o,n,s=!1,a=null,i=!1,p=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>, pads : vec2<i32>, strides : vec2<i32>, dilations : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.outShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.isVec4=((e.inChannels%4===0||e.inChannels%3===0)&&this.isChannelsLast||e.outWidth%4===0&&!this.isChannelsLast)&&e.outChannels%4===0,this.dispatchLayout=this.isChannelsLast?{x:[3],y:[1,2],z:[0]}:{x:[2,3],y:[1],z:[0]},this.workgroupSize=ym(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=bm(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4?(this.outputComponent=4,this.isChannelsLast&&e.inChannels%4!==0?(this.innerElementSize=3,this.variableComponents=[1,4]):(this.innerElementSize=4,this.variableComponents=[4,4]),s&&(this.variableNames.push("bias"),this.variableComponents.push(4)),i&&(this.variableNames.push("preluActivationWeights"),this.variableComponents.push(4))):(this.innerElementSize=this.elementsPerThread[0],s&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights")),this.sequentialAccessByThreads=p,this.addBias=s,this.activation=a,this.hasPreluActivationWeights=i,this.tileAOuter=this.workgroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workgroupSize[0]*this.elementsPerThread[0],this.tileInner=Math.max(this.workgroupSize[0]*this.innerElementSize,this.workgroupSize[1]),this.fitAOuter=t%this.tileAOuter===0,this.fitBOuter=o%this.tileBOuter===0,this.fitInner=n%this.tileInner===0,this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.innerElementSize}_${this.isChannelsLast}_${this.sequentialAccessByThreads}`}getUserCode(){let e=this.isVec4?Fp(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner):Pp(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner,!1,null,this.sequentialAccessByThreads),t=this.isVec4?[this.innerElementSize,4,4]:[1,1,1];return`
${rle(this.isChannelsLast,this.fitAOuter,this.fitBOuter,this.fitInner,this.addBias,this.activation,this.hasPreluActivationWeights,t[0],t[1],t[2])}
${e}
`}};var Ex=class{constructor(e,t=!1,o=null,n=!1){this.variableNames=["x","W"],this.uniforms="filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>,",this.workgroupSize=[4,4,8],this.outputShape=e.outShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.dispatchLayout=this.isChannelsLast?{x:[2],y:[1],z:[0,3]}:{x:[3],y:[2],z:[0,1]},this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.addBias=t,this.activation=o,this.hasPreluActivationWeights=n,t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`conv2dnaive_${this.activation}_${this.isChannelsLast}`}getUserCode(){return`
${gr(this.activation,this.hasPreluActivationWeights,!1,4)}
2022-11-18 17:13:29 +01:00
fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32{
let coords = vec4<i32>(batch, row, col, chan);
if (coordsInBounds4D(coords, uniforms.xShape)) {
return getX(batch, row, col, chan);
} else {
return 0.0;
}
}
fn readFilt(row : i32, col : i32, xChannel : i32, outChannel : i32) -> f32{
let coords = vec4<i32>(row, col, xChannel, outChannel);
if(coordsInBounds4D(coords, uniforms.wShape)) {
return getW(row, col, xChannel, outChannel);
} else {
return 0.0;
}
}
fn writeResult(batch : i32, row : i32, col : i32, chan : i32, valueIn : f32) {
let coords = ${this.isChannelsLast?"vec4<i32>(batch, row, col, chan);":"vec4<i32>(batch, chan, row, col);"}
if (coordsInBounds4D(coords, uniforms.outShape)) {
var value = valueIn;
${no(this.addBias,this.activation)}
2022-11-18 17:13:29 +01:00
setOutputAtCoords(coords.x, coords.y, coords.z, coords.w, value);
}
}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
let coords = getOutputCoords();
let batch = coords[0];
let outChannel = ${this.isChannelsLast?"coords[3];":"coords[1];"}
let outRow = ${this.isChannelsLast?"coords[1];":"coords[2];"}
let outCol = ${this.isChannelsLast?"coords[2];":"coords[3];"}
var acc : f32 = 0.0;
for (var row = 0; row < uniforms.filterDims[0]; row = row + 1) {
for (var col = 0; col < uniforms.filterDims[1]; col = col + 1) {
2023-05-08 15:12:41 +02:00
let xRow = outRow * uniforms.strides[0] + uniforms.dilations[0] * row - uniforms.pads[0];
let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * col - uniforms.pads[1];
2022-11-18 17:13:29 +01:00
for (var xChannel = 0; xChannel < ${this.isChannelsLast?"uniforms.xShape[3];":"uniforms.xShape[1];"} xChannel = xChannel + 1) {
${this.isChannelsLast?"let v = readInp(batch, xRow, xCol, xChannel);":"let v = readInp(batch, xChannel, xRow, xCol);"}
let f = readFilt(row, col, xChannel, outChannel);
acc = acc + v * f;
}
}
}
writeResult(batch, outRow, outCol, outChannel, acc);
}
`}};var $x=class{constructor(e,t){this.variableNames=["x"],this.uniforms=`pads : vec2<i32>, strides : vec2<i32>, dilations : vec2<i32>, outWidth : i32, itemsPerBlockRow : i32,
inChannels : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=t,this.shaderKey=`im2col_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,o=this.isChannelsLast?"coords[1]":"coords[2]",n=this.isChannelsLast?"coords[2]":"coords[1]",s=this.isChannelsLast?"getX(batch, xRow, xCol, ch)":"getX(batch, ch, xRow, xCol)";return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-20 22:20:02 +01:00
let coords = getCoordsFromIndex(index);
if(index < uniforms.size) {
let batch = coords[0];
let row = ${o};
let col = ${n};
2023-05-08 15:12:41 +02:00
let offsetY = (row / uniforms.outWidth) * uniforms.strides[0] - uniforms.pads[0];
let xRow = offsetY + uniforms.dilations[0] * (col / uniforms.itemsPerBlockRow);
2022-11-20 22:20:02 +01:00
var value = 0.0;
if(xRow < uniforms.xShape[${e}] && xRow >= 0) {
2023-05-08 15:12:41 +02:00
let offsetX = (row % uniforms.outWidth) * uniforms.strides[1] -
uniforms.pads[1];
let xCol = offsetX + uniforms.dilations[1] * ((col %
2022-11-20 22:20:02 +01:00
uniforms.itemsPerBlockRow) / uniforms.inChannels);
let ch = col % uniforms.inChannels;
if(xCol < uniforms.xShape[${t}] && xCol >= 0) {
2022-11-20 22:20:02 +01:00
value = ${s};
}
}
setOutputAtIndex(index, value);
}
}
`}};function Rx(r,e){let t=r.length;return t>=3?e?[...r.slice(0,-3),r[t-3]*r[t-2],r[t-1]]:[...r.slice(0,-3),r[t-3],r[t-2]*r[t-1]]:!e&&t===1&&r[0]>1?[r[0],1]:null}function ole({x:r,filter:e,convInfo:t,backend:o,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let p=t.dataFormat==="channelsLast",u=!p,l=!1,c=p&&t.filterHeight===t.inHeight&&t.filterWidth===t.inWidth&&t.padInfo.type==="VALID",m=[],d,f;if(c){let x=t.inHeight*t.inWidth*t.inChannels;d=le({inputs:{x:r},backend:o,attrs:{shape:[1,t.batchSize,x]}}),f=le({inputs:{x:e},backend:o,attrs:{shape:[1,x,t.outChannels]}})}else d=le({inputs:{x:r},backend:o,attrs:{shape:p?[t.batchSize,t.inHeight*t.inWidth,t.inChannels]:[t.batchSize,t.inChannels,t.inHeight*t.inWidth]}}),f=le({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}});if(m.push(d),m.push(f),s!=null){let x=Rx(s.shape,p);x!=null&&(s=le({inputs:{x:s},backend:o,attrs:{shape:x}}),m.push(s))}if(n!=null){let x=Rx(n.shape,p);x!=null&&(n=le({inputs:{x:n},backend:o,attrs:{shape:x}}),m.push(n))}let h=Op({a:p?d:f,b:p?f:d,transposeA:u,transposeB:l,backend:o,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a}),g=le({inputs:{x:h},backend:o,attrs:{shape:t.outShape}});m.push(h);for(let x of m)o.disposeData(x.dataId);return g}function nle({x:r,filter:e,convInfo:t,backend:o,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let{filterWidth:p,filterHeight:u,inChannels:l,strideWidth:c,strideHeight:m,padInfo:d,outWidth:f,outHeight:h,dilationWidth:g,dilationHeight:x,dataFormat:b}=t,w=b==="channelsLast",S=p*u*l,k=h*f,T=w?[t.batchSize,k,S]:[t.batchSize,S,k],E=new $x(T,w),R=[{type:"int32",data:[d.top,d.left]},{type:"int32",data:[m,c]},{type:"int32",data:[x,g]},{type:"int32",data:[f]},{type:"int32",data:[l*p]},{type:"int32",data:[l]}],D=o.runWebGPUProgram(E,[r],r.dtype,R),F=[];F.push(D);let O=le({inputs:{x:e},backend:o,attrs:{shape:[1,S,-1]}});if(F.push(O),s!=null){let U=Rx(s.shape,w);U!=null&&(s=le({inputs:{x:s},backend:o,attrs:{shape:U}}),F.push(s))}if(n!=null){let U=Rx(n.shape,w);U!=null&&(n=le({inputs:{x:n},backend:o,attrs:{shape:U}}),F.push(n))}let B=Op({a:w?D:O,b:w?O:D,transposeA:!w,transposeB:!1,backend:o,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a}),z=le({inputs:{x:B},backend:o,attrs:{shape:t.outShape}});F.push(B);for(let U of F)o.disposeData(U.dataId);return z}function Dx({x:r,filter:e,convInfo:t,backend:o,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let p=n!=null,u=s!=null,l=t.dataFormat==="channelsLast",c=l&&t.filterHeight===t.inHeight&&t.filterWidth===t.inWidth&&t.padInfo.type==="VALID",m=A().getBool("WEBGPU_USE_NAIVE_CONV2D_DEBUG");if(!m&&(c||t.filterHeight===1&&t.filterWidth===1&&t.dilationHeight===1&&t.dilationWidth===1&&t.strideHeight===1&&t.strideWidth===1&&(t.padInfo.type==="SAME"||t.padInfo.type==="VALID")))return ole({x:r,filter:e,convInfo:t,backend:o,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a});let d=A().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),f=d>-1?d:o.thresholdToIncreaseWorkgroups,h=t.batchSize*Math.ceil(t.outHeight*t.outWidth/32)*Math.ceil(t.outChannels/32);if(A().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")||h<=f)return nle({x:r,filter:e,convInfo:t,backend:o,bias:n,preluActivationWeights:s,leakyreluAlpha:a,activation:i});let g,x=[t.padInfo.top,t.padInfo.left],b=[{type:"int32",data:[t.filterHeight,t.filterWidth]},{type:"int32",data:[...x]},{type:"int32",data:[t.strideHeight,t.strideWidth]},{type:"int32",data:[t.dilationHeight,t.dilationWidth]}];if(m)g=new Ex(t,p,i,u);else{let T=l?t.outHeight*t.outWidth:t.outChannels,E=l?t.outChannels:t.outHeight*t.outWidth,R=t.filterHeight*t.filterWidth*t.inChannels;b.push({type:"int32",data:[T]},{type:"int32",data:[E]},{type:"int32",data:[R]});let D=o.adapterInfo.isIntel();g=new _x(t,T,E,R,p,i,u,D)}let w=[],S=[r,e];p&&(!l&&n.shape.length===1&&(n=le({inputs:{x:n},backend:o,attrs:{shape:[n.shape[0],1,1]}}),w.push(n)),S.push(n)),u&&(!l&&s.shape.length===1&&(s=le({inputs:{x:s},backend:o,attrs:{shape:[s
2023-08-05 15:03:11 +02:00
${G()} {
2023-05-08 15:12:41 +02:00
let batch = i32(globalId.z) / uniforms.outShape[1];
let r = i32(globalId.z) % uniforms.outShape[1];
let c = i32(globalId.y) * ${this.workPerThread};
let d1 = i32(globalId.x) * 4;
let dyCorner = vec2<i32>(r, c) - uniforms.pads;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
var dotProd: array<vec4<f32>, ${this.workPerThread}>;
for (var i = 0; i < ${this.workPerThread}; i++) {
dotProd[i] = vec4<f32>(0.0);
}
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {
let dyR = f32(dyCorner.x + wR) / f32(uniforms.strides.x);
let wRPerm = uniforms.filterDims.x - 1 - wR;
if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) ||
fract(dyR) > 0.0) {
continue;
}
let idyR = i32(dyR);
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) {
let dyC = f32(dyCorner.y + wC) / f32(uniforms.strides.y);
let dyC2 = f32(dyCorner.y + 1 + wC) / f32(uniforms.strides.y);
let wCPerm = uniforms.filterDims.y - 1 - wC;
var bDyCVal = true;
var bDyCVal2 = true;
if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) ||
fract(dyC) > 0.0) {
bDyCVal = false;
}
if (dyC2 < 0.0 || dyC2 >= f32(uniforms.outBackprop[2]) ||
fract(dyC2) > 0.0) {
bDyCVal2 = false;
}
let idyC = i32(dyC);
let idyC2 = i32(dyC2);
if (bDyCVal && bDyCVal2) {
let d2Length = uniforms.outBackprop[3];
for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) {
let wValue0 = getW(wRPerm, wCPerm, d1, d2);
let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2);
let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2);
let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2);
var xValue = getDy(batch, idyR, idyC, d2);
let tmpval = vec4<f32>(dot(xValue, wValue0),
dot(xValue, wValue1),
dot(xValue, wValue2),
dot(xValue, wValue3));
dotProd[0] = dotProd[0] + tmpval;
xValue = getDy(batch, idyR, idyC2, d2);
dotProd[1] = dotProd[1] + vec4<f32>(dot(xValue, wValue0),
dot(xValue, wValue1),
dot(xValue, wValue2),
dot(xValue, wValue3));
}
} else if (bDyCVal) {
let d2Length = uniforms.outBackprop[3];
for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) {
let wValue0 = getW(wRPerm, wCPerm, d1, d2);
let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2);
let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2);
let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2);
var xValue = getDy(batch, idyR, idyC, d2);
let tmpval = vec4<f32>(dot(xValue, wValue0),
dot(xValue, wValue1),
dot(xValue, wValue2),
dot(xValue, wValue3));
dotProd[0] = dotProd[0] + tmpval;
}
} else if (bDyCVal2) {
let d2Length = uniforms.outBackprop[3];
for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) {
let wValue0 = getW(wRPerm, wCPerm, d1, d2);
let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2);
let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2);
let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2);
var xValue = getDy(batch, idyR, idyC2, d2);
let tmpval = vec4<f32>(dot(xValue, wValue0),
dot(xValue, wValue1),
dot(xValue, wValue2),
dot(xValue, wValue3));
dotProd[1] = dotProd[1] + tmpval;
}
}
}
}
for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
let coords = vec4<i32>(batch, r, c + i, d1);
if (coordsInBounds4D(coords, uniforms.outShape)) {
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]);
}
}
}
`;return this.isVec4?`
${n}
`:`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-01-06 19:23:06 +01:00
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let d1 = coords[${o}];
let dyCorner = vec2<i32>(coords[${e}], coords[${t}]) - uniforms.pads;
2023-01-06 19:23:06 +01:00
let dyRCorner = dyCorner.x;
let dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
var dotProd = 0.0;
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {
2023-05-08 15:12:41 +02:00
let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.strides.x);
2023-01-06 19:23:06 +01:00
let wRPerm = uniforms.filterDims.x - 1 - wR;
if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 ||
wRPerm < 0) {
continue;
}
let idyR = i32(dyR);
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) {
2023-05-08 15:12:41 +02:00
let dyC = (f32(dyCCorner) + f32(wC)) / f32(uniforms.strides.y);
2023-01-06 19:23:06 +01:00
let wCPerm = uniforms.filterDims.y - 1 - wC;
if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) ||
fract(dyC) > 0.0 || wCPerm < 0) {
continue;
}
let idyC = i32(dyC);
for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) {
2023-05-08 15:12:41 +02:00
let xValue = ${this.isChannelsLast?"getDy(batch, idyR, idyC, d2)":"getDy(batch, d2, idyR, idyC)"};
let wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd = dotProd + xValue * wValue;
2023-01-06 19:23:06 +01:00
}
}
}
setOutputAtIndex(index, dotProd);
}
}
`}},Fx=class{constructor(e){this.variableNames=["x","dy"],this.uniforms="pads : vec2<i32>, strides : vec2<i32>, batchSize : i32, outHeight : i32, outWidth : i32, inHeight : i32, inWidth : i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",this.shaderKey=`conv2DDerFilter_${this.isChannelsLast}`}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-01-06 19:23:06 +01:00
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let wR = coords[0];
let wC = coords[1];
let d1 = coords[2];
let d2 = coords[3];
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
var dotProd = 0.0;
for (var b = 0; b < uniforms.batchSize; b = b + 1) {
for (var yR = 0; yR < uniforms.outHeight; yR = yR + 1) {
2023-05-08 15:12:41 +02:00
let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0];
2023-01-06 19:23:06 +01:00
if (xR < 0 || xR >= uniforms.inHeight) {
continue;
}
for (var yC = 0; yC < uniforms.outWidth; yC = yC + 1) {
2023-05-08 15:12:41 +02:00
let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1];
2023-01-06 19:23:06 +01:00
if (xC < 0 || xC >= uniforms.inWidth) {
continue;
}
if (${this.isChannelsLast}) {
let dyValue = getDy(b, yR, yC, d2);
let xValue = getX(b, xR, xC, d1);
dotProd = dotProd + xValue * dyValue;
} else {
let dyValue = getDy(b, d2, yR, yC);
let xValue = getX(b, d1, xR, xC);
dotProd = dotProd + xValue * dyValue;
}
}
}
}
setOutputAtIndex(index, dotProd);
}
}
`}},Px=class{constructor(e){this.variableNames=["x","dy"],this.uniforms=`pads : vec3<i32>, strides : vec3<i32>, batchSize : i32, outDepth : i32,
outHeight : i32, outWidth : i32, inDepth : i32, inHeight : i32, inWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3DDerFilter"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let wF = coords.x;
let wR = coords.y;
let wC = coords.z;
let d1 = coords.w;
let d2 = coords.u;
var dotProd = 0.0;
for (var b = 0; b < uniforms.batchSize; b++) {
for (var yF = 0; yF < uniforms.outDepth; yF++) {
let xF = wF + yF * uniforms.strides[0] - uniforms.pads[0];
if (xF < 0 || xF >= uniforms.inDepth) {
continue;
}
for (var yR = 0; yR < uniforms.outHeight; yR++) {
let xR = wR + yR * uniforms.strides[1] - uniforms.pads[1];
if (xR < 0 || xR >= uniforms.inHeight) {
continue;
}
for (var yC = 0; yC < uniforms.outWidth; yC++) {
let xC = wC + yC * uniforms.strides[2] - uniforms.pads[2];
if (xC < 0 || xC >= uniforms.inWidth) {
continue;
}
let dyValue = getDy(b, yF, yR, yC, d2);
let xValue = getX(b, xF, xR, xC, d1);
dotProd += xValue * dyValue;
}
}
}
}
setOutputAtIndex(index, dotProd);
}
}
`}},Ox=class{constructor(e){this.variableNames=["dy","W"],this.uniforms=`filterDims : vec3<i32>, pads : vec3<i32>, strides : vec3<i32>,
outDepth : i32, outHeight : i32, outWidth : i32, outChannels : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3DDerInput"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords.x;
let d1 = coords.u;
let dyCorner = vec3<i32>(coords.y, coords.z, coords.w) - uniforms.pads;
let dyFCorner = dyCorner.x;
let dyRCorner = dyCorner.y;
let dyCCorner = dyCorner.z;
var dotProd = 0.0;
for (var wF = 0; wF < uniforms.filterDims[0]; wF++) {
let dyF = f32(dyFCorner + wF) / f32(uniforms.strides[0]);
if (dyF < 0.0 || dyF >= f32(uniforms.outDepth) || fract(dyF) > 0.0) {
continue;
}
let idyF = i32(dyF);
let wFPerm = uniforms.filterDims[0] - 1 - wF;
for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]);
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
continue;
}
let idyR = i32(dyR);
let wRPerm = uniforms.filterDims[1] - 1 - wR;
for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]);
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
continue;
}
let idyC = i32(dyC);
let wCPerm = uniforms.filterDims[2] - 1 - wC;
for (var d2 = 0; d2 < uniforms.outChannels; d2++) {
let xValue = getDy(batch, idyF, idyR, idyC, d2);
let wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutputAtIndex(index, dotProd);
}
}
`}};function ale(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,dataFormat:p,dimRoundingMode:u,filterShape:l}=o,c=C.convertConv2DDataFormat(p),m=C.computeConv2DInfo(n.shape,l,a,1,i,u,!1,c),d=new Fx(m),f=[{type:"int32",data:[m.padInfo.top,m.padInfo.left]},{type:"int32",data:[m.strideHeight,m.strideWidth]},{type:"int32",data:[m.batchSize]},{type:"int32",data:[m.outHeight]},{type:"int32",data:[m.outWidth]},{type:"int32",data:[m.inHeight]},{type:"int32",data:[m.inWidth]}];return t.runWebGPUProgram(d,[n,s],n.dtype,f)}var jW={kernelName:Ui,backendName:"webgpu",kernelFunc:ale};function ile(r=4){let e=s=>{switch(s){case 1:return"return W[getIndexFromCoords4D(coord, uniforms.wShape)];";case 4:return`
2022-11-18 17:13:29 +01:00
let coord1 = vec4<i32>(coordX, coordY, col + 1, rowInner);
let coord2 = vec4<i32>(coordX, coordY, col + 2, rowInner);
let coord3 = vec4<i32>(coordX, coordY, col + 3, rowInner);
let v0 = W[getIndexFromCoords4D(coord, uniforms.wShape)];
let v1 = W[getIndexFromCoords4D(coord1, uniforms.wShape)];
let v2 = W[getIndexFromCoords4D(coord2, uniforms.wShape)];
let v3 = W[getIndexFromCoords4D(coord3, uniforms.wShape)];
return vec4<f32>(v0, v1, v2, v3);
`;default:throw new Error(`innerElementSize ${s} is not supported.`)}},o=`if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
${`
let outRow = row / uniforms.outShape[2];
let outCol = row % uniforms.outShape[2];
let WRow = col / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
let WCol = col / uniforms.outBackprop[3] % uniforms.filterDims[1];
2023-05-08 15:12:41 +02:00
let xR = f32(outRow - uniforms.pads[0] + WRow) / f32(uniforms.strides[0]);
let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.strides[1]);
2022-11-18 17:13:29 +01:00
if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) {
2023-05-08 15:12:41 +02:00
return ${Ae(r)}(0.0);
2022-11-18 17:13:29 +01:00
}
if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) {
2023-05-08 15:12:41 +02:00
return ${Ae(r)}(0.0);
2022-11-18 17:13:29 +01:00
}
let coord = vec4<i32>(
batch,
i32(xR),
i32(xC),
col % uniforms.outBackprop[3]);
return x[getIndexFromCoords4D(coord, uniforms.xShape)/${r}];`}
}
2023-05-08 15:12:41 +02:00
return ${Ae(r)}(0.0);`;return`
2023-08-05 15:03:11 +02:00
fn mm_readA(batch: i32, row : i32, col : i32) -> ${Ae(r)} {
2022-11-18 17:13:29 +01:00
${o}
}
2023-08-05 15:03:11 +02:00
fn mm_readB(batch: i32, row : i32, col : i32) -> ${Ae(r)} {
2022-11-18 17:13:29 +01:00
let coordX = uniforms.filterDims.x - 1 -
row / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
let coordY = uniforms.filterDims.y - 1 -
(row / uniforms.outBackprop[3]) % uniforms.filterDims[1];
if (row < uniforms.dimInner && col < uniforms.dimBOuter &&
coordX >= 0 && coordY >= 0) {
let rowInner = row % uniforms.outBackprop[3];
let coord = vec4<i32>(coordX, coordY, col, rowInner);
${e(r)}
2022-11-18 17:13:29 +01:00
}
2023-05-08 15:12:41 +02:00
return ${Ae(r)}(0.0);
2022-11-18 17:13:29 +01:00
}
2023-08-05 15:03:11 +02:00
fn mm_write(batch: i32, row : i32, col : i32, valueInput : ${Ae(r)}) {
if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {
2022-11-18 17:13:29 +01:00
var value = valueInput;
let outCoord = vec4<i32>(
batch,
row / uniforms.outShape[2],
row % uniforms.outShape[2],
col);
result[getIndexFromCoords4D(outCoord, uniforms.outShape)/${r}] = value;
}
}`}var Mx=class{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>, pads : vec2<i32>, strides : vec2<i32>, outBackprop : vec4<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.inShape,y.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.isVec4=e.inChannels%4===0&&e.outChannels%4===0,this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workgroupSize=ym(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=bm(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4&&(this.outputComponent=4,this.variableComponents=[4,1]),this.shaderKey=`conv2DDerInputMM_${this.isVec4}_${this.elementsPerThread}`}getUserCode(){let e=this.isVec4?Fp(this.elementsPerThread,this.workgroupSize):Pp(this.elementsPerThread,this.workgroupSize);return`
${ile(this.isVec4?4:1)}
${e}
`}};function ule(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{inputShape:a,strides:i,pad:p,dataFormat:u,dimRoundingMode:l}=o,c=C.convertConv2DDataFormat(u),m=C.computeConv2DInfo(a,s.shape,i,1,p,l,!1,c),d=[{type:"int32",data:[m.filterHeight,m.filterWidth]},{type:"int32",data:[m.filterHeight-1-m.padInfo.top,m.filterWidth-1-m.padInfo.left]},{type:"int32",data:[m.strideHeight,m.strideWidth]},{type:"int32",data:[m.batchSize,m.outHeight,m.outWidth,m.outChannels]}],f;if(A().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE")||m.dataFormat!=="channelsLast")f=new Ax(m);else{f=new Mx(m);let h=m.inHeight*m.inWidth,g=m.inChannels,x=m.filterHeight*m.filterWidth*m.outChannels;d.push({type:"uint32",data:[h]},{type:"uint32",data:[g]},{type:"uint32",data:[x]})}return t.runWebGPUProgram(f,[n,s],"float32",d)}var XW={kernelName:$n,backendName:"webgpu",kernelFunc:ule};var Lx=class{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims: vec3<i32>, pads: vec3<i32>, strides: vec3<i32>, dilations: vec3<i32>,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3dnaive"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
2023-05-08 15:12:41 +02:00
let coords = getOutputCoords();
let batch = coords.x;
let d2 = coords.u;
let xFRCCorner = vec3<i32>(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads;
let xFCorner = xFRCCorner.x;
let xRCorner = xFRCCorner.y;
let xCCorner = xFRCCorner.z;
let inputDepthNearestVec4 = (uniforms.xShape.u / 4) * 4;
let inputDepthVec4Remainder = uniforms.xShape.u % 4;
var dotProd = 0.0;
for (var wF = 0; wF < uniforms.filterDims[0]; wF++) {
let xF = xFCorner + wF * uniforms.dilations[0];
if (xF < 0 || xF >= uniforms.xShape.y) {
continue;
}
for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
let xR = xRCorner + wR * uniforms.dilations[1];
if (xR < 0 || xR >= uniforms.xShape.z) {
continue;
}
for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
let xC = xCCorner + wC * uniforms.dilations[2];
if (xC < 0 || xC >= uniforms.xShape.w) {
continue;
}
for (var d1 = 0; d1 < inputDepthNearestVec4; d1 += 4) {
let xValues = vec4<f32>(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
let wValues = vec4<f32>(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (inputDepthVec4Remainder == 1) {
dotProd += getX(batch, xF, xR, xC, inputDepthNearestVec4) *
getW(wF, wR, wC, inputDepthNearestVec4, d2);
} else if (inputDepthVec4Remainder == 2) {
let xValues = vec2<f32>(
getX(batch, xF, xR, xC, inputDepthNearestVec4),
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)
);
let wValues = vec2<f32>(
getW(wF, wR, wC, inputDepthNearestVec4, d2),
getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (inputDepthVec4Remainder == 3) {
let xValues = vec3<f32>(
getX(batch, xF, xR, xC, inputDepthNearestVec4),
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)
);
let wValues = vec3<f32>(
getW(wF, wR, wC, inputDepthNearestVec4, d2),
getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2),
getW(wF, wR, wC, inputDepthNearestVec4 + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutputAtIndex(index, dotProd);
}
}`}};function ple(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:p}=o,u=C.computeConv3DInfo(n.shape,s.shape,a,p,i),l=[u.padInfo.front,u.padInfo.top,u.padInfo.left],c=[{type:"int32",data:[u.filterDepth,u.filterHeight,u.filterWidth]},{type:"int32",data:[...l]},{type:"int32",data:[u.strideDepth,u.strideHeight,u.strideWidth]},{type:"int32",data:[u.dilationDepth,u.dilationHeight,u.dilationWidth]}],m=new Lx(u),d=pt(n.dtype,s.dtype);return t.runWebGPUProgram(m,[n,s],d,c)}var YW={kernelName:Rn,backendName:"webgpu",kernelFunc:ple};function lle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,filterShape:p}=o,u=C.computeConv3DInfo(n.shape,p,a,1,i),l=new Px(u),c=[{type:"int32",data:[u.padInfo.front,u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.strideDepth,u.strideHeight,u.strideWidth]},{type:"int32",data:[u.batchSize]},{type:"int32",data:[u.outDepth]},{type:"int32",data:[u.outHeight]},{type:"int32",data:[u.outWidth]},{type:"int32",data:[u.inDepth]},{type:"int32",data:[u.inHeight]},{type:"int32",data:[u.inWidth]}];return t.runWebGPUProgram(l,[n,s],s.dtype,c)}var QW={kernelName:ti,backendName:"webgpu",kernelFunc:lle};function cle(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{strides:a,pad:i,inputShape:p}=o,u=C.computeConv3DInfo(p,s.shape,a,1,i),l=new Ox(u),c=[{type:"int32",data:[u.filterDepth,u.filterHeight,u.filterWidth]},{type:"int32",data:[u.filterDepth-1-u.padInfo.front,u.filterHeight-1-u.padInfo.top,u.filterWidth-1-u.padInfo.left]},{type:"int32",data:[u.strideDepth,u.strideHeight,u.strideWidth]},{type:"int32",data:[u.outDepth]},{type:"int32",data:[u.outHeight]},{type:"int32",data:[u.outWidth]},{type:"int32",data:[u.outChannels]}];return t.runWebGPUProgram(l,[n,s],n.dtype,c)}var ZW={kernelName:Dn,backendName:"webgpu",kernelFunc:cle};var mle=ye({opType:Z.COS}),JW={kernelName:An,backendName:"webgpu",kernelFunc:mle};var dle=ye({opType:Z.COSH}),eU={kernelName:Fn,backendName:"webgpu",kernelFunc:dle};var Bx=class{constructor(e,t,o,n){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32,",this.workgroupSize=[64,1,1],this.size=!0;let[s]=t;this.outputShape=[s,o[0],o[1],e],this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.methodId=n==="bilinear"?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){let[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[o,n,s]=this.cropHeightBiggerThan1?[`(${e} / f32(uniforms.outShape[1] - 1))`,"(y2-y1) * height_ratio",`y1*${e} + f32(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${e}`],[a,i,p]=this.cropWidthBiggerThan1?[`(${t} / f32(uniforms.outShape[2] - 1))`,"(x2-x1) * width_ratio",`x1*${t} + f32(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${t}`];return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let height_ratio = f32(${o});
let width_ratio = f32(${a});
let b = coords[0];
let y = coords[1];
let x = coords[2];
let d = coords[3];
// get box vals
let y1 = getBoxes(b, 0);
let x1 = getBoxes(b, 1);
let y2 = getBoxes(b, 2);
let x2 = getBoxes(b, 3);
// get image in batch index
let bInd = i32(round(getBoxInd(b)));
if(bInd < 0 || bInd >= uniforms.outShape[0]) {
return;
}
let height_scale = ${n};
2022-11-18 17:13:29 +01:00
let width_scale = ${i};
let in_y = ${s};
if( in_y < 0.0 || in_y > ${e} ) {
2022-11-18 17:13:29 +01:00
setOutputAtIndex(index, uniforms.extrapolationValue);
return;
}
let in_x = ${p};
if( in_x < 0.0 || in_x > ${t} ) {
2022-11-18 17:13:29 +01:00
setOutputAtIndex(index, uniforms.extrapolationValue);
return;
}
let sourceFracIndexCR = vec2<f32>(in_x,in_y);
if(${this.methodId} == 1) {
// Compute the four integer indices.
let sourceFloorCR = vec2<i32>(sourceFracIndexCR);
let sourceCeilCR = vec2<i32>(ceil(sourceFracIndexCR));
let topLeft = getImage(bInd, sourceFloorCR.y, sourceFloorCR.x, d);
let bottomLeft = getImage(bInd, sourceCeilCR.y, sourceFloorCR.x, d);
let topRight = getImage(bInd, sourceFloorCR.y, sourceCeilCR.x, d);
let bottomRight = getImage(bInd, sourceCeilCR.y, sourceCeilCR.x, d);
let fracCR = sourceFracIndexCR - vec2<f32>(sourceFloorCR);
let top = topLeft + (topRight - topLeft) * fracCR.x;
let bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
let newValue = top + (bottom - top) * fracCR.y;
setOutputAtIndex(index, newValue);
} else {
// Compute the coordinators of nearest neighbor point.
let sourceNearestCR = vec2<i32>(floor(
sourceFracIndexCR + vec2<f32>(0.5,0.5)));
let newValue = getImage(
bInd, sourceNearestCR.y, sourceNearestCR.x, d);
setOutputAtIndex(index, newValue);
}
}
}
`}};var fle=r=>{let{inputs:e,backend:t,attrs:o}=r,{image:n,boxes:s,boxInd:a}=e,{cropSize:i,method:p,extrapolationValue:u}=o,l=new Bx(n.shape[3],s.shape,i,p),c=[{type:"float32",data:[u]}];return t.runWebGPUProgram(l,[n,s,a],"float32",c)},tU={kernelName:Mn,backendName:"webgpu",kernelFunc:fle};var Lp;(function(r){r.Prod="*",r.Sum="+"})(Lp||(Lp={}));var Tm=class{constructor(e,t,o,n){this.variableNames=["x"],this.uniforms="index : f32,",this.size=!0,this.workgroupSize=[128,1,1],this.outputShape=t,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.exclusive=o,this.reverse=n,this.op=e,this.shaderKey=`cum_${this.op}_${this.exclusive}_${this.reverse}`}getUserCode(){let e=this.outputShape.length,t=this.op===Lp.Prod?"1.0":"0.0",o=this.exclusive?t:`getX(${rU(e,"coords",this.op)})`,n=this.outputShape[this.outputShape.length-1],s="",a="";return this.exclusive?(s=this.reverse?`end != ${n-1}`:"end != 0",a=this.reverse?"end + 1":"end - 1"):(s=this.reverse?`end + pow2 < ${n}`:"end >= pow2",a=this.reverse?"end + pow2":"end - pow2"),`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
var coords = getCoordsFromIndex(index);
let end = ${oU(e,"coords",this.op)};
2022-11-18 17:13:29 +01:00
var val = ${o};
let pow2 = i32(pow(2.0, uniforms.index));
if (${s}) {
let idx = ${a};
${oU(e,"coords",this.op)} = idx;
val ${this.op}= getX(${rU(e,"coords",this.op)});
2022-11-18 17:13:29 +01:00
}
setOutputAtIndex(index, val);
}
}
`}};function rU(r,e,t){if(r===1)return`${e}`;if(r===2)return`${e}.x, ${e}.y`;if(r===3)return`${e}.x, ${e}.y, ${e}.z`;if(r===4)return`${e}.x, ${e}.y, ${e}.z, ${e}.w`;throw Error(`Cumulative ${t} for rank ${r} is not yet supported`)}function oU(r,e,t){if(r===1)return`${e}`;if(r===2)return`${e}.y`;if(r===3)return`${e}.z`;if(r===4)return`${e}.w`;throw Error(`Cumulative ${t} for rank ${r} is not yet supported`)}function zx(r,e,t,o,n,s){let a=e.shape.length,i=C.getAxesPermutation([o],a),p=e;i!=null&&(p=Cr({inputs:{x:e},backend:t,attrs:{perm:i}}));let u=C.getInnerMostAxes(1,a)[0];if(u!==a-1)throw new Error(`WebGPU cumprod shader expects an inner-most axis=${e.shape.length-1} but got axis=${o}`);let l=p.shape[u],c=Pt({inputs:{x:p},backend:t});for(let m=0;m<=Math.ceil(Math.log2(l))-1;m++){let d=new Tm(r,p.shape,!1,s),f=c,h=[{type:"float32",data:[m]}];c=t.runWebGPUProgram(d,[c],c.dtype,h),t.disposeData(f.dataId)}if(n){let m=new Tm(r,p.shape,n,s),d=c,f=[{type:"float32",data:[0]}];c=t.runWebGPUProgram(m,[c],c.dtype,f),t.disposeData(d.dataId)}if(i!=null){let m=C.getUndoAxesPermutation(i),d=Cr({inputs:{x:c},backend:t,attrs:{perm:m}});return t.disposeData(c.dataId),t.disposeData(p.dataId),d}return c}function hle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o;return zx(Lp.Prod,n,t,s,a,i)}var nU={kernelName:Pn,backendName:"webgpu",kernelFunc:hle};function gle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o;return zx(Lp.Sum,n,t,s,a,i)}var sU={kernelName:On,backendName:"webgpu",kernelFunc:gle};function xle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a,binaryOutput:i}=o,p=n.shape.length===1,l=y.sizeFromShape(s.shape)>0,c=s.dtype,m=p?[n.shape[0]]:[n.shape[0],n.shape[1]],d=p?[a]:[n.shape[0],a],f=Nt({backend:t,attrs:{shape:d,value:0,dtype:c}}),h=new nc(m,l,i),g=[{type:"int32",data:[a]}],x=l?[n,s]:[n];return t.runWebGPUProgram(h,x,c,g,f)}var aU={kernelName:la,backendName:"webgpu",kernelFunc:xle};var Vx=class{constructor(e,t){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let b = coords[0];
let h = ${this.getHeightCoordString()};
let w = ${this.getWidthCoordString()};
let d = ${this.getDepthCoordString()};
let in_h = h / uniforms.blockSize;
let offset_h = h % uniforms.blockSize;
let in_w = w / uniforms.blockSize;
let offset_w = w % uniforms.blockSize;
let offset_d = (offset_h * uniforms.blockSize + offset_w) *
${this.getOutputDepthSize()};
let in_d = d + offset_d;
let rlt = ${this.getInputSamplingString()};
setOutputAtIndex(index, rlt);
}
}`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?"uniforms.outShape[3]":"uniforms.outShape[1]"}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function yle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockSize:s,dataFormat:a}=o,i=n.shape[0],p=a==="NHWC"?n.shape[1]:n.shape[2],u=a==="NHWC"?n.shape[2]:n.shape[3],l=a==="NHWC"?n.shape[3]:n.shape[1],c=p*s,m=u*s,d=l/(s*s),f=a==="NHWC"?[i,c,m,d]:[i,d,c,m],h=[{type:"int32",data:[s]}],g=new Vx(f,a);return t.runWebGPUProgram(g,[n],n.dtype,h)}var iU={kernelName:Ln,backendName:"webgpu",kernelFunc:yle};var Wx=class{constructor(e,t,o,n=!1,s=null,a=!1){this.variableNames=["x","W"],this.uniforms="pads : vec2<i32>, inDims : vec2<i32>,",this.workgroupSize=[16,16,1],this.outputShape=e,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),n&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.addBias=n,this.activation=s,this.hasPreluActivation=a,this.filterHeight=t,this.filterWidth=o,this.shaderKey=`depthwiseNCHW_${this.activation}_${this.filterHeight}_${this.filterWidth}`}getUserCode(){let e=this.filterWidth*this.filterHeight,t=this.workgroupSize[0]*this.workgroupSize[1]*this.workgroupSize[2],o=this.workgroupSize[1]+this.filterHeight-1,n=this.workgroupSize[0]+this.filterWidth-1;return`
${gr(this.activation,this.hasPreluActivation,!1,4)}
2022-11-18 17:13:29 +01:00
var<workgroup> mm_Asub : array<array<f32, ${n}>, ${o}>;
var<workgroup> mm_Bsub : array<array<f32, ${this.filterWidth}>, ${this.filterHeight}>;
fn readX(batch : i32, channel : i32, row : i32, col : i32) -> f32 {
var value = 0.0;
if (row >=0 && row < uniforms.inDims[0] && col >=0 && col < uniforms.inDims[1])
{
value = getX(batch, channel, row, col);
}
return value;
}
2023-08-05 15:03:11 +02:00
${G()} {
2022-11-18 17:13:29 +01:00
let coords = getOutputCoords();
let batch = coords[0];
2023-05-08 15:12:41 +02:00
let xRCCorner = vec2<i32>(coords.zw) - uniforms.pads;
2022-11-18 17:13:29 +01:00
let channelMul = uniforms.wShape[3];
let d1 = coords[1] / channelMul;
let q = coords[1] % channelMul;
let inputRowStart = xRCCorner.x;
let inputColStart = xRCCorner.y;
let localRow = i32(localId.y);
let localCol = i32(localId.x);
// Load one tile of X into local memory.
2022-11-20 22:20:02 +01:00
for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${this.workgroupSize[1]}) {
for (var inputCol = localCol; inputCol < ${n}; inputCol = inputCol + ${this.workgroupSize[0]}) {
2022-11-18 17:13:29 +01:00
let rowOffset = inputRow - localRow;
let colOffset = inputCol - localCol;
mm_Asub[inputRow][inputCol] = readX(batch, d1, inputRowStart + rowOffset, inputColStart + colOffset);
}
}
// Load one tile of W into local memory.
2022-11-20 22:20:02 +01:00
var wIndex = i32(localIndex);
${e<t?`if (wIndex < ${e})`:`for(; wIndex < ${e}; wIndex = wIndex + ${t})`}
2022-11-18 17:13:29 +01:00
{
let wRow = wIndex / ${this.filterWidth};
let wCol = wIndex % ${this.filterWidth};
mm_Bsub[wRow][wCol] = getW(wRow, wCol, d1, q);
}
workgroupBarrier();
var value = 0.0;
for (var wR = 0; wR < ${this.filterHeight}; wR = wR + 1) {
for (var wC = 0; wC < ${this.filterWidth}; wC = wC + 1) {
let xVal = mm_Asub[localRow + wR][localCol + wC];
let wVal = mm_Bsub[wR][wC];
value = fma(xVal, wVal, value);
}
}
${no(this.addBias,this.activation)}
2022-11-18 17:13:29 +01:00
if (coordsInBounds4D(coords, uniforms.outShape)) {
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}
`}};var ac=class{constructor(e,t=!1,o=null,n=!1){this.variableNames=["x","W"],this.uniforms="pads : vec2<i32>, inDims : vec2<i32>, virtualWidth : i32,",this.workgroupSize=[64,1,1],this.workPerThread=4,this.outputComponent=4,this.outputShape=e.outShape,this.virtualWidth=Math.ceil(this.outputShape[2]/this.workPerThread)*this.workPerThread;let s=[this.outputShape[0],this.outputShape[1],this.virtualWidth,this.outputShape[3]];this.dispatchLayout=X(s),this.dispatch=H(this.dispatchLayout,s,this.workgroupSize,[this.outputComponent*this.workPerThread,1,1]),y.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=o,this.hasPreluActivation=n,this.shaderKey=`depthwiseVec4_${o}_${this.convInfo.filterHeight}_${this.convInfo.filterWidth}_${this.convInfo.strideHeight}_${this.convInfo.strideWidth}_${this.workPerThread}`}getUserCode(){let e=(this.workPerThread-1)*this.convInfo.strideWidth+this.convInfo.filterWidth,t=this.convInfo.strideHeight,o=this.convInfo.strideWidth;return`
${gr(this.activation,this.hasPreluActivation,!0,4)}
2022-11-18 17:13:29 +01:00
fn readX(batch : i32, row : i32, col : i32, channel : i32) -> vec4<f32> {
var value = vec4<f32>(0.0);
if (col >=0 && col < uniforms.inDims[1]) {
value = getX(batch, row, col, channel);
}
return value;
}
2023-08-05 15:03:11 +02:00
${G("index")} {
let width0 = uniforms.outShape[3] / ${this.outputComponent};
let d1 = (index % width0) * ${this.outputComponent};
var index1 = index / width0;
let width1 = uniforms.virtualWidth / ${this.workPerThread};
let c = (index1 % width1) * ${this.workPerThread};
index1 = index1 / width1;
let r = index1 % uniforms.outShape[1];
let batch = index1 / uniforms.outShape[1];
let xRCCorner = vec2<i32>(r, c) * vec2<i32>(${t}, ${o}) - uniforms.pads;
2022-11-18 17:13:29 +01:00
let xRCorner = xRCCorner.x;
let xCCorner = xRCCorner.y;
var xVals : array<vec4<f32>, ${e}>;
2022-11-18 17:13:29 +01:00
var dotProd : array<vec4<f32>, ${this.workPerThread}>;
for (var i = 0; i < ${this.workPerThread}; i++) {
dotProd[i] = vec4<f32>(0.0);
}
// Use constant instead of uniform can give better performance.
for (var wR = 0; wR < ${this.convInfo.filterHeight}; wR = wR + 1) {
let xR = xRCorner + wR;
if (xR >=0 && xR < uniforms.inDims[0]) {
for (var i = 0; i < ${e}; i++) {
2022-11-18 17:13:29 +01:00
xVals[i] = readX(batch, xR, xCCorner + i, d1);
}
for (var wC = 0; wC < ${this.convInfo.filterWidth}; wC = wC + 1) {
let wValue = getW(wR, wC, d1, 0);
for (var i = 0; i < ${this.workPerThread}; i++) {
2023-01-06 19:23:06 +01:00
dotProd[i] = fma(xVals[i * ${o} + wC], wValue, dotProd[i]);
2022-11-18 17:13:29 +01:00
}
}
}
}
for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
let coords = vec4<i32>(batch, r, c + i, d1);
if (coordsInBounds4D(coords, uniforms.outShape)) {
var value = dotProd[i];
${no(this.addBias,this.activation)}
2022-11-18 17:13:29 +01:00
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}
}
`}};var ic=class{constructor(e,t=!1,o=null,n=!1){this.variableNames=["x","W"],this.uniforms=`pads : vec2<i32>, inDims : vec2<i32>, filterHeight : i32,
filterWidth : i32, strides : vec2<i32>, dilations : vec2<i32>,`,this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=o,this.hasPreluActivation=n,this.shaderKey=`depthwise_${this.activation}_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?"getX(batch, xR, xC, d1);":"getX(batch, d1, xR, xC);";return`
${gr(this.activation,this.hasPreluActivation,!1,4)}
2022-11-18 17:13:29 +01:00
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-20 22:20:02 +01:00
if (index < uniforms.size) {
let coords = getOutputCoords();
let batch = coords[0];
2023-05-08 15:12:41 +02:00
let xRCCorner = vec2<i32>(coords.${this.isChannelsLast?"yz":"zw"}) * uniforms.strides - uniforms.pads;
2022-11-20 22:20:02 +01:00
let d2 = coords[${this.isChannelsLast?3:1}];
let channelMul = uniforms.wShape[3];
let d1 = d2 / channelMul;
let q = d2 % channelMul;
let inputRowStart = xRCCorner.x;
let inputColStart = xRCCorner.y;
let inputRowEnd = inputRowStart + uniforms.filterHeight *
2023-05-08 15:12:41 +02:00
uniforms.dilations[0];
2022-11-20 22:20:02 +01:00
let inputColEnd = inputColStart + uniforms.filterWidth *
2023-05-08 15:12:41 +02:00
uniforms.dilations[1];
2022-11-20 22:20:02 +01:00
// Convolve x(?, ?, d1)|x(d1, ?, ?) with w(:, :, d1, q) to get
// y(yR, yC, d2)|y(d2, yR, yC). ? = to be determined. : = across all
// values in that axis. x(?, ?, d1) and y(yR, yC, d2) is for NHWC.
// x(d1, ?, ?) and y(d2, yR, yC) is for NCHW.
var value = 0.0;
// Extract if checking out of for loop for performance.
if (inputRowStart >= 0 && inputColStart >= 0 &&
inputRowEnd < uniforms.inDims[0] &&
inputColEnd < uniforms.inDims[1]) {
for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
2023-05-08 15:12:41 +02:00
let xR = inputRowStart + wR * uniforms.dilations[0];
2022-11-20 22:20:02 +01:00
for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
2023-05-08 15:12:41 +02:00
let xC = inputColStart + wC * uniforms.dilations[1];
2022-11-20 22:20:02 +01:00
let xVal = ${e};
2022-11-20 22:20:02 +01:00
let wVal = getW(wR, wC, d1, q);
value = value + xVal * wVal;
}
}
} else {
for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
2023-05-08 15:12:41 +02:00
let xR = inputRowStart + wR * uniforms.dilations[0];
2022-11-18 17:13:29 +01:00
2022-11-20 22:20:02 +01:00
if (xR < 0 || xR >= uniforms.inDims[0]) {
continue;
}
2022-11-18 17:13:29 +01:00
2022-11-20 22:20:02 +01:00
for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
2023-05-08 15:12:41 +02:00
let xC = inputColStart + wC * uniforms.dilations[1];
2022-11-18 17:13:29 +01:00
2022-11-20 22:20:02 +01:00
if (xC < 0 || xC >= uniforms.inDims[1]) {
continue;
}
2022-11-18 17:13:29 +01:00
let xVal = ${e};
2022-11-20 22:20:02 +01:00
let wVal = getW(wR, wC, d1, q);
value = value + xVal * wVal;
}
2022-11-18 17:13:29 +01:00
}
}
${no(this.addBias,this.activation)}
2022-11-20 22:20:02 +01:00
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}
`}};function ble(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dataFormat:p,dilations:u,dimRoundingMode:l}=o,c=C.convertConv2DDataFormat(p),m=u;m==null&&(m=[1,1]);let d=C.computeConv2DInfo(n.shape,s.shape,a,m,i,l,!0,c),f=[{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.inHeight,d.inWidth]}],h=d.dataFormat==="channelsLast",g;return!h&&d.inHeight>16&&d.inWidth>16&&d.strideHeight===1&&d.strideWidth===1&&d.dilationWidth===1&&d.dilationHeight===1&&d.inChannels===d.outChannels?g=new Wx(d.outShape,d.filterHeight,d.filterWidth):h&&d.outHeight>4&&d.outWidth>4&&d.strideWidth<=2&&d.inChannels===d.outChannels&&d.dilationHeight===1&&d.dilationWidth===1&&d.inChannels%4===0?(g=new ac(d),f.push({type:"int32",data:[g.virtualWidth]})):(g=new ic(d),f.push({type:"int32",data:[d.filterHeight]},{type:"int32",data:[d.filterWidth]},{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]})),t.runWebGPUProgram(g,[n,s],n.dtype,f)}var uU={kernelName:Bn,backendName:"webgpu",kernelFunc:ble};var Ux=class{constructor(e){this.variableNames=["x","dy"],this.uniforms=`strides : vec2<i32>, pads : vec2<i32>, filterDims : vec2<i32>, outHeight : i32,
outWidth : i32, inHeight : i32, inWidth : i32, batchSize : i32, channelMul : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="depthwise_conv2d_backprop_filter"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let wR = coords[0];
let wC = coords[1];
let d1 = coords[2];
let dm = coords[3];
let d2 = d1 * uniforms.channelMul + dm;
var dotProd = 0.0;
for (var b = 0; b < uniforms.batchSize; b++) {
for (var yR = 0; yR < uniforms.outHeight; yR++) {
let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0];
if (xR < 0 || xR >= uniforms.inHeight) {
continue;
}
for (var yC = 0; yC < uniforms.outWidth; yC++) {
let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1];
if (xC < 0 || xC >= uniforms.inWidth) {
continue;
}
let dyValue = getDy(b, yR, yC, d2);
let xValue = getX(b, xR, xC, d1);
dotProd += xValue * dyValue;
}
}
}
setOutputAtIndex(index, dotProd);
}
}
`}},Gx=class{constructor(e){this.variableNames=["dy","W"],this.uniforms=`strides : vec2<i32>, pads : vec2<i32>, filterDims : vec2<i32>,
outHeight : i32, outWidth : i32, channelMul : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="depthwise_conv2d_backprop_input"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let d1 = coords[3];
let dyCorner = coords.yz - uniforms.pads;
let dyRCorner = dyCorner.x;
let dyCCorner = dyCorner.y;
var dotProd = 0.0;
for (var wR = 0; wR < uniforms.filterDims[0]; wR++) {
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]);
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
continue;
}
let idyR = i32(dyR);
let wRPerm = uniforms.filterDims[0] - 1 - wR;
for (var wC = 0; wC < uniforms.filterDims[1]; wC++) {
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]);
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
continue;
}
let idyC = i32(dyC);
let wCPerm = uniforms.filterDims[1] - 1 - wC;
for (var dm = 0; dm < uniforms.channelMul; dm++) {
let d2 = d1 * uniforms.channelMul + dm;
let xValue = getDy(batch, idyR, idyC, d2);
let wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutputAtIndex(index, dotProd);
}
}
`}};function Cle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,dilations:i,pad:p,dimRoundingMode:u,filterShape:l}=o,c=C.computeConv2DInfo(n.shape,l,a,i,p,u,!0),m=new Ux(c),d=[{type:"int32",data:[c.strideHeight,c.strideWidth]},{type:"int32",data:[c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.filterHeight,c.filterWidth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"int32",data:[c.inHeight]},{type:"int32",data:[c.inWidth]},{type:"int32",data:[c.batchSize]},{type:"int32",data:[c.outChannels/c.inChannels]}];return t.runWebGPUProgram(m,[n,s],"float32",d)}var pU={kernelName:Gi,backendName:"webgpu",kernelFunc:Cle};function wle(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{strides:a,dilations:i,pad:p,dimRoundingMode:u,inputShape:l}=o,c=C.computeConv2DInfo(l,s.shape,a,i,p,u,!0),m=new Gx(c),d=[{type:"int32",data:[c.strideHeight,c.strideWidth]},{type:"int32",data:[c.filterHeight-1-c.padInfo.top,c.filterWidth-1-c.padInfo.left]},{type:"int32",data:[c.filterHeight,c.filterWidth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"int32",data:[c.outChannels/c.inChannels]}];return t.runWebGPUProgram(m,[n,s],n.dtype,d)}var lU={kernelName:Hi,backendName:"webgpu",kernelFunc:wle};var Hx=class{constructor(e){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,e],this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="diag"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-01-06 19:23:06 +01:00
if (index < uniforms.size) {
let coords = getOutputCoords();
let value = select(0.0, getX(coords[0]), coords[0] == coords[1]);
setOutputAtIndex(index, value);
}
}
`}};function Sle(r){let{inputs:e,backend:t}=r,{x:o}=e,n=[...o.shape,...o.shape],s=y.sizeFromShape(o.shape),a=le({inputs:{x:o},backend:t,attrs:{shape:[s]}}),i=new Hx(s),p=t.runWebGPUProgram(i,[a],a.dtype),u=le({inputs:{x:p},backend:t,attrs:{shape:n}});return t.disposeData(a.dataId),t.disposeData(p.dataId),u}var cU={kernelName:ca,backendName:"webgpu",kernelFunc:Sle};var Kx=class{constructor(e){this.variableNames=["x","w"],this.uniforms="filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="dilation2d"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-01-06 19:23:06 +01:00
if (index < uniforms.size) {
let neg_infinity = -3.4e38;
let coords = getOutputCoords();
let batch = coords.x;
let d1 = coords.w;
2023-05-08 15:12:41 +02:00
let outTopLeftCorner = coords.yz * uniforms.strides - uniforms.pads;
2023-01-06 19:23:06 +01:00
let hBeg = outTopLeftCorner.x;
let wBeg = outTopLeftCorner.y;
var curVal = neg_infinity;
for (var h = 0; h < uniforms.filterDims[0]; h = h + 1) {
2023-05-08 15:12:41 +02:00
let hIn = hBeg + h * uniforms.dilations[0];
2023-01-06 19:23:06 +01:00
if (hIn >= 0 && hIn < uniforms.xShape[1]) {
for (var w = 0; w < uniforms.filterDims[1]; w = w + 1) {
2023-05-08 15:12:41 +02:00
let wIn = wBeg + w * uniforms.dilations[1];
2023-01-06 19:23:06 +01:00
if (wIn >= 0 && wIn < uniforms.xShape[2]) {
let val = getX(batch, hIn, wIn, d1) + getW(h, w, d1);
if (val > curVal) {
curVal = val;
}
}
}
}
}
setOutputAtIndex(index, curVal);
}
}
`}};function Ile(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:p}=o,u=C.computeDilation2DInfo(n.shape,s.shape,a,i,"NHWC",p),l=[u.padInfo.top,u.padInfo.left],c=[{type:"int32",data:[u.filterHeight,u.filterWidth]},{type:"int32",data:[...l]},{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]}],m=new Kx(u);return t.runWebGPUProgram(m,[n,s],n.dtype,c)}var mU={kernelName:zn,backendName:"webgpu",kernelFunc:Ile};var qx=class{constructor(e,t){if(this.variableNames=["x","w","dy"],this.uniforms="filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>, dySize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e.inShape,this.dispatchLayout=X(e.outShape),this.dispatch=H(this.dispatchLayout,e.outShape,this.workgroupSize),t!=="float32"&&t!=="int32")throw new Error(`Dilation2DBackpropInput only supports float32 and int32
types, does not support ${t} type.`);this.type=t,this.shaderKey="dilation2DBackpropInput"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.dySize) {
let coords = getDyCoordsFromIndex(index);
let b = coords[0];
let r = coords[1];
let c = coords[2];
let d = coords[3];
let dyCorner = vec2<i32>(r, c) * uniforms.strides - uniforms.pads;
var curVal = -3.4e38; // neg_infinity
var xRMax = 0;
var xCMax = 0;
// In the case of multiple argmax branches, we only back-propagate
// along the last branch, i.e., the one with largest value of
// 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling
// backward routines.
for (var wR = 0; wR < uniforms.filterDims[0]; wR++) {
let xR = dyCorner.x + wR * uniforms.dilations[0];
if (xR >= 0 && xR < uniforms.xShape[1]) {
for (var wC = 0; wC < uniforms.filterDims[1]; wC++) {
let xC = dyCorner.y + wC * uniforms.dilations[1];
if (xC >= 0 && xC < uniforms.xShape[2]) {
let val = getX(b, xR, xC, d) + getW(wR, wC, d);
if (val > curVal) {
curVal = val;
xRMax = xR;
xCMax = xC;
}
}
}
}
}
let flatIndexIn = d + uniforms.xShape[3] *
(xCMax + uniforms.xShape[2] * (xRMax + uniforms.xShape[1] * b));
let value = getDy(b, r, c, d);
${oo("&result[flatIndexIn]","value",this.type)}
2023-05-08 15:12:41 +02:00
}
}
`}},jx=class{constructor(e,t,o){if(this.variableNames=["x","w","dy"],this.uniforms="filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>, dySize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e.filterShape,this.dispatchLayout=X(e.outShape),this.dispatch=H(this.dispatchLayout,e.outShape,this.workgroupSize),o!=="float32"&&o!=="int32")throw new Error(`Dilation2DBackpropFilter only supports float32 and int32
2023-05-08 15:12:41 +02:00
types, does not support ${o} type.`);this.type=o,this.shaderKey="dilation2DBackpropFilter"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.dySize) {
let coords = getDyCoordsFromIndex(index);
let b = coords[0];
let r = coords[1];
let c = coords[2];
let d = coords[3];
let dyCorner = vec2<i32>(r, c) * uniforms.strides - uniforms.pads;
var curVal = -3.4e38; // neg_infinity
var wRMax = 0;
var wCMax = 0;
// In the case of multiple argmax branches, we only back-propagate
// along the last branch, i.e., the one with largest value of
// 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling
// backward routines.
for (var wR = 0; wR < uniforms.filterDims[0]; wR++) {
let xR = dyCorner.x + wR * uniforms.dilations[0];
if (xR >= 0 && xR < uniforms.xShape[1]) {
for (var wC = 0; wC < uniforms.filterDims[1]; wC++) {
let xC = dyCorner.y + wC * uniforms.dilations[1];
if (xC >= 0 && xC < uniforms.xShape[2]) {
let val = getX(b, xR, xC, d) + getW(wR, wC, d);
if (val > curVal) {
curVal = val;
wRMax = wR;
wCMax = wC;
}
}
}
}
}
let flatIndexIn = d + uniforms.wShape[2] * (wCMax + wRMax * uniforms.wShape[1]);
let value = getDy(b, r, c, d);
${oo("&result[flatIndexIn]","value",this.type)}
2023-08-05 15:03:11 +02:00
}
}
`}};function vle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,dy:a}=e,{strides:i,pad:p,dilations:u}=o,l=C.computeDilation2DInfo(n.shape,s.shape,i,p,"NHWC",u),c=s.dtype,m=new jx(l,s.shape,c),d=[{type:"int32",data:[l.filterHeight,l.filterWidth]},{type:"int32",data:[l.padInfo.top,l.padInfo.left]},{type:"int32",data:[l.strideHeight,l.strideWidth]},{type:"int32",data:[l.dilationHeight,l.dilationWidth]},{type:"int32",data:[y.sizeFromShape(l.outShape)]}],f=Nt({backend:t,attrs:{shape:s.shape,value:0,dtype:c}});return t.runWebGPUProgram(m,[n,s,a],c,d,f)}var dU={kernelName:qi,backendName:"webgpu",kernelFunc:vle};function kle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,dy:a}=e,{strides:i,pad:p,dilations:u}=o,l=C.computeDilation2DInfo(n.shape,s.shape,i,p,"NHWC",u),c=n.dtype,m=new qx(l,c),d=[{type:"int32",data:[l.filterHeight,l.filterWidth]},{type:"int32",data:[l.padInfo.top,l.padInfo.left]},{type:"int32",data:[l.strideHeight,l.strideWidth]},{type:"int32",data:[l.dilationHeight,l.dilationWidth]},{type:"int32",data:[y.sizeFromShape(l.outShape)]}],f=Nt({backend:t,attrs:{shape:l.inShape,value:0,dtype:c}});return t.runWebGPUProgram(m,[n,s,a],c,d,f)}var fU={kernelName:Ki,backendName:"webgpu",kernelFunc:kle};var Xx=class{constructor(e,t,o){this.variableNames=["Image"],this.uniforms="alpha: f32,",this.workgroupSize=[64,1,1],this.pixelsOpType=$i.DRAW,this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.type=t,this.textureFormat=o,this.shaderKey=`draw_${t}_${o}`}getUserCode(){let e,t=this.type==="float32"?"value":"value / 255.0";return e=`
2023-08-05 15:03:11 +02:00
if (uniforms.numChannels == 1) {
rgba[0] = ${t};
rgba[1] = ${t};
rgba[2] = ${t};
2023-08-05 15:03:11 +02:00
} else {
rgba[d] = ${t};
2023-08-05 15:03:11 +02:00
}`,`
@group(0) @binding(0) var outImage : texture_storage_2d<${this.textureFormat}, write>;
${G("index")} {
if (index < uniforms.size) {
var rgba = vec4<f32>(0.0, 0.0, 0.0, uniforms.alpha);
for (var d = 0; d < uniforms.numChannels; d = d + 1) {
let value = f32(inBuf[index * uniforms.numChannels + d]);
${e}
2023-08-05 15:03:11 +02:00
}
rgba.x = rgba.x * rgba.w;
rgba.y = rgba.y * rgba.w;
rgba.z = rgba.z * rgba.w;
let coords = getCoordsFromIndex(index);
textureStore(outImage, vec2<i32>(coords.yx), rgba);
2023-05-08 15:12:41 +02:00
}
}
`}};function Nle(r){let{inputs:e,backend:t,attrs:o}=r,{image:n}=e,{canvas:s,options:a}=o,[i,p]=n.shape.slice(0,2),{imageOptions:u}=a||{},l=(u==null?void 0:u.alpha)||1,c=t.device.features.has("bgra8unorm-storage")?"bgra8unorm":"rgba8unorm",m=[i,p],d=new Xx(m,n.dtype,c);s.width=p,s.height=i;let f="webgpu",h=s.getContext(f),g;h||(g=new OffscreenCanvas(p,i),h=g.getContext(f));let x=n.shape.length===3?n.shape[2]:1;h.configure({device:t.device,format:c,usage:GPUTextureUsage.STORAGE_BINDING,alphaMode:"premultiplied"});let b="int32",w=t.makeTensorInfo(m,b),S=t.tensorMap.get(w.dataId);S.resource=h.getCurrentTexture(),S.external=!0;let k=[{type:"uint32",data:[x]},{type:"float32",data:[l]}];if(t.runWebGPUProgram(d,[n],b,k,w),g){let T=s.getContext("2d");if(!T)throw new Error("Please make sure this canvas has only been used for 2d or webgpu context!");T.drawImage(g,0,0)}return t.disposeData(w.dataId),n}var hU={kernelName:Mu,backendName:"webgpu",kernelFunc:Nle};var Kv=tt({opType:fe.MUL,cpuKernelImpl:YV,supportsComplex:!0}),gU={kernelName:$o,backendName:"webgpu",kernelFunc:Kv};function qv(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;return ao(n,s,a,"sum",t)}var xU={kernelName:As,backendName:"webgpu",kernelFunc:qv};function Tle(r){let{inputs:e,backend:t,attrs:o}=r,{equation:n}=o,s=e,{allDims:a,summedDims:i,idDims:p}=C.decodeEinsumEquation(n,s.length);C.checkEinsumDimSizes(a.length,p,s);let{path:u,steps:l}=C.getEinsumComputePath(i,p),c=l.length,m=null,d=a.length,f=[];for(let h=0;h<c;++h){for(let g of l[h]){let{permutationIndices:x,expandDims:b}=C.getEinsumPermutation(d,p[g]),w;C.isIdentityPermutation(x)?w=s[g]:(w=Cr({inputs:{x:s[g]},backend:t,attrs:{perm:x}}),f.push(w));let S=w.shape.slice();for(let k=0;k<b.length;++k)S.splice(b[k],0,1);y.arraysEqual(w.shape,S)||(w=le({inputs:{x:w},backend:t,attrs:{shape:S}}),f.push(w)),m===null?m=w:(m=Kv({inputs:{a:w,b:m},backend:t}),f.push(m))}h<c-1&&(u[h]>=0&&(m=qv({inputs:{x:m},backend:t,attrs:{axis:u[h]-(a.length-d),keepDims:!1}}),f.push(m)),d--)}for(let h of f)h!==m&&t.disposeData(h.dataId);return m}var yU={kernelName:ji,backendName:"webgpu",kernelFunc:Tle};var _le=ye({opType:Z.ELU}),bU={kernelName:Wn,backendName:"webgpu",kernelFunc:_le};var Ele=r=>{let{inputs:e,backend:t}=r,{dy:o,y:n}=e,s=new Di(fe.ELU_DER,o.shape,n.shape);return t.runWebGPUProgram(s,[o,n],o.dtype)},CU={kernelName:ri,backendName:"webgpu",kernelFunc:Ele};var $le=tt({opType:fe.EQUAL,dtype:"bool",cpuKernelImpl:PV}),wU={kernelName:xo,backendName:"webgpu",kernelFunc:$le};var Rle=ye({opType:Z.ERF}),SU={kernelName:Un,backendName:"webgpu",kernelFunc:Rle};var Dle=ye({opType:Z.EXP,cpuKernelImpl:OV,dtype:"float32"}),IU={kernelName:yo,backendName:"webgpu",kernelFunc:Dle};function Yx(r){let{inputs:e,attrs:t,backend:o}=r,{dim:n}=t,{input:s}=e,a=s.shape.length,i=s.shape.slice(),p=n;return n<0&&(y.assert(-(a+1)<=n,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),p=a+n+1),i.splice(p,0,1),le({inputs:{x:s},backend:o,attrs:{shape:i}})}var vU={kernelName:ma,backendName:"webgpu",kernelFunc:Yx};var Ale=ye({opType:Z.EXPM1,cpuKernelImpl:MV}),kU={kernelName:bo,backendName:"webgpu",kernelFunc:Ale};var _m=class{constructor(e,t){this.variableNames=["real","imag"],this.outputShape=[],this.uniforms="exponentMultiplier : f32, denominator: f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.component=e,this.shaderKey=`fft_${e}`}getUserCode(){return`
2022-11-20 22:20:02 +01:00
fn unaryOpComplex(real: f32, expR: f32, imag: f32, expI: f32) -> f32 {
${this.component==="real"?"return real * expR - imag * expI;":"return real * expI + imag * expR;"}
}
2022-11-18 17:13:29 +01:00
2022-11-20 22:20:02 +01:00
fn mulMatDFT(batch: i32, index: i32) -> f32 {
let indexRatio = f32(index) / f32(uniforms.realShape[1]);
let exponentMultiplierTimesIndexRatio =
uniforms.exponentMultiplier * indexRatio;
2022-11-18 17:13:29 +01:00
2022-11-20 22:20:02 +01:00
var result = 0.0;
2022-11-18 17:13:29 +01:00
2022-11-20 22:20:02 +01:00
for (var i = 0; i < uniforms.realShape[1]; i = i + 1) {
// x = (-2|2 * PI / N) * index * i;
let x = exponentMultiplierTimesIndexRatio * f32(i);
let expR = cos(x);
let expI = sin(x);
let real = getReal(batch, i);
let imag = getImag(batch, i);
2022-11-18 17:13:29 +01:00
2022-11-20 22:20:02 +01:00
result = result +
unaryOpComplex(real, expR, imag, expI) / uniforms.denominator;
}
return result;
}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-20 22:20:02 +01:00
if (index < uniforms.size) {
let coords = getOutputCoords();
setOutputAtIndex(index, mulMatDFT(coords[0], coords[1]));
2022-11-18 17:13:29 +01:00
}
2022-11-20 22:20:02 +01:00
}
`}};function Qx(r,e,t){let o=t.tensorMap.get(r.dataId),n=y.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],a=n/s,i=[],p=le({inputs:{x:r},backend:t,attrs:{shape:[a,s]}});i.push(p);let u=p.shape,l=new _m("real",u),c=new _m("imag",u),m=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:u},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:u}],d=e?2*Math.PI:-2*Math.PI,f=e?u[1]:1,h=[{type:"float32",data:[d]},{type:"float32",data:[f]}],g=t.runWebGPUProgram(l,m,"float32",h);i.push(g);let x=t.runWebGPUProgram(c,m,"float32",h);i.push(x);let b=Uo({inputs:{real:g,imag:x},backend:t});i.push(b);let w=le({inputs:{x:b},backend:t,attrs:{shape:r.shape}});return i.forEach(S=>t.disposeData(S.dataId)),w}function Fle(r){let{inputs:e,backend:t}=r,{input:o}=e;return Qx(o,!1,t)}var NU={kernelName:Xi,backendName:"webgpu",kernelFunc:Fle};var Zx=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let coordX = uniforms.xShape[2] - coords[2] - 1;
let outputValue = getX(coords[0], coords[1], coordX, coords[3]);
setOutputAtIndex(index, outputValue);
}
}
`}};var TU={kernelName:Gn,backendName:"webgpu",kernelFunc:({inputs:r,backend:e})=>{let{image:t}=r,o=e,n=new Zx(t.shape);return o.runWebGPUProgram(n,[t],t.dtype)}};var Ple=ye({opType:Z.FLOOR,cpuKernelImpl:LV}),_U={kernelName:Co,backendName:"webgpu",kernelFunc:Ple};var Ole=tt({opType:fe.FLOOR_DIV,cpuKernelImpl:BV,dtype:"int32"}),EU={kernelName:wo,backendName:"webgpu",kernelFunc:Ole};var Jx=class{constructor(e,t,o=!1){this.pixelsOpType=$i.FROM_PIXELS,this.outputShape=[0],this.variableNames=[],this.workgroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,[t,1,1]),this.importVideo=o,this.shaderKey=`fromPixels_${this.importVideo}`}getUserCode(){let e=this.importVideo?"textureLoad(src, vec2<i32>(coords.yx));":"textureLoad(src, vec2<i32>(coords.yx), 0)";return`
2022-11-18 17:13:29 +01:00
@binding(1) @group(0) var src: ${this.importVideo?"texture_external":"texture_2d<f32>"};
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
let flatIndex = index * uniforms.numChannels;
if (flatIndex < uniforms.size) {
let coords = getCoordsFromIndex(flatIndex);
let values = ${e};
2022-11-18 17:13:29 +01:00
for (var i = 0; i < uniforms.numChannels; i = i + 1) {
result[flatIndex + i] = i32(floor(255.0 * values[i]));
}
}
}
`}};var $U={kernelName:Lu,backendName:"webgpu",kernelFunc:Mle},uc,jv=A().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function Mle(r){let{inputs:e,backend:t,attrs:o}=r,{pixels:n}=e,{numChannels:s}=o;if(n==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let a=typeof HTMLVideoElement!="undefined"&&n instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement,p=typeof HTMLCanvasElement!="undefined"&&n instanceof HTMLCanvasElement||typeof OffscreenCanvas!="undefined"&&n instanceof OffscreenCanvas,u=typeof ImageBitmap!="undefined"&&n instanceof ImageBitmap,[l,c]=a?[n.videoWidth,n.videoHeight]:[n.width,n.height],m=[c,l,s],d=A().getBool("WEBGPU_IMPORT_EXTERNAL_TEXTURE")&&a,f=a||i;if(u||p||f){let b;if(d)b=t.device.importExternalTexture({source:n});else{if(f){let L=A().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(uc==null||L!==jv)&&(jv=L,uc=document.createElement("canvas").getContext("2d",{willReadFrequently:jv})),uc.canvas.width=l,uc.canvas.height=c,uc.drawImage(n,0,0,l,c),n=uc.canvas}let F=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,M=t.textureManager.acquireTexture(m[1],m[0],"rgba8unorm",F);t.queue.copyExternalImageToTexture({source:n},{texture:M},[m[1],m[0]]),b=M}let w=y.sizeFromShape(m),S=y.computeStrides(m),k=new Jx(m,s,d),T=[{type:"uint32",data:[w]},{type:"uint32",data:[s]},{type:"uint32",data:[...S]}],E=t.makeTensorInfo([c,l],"int32"),R=t.tensorMap.get(E.dataId);R.resource=b;let D=t.runWebGPUProgram(k,[E],"int32",T);return t.disposeData(E.dataId),D}let h=n.data,g=h;if(s!=null&&s!==4){g=new Uint8Array(n.width*n.height*s);let b=h.length,w=0;for(let S=0;S<b;S++)S%4<s&&(g[w++]=h[S])}let x=t.makeTensorInfo(m,"int32",new Int32Array(g));return t.uploadToGPU(x.dataId),x}var ey=class{constructor(e,t,o,n,s){this.uniforms="varianceEpsilon : f32,",this.workgroupSize=[128,1,1],this.size=!0,this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,o),this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),n!=null&&(C.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset")),s!=null&&(C.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale")),this.offsetShape=n,this.scaleShape=s,this.shaderKey="batchNorm"}getUserCode(){let e="0.0";this.offsetShape!=null&&(e="getOffsetByOutputIndex(index)");let t="1.0";return this.scaleShape!=null&&(t="getScaleByOutputIndex(index)"),`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size)
{
let xValue = getXByOutputIndex(index);
let meanValue = getMeanByOutputIndex(index);
let varianValue = getVarianceByOutputIndex(index);
let offsetValue = ${e};
let scaleValue = ${t};
2022-11-18 17:13:29 +01:00
let inv = scaleValue * inverseSqrt(varianValue + f32(uniforms.varianceEpsilon));
setOutputAtIndex(index,dot(vec3<f32>(xValue, -meanValue, offsetValue), vec3<f32>(inv, inv, 1.0)));
}
}
`}};var RU={kernelName:Hn,backendName:"webgpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o,scale:n,offset:s,mean:a,variance:i}=r,{varianceEpsilon:p}=e,u=t,l=[o,a,i],c=null;s!=null&&(c=s.shape,l.push(s));let m=null;n!=null&&(m=n.shape,l.push(n));let d=new ey(o.shape,a.shape,i.shape,c,m),f=[{type:"float32",data:[p]}];return u.runWebGPUProgram(d,l,o.dtype,f)}};function Lle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:p,pad:u,dataFormat:l,dilations:c,dimRoundingMode:m,activation:d,leakyreluAlpha:f}=o,h=C.convertConv2DDataFormat(l),g=C.computeConv2DInfo(n.shape,s.shape,p,c,u,m,!1,h);return Dx({x:n,filter:s,convInfo:g,backend:t,bias:a,preluActivationWeights:i,leakyreluAlpha:f,activation:d})}var DU={kernelName:jo,backendName:"webgpu",kernelFunc:Lle};function Ble(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:p,pad:u,dilations:l,dimRoundingMode:c,activation:m,leakyreluAlpha:d}=o,f=l;f==null&&(f=[1,1]),y.assert(C.eitherStridesOrDilationsAreOne(p,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${p} and dilations '${f}'`);let h=C.computeConv2DInfo(n.shape,s.shape,p,f,u,c,!0),g=[n,s],x=a!=null,b=i!=null;x&&g.push(a),b&&g.push(i);let w=[{type:"int32",data:[h.padInfo.top,h.padInfo.left]},{type:"int32",data:[h.inHeight,h.inWidth]}],S;return h.outHeight>4&&h.outWidth>4&&h.strideWidth<=2&&h.inChannels===h.outChannels&&h.dilationHeight===1&&h.dilationWidth===1&&h.inChannels%4===0?(S=new ac(h,x,m,b),w.push({type:"int32",data:[S.virtualWidth]})):(S=new ic(h,x,m,b),w.push({type:"int32",data:[h.filterHeight]},{type:"int32",data:[h.filterWidth]},{type:"int32",data:[h.strideHeight,h.strideWidth]},{type:"int32",data:[h.dilationHeight,h.dilationWidth]})),m==="leakyrelu"&&(w.push({type:"float32",data:[d]}),S.uniforms+=" alpha : f32,"),t.runWebGPUProgram(S,g,"float32",w)}var AU={kernelName:Xo,backendName:"webgpu",kernelFunc:Ble};var ty=class{constructor(e,t){this.variableNames=["A","indices"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${ft(e)},`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
var flattenIndex = 0;
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
let indexTemp = i32(round(getIndices(coords[0], j)));
let strideNum = ${e};
2022-11-18 17:13:29 +01:00
flattenIndex = flattenIndex + indexTemp * strideNum;
}
setOutputAtIndex(index, getA(flattenIndex, coords[1]));
}
}
`}};function zle(r){let{inputs:e,backend:t}=r,{params:o,indices:n}=e,s=n.shape,a=s[s.length-1],i=y.sizeFromShape(o.shape),[p,u,l,c]=C.prepareAndValidate(o,n),m=le({inputs:{x:n},backend:t,attrs:{shape:[u,a]}}),d=le({inputs:{x:o},backend:t,attrs:{shape:[y.sizeFromShape(o.shape)/l,l]}});if(t.shouldExecuteOnCPU([o,n])||o.dtype==="string"){let b=t.readSync(n.dataId),w=t.bufferSync(o),S=zV(b,w,o.dtype,u,a,l,c,o.shape,i);return t.makeTensorInfo(p,o.dtype,S.values)}let f=new ty(a,[u,l]),h=[{type:"int32",data:[a]},{type:"int32",data:c}],g=t.runWebGPUProgram(f,[d,m],d.dtype,h),x=le({inputs:{x:g},backend:t,attrs:{shape:p}});return t.disposeData(m.dataId),t.disposeData(d.dataId),t.disposeData(g.dataId),x}var FU={kernelName:Kn,backendName:"webgpu",kernelFunc:zle};var ry=class{constructor(e,t){this.variableNames=["A","indices"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.slice(),this.aShape=e,this.outputShape=t,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="gather"}getUserCode(){let e=Vle(this.aShape);return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let resRC = getCoordsFromIndex(index);
let indexZ = i32(getIndices(resRC.x, resRC.z));
let inBounds = select(0.0, 1.0, indexZ >= 0 && indexZ < uniforms.aShape[2]);
setOutputAtIndex(index, inBounds * getA(${e}));
2022-11-18 17:13:29 +01:00
}
}
`}};function Vle(r){let e=["resRC.x","resRC.y","resRC.z","resRC.w"],t=[];for(let o=0;o<r.length;o++)o===2?t.push("indexZ"):t.push(`${e[o]}`);return t.join()}function Xv(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,indices:s}=e,{axis:a,batchDims:i}=o,p=y.parseAxisParam(a,n.shape)[0],u=C.segment_util.collectGatherOpShapeInfo(n,s,p,i),l=y.sizeFromShape(s.shape),c=[],m=le({inputs:{x:n},backend:t,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),d=le({inputs:{x:s},backend:t,attrs:{shape:[u.batchSize,l/u.batchSize]}});c.push(m),c.push(d);let f=[u.batchSize,u.outerSize,l/u.batchSize,u.sliceSize];if(t.shouldExecuteOnCPU([n,s])){let w=t.tensorMap.get(d.dataId).values,S=ie(d.shape,d.dtype,w),T=t.tensorMap.get(m.dataId).values,E=ie(m.shape,m.dtype,T),R=VV(E,S,f);return c.forEach(D=>t.disposeData(D.dataId)),t.makeTensorInfo(u.outputShape,R.dtype,R.values)}let h=new ry(m.shape,f),g=t.runWebGPUProgram(h,[m,d],m.dtype);c.push(g);let x=le({inputs:{x:g},backend:t,attrs:{shape:u.outputShape}});return c.forEach(b=>t.disposeData(b.dataId)),x}var PU={kernelName:fa,backendName:"webgpu",kernelFunc:Xv};var Wle=tt({opType:fe.GREATER,cpuKernelImpl:UV,dtype:"bool"}),OU={kernelName:So,backendName:"webgpu",kernelFunc:Wle};var Ule=tt({opType:fe.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:WV}),MU={kernelName:Io,backendName:"webgpu",kernelFunc:Ule};function Gle(r){let{inputs:e,backend:t}=r,{input:o}=e;return Qx(o,!0,t)}var LU={kernelName:Yi,backendName:"webgpu",kernelFunc:Gle};var Hle=ye({opType:Z.IS_FINITE,dtype:"bool"}),BU={kernelName:qn,backendName:"webgpu",kernelFunc:Hle};var Kle=ye({opType:Z.IS_INF,dtype:"bool"}),zU={kernelName:jn,backendName:"webgpu",kernelFunc:Kle};var qle=ye({opType:Z.IS_NAN,dtype:"bool"}),VU={kernelName:Xn,backendName:"webgpu",kernelFunc:qle};function jle(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o,a=[{type:"float32",data:[s]}],i=new so(n.shape,Z.LEAKYRELU,"alpha : f32,");return t.runWebGPUProgram(i,[n],"float32",a)}var WU={kernelName:Yn,backendName:"webgpu",kernelFunc:jle};var Xle=tt({opType:fe.LESS,dtype:"bool",cpuKernelImpl:HV}),UU={kernelName:ko,backendName:"webgpu",kernelFunc:Xle};var Yle=tt({opType:fe.LESS_EQUAL,dtype:"bool",cpuKernelImpl:GV}),GU={kernelName:No,backendName:"webgpu",kernelFunc:Yle};var oy=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="start : f32, step : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e],this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="linSpace"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-01-06 19:23:06 +01:00
if (index < uniforms.size) {
setOutputAtIndex(index, uniforms.start + f32(index) * uniforms.step);
}
}
`}};function Qle(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=(n-o)/(s-1),i=new oy(s),p=[{type:"float32",data:[o]},{type:"float32",data:[a]}];return e.runWebGPUProgram(i,[],"float32",p)}var HU={kernelName:Qn,backendName:"webgpu",kernelFunc:Qle};var Zle=ye({opType:Z.LOG,cpuKernelImpl:KV}),KU={kernelName:To,backendName:"webgpu",kernelFunc:Zle};var Jle=ye({opType:Z.LOG1P}),qU={kernelName:Zn,backendName:"webgpu",kernelFunc:Jle};var ece=tt({opType:fe.LOGICAL_AND,dtype:"bool"}),jU={kernelName:Jn,backendName:"webgpu",kernelFunc:ece};var tce=ye({opType:Z.LOGICAL_NOT}),XU={kernelName:es,backendName:"webgpu",kernelFunc:tce};var rce=tt({opType:fe.LOGICAL_OR}),YU={kernelName:ts,backendName:"webgpu",kernelFunc:rce};var QU=`
2023-01-06 19:23:06 +01:00
var powValue = 0.0;
let basis = uniforms.bias + uniforms.alpha * sum;
if (uniforms.beta == 0.5) {
powValue = inverseSqrt(basis);
} else if (uniforms.beta == 1.0) {
powValue = 1.0 / basis;
} else {
powValue = exp(log(basis) * (-uniforms.beta));
}
`,ny=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.uniforms="radius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="lrn"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-01-06 19:23:06 +01:00
if (index < uniforms.size) {
let coords = getOutputCoords();
let b = coords[0];
let r = coords[1];
let c = coords[2];
let d = coords[3];
let x = getX(b, r, c, d);
var sum = 0.0;
for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) {
let idx = d + i;
if (idx >= 0 && idx < uniforms.xShape[3]) {
let z = getX(b, r, c, idx);
sum = sum + z * z;
}
}
${QU}
2023-01-06 19:23:06 +01:00
setOutputAtIndex(index, x * powValue);
}
}
`}},sy=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.uniforms="radius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[256,1,1],this.maxAllowRadius=16,y.assert(t<=this.maxAllowRadius,()=>`Radius must be less than or equal to ${this.maxAllowRadius}, current radius is ${t}`),this.outputShape=e,this.elementsPerWorkgroup=this.workgroupSize[0]-2*this.maxAllowRadius,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=H(this.dispatchLayout,this.outputShape,[this.elementsPerWorkgroup,this.workgroupSize[1],this.workgroupSize[2]]),this.shaderKey="lrn_shared"}getUserCode(){return`
2023-01-06 19:23:06 +01:00
var <workgroup>lrnSub: array<f32, ${this.workgroupSize[0]}>;
const elementsPerWorkgroup = ${this.elementsPerWorkgroup};
const maxAllowRadius = ${this.maxAllowRadius};
2023-08-05 15:03:11 +02:00
${G()} {
2023-01-06 19:23:06 +01:00
let localDepth = i32(localId.x);
let workgroupDepth = i32(workgroupId.x) * elementsPerWorkgroup;
let xDepth = workgroupDepth + localDepth - maxAllowRadius;
let b = i32(globalId.z) / uniforms.xShape[1];
let r = i32(globalId.z) - b * uniforms.xShape[1];
let c = i32(globalId.y);
let d = workgroupDepth + localDepth;
var x = 0.0;
if (xDepth >= 0 && xDepth < uniforms.xShape[3]) {
x = getX(b, r, c, xDepth);
}
lrnSub[localDepth] = x;
workgroupBarrier();
if (localDepth < elementsPerWorkgroup && d < uniforms.outShape[3]) {
var sum = 0.0;
let index = localDepth + maxAllowRadius;
for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) {
let z = lrnSub[index + i];
sum = sum + z * z;
}
${QU}
2023-01-06 19:23:06 +01:00
setOutputAtCoords(b, r, c, d, lrnSub[index] * powValue);
}
} `}};function oce(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{depthRadius:s,bias:a,alpha:i,beta:p}=o,u;s>16?u=new ny(n.shape):u=new sy(n.shape,s);let l=[{type:"int32",data:[s]},{type:"float32",data:[a]},{type:"float32",data:[i]},{type:"float32",data:[p]}];return t.runWebGPUProgram(u,[n],n.dtype,l)}var ZU={kernelName:rs,backendName:"webgpu",kernelFunc:oce};var ay=class{constructor(e){this.outputShape=[],this.variableNames=["inputImage","outputImage","dy"],this.uniforms="depthRadius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="lrn_grad"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getOutputCoords();
let b = coords[0];
let r = coords[1];
let c = coords[2];
let MIN_DEPTH_BEGIN = 0;
let MAX_DEPTH_END = uniforms.outShape[3];
var result = 0.0;
for (var d = MIN_DEPTH_BEGIN; d < MAX_DEPTH_END; d++) {
let depthBegin = max(MIN_DEPTH_BEGIN, d - uniforms.depthRadius);
let depthEnd = min(MAX_DEPTH_END, d + uniforms.depthRadius + 1);
var norm = 0.0;
for (var k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; k++) {
if (k < depthBegin) {
continue;
} else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
} else {
break;
}
}
norm = uniforms.alpha * norm + uniforms.bias;
for (var k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; k++) {
if (k < depthBegin) {
continue;
} else if (k >= depthBegin && k < depthEnd) {
var dyi = -2.0 * uniforms.alpha * uniforms.beta
* getInputImage(b, r, c, k) * getOutputImage(b, r, c, d) / norm;
if (k == d) {
dyi += pow(norm, -1.0 * uniforms.beta);
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
} else {
break;
}
}
}
setOutputAtIndex(index, result);
}
}
`}};function nce(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,y:s,dy:a}=e,{depthRadius:i,bias:p,alpha:u,beta:l}=o,c=new ay(n.shape),m=[{type:"int32",data:[i]},{type:"float32",data:[p]},{type:"float32",data:[u]},{type:"float32",data:[l]}];return t.runWebGPUProgram(c,[n,s,a],n.dtype,m)}var JU={kernelName:oi,backendName:"webgpu",kernelFunc:nce};var sce=tt({opType:fe.MAX,cpuKernelImpl:jV}),eG={kernelName:_o,backendName:"webgpu",kernelFunc:sce};function ace(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:p}=o,l=C.computePool2DInfo(n.shape,s,a,1,i,p);return bx(n,l,"max",t)}var tG={kernelName:ns,backendName:"webgpu",kernelFunc:ace};function ice(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dataFormat:p,dimRoundingMode:u}=o,l=[1,1,1],c=C.computePool3DInfo(n.shape,s,a,l,i,u,p),m=new $u(c,"max"),d=[{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.padInfo.front,c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.inDepth,c.inHeight,c.inWidth]},{type:"int32",data:[c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth]}];return t.runWebGPUProgram(m,[n],n.dtype,d)}var rG={kernelName:ha,backendName:"webgpu",kernelFunc:ice};var iy=class{constructor(e){this.variableNames=["dy","maxPos"],this.uniforms=`strides : vec2<i32>, pads : vec2<i32>, dilations : vec2<i32>, filterDims : vec2<i32>,
outHeight : i32, outWidth : i32`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="maxPool2DBackprop"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let d = coords[3];
let dyRCCorner = vec2<i32>(coords.yz) - uniforms.pads;
let dyRCorner = dyRCCorner.x;
let dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
var dotProd = 0.0;
let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] - 1;
for (var wR = 0; wR < uniforms.filterDims[0]; wR += uniforms.dilations[0]) {
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]);
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
continue;
}
let idyR = i32(dyR);
for (var wC = 0; wC < uniforms.filterDims[1]; wC += uniforms.dilations[1]) {
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]);
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
continue;
}
let idyC = i32(dyC);
let dyValue = getDy(batch, idyR, idyC, d);
let maxPosValue = lastIndex - i32(getMaxPos(batch, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
let curPosValue = wR * uniforms.filterDims[1] + wC;
let mask = select(0.0, 1.0, maxPosValue == curPosValue);
dotProd += dyValue * mask;
}
}
setOutputAtIndex(index, dotProd);
}
}
`}},uy=class{constructor(e){this.variableNames=["dy","maxPos"],this.uniforms=`strides : vec3<i32>, pads : vec3<i32>, filterDims : vec3<i32>,
outDepth : i32, outHeight : i32, outWidth : i32`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="maxPool3DBackprop"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords.x;
let ch = coords.u;
let dyCorner = vec3<i32>(coords.y, coords.z, coords.w) - uniforms.pads;
let dyDCorner = dyCorner.x;
let dyRCorner = dyCorner.y;
let dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
var dotProd = 0.0;
let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] * uniforms.filterDims[2] - 1;
for (var wD = 0; wD < uniforms.filterDims[0]; wD++) {
let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]);
if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) {
continue;
}
let idyD = i32(dyD);
for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]);
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
continue;
}
let idyR = i32(dyR);
for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]);
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
continue;
}
let idyC = i32(dyC);
let dyValue = getDy(batch, idyD, idyR, idyC, ch);
let maxPosValue = lastIndex - i32(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
let curPosValue = wD * uniforms.filterDims[1] * uniforms.filterDims[2] + wR * uniforms.filterDims[2] + wC;
let mask = select(0.0, 1.0, maxPosValue == curPosValue);
dotProd += dyValue * mask;
}
}
}
setOutputAtIndex(index, dotProd);
}
}
`}};function uce(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:p,pad:u,dimRoundingMode:l}=o,c=[1,1,1],m=C.computePool3DInfo(a.shape,i,p,c,u,l),d=new $u(m,"max",!0),f=[{type:"int32",data:[m.strideDepth,m.strideHeight,m.strideWidth]},{type:"int32",data:[m.padInfo.front,m.padInfo.top,m.padInfo.left]},{type:"int32",data:[m.inDepth,m.inHeight,m.inWidth]},{type:"int32",data:[m.effectiveFilterDepth,m.effectiveFilterHeight,m.effectiveFilterWidth]}],h=t.runWebGPUProgram(d,[a],"int32",f),g=new uy(m);f=[{type:"int32",data:[m.strideDepth,m.strideHeight,m.strideWidth]},{type:"int32",data:[m.effectiveFilterDepth-1-m.padInfo.front,m.effectiveFilterHeight-1-m.padInfo.top,m.effectiveFilterWidth-1-m.padInfo.left]},{type:"int32",data:[m.effectiveFilterDepth,m.effectiveFilterHeight,m.effectiveFilterWidth]},{type:"int32",data:[m.outDepth]},{type:"int32",data:[m.outHeight]},{type:"int32",data:[m.outWidth]}];let x=t.runWebGPUProgram(g,[n,h],a.dtype,f);return t.disposeData(h.dataId),x}var oG={kernelName:Ji,backendName:"webgpu",kernelFunc:uce};function pce(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s,output:a}=e,i=s;wm([s,a],"maxPoolGrad");let{filterSize:p,strides:u,pad:l,dimRoundingMode:c}=o,m=C.computePool2DInfo(i.shape,p,u,1,l,c),d=new Ka(m,"max",!0),f=[{type:"int32",data:[m.strideHeight,m.strideWidth]},{type:"int32",data:[m.padInfo.top,m.padInfo.left]},{type:"int32",data:[m.dilationHeight,m.dilationWidth]},{type:"int32",data:[m.inHeight,m.inWidth]},{type:"int32",data:[m.effectiveFilterHeight,m.effectiveFilterWidth]}],h=t.runWebGPUProgram(d,[i],"int32",f),g=new iy(m);f=[{type:"int32",data:[m.strideHeight,m.strideWidth]},{type:"int32",data:[m.effectiveFilterHeight-1-m.padInfo.top,m.effectiveFilterWidth-1-m.padInfo.left]},{type:"int32",data:[m.dilationHeight,m.dilationWidth]},{type:"int32",data:[m.effectiveFilterHeight,m.effectiveFilterWidth]},{type:"int32",data:[m.outHeight]},{type:"int32",data:[m.outWidth]}];let x=t.runWebGPUProgram(g,[n,h],i.dtype,f);return t.disposeData(h.dataId),x}var nG={kernelName:Zi,backendName:"webgpu",kernelFunc:pce};function lce(r){let{inputs:e,backend:t,attrs:o}=r,{filterSize:n,strides:s,pad:a,includeBatchInIndex:i}=o,{x:p}=e;y.assert(p.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${p.shape.length}.`);let u=[1,1];y.assert(C.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let l=C.computePool2DInfo(p.shape,n,s,u,a),c=[{type:"int32",data:[l.strideHeight,l.strideWidth]},{type:"int32",data:[l.padInfo.top,l.padInfo.left]},{type:"int32",data:[l.dilationHeight,l.dilationWidth]},{type:"int32",data:[l.inHeight,l.inWidth]},{type:"int32",data:[l.effectiveFilterHeight,l.effectiveFilterWidth]}],m=new Ka(l,"max",!1),d=t.runWebGPUProgram(m,[p],p.dtype,c);m=new Ka(l,"max",!0,!0,i);let f=t.runWebGPUProgram(m,[p],"int32",c);return[d,f]}var sG={kernelName:ga,backendName:"webgpu",kernelFunc:lce};function cce(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;return ao(n,s,a,"min",t)}var aG={kernelName:as,backendName:"webgpu",kernelFunc:cce};var mce=tt({opType:fe.MIN,cpuKernelImpl:XV}),iG={kernelName:Eo,backendName:"webgpu",kernelFunc:mce};var py=class{constructor(e,t,o){this.uniforms="",this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((n,s)=>n[0]+e[s]+n[1]),this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.xShape=e,t.map((n,s)=>{this.uniforms+=` pad${s} : vec2<i32>,`}),this.offset=o==="reflect"?0:1,this.shaderKey=`mirrorPad_${o}`}getUserCode(){let e=this.xShape.length,t=this.xShape.map((u,l)=>`uniforms.pad${l}[0]`).join(","),o=this.xShape.map((u,l)=>`uniforms.pad${l}[0] + uniforms.xShape${e>1?`[${l}]`:""}`).join(","),n=e===1?"start":"start[i]",s=e===1?"end":"end[i]",a=e===1?"outC":"outC[i]",i=ft(e),p=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let start = ${i}(${t});
2022-11-18 17:13:29 +01:00
let end = ${i}(${o});
var outC = getCoordsFromIndex(index);
for (var i = 0; i < ${e}; i = i + 1) {
2022-11-18 17:13:29 +01:00
if (${a} < ${n}) {
${a} = ${n} * 2 - ${a} - ${this.offset};
} else if(${a} >= ${s}) {
${a} = (${s} - 1) * 2 - ${a} + ${this.offset};
}
}
let coords = outC - start;
setOutputAtIndex(index, getX(${p}));
}
}
`}};var uG={kernelName:is,backendName:"webgpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{paddings:n,mode:s}=e,a=t,i=n.map(l=>({type:"int32",data:[l[0],l[1]]})),p=new py(o.shape,n,s);return a.runWebGPUProgram(p,[o],o.dtype,i)}};var dce=tt({opType:fe.MOD}),pG={kernelName:us,backendName:"webgpu",kernelFunc:dce};var ly=class{constructor(e,t){this.variableNames=["probs"],this.outputShape=[],this.uniforms="seed : f32, numOutcomes: i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,t],this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="multinomial"}getUserCode(){return`
2023-05-08 15:12:41 +02:00
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
fn random (seed : f32, resultUV : vec2<f32>) -> f32 {
let HASHSCALE1 = 443.8975;
let p = resultUV * seed;
var p3 = fract(vec3<f32>(p.xyx) * HASHSCALE1);
p3 = p3 + dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getOutputCoords();
let batch = coords[0];
let resUV = vec2<f32>(f32(coords[1]) / f32(uniforms.outShape[1]),
f32(coords[0]) / f32(uniforms.outShape[0]));
let r = random(uniforms.seed, resUV);
var cdf = 0.0;
for (var i = 0; i < uniforms.numOutcomes - 1; i = i + 1) {
cdf = cdf + getProbs(batch, i);
if (r < cdf) {
setOutputAtIndexI32(index, i);
return;
}
}
// If no other event happened, last event happened.
setOutputAtIndexI32(index, uniforms.numOutcomes - 1);
}
}
`}};var cy=class{constructor(e){this.variableNames=["logits"],this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=[this.outputShape[0],1,1],this.outputShape[1]>=4096?this.workgroupSize=[256,1,1]:this.workgroupSize=[64,1,1],this.shaderKey="softmax"}getUserCode(){return`
2023-05-08 15:12:41 +02:00
var<workgroup> buf : array<f32, ${this.workgroupSize[0]}>;
var<workgroup> rowMaxShared : f32;
var<workgroup> rowSumShared : f32;
const blockSize = ${this.workgroupSize[0]};
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
let row = index / blockSize;
let tid = i32(localId.x);
let cols = uniforms.outShape[1];
var threadMax = -3.402823e+38f;
for (var col = tid; col < cols; col += blockSize) {
let value = getLogits(row, col);
threadMax = max(threadMax, value);
}
if (tid < cols) {
buf[tid] = threadMax;
}
workgroupBarrier();
var reduceSize = min(cols, blockSize);
for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {
reduceSize = currSize + (reduceSize & 1);
if (tid < currSize) {
buf[tid] = max(buf[tid], buf[tid + reduceSize]);
}
workgroupBarrier();
}
if (tid == 0) {
rowMaxShared = buf[0];
}
workgroupBarrier();
var threadSum = 0.0;
for (var col = tid; col < cols; col += blockSize) {
let subExp = exp(getLogits(row, col) - rowMaxShared);
threadSum += subExp;
}
buf[tid] = threadSum;
workgroupBarrier();
for (var currSize = blockSize >> 1; currSize > 0; currSize = currSize >> 1) {
if (tid < currSize) {
buf[tid] = buf[tid] + buf[tid + currSize];
}
workgroupBarrier();
}
if (tid == 0) {
rowSumShared = buf[0];
}
workgroupBarrier();
for (var col = tid; col < cols; col += blockSize) {
let value = exp(getLogits(row, col) - rowMaxShared) / rowSumShared;
setOutputAtCoords(row, col, value);
}
}
`}};function Yv(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{dim:s}=o,a=le({inputs:{x:n},backend:t,attrs:{shape:[y.sizeFromShape(n.shape)/n.shape[s],n.shape[s]]}}),i=new cy(a.shape),p=t.runWebGPUProgram(i,[a],n.dtype),u=le({inputs:{x:p},backend:t,attrs:{shape:n.shape}});return t.disposeData(a.dataId),t.disposeData(p.dataId),u}var lG={kernelName:Fs,backendName:"webgpu",kernelFunc:Yv};function fce(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o,p=i?n:Yv({inputs:{logits:n},backend:t,attrs:{dim:n.shape.length-1}}),u=p.shape[0],l=p.shape[1],c=new ly(u,s),m=[{type:"float32",data:[a]},{type:"int32",data:[l]}],d=t.runWebGPUProgram(c,[p],"int32",m);return i||t.disposeData(p.dataId),d}var cG={kernelName:ps,backendName:"webgpu",kernelFunc:fce};function hce(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])){let s=t.tensorMap.get(o.dataId),[a,i]=QV(s.values,o.shape,o.dtype);return t.makeTensorInfo(i,o.dtype,a)}let n=new so(o.shape,Z.NEG);return t.runWebGPUProgram(n,[o],o.dtype)}var mG={kernelName:ls,backendName:"webgpu",kernelFunc:hce};function gce(r){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:p}=o,u=t.readSync(n.dataId),l=t.readSync(s.dataId),{selectedIndices:c}=Ut.nonMaxSuppressionV3Impl(u,l,a,i,p);return t.makeTensorInfo([c.length],"int32",new Int32Array(c))}var dG={kernelName:cs,backendName:"webgpu",kernelFunc:gce};function xce(r){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:p,softNmsSigma:u}=o,l=t.readSync(n.dataId),c=t.readSync(s.dataId),m=a,d=i,f=p,h=u,{selectedIndices:g,selectedScores:x}=Ut.nonMaxSuppressionV5Impl(l,c,m,d,f,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var fG={kernelName:ms,backendName:"webgpu",kernelFunc:xce};var my=class{constructor(e,t){this.variableNames=["x"],this.uniforms="onValue : f32, offValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,t],this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="onehot"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-20 22:20:02 +01:00
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
setOutputAtIndex(index, mix(uniforms.offValue, uniforms.onValue,
f32(i32(round(getX(coords.x))) == coords.y)));
}
}
`}};function yce(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{dtype:s,depth:a,onValue:i,offValue:p}=o,u=y.sizeFromShape(n.shape),l=new my(u,a),c=le({inputs:{x:n},backend:t,attrs:{shape:[u]}}),m=[{type:"float32",data:[i]},{type:"float32",data:[p]}],d=t.runWebGPUProgram(l,[c],s,m);t.disposeData(c.dataId);let f=[...n.shape,a],h=le({inputs:{x:d},backend:t,attrs:{shape:f}});return t.disposeData(d.dataId),h}var hG={kernelName:ds,backendName:"webgpu",kernelFunc:yce};function Em(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="complex64"){let n=Fi({inputs:{input:o},backend:t}),s=Em({inputs:{x:n},backend:t}),a=Mp({inputs:{input:o},backend:t}),i=Em({inputs:{x:a},backend:t}),p=Uo({inputs:{real:s,imag:i},backend:t});return t.disposeData(n.dataId),t.disposeData(s.dataId),t.disposeData(a.dataId),t.disposeData(i.dataId),p}else return Nt({attrs:{shape:o.shape,dtype:o.dtype,value:o.dtype==="string"?"":0},backend:t})}var gG={kernelName:_a,backendName:"webgpu",kernelFunc:Em};function xG(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(o.dtype==="complex64"){let n=Fi({inputs:{input:o},backend:t}),s=xG({inputs:{x:n},backend:t}),a=Mp({inputs:{input:o},backend:t}),i=Em({inputs:{x:a},backend:t}),p=Uo({inputs:{real:s,imag:i},backend:t});return t.disposeData(n.dataId),t.disposeData(s.dataId),t.disposeData(a.dataId),t.disposeData(i.dataId),p}else return Nt({attrs:{shape:o.shape,dtype:o.dtype,value:1},backend:t})}var yG={kernelName:xa,backendName:"webgpu",kernelFunc:xG};function bce(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return Yx({inputs:{input:e[0]},backend:t,attrs:{dim:n}});let s=e[0].shape,a=e[0].dtype;e.forEach(l=>{y.assertShapesMatch(s,l.shape,"All tensors passed to stack must have matching shapes"),y.assert(a===l.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],p=e.map(l=>{let c=Yx({inputs:{input:l},backend:t,attrs:{dim:n}});return i.push(c),c}),u=Hv({inputs:p,backend:t,attrs:{axis:n}});return i.forEach(l=>t.disposeData(l.dataId)),u}var bG={kernelName:ya,backendName:"webgpu",kernelFunc:bce};function Qv(r,e=!1){let t=r.length,o=ft(t),n=r.map((c,m)=>`uniforms.pad${m}[0]`).join(","),s=r.map((c,m)=>`uniforms.pad${m}[0] + uniforms.xShape${t>1?`[${m}]`:""}`).join(","),a=t>1?`${o}(${n})`:`${n}`,i=t>1?`${o}(${s})`:`${s}`,p=t>1?"any(paddedCoords < start)":"paddedCoords < start",u=t>1?"any(paddedCoords >= end)":"paddedCoords >= end",l=t>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,t):"coords";return`
let start = ${a};
let end = ${i};
if (${p} || ${u}) {
setOutputAtIndex(index, ${e?0:"uniforms.constantValue"});
} else {
let coords = paddedCoords - start;
setOutputAtIndex(index, getX(${l}));
}
`}var dy=class{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((o,n)=>o[0]+e[n]+o[1]),this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),t.map((o,n)=>{this.uniforms+=` pad${n} : vec2<i32>,`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let paddedCoords = getCoordsFromIndex(index);
${Qv(this.xShape)}
2022-11-18 17:13:29 +01:00
}
}
`}};var Cce=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,constantValue:a}=o;if(s.every(u=>y.arraysEqual(u,[0,0])))return Pt({inputs:{x:n},backend:t});if(y.sizeFromShape(n.shape)===0){let u=s.map((l,c)=>l[0]+n.shape[c]+l[1]);return Nt({backend:t,attrs:{shape:u,value:a,dtype:n.dtype}})}let i=[{type:"float32",data:[a]}];s.map(u=>i.push({type:"int32",data:[u[0],u[1]]}));let p=new dy(n.shape,s);return t.runWebGPUProgram(p,[n],n.dtype,i)},CG={kernelName:fs,backendName:"webgpu",kernelFunc:Cce};var wce=tt({opType:fe.POW}),wG={kernelName:hs,backendName:"webgpu",kernelFunc:wce};function Sce(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e,s=new Di(fe.PRELU,o.shape,n.shape);return t.runWebGPUProgram(s,[o,n],"float32")}var SG={kernelName:gs,backendName:"webgpu",kernelFunc:Sce};function Ice(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;return ao(n,s,a,"prod",t)}var IG={kernelName:Ho,backendName:"webgpu",kernelFunc:Ice};var vce=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=eW(o,n,s,a);return e.makeTensorInfo([i.length],a,i)},vG={kernelName:ba,backendName:"webgpu",kernelFunc:vce};var kce=tt({opType:fe.DIV}),kG={kernelName:Vn,backendName:"webgpu",kernelFunc:kce};var Nce=ye({opType:Z.RECIPROCAL}),NG={kernelName:xs,backendName:"webgpu",kernelFunc:Nce};var Tce=ye({opType:Z.RELU}),TG={kernelName:ys,backendName:"webgpu",kernelFunc:Tce};var _ce=ye({opType:Z.RELU6}),_G={kernelName:ws,backendName:"webgpu",kernelFunc:_ce};var fy=class{constructor(e,t,o){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>, halfPixelCenters : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,o,e[3]],this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let b = coords[0];
let d = coords[3];
let rc = coords.yz;
let effectiveInSize = vec2<f32>(
f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveOutSize = vec2<f32>(
f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveInputOverOutputRatioRC =
effectiveInSize / effectiveOutSize;
// Fractional source index
let sourceFracIndexRC =
(vec2<f32>(rc) + vec2<f32>(uniforms.halfPixelCenters)) *
effectiveInputOverOutputRatioRC - vec2<f32>(uniforms.halfPixelCenters);
// Compute the four integer indices.
let sourceFloorRC = vec2<i32>(sourceFracIndexRC);
let sourceCeilRC = vec2<i32>(
min(vec2<f32>(uniforms.xShape.yz) - vec2<f32>(1.0), ceil(sourceFracIndexRC)));
let topLeft = getX(b, sourceFloorRC.x, sourceFloorRC.y, d);
let bottomLeft = getX(b, sourceCeilRC.x, sourceFloorRC.y, d);
let topRight = getX(b, sourceFloorRC.x, sourceCeilRC.y, d);
let bottomRight = getX(b, sourceCeilRC.x, sourceCeilRC.y, d);
let fracRC = sourceFracIndexRC - vec2<f32>(sourceFloorRC);
let top = topLeft + (topRight - topLeft) * fracRC.y;
let bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
let newValue = top + (bottom - top) * fracRC.x;
setOutputAtIndex(index, newValue);
}
}
`}};function Ece(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,size:a,halfPixelCenters:i}=o,[p,u]=a,l=s&&p>1?1:0,c=s&&u>1?1:0,d=[{type:"float32",data:[l,c]},{type:"float32",data:[i?.5:0]}],f=new fy(n.shape,p,u);return t.runWebGPUProgram(f,[n],"float32",d)}var EG={kernelName:Cs,backendName:"webgpu",kernelFunc:Ece};var hy=class{constructor(e,t){this.variableNames=["dy"],this.uniforms=`effectiveXSize : vec2<i32>, effectiveYSize : vec2<i32>, heightScale : f32, widthScale : f32,
invHeightScale : f32, invWidthScale : f32, winHeight : i32, winWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.alignCorners=t,this.shaderKey=`resizeBilinearBackprop_${t}`}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getOutputCoords();
let b = coords[0];
let d = coords[3];
let r = coords[1];
let c = coords[2];
var accumulator = 0.0;
// Compute bounds for where in dy we will look
let startRLerp = floor(f32(r) * uniforms.invHeightScale);
let startDyR = i32(startRLerp - f32(uniforms.winHeight / 2));
let startCLerp = floor(f32(c) * uniforms.invWidthScale);
let startDyC = i32(startCLerp - f32(uniforms.winWidth / 2));
// Loop over dy
for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) {
let dyR = startDyR + dyROffset;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= uniforms.dyShape[1]) {
continue;
}
for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) {
let dyC = startDyC + dyCOffset;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= uniforms.dyShape[2]) {
continue;
}
let dxR = f32(dyR) * uniforms.heightScale;
let topDxRIndex = i32(floor(dxR));
let bottomDxRIndex = i32(min(ceil(dxR), f32(uniforms.outShape[1] - 1)));
let dxRLerp = dxR - f32(topDxRIndex);
let inverseDxRLerp = 1.0 - dxRLerp;
let dxC = f32(dyC) * uniforms.widthScale;
let leftDxCIndex = i32(floor(dxC));
let rightDxCIndex = i32(min(ceil(dxC), f32(uniforms.outShape[2] - 1)));
let dxCLerp = dxC - f32(leftDxCIndex);
let inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutputAtIndex(index, accumulator);
}
}
`}};function $ce(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,[,i,p]=n.shape,[,u,l]=s.shape,c=[a&&u>1?i-1:i,a&&l>1?p-1:p],m=[a&&u>1?u-1:u,a&&l>1?l-1:l],d=c[0]/m[0],f=c[1]/m[1],h=1/d,g=1/f,x=Math.ceil(h)*2+2,b=Math.ceil(g)*2+2,w=new hy(n.shape,a),S=[{type:"int32",data:c},{type:"int32",data:m},{type:"float32",data:[d]},{type:"float32",data:[f]},{type:"float32",data:[h]},{type:"float32",data:[g]},{type:"int32",data:[x]},{type:"int32",data:[b]}];return t.runWebGPUProgram(w,[s],s.dtype,S)}var $G={kernelName:ii,backendName:"webgpu",kernelFunc:$ce};var gy=class{constructor(e,t,o,n){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>, roundBase : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,o,e[3]],this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.halfPixelCenters=n,this.shaderKey=`resizeNearest_${n}`}getUserCode(){let e;return this.halfPixelCenters?e="max((vec2<f32>(rc) + vec2<f32>(0.5)) * effectiveInputOverOutputRatioRC, vec2<f32>(0.0))":e="vec2<f32>(rc) * effectiveInputOverOutputRatioRC",`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let b = coords[0];
let d = coords[3];
let rc = coords.yz;
let effectiveInSize = vec2<f32>(
f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveOutSize = vec2<f32>(
f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveInputOverOutputRatioRC =
effectiveInSize / effectiveOutSize;
// Fractional source index
let sourceFracIndexRC = ${e};
2022-11-18 17:13:29 +01:00
// Compute the coordinators of nearest neighbor point.
let inputShapeRC = vec2<f32>(f32(uniforms.xShape.y), f32(uniforms.xShape.z));
let sourceNearestRC = vec2<i32>(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + uniforms.roundBase)));
let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutputAtIndex(index, newValue);
}
}
`}};function Rce(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[p,u]=i,l=s&&p>1?1:0,c=s&&u>1?1:0,d=[{type:"float32",data:[l,c]},{type:"float32",data:[s?.5:0]}],f=new gy(n.shape,p,u,a);return t.runWebGPUProgram(f,[n],n.dtype,d)}var RG={kernelName:bs,backendName:"webgpu",kernelFunc:Rce};var xy=class{constructor(e,t){this.variableNames=["dy"],this.uniforms=`effectiveXSize : vec2<i32>, effectiveYSize : vec2<i32>, invHeightScale : f32, invWidthScale : f32,
winHeight : i32, winWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.alignCorners=t,this.shaderKey=`resizeNearestNeigborBackprop_${t}`}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.size) {
let coords = getOutputCoords();
let b = coords[0];
let d = coords[3];
let r = coords[1];
let c = coords[2];
var accumulator = 0.0;
// Compute bounds for where in dy we will look
let startRLerp = floor(f32(r) * uniforms.invHeightScale);
let startDyR = i32(floor(startRLerp - f32(uniforms.winHeight / 2)));
let startCLerp = floor(f32(c) * uniforms.invWidthScale);
let startDyC = i32(floor(startCLerp - f32(uniforms.winWidth / 2)));
// Loop over dy
for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) {
let dyR = startDyR + dyROffset;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= uniforms.dyShape[1]) {
continue;
}
for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) {
let dyC = startDyC + dyCOffset;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= uniforms.dyShape[2]) {
continue;
}
let sourceFracRow = f32(uniforms.effectiveXSize[0]) *
(f32(dyR) / f32(uniforms.effectiveYSize[0]));
let sourceFracCol = f32(uniforms.effectiveXSize[1]) *
(f32(dyC) / f32(uniforms.effectiveYSize[1]));
let sourceNearestRow =
i32(min(f32(uniforms.outShape[1] - 1),
${this.alignCorners?"floor(sourceFracRow + 0.5)":"floor(sourceFracRow)"}));
let sourceNearestCol =
i32(min(f32(uniforms.outShape[2] - 1),
${this.alignCorners?"floor(sourceFracCol + 0.5)":"floor(sourceFracCol)"}));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutputAtIndex(index, accumulator);
}
}
`}};function Dce(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,[,i,p]=n.shape,[,u,l]=s.shape,c=[a&&u>1?i-1:i,a&&l>1?p-1:p],m=[a&&u>1?u-1:u,a&&l>1?l-1:l],d=c[0]/m[0],f=c[1]/m[1],h=1/d,g=1/f,x=Math.ceil(h)*2+2,b=Math.ceil(g)*2+2,w=new xy(n.shape,a),S=[{type:"int32",data:c},{type:"int32",data:m},{type:"float32",data:[h]},{type:"float32",data:[g]},{type:"int32",data:[x]},{type:"int32",data:[b]}];return t.runWebGPUProgram(w,[s],s.dtype,S)}var DG={kernelName:ai,backendName:"webgpu",kernelFunc:Dce};var yy=class{constructor(e){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=" axis : vec4<i32>,",this.shaderKey="reverse"}getUserCode(){return`
2022-11-20 22:20:02 +01:00
// Using uniform variables as judging conditions, so the function has
// coherent execution within all threads.
fn getReverseCoords(coords : vec4<i32>) -> vec4<i32> {
var reverseCoords = coords;
if (uniforms.axis[0] == 1) {
reverseCoords[0] = uniforms.xShape[0] - coords[0] - 1;
}
if (uniforms.axis[1] == 1) {
reverseCoords[1] = uniforms.xShape[1] - coords[1] - 1;
}
if (uniforms.axis[2] == 1) {
reverseCoords[2] = uniforms.xShape[2] - coords[2] - 1;
}
if (uniforms.axis[3] == 1) {
reverseCoords[3] = uniforms.xShape[3] - coords[3] - 1;
}
return reverseCoords;
}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-20 22:20:02 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let reverseCoords = getReverseCoords(coords);
setOutputAtIndex(index, getX(reverseCoords[0],
reverseCoords[1], reverseCoords[2], reverseCoords[3]));
}
}
`}};function Ace(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o,a=n.shape.length;if(a===0)return Pt({inputs:{x:n},backend:t});let i=n.shape,p=[1,1,1,1];i.forEach((g,x)=>{let b=x+4-a;p[b]=g});let u=y.parseAxisParam(s,n.shape),l=[0,0,0,0];u.forEach(g=>{let x=g+4-a;l[x]=1});let c=[{type:"int32",data:l}],m=le({inputs:{x:n},backend:t,attrs:{shape:p}}),d=new yy(p),f=t.runWebGPUProgram(d,[m],m.dtype,c);t.disposeData(m.dataId);let h=le({inputs:{x:f},backend:t,attrs:{shape:i}});return t.disposeData(f.dataId),h}var AG={kernelName:Ss,backendName:"webgpu",kernelFunc:Ace};var by=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=`centerX : f32, centerY : f32, sinRadians : f32,
cosRadians : f32,`,this.shaderKey="rotate",this.outputShape=e,typeof t=="number"?(this.uniforms+=" fillValue : f32,",this.fillSnippet="var outputValue = uniforms.fillValue;",this.shaderKey+="_float"):(this.uniforms+=" fillValue : vec3<f32>,",this.fillSnippet="var outputValue = uniforms.fillValue[coords[3]];",this.shaderKey+="_vec3")}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let coordXFloat = (f32(coords[2]) - uniforms.centerX) *
uniforms.cosRadians - (f32(coords[1]) - uniforms.centerY) *
uniforms.sinRadians;
let coordYFloat = (f32(coords[2]) - uniforms.centerX) *
uniforms.sinRadians + (f32(coords[1]) - uniforms.centerY) *
uniforms.cosRadians;
let coordX = i32(round(coordXFloat + uniforms.centerX));
let coordY = i32(round(coordYFloat + uniforms.centerY));
${this.fillSnippet}
if(coordX >= 0 && coordX < uniforms.xShape[2] && coordY >= 0 &&
coordY < uniforms.xShape[1]) {
outputValue = getX(coords[0], coordY, coordX, coords[3]);
}
setOutputAtIndex(index, outputValue);
}
}
`}};var FG={kernelName:Vs,backendName:"webgpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:o}=r,{radians:n,fillValue:s,center:a}=e,i=t,p=new by(o.shape,s),[u,l]=C.getImageCenter(a,o.shape[1],o.shape[2]),c=[{type:"float32",data:[u]},{type:"float32",data:[l]},{type:"float32",data:[Math.sin(n)]},{type:"float32",data:[Math.cos(n)]}];return typeof s=="number"?c.push({type:"float32",data:[Number.parseFloat(s.toFixed(2))]}):c.push({type:"float32",data:s}),i.runWebGPUProgram(p,[o],o.dtype,c)}};var Fce=ye({opType:Z.ROUND}),PG={kernelName:Is,backendName:"webgpu",kernelFunc:Fce};var Pce=ye({opType:Z.RSQRT,cpuKernelImpl:tW}),OG={kernelName:Do,backendName:"webgpu",kernelFunc:Pce};var qa=class{constructor(e,t,o,n,s,a,i,p=!0){this.variableNames=["updates","indices"],this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=a,this.type=i,this.sumDupeIndices=p,this.dispatchLayout=X(e),this.dispatch=H(this.dispatchLayout,e,this.workgroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${o}_${n}_${this.sliceDimGreaterThanOne}_${i}_${p}_${s.length}`;let u=ft(s.length);this.uniforms=`sliceDim : i32, strides: ${u}, updatesSize: i32,`,this.updatesRank=n,this.indicesRank=o}getUserCode(){let e="";this.indicesRank===1?e="coords[0]":this.indicesRank===2&&(e="coords[0], j");let t=`getIndices(${e})`,o=this.sliceDimGreaterThanOne?"uniforms.strides[j]":"uniforms.strides",n="",s="";this.dispatchLayout.x.length===1?(n="flattenedIndex",s=`
2022-11-18 17:13:29 +01:00
fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 {
return index;
}
`):this.dispatchLayout.x.length===2&&(n="vec2<i32>(flattenedIndex, coords[1])",s=`
fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2<i32> {
// N.B. |updates| could be a scalar tensor, conceptually representing a
// 2D tensor with all values equal to that. By design, its size must be
// the same as |outShape[1]| in one dimension, and |indicesShape[0]|
// gives the other.
let sliceSize = uniforms.outShape[1];
let d0 = index / sliceSize;
let d1 = index - d0 * sliceSize;
return vec2<i32>(d0, d1);
}
`);let i=`getUpdates(${Array.from({length:this.updatesRank},(u,l)=>`coords[${l}]`).join(", ")})`;return`
2022-11-18 17:13:29 +01:00
${s}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-20 22:20:02 +01:00
if (index < uniforms.updatesSize) {
2022-11-18 17:13:29 +01:00
let coords = getUpdatesCoordsFromFlatIndex(index);
var flattenedIndex = 0;
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
let indexInside = i32(round(${t}));
2022-11-18 17:13:29 +01:00
flattenedIndex = flattenedIndex + indexInside * ${o};
}
let updateValue =
${Eu(this.type)}(${i});
2022-11-18 17:13:29 +01:00
let flatIndex = getOutputIndexFromCoords(${n});
${this.sumDupeIndices?oo("&result[flatIndex]","updateValue",this.type):"atomicStore(&result[flatIndex], bitcast<i32>(updateValue));"}
2022-11-18 17:13:29 +01:00
}
}`}};function Oce(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n,updates:s}=e,{shape:a}=o,{sliceRank:i,numUpdates:p,sliceSize:u,strides:l,outputSize:c}=C.calculateShapes(s,n,a),m=[c/u,u];if(c===0)return t.makeTensorInfo(a,n.dtype);let d=le({inputs:{x:n},backend:t,attrs:{shape:[p,i]}}),f=le({inputs:{x:s},backend:t,attrs:{shape:[p,u]}}),h=f.dtype,g=Nt({backend:t,attrs:{shape:m,value:0,dtype:h}}),x=y.sizeFromShape(f.shape),b=[{type:"int32",data:[i]},{type:"int32",data:l},{type:"int32",data:[x]}],w=new qa(f.shape,i,d.shape.length,f.shape.length,l,m,h),S=t.runWebGPUProgram(w,[f,d],h,b,g),k=le({inputs:{x:S},backend:t,attrs:{shape:a}});return t.disposeData(d.dataId),t.disposeData(f.dataId),t.disposeData(S.dataId),k}var MG={kernelName:vs,backendName:"webgpu",kernelFunc:Oce};var Cy=class{constructor(e,t){this.outputShape=[],this.variableNames=["sortedSequence","values"],this.uniforms="numInputs : i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.side=t,this.shaderKey=`search_sorted_${t}`}getUserCode(){return`
2022-11-20 22:20:02 +01:00
fn findBound(batch: i32, value: f32) -> i32 {
var left = i32(0);
var right = uniforms.numInputs;
while (left < right) {
var mid = (left + right) / 2;
if (getSortedSequence(batch, mid) ${this.side==="left"?"<":"<="} value) {
left = mid + 1;
} else {
right = mid;
}
}
return right;
}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-20 22:20:02 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let value = getValuesByOutputIndex(index);
setOutputAtIndexI32(index, findBound(coords[0], value));
}
}
`}};function Mce(r){let{inputs:e,backend:t,attrs:o}=r,{sortedSequence:n,values:s}=e,{side:a}=o,i=new Cy([s.shape[0],s.shape[1]],a),p=[{type:"int32",data:[n.shape[1]]}];return t.runWebGPUProgram(i,[n,s],"int32",p)}var LG={kernelName:Ns,backendName:"webgpu",kernelFunc:Mce};var wy=class{constructor(e,t,o){this.variableNames=["c","a","b"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.cRank=e,this.rank=o,this.shaderKey="select"}getUserCode(){let e,t;if(this.rank>4)throw Error(`Where for rank ${this.rank} is not yet supported`);if(this.rank===1)t="resRC",e="resRC";else{let n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[],a=[];for(let i=0;i<this.outputShape.length;i++)a.push(`${n[i]}`),i<this.cRank&&s.push(`${n[i]}`);e=s.join(),t=a.join()}return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let resRC = getCoordsFromIndex(index);
let cVal = getC(${e});
2022-11-18 17:13:29 +01:00
if (cVal >= 1.0) {
setOutputAtIndex(index, getA(${t}));
2022-11-18 17:13:29 +01:00
} else {
setOutputAtIndex(index, getB(${t}));
2022-11-18 17:13:29 +01:00
}
}
}
`}};function Lce(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e,a=new wy(o.shape.length,n.shape,n.shape.length);return t.runWebGPUProgram(a,[o,n,s],pt(n.dtype,s.dtype))}var BG={kernelName:wa,backendName:"webgpu",kernelFunc:Lce};var Bce=ye({opType:Z.SELU}),zG={kernelName:Ts,backendName:"webgpu",kernelFunc:Bce};var zce=ye({opType:Z.SIGMOID}),VG={kernelName:Ao,backendName:"webgpu",kernelFunc:zce};var Vce=ye({opType:Z.SIGN}),WG={kernelName:Rs,backendName:"webgpu",kernelFunc:Vce};var Wce=ye({opType:Z.SIN}),UG={kernelName:Es,backendName:"webgpu",kernelFunc:Wce};var Uce=ye({opType:Z.SINH}),GG={kernelName:$s,backendName:"webgpu",kernelFunc:Uce};var Gce=ye({opType:Z.SOFTPLUS}),HG={kernelName:Ds,backendName:"webgpu",kernelFunc:Gce};var Sy=class{constructor(e,t,o,n,s,a){this.variableNames=["x"],this.outputShape=[],this.uniforms="",this.workgroupSize=[64,1,1],this.size=!0;let i=new Array(n.length);for(let p=0;p<i.length;p++)i[p]=n[s[p]];this.outputShape=i,this.newDim=s,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.xShape=e,this.paddedXShape=t,this.uniforms+=`reshapedPaddedXShape : ${ft(n.length)}, paddedXShapeStrides : ${ft(a)}, `,o.map((p,u)=>{this.uniforms+=` pad${u} : vec2<i32>,`}),this.shaderKey=`spaceToBatchND_${s}`}getUserCode(){let e=ft(this.outputShape.length),t=Bv(this.newDim);return`
${xm(this.paddedXShape,"PaddedX")}
2023-08-05 15:03:11 +02:00
${G("index")} {
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let switchedIndex = getIndexFromCoords${this.outputShape.length}D(${e}(${t}), uniforms.reshapedPaddedXShape);
let paddedCoords = getPaddedXCoordsFromIndex(switchedIndex);
${Qv(this.xShape,!0)}
2023-08-05 15:03:11 +02:00
}
}
`}};var Hce=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,paddings:a}=o;y.assert(n.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");let i=s.reduce((b,w)=>b*w),p=[[0,0]];p.push(...a);for(let b=1+s.length;b<n.shape.length;++b)p.push([0,0]);let u=p.map((b,w)=>b[0]+n.shape[w]+b[1]),l=C.getReshaped(u,s,i,!1),c=C.getPermuted(l.length,s.length,!1),m=C.getReshapedPermuted(u,s,i,!1),d=y.computeStrides(u),f=new Sy(n.shape,u,p,l,c,d.length),h=[{type:"int32",data:l},{type:"int32",data:d}];p.map(b=>h.push({type:"int32",data:[b[0],b[1]]}));let g=t.runWebGPUProgram(f,[n],n.dtype,h),x=le({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeData(g.dataId),x},KG={kernelName:Sa,backendName:"webgpu",kernelFunc:Hce};var Iy=class{constructor(e,t,o){this.variableNames=["input","indices","segmentIds"],this.outputShape=[],this.uniforms="segmentSize : i32, sparseSize : i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e,this.type=o,this.dispatchLayout=X([t]),this.dispatch=H(this.dispatchLayout,[t],this.workgroupSize),this.shaderKey="sparseSegmentSum"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
if (index < uniforms.sparseSize) {
let indexInSegmentIds = index / uniforms.segmentSize;
let indexInSegment = index % uniforms.segmentSize;
let indexInInput = indices[indexInSegmentIds];
let segmentId = segmentIds[indexInSegmentIds];
let value = input[indexInInput * uniforms.segmentSize + indexInSegment];
let outIndex = segmentId * uniforms.segmentSize + indexInSegment;
${oo("&result[outIndex]","value",this.type)}
2023-08-05 15:03:11 +02:00
}
}
`}},vy=class{constructor(e,t){this.variableNames=["segmentIds"],this.outputShape=[],this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=[e],this.dispatchLayout=X(t),this.dispatch=H(this.dispatchLayout,t,this.workgroupSize),this.shaderKey="sparseSegmentIdCountProgram"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
if (index < uniforms.segmentIdsShape) {
let segmentId = segmentIds[index];
${oo("&result[segmentId]","1","int32")}
2023-08-05 15:03:11 +02:00
}
}
`}},ky=class{constructor(e,t){this.variableNames=["segmentSum","sameSegmentIdCount"],this.outputShape=[],this.uniforms="segmentSize : i32",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.type=t,this.dispatchLayout=X(e),this.dispatch=H(this.dispatchLayout,e,this.workgroupSize),this.shaderKey="sparseSegmentMean"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
if (index < uniforms.size) {
let segmentId = index / uniforms.segmentSize;
let count = sameSegmentIdCount[segmentId];
if (count != 0) {
${this.type==="float32"?"setOutputAtIndex(index, segmentSum[index] / f32(count));":"setOutputAtIndexI32(index, segmentSum[index] / count);"}
}
}
2023-08-05 15:03:11 +02:00
}
`}};function Ny(r,e,t,o=!1,n){let a=y.sizeFromShape(r.shape)/r.shape[0],i=r.dtype,p=y.sizeFromShape(e.shape),u=n.readSync(t.dataId),c=p>0?u[p-1]+1:0,m,d=r.shape.slice();d[0]=c;let f=p*a,h=Nt({backend:n,attrs:{shape:d,value:0,dtype:i}});m=new Iy(d,f,i);let g=[{type:"int32",data:[a]},{type:"int32",data:[f]}],x=n.runWebGPUProgram(m,[r,e,t],i,g,h);if(o)return x;let b=Nt({backend:n,attrs:{shape:[c],value:0,dtype:"int32"}});m=new vy(c,t.shape);let w=n.runWebGPUProgram(m,[t],"int32",null,b),S=Nt({backend:n,attrs:{shape:d,value:0,dtype:i}});m=new ky(d,i),g=[{type:"int32",data:[a]}];let k=n.runWebGPUProgram(m,[x,w],i,g,S);return n.disposeData(x.dataId),n.disposeData(w.dataId),k}function Kce(r){let{inputs:e,backend:t}=r,{data:o,indices:n,segmentIds:s}=e;return Ny(o,n,s,!1,t)}var qG={kernelName:va,backendName:"webgpu",kernelFunc:Kce};function qce(r){let{inputs:e,backend:t}=r,{data:o,indices:n,segmentIds:s}=e;return Ny(o,n,s,!0,t)}var jG={kernelName:ka,backendName:"webgpu",kernelFunc:qce};var Ty=class{constructor(e,t){this.variableNames=["A"],this.workgroupSize=[64,1,1],this.size=!0;let o=new Array(e.length);for(let n=0;n<o.length;n++)o[n]=e[n]*t[n];this.outputShape=o,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.rank=this.outputShape.length,this.shaderKey="tile"}getUserCode(){let e=jce(this.rank,"uniforms.");return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let resRC = getCoordsFromIndex(index);
setOutputAtIndex(index, getA(${e}));
2022-11-18 17:13:29 +01:00
}
}
`}};function jce(r,e=""){if(r>=5)throw Error(`Tile for rank ${r} is not yet supported`);if(r===1)return`(resRC % ${e}aShape)`;let t=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[];for(let n=0;n<r;n++)o.push(`(${t[n]} % ${e}aShape[${n}])`);return o.join()}function $m(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;if(t.shouldExecuteOnCPU([n])||n.dtype==="string"||n.shape.length>=5){let p=t.readSync(n.dataId),u=n.dtype==="string"?p.map(m=>y.decodeString(m)):p,l=ie(n.shape,n.dtype,u),c=uW(l,s);return t.makeTensorInfo(c.shape,c.dtype,c.values)}let a=new Ty(n.shape,s);return t.runWebGPUProgram(a,[n],n.dtype)}var XG={kernelName:Mo,backendName:"webgpu",kernelFunc:$m};function Xce(r){let{inputs:e,backend:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=e,{outputShape:i}=o,{sliceRank:p,numUpdates:u,sliceSize:l,strides:c,outputSize:m}=C.calculateShapes(s,n,i),d=!1;if(s.dtype==="string"){let R=t.bufferSync(n),D=t.bufferSync(s),F=y.decodeString(t.readSync(a.dataId)[0]),O=rW(R,D,i,m,l,u,p,c,F,d);return t.makeTensorInfo(i,O.dtype,O.values)}let f=[m/l,l],h=le({inputs:{x:n},backend:t,attrs:{shape:[u,p]}}),g=s.shape.length?le({inputs:{x:s},backend:t,attrs:{shape:[u,l]}}):Pt({inputs:{x:s},backend:t}),x=g.dtype,b=t.makeTensorInfo([],x,y.makeZerosTypedArray(1,x)),w=le({inputs:{x:a},backend:t,attrs:{shape:Array(f.length).fill(1)}}),S=$m({inputs:{x:w},backend:t,attrs:{reps:f}}),k=y.sizeFromShape([u,l]),T=[{type:"int32",data:[p]},{type:"int32",data:c},{type:"int32",data:[k]}];switch(u){case 0:break;case 1:{let R=new qa([u,l],p,h.shape.length,g.shape.length,c,f,x,d);t.runWebGPUProgram(R,[g,h],x,T,S)}break;default:{let R=new qa([u,l],p,h.shape.length,b.shape.length,c,f,x,d);t.runWebGPUProgram(R,[b,h],x,T,S)}{let R=new qa([u,l],p,h.shape.length,g.shape.length,c,f,x);t.runWebGPUProgram(R,[g,h],x,T,S)}}let E=le({inputs:{x:S},backend:t,attrs:{shape:i}});return t.disposeData(h.dataId),t.disposeData(g.dataId),t.disposeData(w.dataId),t.disposeData(b.dataId),t.disposeData(S.dataId),E}var YG={kernelName:Ps,backendName:"webgpu",kernelFunc:Xce};function Yce(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=o,i=y.parseAxisParam(a,n.shape)[0],p=C.prepareSplitSize(n,s,i),u=n.shape.length,l=new Array(u).fill(0),c=n.shape.slice();return p.map(m=>{let d=[...c];d[i]=m;let f=ea({inputs:{x:n},backend:t,attrs:{begin:l,size:d}});return l[i]+=m,f})}var QG={kernelName:Ia,backendName:"webgpu",kernelFunc:Yce};var Qce=ye({opType:Z.SQRT}),ZG={kernelName:Fo,backendName:"webgpu",kernelFunc:Qce};var JG={kernelName:tu,backendName:"webgpu",kernelFunc:({inputs:r,backend:e})=>{let{x:t}=r,o=e,n=new so(t.shape,Z.SQUARE);return o.runWebGPUProgram(n,[t],t.dtype)}};var Zce=tt({opType:fe.SQUARED_DIFFERENCE}),e4={kernelName:Po,backendName:"webgpu",kernelFunc:Zce};function Jce({inputs:r,attrs:e,backend:t}){let{x:o}=r,n=new so(o.shape,Z.STEP,"stepAlpha : f32,"),s=[{type:"float32",data:[e.alpha]}];return t.runWebGPUProgram(n,[o],o.dtype,s)}var t4={kernelName:Ko,backendName:"webgpu",kernelFunc:Jce};var _y=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]);let t=ft(this.outputShape.length);this.uniforms=`begin : ${t}, strides : ${t}, `,this.shaderKey="stridedSlice"}getUserCode(){let e=this.outputShape.length,t="";if(e===1)t="coords * uniforms.strides + uniforms.begin";else{let n=0;t=this.outputShape.map((s,a)=>(n++,this.outputShape.length===1?`coords * uniforms.strides[${a}] + uniforms.begin[${a}]`:`coords[${n-1}] * uniforms.strides[${a}] + uniforms.begin[${a}]`)).join(",")}return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
setOutputAtIndex(index, getX(${t}));
2022-11-18 17:13:29 +01:00
}
}
`}};function eme(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,end:a,strides:i,beginMask:p,endMask:u,ellipsisMask:l,newAxisMask:c,shrinkAxisMask:m}=o,{finalShapeSparse:d,finalShape:f,isIdentity:h,sliceDim0:g,isSimpleSlice:x,begin:b,end:w,strides:S}=nt.sliceInfo(n.shape,s,a,i,p,u,l,c,m),k;if(h)k=le({inputs:{x:n},backend:t,attrs:{shape:f}});else if(g||x){y.assert(n.shape.length>=1,()=>`Input must have rank at least 1, got: ${n.shape.length}`);let T=nt.computeOutShape(b,w,S),E=ea({inputs:{x:n},backend:t,attrs:{begin:b,size:T}});k=le({inputs:{x:E},backend:t,attrs:{shape:f}}),t.disposeData(E.dataId)}else if(t.shouldExecuteOnCPU([n])){let E=t.readSync(n.dataId),R=ie(n.shape,n.dtype,E),D=sW(d,R,S,b);k=t.makeTensorInfo(f,n.dtype,D.values)}else{let E=new _y(d),R=[{type:"int32",data:b},{type:"int32",data:S}],D=t.runWebGPUProgram(E,[n],n.dtype,R);k=le({inputs:{x:D},backend:t,attrs:{shape:f}}),t.disposeData(D.dataId)}return k}var r4={kernelName:Os,backendName:"webgpu",kernelFunc:eme};function tme(r){let{inputs:e,backend:t,attrs:o}=r,{separator:n,nGramWidths:s,leftPad:a,rightPad:i,padWidth:p,preserveShortSequences:u}=o,{data:l,dataSplits:c}=e,m=t.readSync(l.dataId),d=t.readSync(c.dataId),[f,h]=aW(m,d,n,s,a,i,p,u);return[t.makeTensorInfo([f.length],"string",f),t.makeTensorInfo(c.shape,"int32",h)]}var o4={kernelName:Na,backendName:"webgpu",kernelFunc:tme};var rme=tt({opType:fe.SUB,cpuKernelImpl:iW,supportsComplex:!0}),n4={kernelName:Oo,backendName:"webgpu",kernelFunc:rme};var ome=ye({opType:Z.TAN}),s4={kernelName:Ms,backendName:"webgpu",kernelFunc:ome};var nme=ye({opType:Z.TANH}),a4={kernelName:Ls,backendName:"webgpu",kernelFunc:nme};function sme(r){let{inputs:e,backend:t,attrs:o}=r,{tensor:n,indices:s,updates:a}=e,{}=o,{sliceRank:i,numUpdates:p,sliceSize:u,strides:l,outputSize:c}=C.calculateShapes(a,s,n.shape),m=[c/u,u];if(c===0)return t.makeTensorInfo(n.shape,s.dtype);let d=[],f=le({inputs:{x:s},backend:t,attrs:{shape:[p,i]}});d.push(f);let h=le({inputs:{x:a},backend:t,attrs:{shape:[p,u]}});d.push(h);let g=le({inputs:{x:n},backend:t,attrs:{shape:m}});d.push(g);let x=$m({inputs:{x:g},backend:t,attrs:{reps:Array(m.length).fill(1)}}),b=new qa([p,u],i,f.shape.length,h.shape.length,l,m,n.dtype,!1),w=y.sizeFromShape([p,u]),S=[{type:"int32",data:[i]},{type:"int32",data:l},{type:"int32",data:[w]}],k=t.runWebGPUProgram(b,[h,f],g.dtype,S,x);d.push(k);let T=le({inputs:{x:k},backend:t,attrs:{shape:n.shape}});return d.forEach(E=>t.disposeData(E.dataId)),T}var i4={kernelName:ks,backendName:"webgpu",kernelFunc:sme};var Ey=class{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=`inputSize : i32, firstPass : i32, negativeInf : f32,
2022-11-18 17:13:29 +01:00
dir : i32, inc : i32,`,this.shaderKey="swap"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let outC = getCoordsFromIndex(index);
let batch = outC[0];
let elemIdx = outC[1];
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced
// above, Figure5(a) shows that element[1] is in the second half of
// the group when group size is 2, but it is in the first half of
// the group when group size is 4.
let isFirstInPair = elemIdx % (2 * uniforms.inc) < uniforms.inc;
var i = 0;
if (isFirstInPair) {
i = elemIdx;
} else {
i = elemIdx - uniforms.inc;
}
var i0 = 0;
if (uniforms.firstPass == 1) {
i0 = i;
} else {
i0 = i32(getIndices(batch, i));
}
var i1 = 0;
if (uniforms.firstPass == 1) {
i1 = i + uniforms.inc;
} else {
i1 = i32(getIndices(batch, i + uniforms.inc));
}
var x0 = f32(0.0);
var x1 = f32(0.0);
if (i0 < uniforms.inputSize) {
x0 = getX(batch, i0);
} else {
x0 = uniforms.negativeInf;
}
if (i1 < uniforms.inputSize) {
x1 = getX(batch, i1);
} else {
x1 = uniforms.negativeInf;
}
let reverse = elemIdx % (2 * uniforms.dir) >= uniforms.dir;
let isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
if (reverse == isGreater) {
// Elements in opposite order of direction
let iTemp = i0;
i0 = i1;
i1 = iTemp;
}
if (isFirstInPair) {
setOutputAtIndex(index, f32(i0));
} else {
setOutputAtIndex(index, f32(i1));
}
}
}
`}},$y=class{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let outC = getCoordsFromIndex(index);
let batch = outC[0];
let elemIdx = outC[1];
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _
// (k=4), we only need to output the indices at positions |, the
// indices at positions _ can be thrown away, see Figure5(b) After
// Phase 2 (Merge phase) in the Bitonic Top K paper referenced
// above.
// For example, the paper shows we only need to output the orange
// bars. The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back to
// the previous sequence to find the corresponding value, we need
// to double the index. When we double the index, we basically
// interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k
// position of each 2k positions by - elemIdx % k. E.g. for output
// at index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
var i = 0;
if (elemIdx < uniforms.k) {
i = elemIdx;
} else {
i = elemIdx * 2 - elemIdx % uniforms.k;
}
var i0 = 0;
if (uniforms.firstPass == 1) {
i0 = i;
} else {
i0 = i32(getIndices(batch, i));
}
var i1 = 0;
if (uniforms.firstPass == 1) {
i1 = i + uniforms.k;
} else {
i1 = i32(getIndices(batch, i + uniforms.k));
}
let x0 = getX(batch, i0);
var x1 = f32(0.0);
if (i1 < uniforms.inputSize) {
x1 = getX(batch, i1);
} else {
x1 = x0;
}
if (x0 >= x1) {
setOutputAtIndex(index, f32(i0));
} else {
setOutputAtIndex(index, f32(i1));
}
}
}
`}};function pc(r,e){e!==null&&r.disposeData(e.dataId)}function u4(r){let e=1;for(;e<r;)e*=2;return e}function ame(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o,i=n.shape,p=i[i.length-1];if(t.shouldExecuteOnCPU([n])){let k=t.readSync(n.dataId),[T,E]=pW(k,i,n.dtype,s,a);return[t.makeTensorInfo(T.shape,T.dtype,T.values),t.makeTensorInfo(E.shape,E.dtype,E.values)]}if(s===0)return i[i.length-1]=0,[t.makeTensorInfo(i,n.dtype,[]),t.makeTensorInfo(i,"int32",[])];if(p===1)return[n,Nt({attrs:{shape:i,dtype:"int32",value:0},backend:t})];let l=y.sizeFromShape(i)/p,c=le({inputs:{x:n},attrs:{shape:[l,p]},backend:t}),m=u4(s),d=u4(p),f=null,h=()=>f===null?[c,c]:[c,f],g=(k,T,E)=>{let R=h(),D=new Ey(E),O=[{type:"int32",data:[p]},{type:"int32",data:[f===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[k]},{type:"int32",data:[T]}],M=f;f=t.runWebGPUProgram(D,R,"int32",O),pc(t,M)};for(let k=1;k<m;k*=2){let T=k*2;for(let E=k;E>=1;E/=2)g(T,E,[l,d])}for(let k=d;k>m;k/=2){let T=h(),E=new $y([l,k/2]),D=[{type:"int32",data:[p]},{type:"int32",data:[f===null?1:0]},{type:"int32",data:[m]}],F=f;f=t.runWebGPUProgram(E,T,"int32",D),pc(t,F);let O=m/2,M=O*2;for(let L=O;L>=1;L/=2)g(M,L,f.shape)}let x=f;f=ea({inputs:{x:f},backend:t,attrs:{begin:0,size:[l,s]}}),pc(t,x);let b=Xv({inputs:{x:c,indices:f},backend:t,attrs:{axis:1,batchDims:1}});pc(t,c);let w=i.slice(0,-1);w.push(s),x=f,f=le({inputs:{x:f},attrs:{shape:w},backend:t}),pc(t,x);let S=b;return b=le({inputs:{x:b},attrs:{shape:w},backend:t}),pc(t,S),[b,f]}var p4={kernelName:Bs,backendName:"webgpu",kernelFunc:ame};var Ry=class{constructor(e){this.variableNames=["Image","Transforms"],this.uniforms="interpolationModeId : i32, fillModeId : i32, fillValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=X(this.outputShape),this.dispatch=H(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="transform"}getUserCode(){return`
2022-11-18 17:13:29 +01:00
fn mapCoord(outCoord : f32, len : f32) -> f32{
var inCoord = outCoord;
if(uniforms.fillModeId == 2) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
let sz2 = 2.0 * len;
if (inCoord < sz2) {
inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) +
inCoord;
}
if (inCoord < -len) {
inCoord = inCoord + sz2;
} else {
inCoord = -inCoord - 1.0;
}
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
let sz2 = 2.0 * len;
inCoord = inCoord - sz2 * f32(i32(f32(inCoord / sz2)));
if (inCoord >= len) {
inCoord = sz2 - inCoord - 1.0;
}
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (uniforms.fillModeId == 3) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
let sz = len - 1.0;
inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0);
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
let sz = len - 1.0;
inCoord = inCoord - len * f32(i32(f32(inCoord / sz)));
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (uniforms.fillModeId == 4) {
return clamp(outCoord, 0.0, len - 1.0);
}
return outCoord;
}
fn readWithFillValue(batch : i32, coordY : i32, coordX : i32,
channel : i32) -> f32 {
var outputValue : f32;
if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) {
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = uniforms.fillValue;
}
return outputValue;
}
2023-08-05 15:03:11 +02:00
${G("index")} {
2022-11-18 17:13:29 +01:00
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
var outputValue : f32;
let batch = coords[0];
let x = coords[2];
let y = coords[1];
let channel = coords[3];
let xf = f32(x);
let yf = f32(y);
let a1 = getTransforms(batch, 0);
let a2 = getTransforms(batch, 1);
let a3 = getTransforms(batch, 2);
let b1 = getTransforms(batch, 3);
let b2 = getTransforms(batch, 4);
let b3 = getTransforms(batch, 5);
let c1 = getTransforms(batch, 6);
let c2 = getTransforms(batch, 7);
let projection = c1 * xf + c2 * yf + 1.0;
if (projection == 0.0) {
outputValue = uniforms.fillValue;
} else {
let inX = (a1 * xf + a2 * yf + a3) / projection;
let inY = (b1 * xf + b2 * yf + b3) / projection;
let mapX = mapCoord(inX, f32(uniforms.imageShape[2]));
let mapY = mapCoord(inY, f32(uniforms.imageShape[1]));
if (uniforms.interpolationModeId == 1) {
let coordY = i32(round(mapY));
let coordX = i32(round(mapX));
outputValue = readWithFillValue(batch, coordY, coordX,
channel);
} else {
let yFloor = floor(mapY);
let xFloor = floor(mapX);
let yCeil = yFloor + 1.0;
let xCeil = xFloor + 1.0;
let valueYFloor = (xCeil - mapX) *
readWithFillValue(batch, i32(yFloor), i32(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, i32(yFloor), i32(xCeil), channel);
let valueYCeil = (xCeil - mapX) *
readWithFillValue(batch, i32(yCeil), i32(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, i32(yCeil), i32(xCeil), channel);
outputValue = (yCeil - mapY) * valueYFloor +
(mapY - yFloor) * valueYCeil;
}
}
setOutputAtIndex(index, outputValue);
}
}
`}};function ime(r){let{inputs:e,backend:t,attrs:o}=r,{image:n,transforms:s}=e,{interpolation:a,fillMode:i,fillValue:p,outputShape:u}=o,[l,c,m,d]=n.shape,[f,h]=u!=null?u:[c,m],g=[l,f,h,d],x=new Ry(g),b=a==="nearest"?1:2,w;switch(i){case"constant":w=1;break;case"reflect":w=2;break;case"wrap":w=3;break;case"nearest":w=4;break;default:w=1;break}let S=[{type:"int32",data:[b]},{type:"int32",data:[w]},{type:"float32",data:[p]}];return t.runWebGPUProgram(x,[n,s],"float32",S)}var l4={kernelName:zs,backendName:"webgpu",kernelFunc:ime};function ume(r){let{inputs:e,backend:t,attrs:o}=r,{value:n}=e,{axis:s}=o;s<0&&(s+=n.shape.length);let a=n,i=a.shape.length,p=n.shape[s],u=new Array(i-1),l=0;for(let h=0;h<i;h++)h!==s&&(u[l++]=a.shape[h]);let c=[],m=new Array(i).fill(0),d=a.shape.slice();d[s]=1;let f=new Array(p);for(let h=0;h<f.length;h++){m[s]=h;let g=ea({inputs:{x:a},backend:t,attrs:{begin:m,size:d}}),x=le({inputs:{x:g},backend:t,attrs:{shape:u}});f[h]=x,c.push(g)}return c.forEach(h=>t.disposeData(h.dataId)),f}var c4={kernelName:Ta,backendName:"webgpu",kernelFunc:ume};var Dy=class{constructor(e,t,o){if(this.outputShape=[],this.variableNames=["x","segmentIds"],this.uniforms="numSegments : i32, xSize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=t,this.dispatchLayout=X(e),this.dispatch=H(this.dispatchLayout,e,this.workgroupSize),o!=="float32"&&o!=="int32")throw new Error(`UnsortedSegmentSum only supports float32 and int32
2023-05-08 15:12:41 +02:00
types, does not support ${o} type.`);this.type=o,this.shaderKey="unsortedSegmentSum"}getUserCode(){return`
2023-08-05 15:03:11 +02:00
${G("index")} {
2023-05-08 15:12:41 +02:00
if (index < uniforms.xSize) {
let coords = getXCoordsFromIndex(index);
let b = coords[0];
let inCol = coords[1];
let segmentId = i32(getSegmentIds(inCol));
if (segmentId >= 0) {
let flatIndex = b * uniforms.numSegments + segmentId % uniforms.numSegments;
let value = getX(b, inCol);
${oo("&result[flatIndex]","value",this.type)}
2023-05-08 15:12:41 +02:00
}
}
}
`}};function pme(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,segmentIds:s}=e,{numSegments:a}=o,i=n.shape.length,p=[],u=0,l=C.getAxesPermutation([u],i),c=n;l!=null&&(c=Cr({inputs:{x:n},backend:t,attrs:{perm:l}}),p.push(c),u=C.getInnerMostAxes(1,i)[0]);let m=C.segment_util.computeOutShape(c.shape,u,a),d=y.sizeFromShape([c.shape[u]]),f=le({inputs:{x:c},backend:t,attrs:{shape:[-1,d]}});p.push(f);let h=n.dtype,g=[f.shape[0],a],x=Nt({backend:t,attrs:{shape:g,value:0,dtype:h}}),b=new Dy(f.shape,g,h),w=[{type:"int32",data:[a]},{type:"int32",data:[y.sizeFromShape(f.shape)]}],S=t.runWebGPUProgram(b,[f,s],h,w,x),k=le({inputs:{x:S},backend:t,attrs:{shape:m}});p.push(S);let T=k;if(l!=null){p.push(k);let E=C.getUndoAxesPermutation(l);T=Cr({inputs:{x:T},backend:t,attrs:{perm:E}})}return p.forEach(E=>t.disposeData(E.dataId)),T}var m4={kernelName:su,backendName:"webgpu",kernelFunc:pme};var lme=[jz,cW,mW,dW,fW,hW,xW,yW,bW,CW,wW,SW,IW,vW,kW,_W,EW,$W,RW,DW,FW,PW,OW,zW,VW,WW,Yz,GW,KW,qW,jW,XW,YW,QW,ZW,JW,eU,tU,nU,sU,aU,iU,pU,lU,uU,cU,mU,dU,fU,hU,yU,bU,CU,wU,SU,IU,vU,kU,NU,Kz,TU,$U,_U,EU,RU,DU,AU,FU,PU,OU,MU,Xz,LU,HW,BU,zU,VU,WU,UU,GU,HU,qU,KU,jU,XU,YU,ZU,JU,NW,eG,tG,nG,rG,oG,sG,TW,aG,iG,uG,pG,cG,gU,mG,dG,fG,MW,hG,yG,bG,CG,wG,SG,IG,vG,LW,kG,NG,TG,_G,qz,EG,$G,RG,DG,AG,FG,PG,OG,MG,LG,BG,zG,VG,WG,UG,GG,AW,t4,r4,o4,lG,HG,KG,qG,jG,YG,QG,ZG,JG,e4,n4,xU,s4,a4,i4,XG,p4,l4,gW,c4,m4,gG];for(let r of lme)li(r);var d4="4.17.0",cme="4.17.0",mme="4.17.0",dme="4.17.0",fme="4.17.0",hme="4.14.0",gme={tfjs:d4,"tfjs-core":d4,"tfjs-converter":cme,"tfjs-backend-cpu":mme,"tfjs-backend-webgl":dme,"tfjs-backend-wasm":fme,"tfjs-backend-webgpu":hme};var qtr=void 0;export{fn as Abs,hn as Acos,gn as Acosh,sp as AdadeltaOptimizer,ap as AdagradOptimizer,ip as AdamOptimizer,up as AdamaxOptimizer,Rr as Add,xn as AddN,yn as All,bn as Any,na as ArgMax,sa as ArgMin,Cn as Asin,wn as Asinh,Sn as Atan,vn as Atan2,In as Atanh,kn as AvgPool,aa as AvgPool3D,Vi as AvgPool3DGrad,zi as AvgPoolGrad,gm as BackendWasm,Nn as BatchMatMul,ia as BatchToSpaceND,Tn as Bincount,_n as BitwiseAnd,ua as BroadcastArgs,Sme as BroadcastTo,ho as Cast,go as Ceil,Go as ClipByValue,ei as Complex,Wi as ComplexAbs,pa as Concat,En as Conv2D,Ui as Conv2DBackpropFilter,$n as Conv2DBackpropInput,Rn as Conv3D,ti as Conv3DBackpropFilterV2,Dn as Conv3DBackpropInputV2,An as Cos,Fn as Cosh,Mn as CropAndResize,Pn as Cumprod,On as Cumsum,mn as DataStorage,la as DenseBincount,Ln as DepthToSpace,Bn as DepthwiseConv2dNative,Gi as DepthwiseConv2dNativeBackpropFilter,Hi as DepthwiseConv2dNativeBackpropInput,ca as Diag,zn as Dilation2D,qi as Dilation2DBackpropFilter,Ki as Dilation2DBackpropInput,Mu as Draw,xw as ENV,ji as Einsum,Wn as Elu,ri as EluGrad,Cc as Environment,xo as Equal,Un as Erf,yo as Exp,ma as ExpandDims,bo as Expm1,Xi as FFT,da as Fill,Gn as FlipLeftRight,Co as Floor,wo as FloorDiv,Lu as FromPixels,Hn as FusedBatchNorm,jo as FusedConv2D,Xo as FusedDepthwiseConv2D,kp as GPGPUContext,Kn as GatherNd,fa as GatherV2,Kc as GraphModel,So as Greater,Io as GreaterEqual,Yi as IFFT,vo as Identity,Qi as Imag,qn as IsFinite,jn as IsInf,Xn as IsNan,mo as KernelBackend,rs as LRN,oi as LRNGrad,Yn as LeakyRelu,ko as Less,No as LessEqual,Qn as LinSpace,To as Log,Zn as Log1p,Ime as LogSoftmax,Jn as LogicalAnd,es as LogicalNot,ts as LogicalOr,gk as LogicalXor,vme as LowerBound,Il as MathBackendCPU,Ul as MathBackendWebGL,kme as MatrixBandPart,os as Max,ns as MaxPool,ha as MaxPool3D,Ji as MaxPool3DGrad,Zi as MaxPoolGrad,ga as MaxPoolWithArgmax,_o as Maximum,ss as Mean,as as Min,Eo as Minimum,is as MirrorPad,us as Mod,pp as MomentumOptimizer,ps as Multinomial,$o as Multiply,ls as Neg,cs as NonMaxSuppressionV3,ni as NonMaxSuppressionV4,ms as NonMaxSuppressionV5,Ro as NotEqual,Bw as OP_SCOPE_SUFFIX,ds as OneHot,xa as OnesLike,_r as Optimizer,Vc as OptimizerConstructors,ya as Pack,fs as PadV2,Nme as Pool,hs as Pow,gs as Prelu,Ho as Prod,lp as RMSPropOptimizer,Qp as RaggedGather,Zp as RaggedRange,Jp as RaggedTensorToTensor,ba as Range,Ew as Rank,si as Real,Vn as RealDiv,xs as Reciprocal,Dt as Reduction,ys as Relu,ws as Relu6,Ca as Res