face-api/dist/tfjs.esm.js

4883 lines
1.1 MiB
JavaScript
Raw Normal View History

2021-09-08 19:51:28 +02:00
/*
Face-API
homepage: <https://github.com/vladmandic/face-api>
author: <https://github.com/vladmandic>'
2021-09-08 19:51:28 +02:00
*/
2022-03-07 19:17:31 +01:00
var tU=Object.create;var Yg=Object.defineProperty;var eU=Object.getOwnPropertyDescriptor;var rU=Object.getOwnPropertyNames;var nU=Object.getPrototypeOf,oU=Object.prototype.hasOwnProperty;var sU=r=>Yg(r,"__esModule",{value:!0});var Fe=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Xt=(r,t)=>{for(var e in t)Yg(r,e,{get:t[e],enumerable:!0})},iU=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rU(t))!oU.call(r,o)&&(e||o!=="default")&&Yg(r,o,{get:()=>t[o],enumerable:!(n=eU(t,o))||n.enumerable});return r},gu=(r,t)=>iU(sU(Yg(r!=null?tU(nU(r)):{},"default",!t&&r&&r.__esModule?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var o1=Fe((gat,n1)=>{n1.exports=Ke;var ao=null;try{ao=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 Ke(r,t,e){this.low=r|0,this.high=t|0,this.unsigned=!!e}Ke.prototype.__isLong__;Object.defineProperty(Ke.prototype,"__isLong__",{value:!0});function Pn(r){return(r&&r.__isLong__)===!0}Ke.isLong=Pn;var jT={},XT={};function Iu(r,t){var e,n,o;return t?(r>>>=0,(o=0<=r&&r<256)&&(n=XT[r],n)?n:(e=je(r,(r|0)<0?-1:0,!0),o&&(XT[r]=e),e)):(r|=0,(o=-128<=r&&r<128)&&(n=jT[r],n)?n:(e=je(r,r<0?-1:0,!1),o&&(jT[r]=e),e))}Ke.fromInt=Iu;function lo(r,t){if(isNaN(r))return t?Cu:uo;if(t){if(r<0)return Cu;if(r>=QT)return r1}else{if(r<=-ZT)return On;if(r+1>=ZT)return e1}return r<0?lo(-r,t).neg():je(r%Bp|0,r/Bp|0,t)}Ke.fromNumber=lo;function je(r,t,e){return new Ke(r,t,e)}Ke.fromBits=je;var ex=Math.pow;function Av(r,t,e){if(r.length===0)throw Error("empty string");if(r==="NaN"||r==="Infinity"||r==="+Infinity"||r==="-Infinity")return uo;if(typeof t=="number"?(e=t,t=!1):t=!!t,e=e||10,e<2||36<e)throw RangeError("radix");var n;if((n=r.indexOf("-"))>0)throw Error("interior hyphen");if(n===0)return Av(r.substring(1),t,e).neg();for(var o=lo(ex(e,8)),s=uo,i=0;i<r.length;i+=8){var a=Math.min(8,r.length-i),u=parseInt(r.substring(i,i+a),e);if(a<8){var l=lo(ex(e,a));s=s.mul(l).add(lo(u))}else s=s.mul(o),s=s.add(lo(u))}return s.unsigned=t,s}Ke.fromString=Av;function Bs(r,t){return typeof r=="number"?lo(r,t):typeof r=="string"?Av(r,t):je(r.low,r.high,typeof t=="boolean"?t:r.unsigned)}Ke.fromValue=Bs;var YT=1<<16,_U=1<<24,Bp=YT*YT,QT=Bp*Bp,ZT=QT/2,JT=Iu(_U),uo=Iu(0);Ke.ZERO=uo;var Cu=Iu(0,!0);Ke.UZERO=Cu;var zp=Iu(1);Ke.ONE=zp;var t1=Iu(1,!0);Ke.UONE=t1;var Ev=Iu(-1);Ke.NEG_ONE=Ev;var e1=je(-1,2147483647,!1);Ke.MAX_VALUE=e1;var r1=je(-1,-1,!0);Ke.MAX_UNSIGNED_VALUE=r1;var On=je(0,-2147483648,!1);Ke.MIN_VALUE=On;var yt=Ke.prototype;yt.toInt=function(){return this.unsigned?this.low>>>0:this.low};yt.toNumber=function(){return this.unsigned?(this.high>>>0)*Bp+(this.low>>>0):this.high*Bp+(this.low>>>0)};yt.toString=function(t){if(t=t||10,t<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(On)){var e=lo(t),n=this.div(e),o=n.mul(e).sub(this);return n.toString(t)+o.toInt().toString(t)}else return"-"+this.neg().toString(t);for(var s=lo(ex(t,6),this.unsigned),i=this,a="";;){var u=i.div(s),l=i.sub(u.mul(s)).toInt()>>>0,c=l.toString(t);if(i=u,i.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}};yt.getHighBits=function(){return this.high};yt.getHighBitsUnsigned=function()
`),Q=T=>U.writeSync(2,T+`
`));var rt=l.print||j,X=l.printErr||Q;Object.assign(l,f),f=null,l.arguments&&(d=l.arguments),l.thisProgram&&(h=l.thisProgram),l.quit&&(g=l.quit);var nt=4;function st(T){st.shown||(st.shown={}),st.shown[T]||(st.shown[T]=1,X(T))}function it(T,F){if(typeof WebAssembly.Function=="function"){for(var V={i:"i32",j:"i64",f:"f32",d:"f64"},Y={parameters:[],results:F[0]=="v"?[]:[V[F[0]]]},ht=1;ht<F.length;++ht)Y.parameters.push(V[F[ht]]);return new WebAssembly.Function(Y,T)}var wt=[1,0,1,96],Nt=F.slice(0,1),zt=F.slice(1),nr={i:127,j:126,f:125,d:124};wt.push(zt.length);for(var ht=0;ht<zt.length;++ht)wt.push(nr[zt[ht]]);Nt=="v"?wt.push(0):wt=wt.concat([1,nr[Nt]]),wt[1]=wt.length-2;var Go=new Uint8Array([0,97,115,109,1,0,0,0].concat(wt,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0])),Wo=new WebAssembly.Module(Go),Xg=new WebAssembly.Instance(Wo,{e:{f:T}}),mf=Xg.exports.f;return mf}var ft=[],at;function xt(){if(ft.length)return ft.pop();try{Un.grow(1)}catch(T){throw T instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":T}return Un.length-1}function dt(T,F){for(var V=T;V<T+F;V++){var Y=Xc(V);Y&&at.set(Y,V)}}var bt=0,kt=T=>{bt=T},At=Atomics.load,$t=Atomics.store,qt=Atomics.compareExchange,Kt;l.wasmBinary&&(Kt=l.wasmBinary);var ce=l.noExitRuntime||!0;typeof WebAssembly!="object"&&qc("no native wasm support detected");var Ot,Ee,Ie=!1,ae;function qe(T,F){T||qc(F)}function Re(T){var F=l["_"+T];return F}function Jr(T,F,V,Y,ht){var wt={string:function(Rn){var rp=0;if(Rn!=null&&Rn!==0){var MT=(Rn.length<<2)+1;rp=ep(MT),$n(Rn,rp,MT)}return rp},array:function(Rn){var rp=ep(Rn.length);return hl(Rn,rp),rp}};function Nt(Rn){return F==="string"?Hr(Rn):F==="boolean"?Boolean(Rn):Rn}var zt=Re(T),nr=[],Go=0;if(Y)for(var Wo=0;Wo<Y.length;Wo++){var Xg=wt[V[Wo]];Xg?(Go===0&&(Go=gv()),nr[Wo]=Xg(Y[Wo])):nr[Wo]=Y[Wo]}var mf=zt.apply(null,nr);function QW(Rn){return Go!==0&&Hg(Go),Nt(Rn)}return mf=QW(mf),mf}function ze(T,F,V,Y){V=V||[];var ht=V.every(function(Nt){return Nt==="number"}),wt=F!=="string";return wt&&ht&&!Y?Re(T):function(){return Jr(T,F,V,arguments,Y)}}var Po=1;function Fr(T){var F=new TextDecoder(T);this.decode=V=>(V.buffer instanceof SharedArrayBuffer&&(V=new Uint8Array(V)),F.decode.call(F,V))}var Qr=typeof TextDecoder!="undefined"?new Fr("utf8"):void 0;function tn(T,F,V){for(var Y=F+V,ht=F;T[ht]&&!(ht>=Y);)++ht;if(ht-F>16&&T.subarray&&Qr)return Qr.decode(T.subarray(F,ht));for(var wt="";F<ht;){var Nt=T[F++];if(!(Nt&128)){wt+=String.fromCharCode(Nt);continue}var zt=T[F++]&63;if((Nt&224)==192){wt+=String.fromCharCode((Nt&31)<<6|zt);continue}var nr=T[F++]&63;if((Nt&240)==224?Nt=(Nt&15)<<12|zt<<6|nr:Nt=(Nt&7)<<18|zt<<12|nr<<6|T[F++]&63,Nt<65536)wt+=String.fromCharCode(Nt);else{var Go=Nt-65536;wt+=String.fromCharCode(55296|Go>>10,56320|Go&1023)}}return wt}function Hr(T,F){return T?tn(n(),T,F):""}function eo(T,F,V,Y){if(!(Y>0))return 0;for(var ht=V,wt=V+Y-1,Nt=0;Nt<T.length;++Nt){var zt=T.charCodeAt(Nt);if(zt>=55296&&zt<=57343){var nr=T.charCodeAt(++Nt);zt=65536+((zt&1023)<<10)|nr&1023}if(zt<=127){if(V>=wt)break;F[V++]=zt}else if(zt<=2047){if(V+1>=wt)break;F[V++]=192|zt>>6,F[V++]=128|zt&63}else if(zt<=65535){if(V+2>=wt)break;F[V++]=224|zt>>12,F[V++]=128|zt>>6&63,F[V++]=128|zt&63}else{if(V+3>=wt)break;F[V++]=240|zt>>18,F[V++]=128|zt>>12&63,F[V++]=128|zt>>6&63,F[V++]=128|zt&63}}return F[V]=0,V-ht}function $n(T,F,V){return eo(T,n(),F,V)}function Mo(T){for(var F=0,V=0;V<T.length;++V){var Y=T.charCodeAt(V);Y>=55296&&Y<=57343&&(Y=65536+((Y&1023)<<10)|T.charCodeAt(++V)&1023),Y<=127?++F:Y<=2047?F+=2:Y<=65535?F+=3:F+=4}return F}var ro=typeof TextDecoder!="undefined"?new Fr("utf-16le"):void 0;function hl(T,F){e().set(T,F)}function uu(T,F,V){for(var Y=0;Y<T.length;++Y)e()[F++>>0]=T.charCodeAt(Y);V||(e()[F>>0]=0)}function Gc(T,F){return T%F>0&&(T+=F-T%F),T}var hr,Wc,Uc,tf,yg,bg,xT,wg,vg;v&&(hr=l.buffer);function Lo(T){hr=T,l.HEAP8=Wc=new Int8Array(T),l.HEAP16=tf=new Int16Array(T),l.HEAP32=bg=new Int32Array(T),l.HEAPU8=Uc=new Uint8Array(T),l.HEAPU16=yg=new Uint16Array(T),l.HEAPU32=xT=new Uint32Array(T),l.HEAPF32=wg=new Float32Array(T),l.HEAPF64=vg=ne
`)),u.join(`
`)}function LU(r,t,e,n){let o=re(t),s=n[n.length-1],i=new Array(s).fill(0),a=t.length,u=e==="complex64"?kf(r):r;if(a>1)for(let l=0;l<o/s;l++){let c=l*s;for(let p=0;p<s;p++)i[p]=Math.max(i[p],Sf(u[c+p],0,e).length)}return i}function Sf(r,t,e){let n;return Array.isArray(r)?n=`${parseFloat(r[0].toFixed(Fv))} + ${parseFloat(r[1].toFixed(Fv))}j`:Ho(r)?n=`'${r}'`:e==="bool"?n=f1(r):n=parseFloat(r.toFixed(Fv)).toString(),yu(n,t)}function f1(r){return r===0?"false":"true"}function nx(r,t,e,n,o,s=!0){let i=e==="complex64"?2:1,a=t[0],u=t.length;if(u===0){if(e==="complex64"){let h=kf(r);return[Sf(h[0],0,e)]}return e==="bool"?[f1(r[0])]:[r[0].toString()]}if(u===1){if(a>p1){let g=If*i,y=Array.from(r.slice(0,g)),b=Array.from(r.slice((a-If)*i,a*i));return e==="complex64"&&(y=kf(y),b=kf(b)),["["+y.map((w,v)=>Sf(w,o[v],e)).join(", ")+", ..., "+b.map((w,v)=>Sf(w,o[a-If+v],e)).join(", ")+"]"]}let h=e==="complex64"?kf(r):Array.from(r);return["["+h.map((g,y)=>Sf(g,o[y],e)).join(", ")+"]"]}let l=t.slice(1),c=n.slice(1),p=n[0]*i,m=[];if(a>p1){for(let h=0;h<If;h++){let g=h*p,y=g+p;m.push(...nx(r.slice(g,y),l,e,c,o,!1))}m.push("...");for(let h=a-If;h<a;h++){let g=h*p,y=g+p;m.push(...nx(r.slice(g,y),l,e,c,o,h===a-1))}}else for(let h=0;h<a;h++){let g=h*p,y=g+p;m.push(...nx(r.slice(g,y),l,e,c,o,h===a-1))}let f=u===2?",":"";m[0]="["+m[0]+f;for(let h=1;h<m.length-1;h++)m[h]=" "+m[h]+f;let d=`,
`;for(let h=2;h<u;h++)d+=`
`;return m[m.length-1]=" "+m[m.length-1]+"]"+(s?"":d),m}function kf(r){let t=[];for(let e=0;e<r.length;e+=2)t.push([r[e],r[e+1]]);return t}var me=class{constructor(t,e,n){if(this.dtype=e,this.shape=t.slice(),this.size=re(t),n!=null){let o=n.length;A(o===this.size,()=>`Length of values '${o}' does not match the size inferred by the shape '${this.size}'.`)}if(e==="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=n||wv(e,this.size),this.strides=fi(t)}set(t,...e){e.length===0&&(e=[0]),A(e.length===this.rank,()=>`The number of provided coordinates (${e.length}) must match the rank (${this.rank})`);let n=this.locToIndex(e);this.values[n]=t}get(...t){t.length===0&&(t=[0]);let e=0;for(let o of t){if(o<0||o>=this.shape[e]){let s=`Requested out of range element at ${t}. Buffer shape=${this.shape}`;throw new Error(s)}e++}let n=t[t.length-1];for(let o=0;o<t.length-1;++o)n+=this.strides[o]*t[o];return this.values[n]}locToIndex(t){if(this.rank===0)return 0;if(this.rank===1)return t[0];let e=t[t.length-1];for(let n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e}indexToLoc(t){if(this.rank===0)return[];if(this.rank===1)return[t];let e=new Array(this.shape.length);for(let n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e}get rank(){return this.shape.length}toTensor(){return Vs().makeTensor(this.values,this.shape,this.dtype)}},Vs=null,Wp=null,zU=null;function d1(r){Vs=r}function h1(r){Wp=r}function g1(r){zU=r}var Bt=class{constructor(t,e,n,o){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=re(t),this.strides=fi(t),this.dataId=n,this.id=o,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let t=await this.data();return Wp.buffer(this.shape,this.dtype,t)}bufferSync(){return Wp.buffer(this.shape,this.dtype,this.dataSync())}async array(){let t=await this.data();return xu(this.shape,t,this.dtype==="complex64")}arraySync(){return xu(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let t=Vs().read(this.dataId);if(this.dtype==="string"){let e=await t;try{return e.map(n=>Gp(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return t}dataToGPU(t){return this.throwIfDisposed(),Vs().readToGPU(this.dataId,t)}dataSync(){this.throwIfDisposed();let t=Vs().readSync(this.dataId);if(this.dtype==="string")try{return t.map(e=>Gp(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t}async bytes(){this.throwIfDisposed();let t=await Vs().read(this.dataId);return this.dtype==="string"?t:new Uint8Array(t.buffer)}dispose(){this.isDisposed||(Vs().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(t=!1){return Wp.print(this,t)}clone(){return this.throwIfDisposed(),Wp.clone(this)}toString(t=!1){let e=this.dataSync();return m1(e,this.shape,this.dtype,t)}cast(t){return this.throwIfDisposed(),Wp.cast(this,t)}variable(t=!0,e,n){return this.throwIfDisposed(),Vs().makeVariable(this,t,e,n)}};Object.defineProperty(Bt,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});function L(){return gf("Tensor",()=>Bt)}L();var Ml=class extends Bt{constructor(t,e,n,o){super(t.shape,t.dtype,t.dataId,o);this.trainable=e,this.name=n}assign(t){if(t.dtype!==this.dtype)throw new Error(`dtype of the new value (${t.dtype}) and previous value (${this.dtype}) must match`);if(!Fn(t.shape,this.shape))throw new Error(`shape of the new value (${t.shape}) and previous value (${this.shape}) must match`);Vs().disposeTensor(this),this.dataId=t.dataId,Vs().incRef(this,null)}dispose(){Vs().disposeVariable(this),this.isDisposedInternal=!0}};Obje
Manifest JSON has weights with names: ${a.join(", ")}.`)}let u=o.reduce((f,d,h)=>(d&&f.push(h),f),[]),l=[];u.forEach(f=>{t[f].paths.forEach(d=>{let h=e+(e.endsWith("/")?"":"/")+d;l.push(h)})});let c=await r(l),p={},m=0;return u.forEach(f=>{let d=t[f].paths.length,h=0;for(let v=0;v<d;v++)h+=c[m+v].byteLength;let g=new ArrayBuffer(h),y=new Uint8Array(g),b=0;for(let v=0;v<d;v++){let I=new Uint8Array(c[m+v]);y.set(I,b),b+=I.byteLength}s[f].forEach(v=>{let I=g.slice(v.groupOffset,v.groupOffset+v.sizeBytes),E=sx(I,[v.manifestEntry]);for(let D in E)p[D]=E[D]}),m+=d}),p}}var y4="application/octet-stream",b4="application/json",ux=class{constructor(t,e){if(this.DEFAULT_METHOD="POST",e==null&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,this.weightUrlConverter=e.weightUrlConverter,e.fetchFunc!=null?(A(typeof e.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=e.fetchFunc):this.fetch=G().platform.fetch,A(t!=null&&t.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(t)&&A(t.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${t.length}).`),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);e.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],o=ix(t,n);e.body.append("model.json",new Blob([JSON.stringify(o)],{type:b4}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:y4}),"model.weights.bin");let s=await this.fetch(this.path,e);if(s.ok)return{modelArtifactsInfo:Ri(t),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async load(){let t=await this.fetch(this.path,this.requestInit);if(!t.ok)throw new Error(`Request to ${this.path} failed with status code ${t.status}. Please verify this URL points to the model JSON of the model to load.`);let e;try{e=await t.json()}catch(s){let i=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?i+=" 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.":i+=" Please make sure the server is serving valid JSON for this request.",new Error(i)}let n=e.modelTopology,o=e.weightsManifest;if(n==null&&o==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Hp(e,s=>this.loadWeights(s))}async loadWeights(t){let e=Array.isArray(this.path)?this.path[1]:this.path,[n,o]=w4(e),s=this.weightPathPrefix||n,i=[];for(let c of t)i.push(...c.weights);let a=[],u=[];for(let c of t)for(let p of c.paths)this.weightUrlConverter!=null?u.push(this.weightUrlConverter(p)):a.push(s+p+o);this.weightUrlConverter&&a.push(...await Promise.all(u));let l=await r0(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,Up(l)]}};ux.URL_SCHEME_REGEX=/^https?:\/\//;function w4(r){let t=r.lastIndexOf("/"),e=r.lastIndexOf("?"),n=r.substring(0,t),o=e>t?r.substring(e):"";return[n+"/",o]}function lx(r){return r.match(ux.URL_SCHEME_REGEX)!=null}var j1=(r,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let e=!0;if(Array.isArray(r)?e=r.every(n=>lx(n)):e=lx(r),e)return cx(r,t)}return null};Ae.registerSaveRouter(j1);Ae.registerLoadRouter(j1);function cx(r,t){return new ux(r,t)}function X1(r,t){return cx(r,t)}var px=class{
Actual: ${o}.
Expected: ${s}.`);for(let i=0;i<s.length;++i){let a=o[i],u=s[i];if(!e(a,u))throw new Error(`Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${u}.
Actual: ${o}.
Expected: ${s}.`)}}function W4(r,t){r().then(()=>t.fail(),()=>t())}function U4(r,t){let e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Ho(r)||Ho(r[0])||Ho(t)||Ho(t[0])?l0(r,e,(n,o)=>n==o):l0(r,t,(n,o)=>u0(n,o,0))}function h_(r,t,e){if(e==null&&(e=gx()),!u0(r,t,e))throw new Error(`Numbers differ: actual === ${r}, expected === ${t}`)}function u0(r,t,e){return!isFinite(r)&&!isFinite(t)?!0:!(isNaN(r)||isNaN(t)||Math.abs(r-t)>e)}function H4(r,t,e){for(let n=0;n<r.length;n++)if(r[n]<t||r[n]>e)throw new Error(`Value out of range:${r[n]} low: ${t}, high: ${e}`)}function q4(r,t){let e=new Float32Array(r),n=new Float32Array(t);if(e.length!==n.length)throw new Error(`Expected ArrayBuffer to be of length ${n.length}, but it was ${e.length}`);for(let o=0;o<n.length;o++)if(e[o]!==n[o])throw new Error(`Expected ArrayBuffer value at ${o} to be ${n[o]} but got ${e[o]} instead`)}function g_(r){for(let t=0;t<r.length;t++){let e=r[t];Array.isArray(e)?g_(e):r[t]=Pl(e)}return r}var y_="3.14.0";function Oct(){G().set("PROD",!0)}function Pct(){G().set("DEBUG",!0)}function Mct(){G().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function c0(r){G().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}g1(c0);function Lct(){_.disposeVariables()}function po(){return _}function Ef(){return _.memory()}function zct(r){return _.profile(r)}function B(r,t){return _.tidy(r,t)}function _t(r){Nf(r).forEach(e=>e.dispose())}function Pe(r){return _.keep(r)}function Bct(r){return _.time(r)}function K4(r){return _.setBackend(r)}function Vct(){return _.ready()}function Gct(){return _.backendName}function Wct(r){_.removeBackend(r)}function Uct(r){return _.findBackend(r)}function Hct(r){return _.findBackendFactory(r)}function jp(r,t,e=1){return _.registerBackend(r,t,e)}function b_(){return _.backend}function qct(r,t){G().setPlatform(r,t)}function j4(r,t){let e=C(r,"a","add"),n=C(t,"b","add");[e,n]=jt(e,n);let o={a:e,b:n};return _.runKernel(Kn,o)}var J=N({add_:j4});function X4(r,t){let e=C(r,"a","floorDiv"),n=C(t,"b","floorDiv");[e,n]=jt(e,n);let o={a:e,b:n};return _.runKernel(as,o)}var Du=N({floorDiv_:X4});function Y4(r,t){let e=C(r,"a","div"),n=C(t,"b","div");if([e,n]=jt(e,n),e.dtype==="int32"&&n.dtype==="int32")return Du(e,n);let o={a:e,b:n},s={};return _.runKernel(ns,o,s)}var ct=N({div_:Y4});function Z4(r,t){let e=C(r,"a","mul"),n=C(t,"b","mul");[e,n]=jt(e,n);let o={a:e,b:n};return _.runKernel(bs,o)}var P=N({mul_:Z4});function J4(r){let t=C(r,"x","abs");if(t.dtype==="complex64"){let e={x:t};return _.runKernel(Cl,e)}else{let e={x:t};return _.runKernel(di,e)}}var Se=N({abs_:J4});function Q4(r){let e={x:C(r,"x","acos")};return _.runKernel(ji,e)}var Af=N({acos_:Q4});function tH(r){let e={x:C(r,"x","acosh")};return _.runKernel(Xi,e)}var Df=N({acosh_:tH});function eH(r){A(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),A(r.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${r.length}`);let t=r.map((o,s)=>C(o,`tensors${s}`,"addN")),e=t[0];t.forEach(o=>{if(o.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(o=>{if(!Fn(o.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let n=t;return _.runKernel(qo,n)}var p0=N({addN_:eH});function rH(r,t=null,e=!1){let o={x:C(r,"x","all","bool")},s={axis:t,keepDims:e};return _.runKernel(Yi,o,s)}var $u=N({all_:rH});function nH(r,t=null,e=!1){let o={x:C(r,"x","any","bool")},s={axis:t,keepDims:e};return _.runKernel(Zi,o,s)}var Vl=N({any_:nH});function oH(r,t=0){let n={x:C(r,"x","argMax")},o={axis:t};return _.runKernel(Ko,n,o)}var Us=N({argMax_:oH});function sH(r,t=0){let n={x:C(r,"x","argMin")},o={axis:t};return _.runKernel(wl,n,o)}var $f=N({argMin_:sH});function iH(r){let e={x:C(r,"x","asin")};return _.runKernel(Ji,e)}var Rf=N({asin_:iH});function aH(r){let e={x:C(r,"x","asinh")};return _.runKernel(Qi,e)}var Ff=N({asinh_:a
with dtype ${s.dtype}. `)}),e.length===1)return Cn(e[0]);let n=e,o={axis:t};return _.runKernel(gi,n,o)}var se=N({concat_:wH});function vH(r){let e={x:C(r,"x","sigmoid","float32")};return _.runKernel(Ds,e)}var Lr=N({sigmoid_:vH});function CH(r,t,e){let n=C(r,"x","slice","string_or_numeric");if(n.rank===0)throw new Error("Slicing scalar is not possible");let o={x:n},s={begin:t,size:e};return _.runKernel(Si,o,s)}var Rt=N({slice_:CH});function IH(r){let e={x:C(r,"x","tanh","float32")};return _.runKernel(Ls,e)}var Hs=N({tanh_:IH});function SH(r,t,e,n,o,s){let i=C(r,"forgetBias","basicLSTMCell"),a=C(t,"lstmKernel","basicLSTMCell"),u=C(e,"lstmBias","basicLSTMCell"),l=C(n,"data","basicLSTMCell"),c=C(o,"c","basicLSTMCell"),p=C(s,"h","basicLSTMCell"),m=se([l,p],1),f=Mt(m,a),d=J(f,u),h=d.shape[0],g=d.shape[1]/4,y=[h,g],b=Rt(d,[0,0],y),w=Rt(d,[0,g],y),v=Rt(d,[0,g*2],y),I=Rt(d,[0,g*3],y),E=J(P(Lr(b),Hs(w)),P(c,Lr(J(i,v)))),D=P(Hs(E),Lr(I));return[E,D]}var kH=N({basicLSTMCell_:SH});function NH(r,t,e){let n=C(r,"x","batchToSpaceND"),o=t.reduce((a,u)=>a*u);A(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),A(e.length===t.length,()=>`crops.length is ${e.length} but should be equal to blockShape.length ${t.length}`),A(n.shape[0]%o===0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${o}`);let s={x:n},i={blockShape:t,crops:e};return _.runKernel(hi,s,i)}var Va=N({batchToSpaceND_:NH});function C_(r){let t;return r.rank===0||r.rank===1?t=O(r,[1,1,1,r.size]):r.rank===2?t=O(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?t=O(r,[1,r.shape[0],r.shape[1],r.shape[2]]):t=r,t}function TH(r,t,e,n,o,s){s==null&&(s=.001);let i=C(r,"x","batchNorm"),a=C(t,"mean","batchNorm"),u=C(e,"variance","batchNorm"),l;o!=null&&(l=C(o,"scale","batchNorm"));let c;n!=null&&(c=C(n,"offset","batchNorm")),A(a.rank===u.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(c==null||a.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(l==null||a.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:C_(i),scale:l,offset:c,mean:a,variance:u},f={varianceEpsilon:s},d=_.runKernel(ls,m,f);return O(d,i.shape)}var mo=N({batchNorm_:TH});function _H(r,t,e,n,o,s){let i=C(r,"x","batchNorm"),a=C(t,"mean","batchNorm"),u=C(e,"variance","batchNorm"),l;o!=null&&(l=C(o,"scale","batchNorm"));let c;return n!=null&&(c=C(n,"offset","batchNorm")),A(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),A(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),A(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`),l!=null&&A(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&A(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),mo(i,a,u,c,l,s)}var h0=N({batchNorm2d_:_H});function EH(r,t,e,n,o,s){let i=C(r,"x","batchNorm"),a=C(t,"mean","batchNorm"),u=C(e,"variance","batchNorm"),l;o!=null&&(l=C(o,"scale","batchNorm"));let c;return n!=null&&(c=C(n,"offset","batchNorm")),A(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),A(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),A(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`),l!=null&&A(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&A(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),mo(i,a,u,c,l,s)}var g0=N({batchNorm3d_:EH});function AH(r,t,e,n,o,s){let i=C(r,"x","batchNorm"),a=C(t,"mean","batchNorm"),u=C(e,"variance","batchNorm"),l;o!=null&&(l=C(o,"scale","batchNorm")
${o} and ${t} for depthToSpace with input shape
${n.shape}`),A(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${s} and ${t} for depthToSpace with input shape
${n.shape}`),A(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${n.shape}`);let a={x:n},u={blockSize:t,dataFormat:e};return _.runKernel(oa,a,u)}var Gf=N({depthToSpace_:ZH});function JH(r,t,e,n,o="NHWC",s=[1,1],i){let a=C(r,"x","depthwiseConv2d","float32"),u=C(t,"filter","depthwiseConv2d","float32"),l=a,c=!1;a.rank===3&&(c=!0,l=O(a,[1,a.shape[0],a.shape[1],a.shape[2]])),A(l.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`),A(u.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`),A(l.shape[3]===u.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),ke("depthwiseConv2d",n,i);let p={x:l,filter:u},m={strides:e,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i},f=_.runKernel(rs,p,m);return c?O(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var qs=N({depthwiseConv2d_:JH});function QH(r){let e={x:C(r,"x","diag")};return _.runKernel(yp,e)}var tq=N({diag_:QH});function eq(r,t,e,n,o=[1,1],s="NHWC"){let i=C(r,"x","dilation2d"),a=C(t,"filter","dilation2d");A(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),A(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),A(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let u=i,l=!1;i.rank===3&&(u=O(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=!0);let c={x:u,filter:a},p={strides:e,pad:n,dilations:o},m=_.runKernel(Sl,c,p);return l?O(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Wf=N({dilation2d_:eq});function rq(r,t){let e=C(r,"a","equal","string_or_numeric"),n=C(t,"b","equal","string_or_numeric");[e,n]=jt(e,n),Lt(e.shape,n.shape);let o={a:e,b:n};return _.runKernel(ia,o)}var Sr=N({equal_:rq});function nq(r,t,e){let n=C(t,"a","where"),o=C(e,"b","where"),s=C(r,"condition","where","bool"),i=Lt(Lt(s.shape,n.shape),o.shape),a=Ga(s,i),u=Ga(n,i),l=Ga(o,i),c={condition:a,t:u,e:l};return _.runKernel(Ii,c)}var Ne=N({where_:nq});function oq(r){let e={x:C(r,"x","zerosLike")};return _.runKernel(_i,e)}var St=N({zerosLike_:oq});function sq(r,t){let e=C(r,"a","div"),n=C(t,"b","div");[e,n]=jt(e,n);let o=ct(e,n),s=St(o),i=Sr(n,s);return Ne(i,s,o)}var Uf=N({divNoNan_:sq});function iq(r,t){let e=C(r,"t1","dot"),n=C(t,"t2","dot");A((e.rank===1||e.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${e.rank} and ${n.rank}.`);let o=e.rank===1?e.size:e.shape[1],s=n.rank===1?n.size:n.shape[0];if(A(o===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${o} and ${s}.`),e.rank===1&&n.rank===1){let i=O(e,[1,-1]),a=O(n,[-1,1]),u=Mt(i,a);return O(u,[])}else if(e.rank===1&&n.rank===2){let i=O(e,[1,-1]),a=O(n,[n.shape[0],n.shape[1]]),u=Mt(i,a);return O(u,[u.size])}else if(e.rank===2&&n.rank===1){let i=O(n,[-1,1]),a=Mt(e,i);return O(a,[a.size])}else{let i=O(n,[n.shape[0],n.shape[1]]);return Mt(e,i)}}var k0=N({dot_:iq});function aq(r,...t){let e=t.map((o,s)=>C(o,`tensors${s}`,"einsum")),n={equation:r};return _.runKernel(bp,e,n)}var N0=N({einsum_:aq});function lq(r){let e={x:C(r,"x","elu","float32")};return _.runKernel(os,e)}var Ks=N({elu_:lq});function uq(r){let t=C(r,"x","erf");A(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=Z(t,"float32"));let e={x:t};return _.runKernel(sa,e)}var Hf=N({erf_:uq});function cq(r){let e={x:C(r,"x","exp")};return _.runKernel(ss,e)}var Xe=N({exp_:cq});function pq(r,t=0){let e=C(r,"x","expandDims","string_or_numeric");A(t<=e.rank,()=>"Axis must be <= rank of the tensor");let n={input:e},o={dim:t};return _.runKernel(xi,n,o)}var mr=N({expandDims_:pq});function mq(r){let e={x:C(r,"x","expm1")};return _.runKernel(aa,e)}var qf=N({expm1_:mq});function fq(r,t){let e=C(r,"x","tile","string_or_numeric");A(e.rank===t.length,()=>`Error in transpose: rank of input ${e.rank} must match length of reps ${t}.`);let n={x:e},o={reps:
rank ${s.rank}.`),A(Ki(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,a=!1;s.rank===3&&(a=!0,i=O(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let u={x:i},l={depthRadius:t,bias:e,alpha:n,beta:o},c=_.runKernel(Nl,u,l);return a?O(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var jf=N({localResponseNormalization_:Nq});function Tq(r){let e={x:C(r,"x","log","float32")};return _.runKernel(ps,e)}var wr=N({log_:Tq});function _q(r){let e={x:C(r,"x","log1p")};return _.runKernel(ga,e)}var Ha=N({log1p_:_q});function Eq(r){return A(mi(r),()=>"The f passed in grad(f) must be a function"),(t,e)=>{let n=C(t,"x","tf.grad","string_or_numeric"),o=e!=null?C(e,"dy","tf.grad"):null;return _.tidy(()=>{let{value:s,grads:i}=_.gradients(()=>r(n),[n],o);return o!=null&&Oe(s.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),wx(i),i[0]})}}function Aq(r){return A(mi(r),()=>"The f passed in grads(f) must be a function"),(t,e)=>{A(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let n=Oa(t,"args","tf.grads","string_or_numeric"),o=e!=null?C(e,"dy","tf.grads"):null;return _.tidy(()=>{let{value:s,grads:i}=_.gradients(()=>r(...n),n,o);return o!=null&&Oe(s.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),wx(i),i})}}function Dq(r){return A(mi(r),()=>"The f passed in valueAndGrad(f) must be a function"),(t,e)=>{A(t instanceof Bt,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(e==null||e instanceof Bt,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:n,value:o}=_.gradients(()=>r(t),[t],e);return wx(n),{grad:n[0],value:o}}}function $q(r){return A(mi(r),()=>"The f passed in valueAndGrads(f) must be a function"),(t,e)=>{A(Array.isArray(t)&&t.every(o=>o instanceof Bt),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(e==null||e instanceof Bt,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let n=_.gradients(()=>r(...t),t,e);return e!=null&&Oe(n.value.shape,e.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),wx(n.grads),n}}function bx(r,t){A(mi(r),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(l=>l instanceof Ml),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let e=t!=null;if(!e){t=[];for(let l in _.registeredVariables)t.push(_.registeredVariables[l])}let n=e?t.filter(l=>!l.trainable):null,o=t.length;t=t.filter(l=>l.trainable),A(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);let s=!0,{value:i,grads:a}=_.gradients(r,t,null,s);A(a.some(l=>l!=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(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let u={};return t.forEach((l,c)=>{a[c]!=null&&(u[l.name]=a[c])}),n!=null&&n.forEach(l=>u[l.name]=null),{value:i,grads:u}}function un(r){return _.customGrad(r)}function wx(r){if(r.filter(e=>e==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 Rq(r){let e={x:C(r,"x","neg")};return _.runKernel(bi,e)}var Yt=N({neg_:Rq});function Fq(r){let e={x:C(r,"x","softplus")};return _.runKernel(Ea,e)}var ho=N({softplus_:Fq});function Oq(r){let t=C(r,"x","logSigmoid");return un(n=>({value:Yt(ho(Yt(n))),gradFunc:i=>P(i,Lr(Yt(n)))}))(t)}var A0=N({logSigmoid_:Oq});function Pq(r,t=null,e=!1){let o={x:C(r,"x","max")},s={reductionIndices:t,keepDims:e};return _.runKernel(ms,o,s)}var $r=N({max_:Pq});function Mq(r,t){let e=C(r,"a","sub"),n=C(t,"b","sub");[e,n]=jt(e,n);let o={a:e,b:n};return _.runKernel(Ps,o)}var lt=N({sub_:Mq});function Lq(r,t=null,e=!1){let n=C(r,"x","sum");n.dtype==="bool"&&(n=Z(n,"int32"));let o={x:n},s={axis:t,keepDims:e};return _.runKernel(Rs,o,s)}var mt=N({sum_:Lq});function zq(r,t=-1){let e=C(r,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and axis was ${t}`);return un((o,s)=>{let a=$r(o,t,!0),u=lt(o,a),l=lt(Z(u,"float32"),wr(mt(Xe(u),t,!0)));return s([l]),{value:l,gradFunc:(p,m)=>{let[f]=m,d=!0,h=Xe(f);return lt(p,P(mt(p,t,d),h))}}})(e)}var Vu=N({logSoftmax_:zq});function D0(r,t){for(let e=0;e<r.length;++e)if(r[r.length-e-1]!==t-1-e)return!1;return!0}function I_(r,t,e){let n=r.length+t.length,o=[],s=0,i=0;for(let a=0;a<n;a++)e.indexOf(a)===-1?o.push(r[s++]):o.push(t[i++]);return o}function $0(r,t){let e=[],n=r.length;for(let s=0;s<n;s++)t.indexOf(s)===-1&&e.push(r[s]);let o=t.map(s=>r[s]);return[e,o]}function go(r,t){let e=t.map(n=>1);return I_(r,e,t)}function Bq(r,t,e){A(D0(t,e),()=>`${r} supports only inner-most axes for now. Got axes ${t} and rank-${e} input.`)}function R0(r,t){if(D0(r,t))return null;let e=[];for(let n=0;n<t;++n)r.indexOf(n)===-1&&e.push(n);return r.forEach(n=>e.push(n)),e}function Xf(r){return r.map((t,e)=>[e,t]).sort((t,e)=>t[1]-e[1]).map(t=>t[0])}function Vq(r,t){let e=[];for(let n=t-r;n<t;++n)e.push(n);return e}function Gq(r,t=null,e=!1){let n=C(r,"x","logSumExp"),o=pr(t,n.shape),s=$r(n,o,!0),i=lt(n,s),a=Xe(i),u=mt(a,o),l=wr(u),c=J(O(s,l.shape),l);if(e){let p=go(c.shape,o);return O(c,p)}return c}var Yf=N({logSumExp_:Gq});function Wq(r,t){let e=C(r,"a","logicalAnd","bool"),n=C(t,"b","logicalAnd","bool");Lt(e.shape,n.shape);let o={a:e,b:n};return _.runKernel(xa,o)}var Nr=N({logicalAnd_:Wq});function Uq(r){let e={x:C(r,"x","logicalNot","bool")};return _.runKernel(bu,e)}var qa=N({logicalNot_:Uq});function Hq(r,t){let e=C(r,"a","logicalOr","bool"),n=C(t,"b","logicalOr","bool");Lt(e.shape,n.shape);let o={a:e,b:n};return _.runKernel(wu,o)}var Gu=N({logicalOr_:Hq});function qq(r,t){let e=C(r,"a","logicalXor","bool"),n=C(t,"b","logicalXor","bool");return Lt(e.shape,n.shape),Nr(Gu(r,t),qa(Nr(r,t)))}var O0=N({logicalXor_:qq});function Kq(r,t,e,n,o){let s=C(r,"x","maxPool"),i=1,a=s,u=!1;s.rank===3&&(u=!0,a=O(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),A(Dr(e,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`),ke("maxPool",n,o);let l={x:a},c={filterSize:t,strides:e,pad:n,dimRoundingMode:o},p=_.runKernel(ds,l,c);return u?O(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Ka=N({maxPool_:Kq});function jq(r,t=[1,1,1],e,n,o,s="NDHWC"){let i=C(r,"x","maxPool3d"),a=i,u=!1;i.rank===4&&(u=!0,a=O(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(a.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${a.rank}.`),A(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),ke("maxPool3d",n,o);let l={x:a},c={filterSize:t,strides:e,pad:n,dimRoundingMode:o,dataFormat:s},p=_.runKernel(Tl,l,c);return u?O(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Zf=N({maxPool3d_:jq});function Xq(r,t,e,n,o=!1){let i={x:C(r,"x","maxPoolWithArgmax")},a={filterSize:t,strides:e,pad:n,includeBatchInIndex:o},u=_.runKernel(_p,i,a);return{result:u[0],indexes:u[1]}}var P0=N({maxPoolWithArgmax_:Xq});functio
${o.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(a.rank!==0)throw new Error(`Default value should be a scalar but received shape ${a.shape}`);let u={indices:o,values:s,denseShape:i,defaultValue:a},l=_.runKernel(Al,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}var CE=N({sparseFillEmptyRows_:$6});function R6(r,t,e){let n=C(r,"inputIndices","sparseReshape","int32"),o=C(t,"inputShape","sparseReshape","int32"),s=C(e,"newShape","sparseReshape","int32");if(n.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
${n.shape}`);if(o.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${o.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:n,inputShape:o,newShape:s},a=_.runKernel(Aa,i);return{outputIndices:a[0],outputShape:a[1]}}var IE=N({sparseReshape_:R6});function F6(r,t,e){let n=C(r,"data","sparseSegmentMean"),o=C(t,"indices","sparseSegmentMean","int32"),s=C(e,"segmentIds","sparseSegmentMean","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
${o.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);let i={data:n,indices:o,segmentIds:s};return _.runKernel(Dl,i)}var SE=N({sparseSegmentMean_:F6});function O6(r,t,e){let n=C(r,"data","sparseSegmentSum"),o=C(t,"indices","sparseSegmentSum","int32"),s=C(e,"segmentIds","sparseSegmentSum","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
${o.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);let i={data:n,indices:o,segmentIds:s};return _.runKernel($l,i)}var kE=N({sparseSegmentSum_:O6});function P6(r,t,e,n,o,s,i,a){let u=C(r,"data","stringNGrams","string");if(u.dtype!=="string")throw new Error("Data must be of datatype string");if(u.shape.length!==1)throw new Error(`Data must be a vector, saw: ${u.shape}`);let l=C(t,"dataSplits","stringNGrams");if(l.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let c={separator:e,nGramWidths:n,leftPad:o,rightPad:s,padWidth:i,preserveShortSequences:a},p={data:u,dataSplits:l},m=_.runKernel(Fp,p,c);return{nGrams:m[0],nGramsSplits:m[1]}}var NE=N({stringNGrams_:P6});function M6(r,t,e=!0){let n=C(r,"input","stringSplit","string"),o=C(t,"delimiter","stringSplit","string");if(n.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${n.shape}`);if(o.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${o.shape}`);let s={skipEmpty:e},i={input:n,delimiter:o},a=_.runKernel(Op,i,s);return{indices:a[0],values:a[1],shape:a[2]}}var TE=N({stringSplit_:M6});function L6(r,t){let e=C(r,"input","stringToHashBucketFast","string"),n={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let o={input:e};return _.runKernel(Pp,o,n)}var _E=N({stringToHashBucketFast_:L6});var ORt={fft:Ja,ifft:Fi,rfft:Qa,irfft:Zu},BRt={hammingWindow:j_,hannWindow:Ax,frame:Dx,stft:X_},Nn={flipLeftRight:Z_,grayscaleToRGB:J_,resizeNearestNeighbor:Px,resizeBilinear:Ox,rotateWithOffset:Q_,cropAndResize:Y_,nonMaxSuppression:tE,nonMaxSuppressionAsync:nE,nonMaxSuppressionWithScore:oE,nonMaxSuppressionWithScoreAsync:sE,nonMaxSuppressionPadded:iE,nonMaxSuppressionPaddedAsync:aE,threshold:lE,transform:uE},EE={bandPart:cE,gramSchmidt:pE,qr:fE},fFt={absoluteDifference:dE,computeWeightedLoss:Br,cosineDistance:hE,hingeLoss:gE,huberLoss:xE,logLoss:yE,meanSquaredError:bE,sigmoidCrossEntropy:wE,softmaxCrossEntropy:vE},cd={sparseFillEmptyRows:CE,sparseReshape:IE,sparseSegmentMean:SE,sparseSegmentSum:kE},Mx={stringNGrams:NE,stringSplit:TE,stringToHashBucketFast:_E};var jr=class extends hx{minimize(t,e=!1,n){let{value:o,grads:s}=this.computeGradients(t,n);if(n!=null){let i=n.map(a=>({name:a.name,tensor:s[a.name]}));this.applyGradients(i)}else this.applyGradients(s);return _t(s),e?o:(o.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(t,e){return bx(t,e)}dispose(){this.iterations_!=null&&_t(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:pt(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(t){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(t){return this.iterations_=(await t[0].tensor.data())[0],t.slice(1)}};Object.defineProperty(jr,Symbol.hasInstance,{value:r=>r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null});var oc=class extends jr{constructor(t,e,n=null){super();this.learningRate=t,this.rho=e,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=_.backend.epsilon())}applyGradients(t){(Array.isArray(t)?t.map(n=>n.name):Object.keys(t)).forEach((n,o)=>{let s=_.registeredVariables[n],i=!1;this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${n}/accum_grad`,variable:B(()=>St(s).variable(i))}),this.accumulatedUpdates[o]==null&&(this.accumulatedUpdates[o]={originalName:`${n}/accum_var`,variable:B(()=>St(s).variable(i))});let a=Array.isArray(t)?t[o].tensor:t[n];if(a==null)return;let u=this.accumulatedGrads[o].variable,l=this.accumulatedUpdates[o].variable;B(()=>{let c=J(P(u,this.rho),P(Gt(a),1-this.rho)),p=P(ct(be(J(l,this.epsilon)),be(J(u,this.epsilon))),a),m=J(P(l,this.rho),P(Gt(p),1-this.rho));u.assign(c),l.assign(m);let f=J(P(p,-this.learningRate),s);s.assign(f)})}),this.incrementIterations()}dispose(){this.accu
indices.shape[0] = ${r}`}function y5(r,t){return`indices(${r}, 0) is invalid: ${t} < 0`}function b5(r,t,e){return`indices(${r}, 0) is invalid: ${t} >= ${e}`}function w5(r,t){return`only one output dimension may be -1, not both ${r} and ${t}`}function v5(r,t){return`size ${r} must be non-negative, not ${t}`}function C5(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function I5(r,t){let e=re(r),n=re(t);return`Input to reshape is a SparseTensor with ${e}
dense values, but the requested shape requires a multiple of ${n}. inputShape=${r} outputShape= ${t}`}function S5(r,t){let e=re(r),n=re(t);return`Input to reshape is a tensor with ${e} dense values, but the requested shape has ${n}. inputShape=${r} outputShape=${t}`}function k5(){return"segment ids must be >= 0"}function N5(){return"segment ids are not increasing"}function T5(r,t){return`Segment id ${r} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function _5(r,t,e){return`Bad: indices[${r}] == ${t} out of range [0, ${e})`}var rC={};Xt(rC,{collectGatherOpShapeInfo:()=>D5,computeOutShape:()=>A5,segOpComputeOptimalWindowSize:()=>E5});function E5(r,t){let e=!1,n;for(r<=Lx?(n=r,e=!0):n=sp(r,Math.floor(Math.sqrt(r)));!e;)n>t||n===r?e=!0:n=sp(r,n+1);return n}function A5(r,t,e){let n=[],o=r.length;for(let s=0;s<o;s++)s!==t?n.push(r[s]):n.push(e);return n}function D5(r,t,e,n){let o=t.shape.length,s=r.shape.length;if(n!==0&&(n<-o||n>o))throw new Error(`Expect batchDims in the range of [-${o}, ${o}], but got ${n}`);if(n<0&&(n+=o),n>s)throw new Error(`batchDims (${n}) must be less than rank(x) (
${s}).`);if(e<n)throw new Error(`batchDims (${n}) must be less than or equal to axis (${e}).`);for(let p=0;p<n;++p)if(r.shape[p]!==t.shape[p])throw new Error(`x.shape[${p}]: ${r.shape[p]} should be equal to indices.shape[${p}]: ${t.shape[p]}.`);let i=r.shape[e],a=[],u=1,l=1,c=1;for(let p=0;p<n;++p)a.push(r.shape[p]),u*=r.shape[p];for(let p=n;p<e;p++)a.push(r.shape[p]),l*=r.shape[p];for(let p=n;p<o;p++)a.push(t.shape[p]);for(let p=e+1;p<s;p++)a.push(r.shape[p]),c*=r.shape[p];return{batchSize:u,sliceSize:c,outerSize:l,dimSize:i,outputShape:a}}function $5(r){try{return r.map(t=>Gp(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function R5(r){return r.map(t=>Pl(t))}var Vr={};Xt(Vr,{nonMaxSuppressionV3Impl:()=>$x,nonMaxSuppressionV4Impl:()=>Rx,nonMaxSuppressionV5Impl:()=>Fx,whereImpl:()=>kx});var zx={kernelName:di,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>P(r,Js(Z(e,"float32"),-1))}}};var $E={kernelName:ji,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>{let n=Gt(Z(e,"float32")),o=be(lt(pt(1),n));return Yt(ct(r,o))}}}};var RE={kernelName:Xi,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>{let n=be(lt(Gt(Z(e,"float32")),1));return ct(r,n)}}}};var FE={kernelName:Kn,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=Lt(e.shape,n.shape);return{a:()=>{let a=r,u=ge(e.shape,o);return u.length>0&&(a=mt(a,u)),O(a,e.shape)},b:()=>{let a=r,u=ge(n.shape,o);return u.length>0&&(a=mt(a,u)),O(a,n.shape)}}}};var OE={kernelName:qo,saveAllInputs:!0,gradFunc:(r,t)=>{let e={};return t.forEach((n,o)=>{e[o]=()=>r.clone()}),e}};var PE={kernelName:Ko,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>St(e)}}};var ME={kernelName:wl,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>St(e)}}};var LE={kernelName:Ji,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,be(lt(pt(1),Gt(Z(e,"float32")))))}}};var zE={kernelName:Qi,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>{let n=be(J(pt(1),Gt(Z(e,"float32"))));return ct(r,n)}}}};var BE={kernelName:ra,inputsToSave:["a","b"],gradFunc:(r,t)=>{let[e,n]=t,o=Lt(e.shape,n.shape);return{a:()=>{let a=J(Gt(e),Gt(n)),u=P(r,ct(n,a)),l=ge(e.shape,o);return l.length>0&&(u=mt(u,l)),O(u,e.shape)},b:()=>{let a=J(Gt(e),Gt(n)),u=Yt(P(r,ct(e,a))),l=ge(n.shape,o);return l.length>0&&(u=mt(u,l)),O(u,n.shape)}}}};var VE={kernelName:ta,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,J(Gt(Z(e,"float32")),1))}}};var GE={kernelName:ea,inputsToSave:["x"],gradFunc:(r,t)=>{let[e]=t;return{x:()=>ct(r,lt(pt(1),Gt(Z(e,"float32"))))}}};function F5(r,t,e,n,o,s){let i=C(r,"dy","avgPool3dGrad"),a=C(t,"input","avgPool3dGrad"),u=i,l=a,c=!1;a.rank===4&&(c=!0,u=O(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),l=O(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),A(u.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),A(l.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`),ke("avgPool3dGrad",o,s);let p={dy:u,input:l},m={filterSize:e,strides:n,pad:o,dimRoundingMode:s},f=_.runKernel(lp,p,m);return c?O(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}var WE=N({avgPool3dGrad_:F5});var UE={kernelName:vl,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{filterSize:o,strides:s,pad:i,dimRoundingMode:a}=e;return{x:()=>WE(r,n,o,s,i,a)}}};function O5(r,t,e,n,o){let s=C(r,"dy","avgPoolGrad"),i=C(t,"input","avgPoolGrad");A(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let a=i,u=s,l=!1;i.rank===3&&(l=!0,a=O(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=O(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(u.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${u.rank}.`),A(a.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${a.rank}.`);let c={dy:u,input:a},p={filterSize:e,strides:n,pad:o},m=_.runKernel(ap,c,p);return l?O(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var HE=N({avgPoolGrad_:O5});var qE={kernelName:jo,inputsToSave:["x"],gradFunc:(r,t,e)=>{let[n]=t,{filterSize:o,strides:s,pad:i}=e;retu
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=r;if(s.className==null||s.config==null)throw new z(`${n}: Improper config format: ${JSON.stringify(s)}.
'className' and 'config' must set.`);let i=s.className,a,u;if(i in e?[a,u]=e[i]:i in wo?[a,u]=wo.className:i in t&&([a,u]=t[i]),a==null)throw new z(`Unknown ${n}: ${i}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(u!=null){let l={};for(let f of Object.keys(wo))l[f]=wo[f];for(let f of Object.keys(e))l[f]=e[f];let c=s.config;c.customObjects=l;let p=Object.assign({},wo);for(let f of Object.keys(e))wo[f]=e[f];lC(s.config);let m=u(a,s.config,e,o);return wo=Object.assign({},p),m}else{let l=Object.assign({},wo);for(let p of Object.keys(e))wo[p]=e[p];let c=new a(s.config);return wo=Object.assign({},l),c}}}function G5(r,t){return r<t?-1:r>t?1:0}function md(r,t){return-1*G5(r,t)}function Io(r){if(r==null)return r;let t=[];for(let e of r)t.indexOf(e)===-1&&t.push(e);return t}function T2(r){if(r==null)throw new z(`Invalid value in obj: ${JSON.stringify(r)}`);for(let t in r)if(r.hasOwnProperty(t))return!1;return!0}function Li(r,t,e){if(e!=null&&r.indexOf(e)<0)throw new z(`${e} is not a valid ${t}. Valid values are ${r} or null/undefined.`)}function Vx(r,t,e=0,n=1/0){return Zn(e>=0),Zn(n>=e),Array.isArray(r)&&r.length>=e&&r.length<=n&&r.every(o=>typeof o===t)}function Qe(r,t){Array.isArray(r)?(x.assert(r.length>0,()=>`${t} is unexpectedly an empty array.`),r.forEach((e,n)=>Qe(e,`element ${n+1} of ${t}`))):x.assert(Number.isInteger(r)&&r>0,()=>`Expected ${t} to be a positive integer, but got ${_2(r)}.`)}function _2(r){return r===null?"null":Array.isArray(r)?"["+r.map(t=>_2(t)).join(",")+"]":typeof r=="string"?`"${r}"`:`${r}`}function E2(r,t,e){let n=e!=null?e():x.now(),o;return(...i)=>{let a=e!=null?e():x.now();return a-n<t||(n=a,o=r(...i)),o}}function Gx(r){return r==="relu"?"relu":r==="linear"?"linear":r==="elu"?"elu":null}function cC(r,t){return B(()=>be(mt(P(r,r),t,!0)))}var sm=class extends et.Serializable{getConfig(){return{}}},fd=class extends sm{constructor(t){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return B(()=>{let e=cC(t,this.axis),n=br(e,0,this.maxValue);return P(t,ct(n,J(ur(),e)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};fd.className="MaxNorm";et.registerClass(fd);var dd=class extends sm{constructor(t){super();this.defaultAxis=0,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return B(()=>ct(t,J(ur(),cC(t,this.axis))))}getConfig(){return{axis:this.axis}}};dd.className="UnitNorm";et.registerClass(dd);var hd=class extends sm{apply(t){return Tr(t)}};hd.className="NonNeg";et.registerClass(hd);var gd=class extends sm{constructor(t){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=t.minValue!=null?t.minValue:this.defaultMinValue,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.rate=t.rate!=null?t.rate:this.defaultRate,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return B(()=>{let e=cC(t,this.axis),n=J(P(this.rate,br(e,this.minValue,this.maxValue)),P(1-this.rate,e));return P(t,ct(n,J(ur(),e)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};gd.className="MinMaxNorm";et.registerClass(gd);var A2={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function We(r){return om(r)}function D2(r,t={}){return Mi(r,et.SerializationMap.getMap().classNameMap,t,"constraint")}function Ue(r){if(r==null)return null;if(typeof r=="string"){let e={className:r in A2?A2[r]:r,config:{}};return D2(e)}else return r instanceof sm?r:D2(r)}function W5(r){return new fd(r)}function U5(r){return new dd(r)}function H5(){return new hd}function q5(r){return new gd(r)}var J2={};Xt(J2,{constant:()=>tX,glorotNormal:()=>aX,glorotUniform:()=>iX,heNormal:()=>lX,heUniform:()=>uX,identity:()=>oX,leCunNormal:()=>cX,leCunUniform:()=>pX,ones:()=>Q5,orthogonal:()=>mX,randomNormal:()=>rX,randomUniform:()=>eX,truncatedNormal:()=>nX,varianceScaling:()=>sX,zeros:()=>J5});var R2=["channelsFirst","channelsLast"],F2=["nearest","bilinear"],O2=["valid","same","causal"],P2=["max","avg"],M2=["sum","mul","concat","ave"];var im=new Map;function Me(r){Li(R2,"Da
because the value dtype is ${e.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=e.shape),Bn(this.elementShape,e.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${t}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${t}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${t}, because it has already been written.`);n.tensor=e,Pe(e),n.written=!0,this.tensors[t]=n}writeMany(t,e){if(t.length!==e.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${t.length} is not the same as tensors size: ${e.length}.`);t.forEach((n,o)=>this.write(n,e[o]))}gather(t,e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${e}`);if(t)t=t.slice(0,this.size());else{t=[];for(let o=0;o<this.size();o++)t.push(o)}if(t.length===0)return Ar([],[0].concat(this.elementShape));let n=this.readMany(t);return Bn(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Ye(n,0)}concat(t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${t}`);if(this.size()===0)return Ar([],[0].concat(this.elementShape));let e=[];for(let o=0;o<this.size();o++)e.push(o);let n=this.readMany(e);return Bn(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),se(n,0)}scatter(t,e){if(e.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${e.dtype}`);if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let n=Math.max(...t);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(t,vr(e,0))}split(t,e){if(e.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${e.dtype}`);let n=0,o=t.map(u=>(n+=u,n));if(n!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${e.shape}`);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${t.length}), and the TensorArray is not marked as dynamically resizeable`);let s=n===0?0:e.size/n,i=[];B(()=>{e=O(e,[1,n,s]);for(let u=0;u<t.length;++u){let l=u===0?0:o[u-1],c=[0,l,0],p=[1,t[u],s];i[u]=O(Rt(e,c,p),this.elementShape)}return i});let a=[];for(let u=0;u<t.length;u++)a[u]=u;this.writeMany(a,i)}};var vc=class{constructor(t,e,n,o=-1){this.tensors=t,this.elementShape=e,this.elementDtype=n,t!=null&&t.forEach(s=>{if(n!==s.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${s.dtype}`);Bn(e,s.shape,"TensorList shape mismatch: "),Pe(s)}),this.idTensor=pt(0),this.maxNumElements=o,Pe(this.idTensor)}get id(){return this.idTensor.id}copy(){return new vc([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(t){this.tensors.forEach(e=>{(t==null||!t.has(e.id))&&e.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(t,e,n=-1){if(e!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Bn(t,this.elementShape,"TensorList shape mismatch: ");let o=Em(this.elementShape,this.tensors,t);return B(()=>{let s=this.tensors.map(i=>O(i,o));return Ye(s,0)})}popBack(t,e){if(e!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Em(this.elementShape,this.tensors,t),o=this.tensors.pop();return Bn(o.shape,t,"TensorList shape mismatch: "),O(o,n)}pushBack(t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(Bn(t.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Pe(t),this.tensors.push(t)}resize(t){if(t<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${t}`);if(this.maxNumElements!==-1&&t>this.maxNumElements)throw new Error(`TensorListResize input size ${t} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=t}getItem(t,e,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(t<0||t>this.tensors.length)throw new Error(`Trying to access element ${t} in a list with ${this.tensors.length} elements.`);if(this.tensors[t]==null)throw new Error(`element at index ${t} is null.`);Bn(this.tensors[t].shape,e,"TensorList shape mismatch: ");let o=Em(this.elementShape,this.tensors,e);return O(this.tensors[t],o)}setItem(t,e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(t<0||this.maxNumElements!==-1&&t>=this.maxNumElements)throw new Error(`Trying to set element ${t} in a list with max ${this.maxNumElements} elements.`);Bn(this.elementShape,e.shape,"TensorList shape mismatch: "),Pe(e),this.tensors[t]=e}gather(t,e,n){if(e!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e}, but list elements ${this.elementDtype}`);Bn(this.elementShape,n,"TensorList shape mismatch: "),t=t.slice(0,this.size());let o=Em(this.elementShape,this.tensors,n);return t.length===0?Ar([],[0].concat(o)):B(()=>{let s=t.map(i=>O(this.tensors[i],o));return Ye(s,0)})}concat(t,e){if(!!t&&t!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${t}`);Bn(this.elementShape,e,"TensorList shape mismatch: ");let n=Em(this.elementShape,this.tensors,e);return this.size()===0?Ar([],[0].concat(n)):B(()=>{let o=this.tensors.map(s=>O(s,n));return se(o,0)})}};function jD(r,t,e){let n=r.dtype;if(r.shape.length<1)throw new Error(`Tens
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${r.shape}`);let s=r.shape.slice(1),i=Ey(s,e),a=n===0?0:r.size/n,u=B(()=>{let c=[];r=O(r,[1,n,a]);for(let p=0;p<t.length;++p){let m=p===0?0:o[p-1],f=[0,m,0],d=[1,t[p],a];c[p]=O(Rt(r,f,d),i)}return r.dispose(),c}),l=new vc([],e,r.dtype,t.length);for(let c=0;c<u.length;c++)l.setItem(c,u[c]);return l}var JD=async(r,t,e)=>{switch(r.op){case"If":case"StatelessIf":{let n=S("thenBranch",r,t,e),o=S("elseBranch",r,t,e),s=S("cond",r,t,e),i=S("args",r,t,e);return(await s.data())[0]?e.functionMap[n].executeFunctionAsync(i,e.tensorArrayMap,e.tensorListMap):e.functionMap[o].executeFunctionAsync(i,e.tensorArrayMap,e.tensorListMap)}case"While":case"StatelessWhile":{let n=S("body",r,t,e),o=S("cond",r,t,e),s=S("args",r,t,e),i=await e.functionMap[o].executeFunctionAsync(s,e.tensorArrayMap,e.tensorListMap),a=s.map(c=>c.id),u=await i[0].data();i.forEach(c=>{!c.kept&&a.indexOf(c.id)===-1&&c.dispose()});let l=s;for(;u[0];){let c=l;l=await e.functionMap[n].executeFunctionAsync(l,e.tensorArrayMap,e.tensorListMap);let p=l.map(f=>f.id);c.forEach(f=>{!f.kept&&a.indexOf(f.id)===-1&&p.indexOf(f.id)===-1&&f.dispose()});let m=await e.functionMap[o].executeFunctionAsync(l,e.tensorArrayMap,e.tensorListMap);u=await m[0].data(),m.forEach(f=>{!f.kept&&a.indexOf(f.id)===-1&&p.indexOf(f.id)===-1&&f.dispose()})}return l}case"LoopCond":{let n=S("pred",r,t,e);return[ii(n)]}case"Switch":{let n=S("pred",r,t,e),o=S("data",r,t,e);return o.kept||(o=ii(o)),(await n.data())[0]?[void 0,o]:[o,void 0]}case"Merge":{let n=r.inputNames.find(o=>Cr(o,t,e)!==void 0);if(n){let o=Cr(n,t,e);return[ii(o)]}return}case"Enter":{let n=S("frameName",r,t,e),o=S("tensor",r,t,e);return e.enterFrame(n),[ii(o)]}case"Exit":{let n=S("tensor",r,t,e);return e.exitFrame(),[ii(n)]}case"NextIteration":{let n=S("tensor",r,t,e);return e.nextIteration(),[ii(n)]}case"TensorArrayV3":{let n=S("size",r,t,e),o=S("dtype",r,t,e),s=S("elementShape",r,t,e),i=S("dynamicSize",r,t,e),a=S("clearAfterRead",r,t,e),u=S("identicalElementShapes",r,t,e),l=S("name",r,t,e),c=new _I(l,o,n,s,u,i,a);return e.addTensorArray(c),[c.idTensor,pt(1)]}case"TensorArrayWriteV3":{let n=S("tensorArrayId",r,t,e),o=S("index",r,t,e),s=S("tensor",r,t,e),i=e.getTensorArray(n.id);return i.write(o,s),[i.idTensor]}case"TensorArrayReadV3":{let n=S("tensorArrayId",r,t,e),o=S("index",r,t,e);return[e.getTensorArray(n.id).read(o)]}case"TensorArrayGatherV3":{let n=S("tensorArrayId",r,t,e),o=S("indices",r,t,e),s=S("dtype",r,t,e);return[e.getTensorArray(n.id).gather(o,s)]}case"TensorArrayScatterV3":{let n=S("tensorArrayId",r,t,e),o=S("indices",r,t,e),s=S("tensor",r,t,e),i=e.getTensorArray(n.id);return i.scatter(o,s),[i.idTensor]}case"TensorArrayConcatV3":{let n=S("tensorArrayId",r,t,e),o=e.getTensorArray(n.id),s=S("dtype",r,t,e);return[o.concat(s)]}case"TensorArraySplitV3":{let n=S("tensorArrayId",r,t,e),o=S("tensor",r,t,e),s=S("lengths",r,t,e),i=e.getTensorArray(n.id);return i.split(s,o),[i.idTensor]}case"TensorArraySizeV3":{let n=S("tensorArrayId",r,t,e),o=e.getTensorArray(n.id);return[pt(o.size(),"int32")]}case"TensorArrayCloseV3":{let n=S("tensorArrayId",r,t,e),o=e.getTensorArray(n.id);return o.clearAndClose(),[o.idTensor]}case"TensorListSetItem":{let n=S("tensorListId",r,t,e),o=S("index",r,t,e),s=S("tensor",r,t,e),i=e.getTensorList(n.id);return i.setItem(o,s),[i.idTensor]}case"TensorListGetItem":{let n=S("tensorListId",r,t,e),o=S("index",r,t,e),s=S("elementShape",r,t,e),i=S("elementDType",r,t,e);return[e.getTensorList(n.id).getItem(o,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let n=S("indices",r,t,e),o=S("tensor",r,t,e),s=S("elementShape",r,t,e),i=S("numElements",r,t,e),a=YD(o,n,s,i);return e.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let n=S("elementShape",r,t,e),o=S("elementDType",r,t,e),s;r.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=S(s,r,t,e),a=XD(n,o,i);return e.addTensorList(a),[a.idTensor]}case"TensorListGather":{let n=S("tensorListId",r,t,e),o=S("indices",r,t,e),s=S("elementShape",r,t,e),i=S("elementDType",r,t,e);return[e.getTensor
${t}`);let o;return this.size===1/0||this.size==null?o=this.size:e?o=Math.ceil(this.size/t):o=Math.floor(this.size/t),An(async()=>(await n.iterator()).columnMajorBatch(t,e,nZ),o)}concatenate(t){let e=this,n;return this.size===1/0||t.size===1/0?n=1/0:this.size!=null&&t.size!=null?n=this.size+t.size:n=null,An(async()=>(await e.iterator()).concatenate(await t.iterator()),n)}filter(t){let e=this,n;return this.size===1/0?n=1/0:n=null,An(async()=>(await e.iterator()).filter(o=>B(()=>t(o))),n)}async forEachAsync(t){return(await this.iterator()).forEachAsync(t)}map(t){let e=this;return An(async()=>(await e.iterator()).map(n=>B(()=>t(n))),this.size)}mapAsync(t){let e=this;return An(async()=>(await e.iterator()).mapAsync(t),this.size)}prefetch(t){if(t==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let e=this;return An(async()=>(await e.iterator()).prefetch(t),this.size)}repeat(t){let e=this,n;return this.size!=null&&t>0?n=this.size*t:t===0?n=0:this.size!=null&&(t===void 0||t<0)?n=1/0:n=null,An(async()=>{let o=Ph(async()=>({value:await e.iterator(),done:!1}));return z$(o.take(t))},n)}skip(t){let e=this,n;return this.size!=null&&t>=0&&this.size>=t?n=this.size-t:this.size!=null&&(this.size<t||t===void 0||t<0)?n=0:n=null,An(async()=>(await e.iterator()).skip(t),n)}shuffle(t,e,n=!0){if(t==null||t<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let o=this,s=Q$.alea(e||x.now().toString());return An(async()=>{let i=s.int32();return n&&(i+=s.int32()),(await o.iterator()).shuffle(t,i.toString())},this.size)}take(t){let e=this,n;return this.size!=null&&this.size>t?n=t:this.size!=null&&this.size<=t?n=this.size:n=null,An(async()=>(await e.iterator()).take(t),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};Gi.MAX_BUFFER_SIZE=1e4;function An(r,t=null){return new class extends Gi{constructor(){super(...arguments);this.size=t}async iterator(){return r()}}}function tR(r){return An(async()=>qI(r),r.length)}function eR(r){if(!eu(r))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(r))for(let e=0;e<r.length;e++)t=t==null?r[e].size:Math.min(t,r[e].size);else if(r instanceof Object)for(let e in r)t=t==null?r[e].size:Math.min(t,r[e].size);return An(async()=>{let e=await Ry(r,n=>{if(n instanceof Gi)return{value:n.iterator(),recurse:!1};if(eu(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return B$(e,il.SHORTEST)},t)}function nZ(r){if(r===null)return null;let t=r[0];return P$(t)?{value:oZ(r),recurse:!1}:{value:null,recurse:!0}}function oZ(r){if(r.length===0)throw new Error("Can't make a batch of zero elements.");return r[0]instanceof Bt?Ye(r):Ar(r)}var Mh=class extends Gi{constructor(t){super();this.input=t}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
`).map(o=>(o.endsWith("\r")&&(o=o.slice(0,-1)),o))}};var Fy='"',Lh=Symbol("out"),rR=Symbol("field"),Oy=Symbol("quote"),XI=Symbol("quoteafterquote"),nR=Symbol("quoteinquote"),zh=class extends Gi{constructor(t,e){super();this.input=t,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new Mh(t),e||(e={}),this.hasHeader=e.hasHeader!==!1,this.fullColumnNames=e.columnNames,this.columnConfigs=e.columnConfigs,this.configuredColumnsOnly=e.configuredColumnsOnly,e.delimWhitespace?(x.assert(e.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=e.delimiter?e.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let t=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!t)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&t&&x.assert(t.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+t.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=t);let e=this.fullColumnNames.reduce((o,s)=>(o[s]=o[s]+1||1,o),{}),n=Object.keys(e).filter(o=>e[o]>1);if(x.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let o of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(o)===-1)throw new Error('The key "'+o+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let e=await(await this.base.iterator()).next();if(e.done)throw new Error("No data was found for CSV parsing.");let n=e.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let t=await this.base.iterator();return this.hasHeader&&(t=t.skip(1)),t.map(e=>this.makeDataElement(e))}makeDataElement(t){let e=this.parseRow(t),n={},o={};for(let s=0;s<this.fullColumnNames.length;s++){let i=this.fullColumnNames[s],a=this.columnConfigs?this.columnConfigs[i]:null;if(!(this.configuredColumnsOnly&&!a)){let u=e[s],l=null;if(u==="")if(a&&a.default!==void 0)l=a.default;else{if(a&&(a.required||a.isLabel))throw new Error(`Required column ${i} is empty in this line: ${t}`);l=void 0}else{let c=Number(u);if(isNaN(c))a&&a.dtype==="bool"?l=this.getBoolean(u):l=u;else if(!a||!a.dtype)l=c;else switch(a.dtype){case"float32":l=c;break;case"int32":l=Math.floor(c);break;case"bool":l=this.getBoolean(u);break;default:l=c}}a&&a.isLabel?o[i]=l:n[i]=l}}return Object.keys(o).length===0?n:{xs:n,ys:o}}getBoolean(t){return t==="1"||t.toLowerCase()==="true"?1:0}parseRow(t,e=!0){let n=[],o=0,s=t.length,i=Lh;for(let a=0;a<s;a++)switch(i){case Lh:switch(t.charAt(a)){case Fy:o=a+1,i=Oy;break;case this.delimiter:if(o=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),i=Lh;break;default:i=rR,o=a;break}break;case rR:switch(t.charAt(a)){case this.delimiter:n.push(t.substring(o,a)),i=Lh,o=a+1;break;default:}break;case Oy:switch(t.charAt(a)){case Fy:i=XI;break;default:}break;case XI:switch(t.charAt(a)){case this.delimiter:n.push(t.substring(o,a-1)),i=Lh,o=a+1;break;case Fy:i=Oy;break;default:i=nR;break}break;case nR:switch(t.charAt(a)){case Fy:i=Oy;break;default:}break;default:}if(i===XI?n.push(t.substring(o,s-1)):n.push(t.substring(o)),e&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}};var Bh=class extends sr{constructor(t){super();this.microphoneConfig=t,this.isClosed=!1,this.fftSize=t.fftSize||1024;let e=Math.log2(this.fftSize);if(this.fftSize<0||e<4||e>14||!Number.isInteger(e))throw new Error(`Inval
============================
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
============================`));let o={id:this.nextDataId()};return this.data.set(o,{values:t,dtype:n,refCount:1}),o}makeTensorInfo(t,e,n){let o;if(e==="string"&&n!=null&&n.length>0&&x.isString(n[0])){let s=n.map(i=>x.encodeString(i));o=this.write(s,t,e)}else o=this.write(n,t,e);return{dataId:o,shape:t,dtype:e}}refCount(t){return this.data.has(t)?this.data.get(t).refCount:0}incRef(t){let e=this.data.get(t);e.refCount++}decRef(t){if(this.data.has(t)){let e=this.data.get(t);e.refCount--}}move(t,e,n,o,s){this.data.set(t,{values:e,dtype:o,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(t){return this.readSync(t)}readSync(t){let{dtype:e,complexTensorInfos:n}=this.data.get(t);if(e==="complex64"){let o=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return k.mergeRealAndImagArrays(o,s)}return this.data.get(t).values}bufferSync(t){let e=this.readSync(t.dataId),n=e;if(t.dtype==="string")try{n=e.map(o=>x.decodeString(o))}catch(o){throw new Error("Failed to decode encoded string bytes into utf-8")}return It(t.shape,t.dtype,n)}makeOutput(t,e,n){let o=this.write(t,e,n);return po().makeTensorFromDataId(o,e,n,this)}disposeData(t,e=!1){if(this.data.has(t)){if(this.data.get(t).refCount--,!e&&this.data.get(t).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(t);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(t)}return!0}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}async time(t){let e=x.now();return t(),{kernelMs:x.now()-e}}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(t){ot([t],"where");let e=this.readSync(t.dataId);return iZ(t.shape,e)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Ic.nextDataId=0;var Qy={};Xt(Qy,{addImpl:()=>QI,bincountImpl:()=>Om,bincountReduceImpl:()=>zy,ceilImpl:()=>tS,concatImpl:()=>Sc,equalImpl:()=>eS,expImpl:()=>nS,expm1Impl:()=>sS,floorImpl:()=>iS,gatherNdImpl:()=>By,gatherV2Impl:()=>Vy,greaterEqualImpl:()=>lS,greaterImpl:()=>aS,lessEqualImpl:()=>cS,lessImpl:()=>uS,linSpaceImpl:()=>Gy,logImpl:()=>pS,maxImpl:()=>Wy,maximumImpl:()=>mS,minimumImpl:()=>fS,multiplyImpl:()=>qh,negImpl:()=>dS,notEqualImpl:()=>hS,prodImpl:()=>gS,rangeImpl:()=>Nc,rsqrtImpl:()=>xS,sigmoidImpl:()=>zR,simpleAbsImpl:()=>JI,sliceImpl:()=>Tc,sparseFillEmptyRowsImpl:()=>Uy,sparseReshapeImpl:()=>Hy,sparseSegmentReductionImpl:()=>Mm,sqrtImpl:()=>GR,squaredDifferenceImpl:()=>bS,stridedSliceImpl:()=>qy,stringNGramsImpl:()=>Ky,stringSplitImpl:()=>jy,stringToHashBucketFastImpl:()=>Xy,subImpl:()=>wS,tileImpl:()=>Yy,topKImpl:()=>Zy,transposeImpl:()=>Pm,uniqueImpl:()=>Jy});function JI(r){let t=new Float32Array(r.length);for(let e=0;e<r.length;++e)t[e]=Math.abs(r[e]);return t}var aZ=r=>{let{x:t}=r.inputs,e=r.backend;ot(t,"abs");let n=new Float32Array(x.sizeFromShape(t.shape)),o=e.data.get(t.dataId).values;return n=JI(o),e.makeOutput(n,t.shape,t.dtype)},hR={kernelName:di,backendName:"cpu",kernelFunc:aZ};function te(r){return(t,e,n,o,s)=>{let i=k.assertAndGetBroadcastShape(t,e),a=i.length,u=x.computeStrides(i),l=x.sizeFromShape(i),c=x.getTypedArrayFromDType(s,l),p=t.length,m=e.length,f=x.computeStrides(t),d=x.computeStrides(e),h=k.getBroadcastDims(t,i),g=k.getBroadcastDims(e,i);if(h.length+g.length===0)for(let y=0;y<c.length;++y)c[y]=r(n[y%n.length],o[y%o.length]);else for(let y=0;y<c.length;++y){let b=x.indexToLoc(y,a,u),w=b.slice(-p);h.forEach(D=>w[D]=0);let v=x.locToIndex(w,p,f),I=b.slice(-m);g.forEach(D=>I[D]=0);let E=x.locToIndex(I,m,d);c[y]=r(n[v],o[E])}return[c,i]}}function Ir(r){let{inputs:t,backend:e}=r,{real:n,imag:o}=t,s=e.data.get(n.dataId).values,i=e.data.get(o.dataId).values,a=e.makeTensorInfo(n.shape,"complex64"),u=e.data.get(a.dataId);return u.complexTensorInfos={real:e.makeTensorInfo(n.shape,"float32",s),imag:e.makeTensorInfo(o.shape,"float32",i)},a}var gR={kernelName:pp,backendName:"cpu",kernelFunc:Ir};function Rm(r,t,e="float32"){if(e==="complex64"){let o=Rm(r,t,"float32"),s=Rm(r,t,"float32")
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${n.shape}`);if(o.shape.length!==1)throw new Error(`Values must be a vector, saw:
${o.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${i.shape}`);let a=e.data.get(n.dataId).values,u=e.data.get(o.dataId).values,l=e.data.get(s.dataId).values,c=e.data.get(i.dataId).values[0],[p,m,f,d,h]=Uy(a,n.shape,n.dtype,u,o.dtype,l,c);return[e.makeTensorInfo(m,n.dtype,p),e.makeTensorInfo([m[0]],o.dtype,f),e.makeTensorInfo([d.length],"bool",new Uint8Array(d.map(g=>Number(g)))),e.makeTensorInfo([h.length],n.dtype,new Int32Array(h))]}var nP={kernelName:Al,backendName:"cpu",kernelFunc:RJ};function FJ(r){let{inputs:t,backend:e}=r,{inputIndices:n,inputShape:o,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
${n.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
${o.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(e.data.get(o.dataId).values),a=e.data.get(n.dataId).values,u=Array.from(e.data.get(s.dataId).values),[l,c,p]=Hy(a,n.shape,n.dtype,i,u);return[e.makeTensorInfo(c,n.dtype,l),e.makeTensorInfo([p.length],s.dtype,new Int32Array(p))]}var oP={kernelName:Aa,backendName:"cpu",kernelFunc:FJ};function OJ(r){let{inputs:t,backend:e}=r,{data:n,indices:o,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);if(o.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=e.data.get(n.dataId).values,a=e.data.get(o.dataId).values,u=e.data.get(s.dataId).values,[l,c]=Mm(i,n.shape,n.dtype,a,u,!0);return e.makeTensorInfo(c,n.dtype,l)}var sP={kernelName:Dl,backendName:"cpu",kernelFunc:OJ};function PJ(r){let{inputs:t,backend:e}=r,{data:n,indices:o,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);if(o.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=e.data.get(n.dataId).values,a=e.data.get(o.dataId).values,u=e.data.get(s.dataId).values,[l,c]=Mm(i,n.shape,n.dtype,a,u);return e.makeTensorInfo(c,n.dtype,l)}var iP={kernelName:$l,backendName:"cpu",kernelFunc:PJ};function MJ(r){let{inputs:t,backend:e,attrs:n}=r,{sparseIndices:o,sparseValues:s,defaultValue:i}=t,{outputShape:a}=n,{sliceRank:u,numUpdates:l,sliceSize:c,strides:p,outputSize:m}=k.calculateShapes(s,o,a),f=!1,d=e.bufferSync(o),h=e.bufferSync(s),g=e.data.get(i.dataId).values[0],y=ob(d,h,a,m,c,l,u,p,g,f);return e.makeTensorInfo(a,y.dtype,y.values)}var aP={kernelName:Rp,backendName:"cpu",kernelFunc:MJ};function LJ(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{numOrSizeSplits:s,axis:i}=n,a=x.parseAxisParam(i,o.shape)[0],u=k.prepareSplitSize(o,s,a),l=new Array(o.shape.length).fill(0),c=o.shape.slice();return u.map(p=>{let m=[...c];m[a]=p;let f=Do({inputs:{x:o},backend:e,attrs:{begin:l,size:m}});return l[a]+=p,f})}var lP={kernelName:Ni,backendName:"cpu",kernelFunc:LJ};var uP={kernelName:Rl,backendName:"cpu",kernelFunc:({inputs:r,backend:t})=>{let{x:e}=r,n=t;ot(e,"square");let o=n.data.get(e.dataId).values,s=new Float32Array(o.length);for(let a=0;a<o.length;++a){let u=o[a];s[a]=u*u}return{dataId:n.write(s,e.shape,e.dtype),shape:e.shape,dtype:e.dtype}}};var zJ=Et(io,(r,t)=>{let e=t;return isNaN(r)?NaN:r>0?1:e.alpha}),cP={kernelName:io,backendName:"cpu",kernelFunc:zJ};function BJ(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{begin:s,end:i,strides:a,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=n;ot(o,"stridedSlice");let{finalShapeSparse:f,finalShape:d,isIdentity:h,sliceDim0:g,isSimpleSlice:y,begin:b,end:w,strides:v}=Ve.sliceInfo(o.shape,s,i,a,u,l,c,p,m),I;if(h)I=ne({inputs:{x:o},backend:e,attrs:{shape:d}});else if(g||y){x.assert(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);let E=Ve.computeOutShape(b,w,v),D=Do({inputs:{x:o},backend:e,attrs:{begin:b,size:E}});I=ne({inputs:{x:D},backend:e,attrs:{shape:d}}),e.disposeIntermediateTensorInfo(D)}else{let E=e.bufferSync(o),D=qy(f,E,v,b);I=e.makeTensorInfo(d,D.dtype,D.values)}return I}var pP={kernelName:Da,backendName:"cpu",kernelFunc:BJ};function VJ(r){let{inputs:t,backend:e,attrs:n}=r,{separator:o,nGramWidths:s,leftPad:i,rightPad:a,padWidth:u,preserveShortSequences:l}=n,{data:c,dataSplits:p}=t,m=e.data.get(c.dataId).values,f=e.data.get(p.dataId).values,[d,h]=Ky(m,f,o,s,i,a,u,l);return[e.makeTensorInfo([d.length],"string",d),e.makeTensorInfo(p.shape,"int32",h)]}var mP={kernelName:Fp,backendName:"cpu",kernelFunc:VJ};function GJ(r){let{inputs:t,backend:e,attrs:n}=r,{skipEmpty:o}=n,{input:s,delimiter:i}=t;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(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let a=e.data.get(s.dataId).values,u=e.data.get(i.dataId).values[0],[l,c,p]=jy(a,u,o),m=c.length;return[e.makeTensorInfo([m,2],"int32",l),e.makeTensorInfo([m],"string",c),e.makeTensorInfo([2],"int32",new Int32Array(p))]}var fP={kernelName:Op,backendName:"cpu",kernelFunc:GJ};function WJ(r){let{inputs:t,backend:e,attrs:n}=r,{numBuckets:o}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");let i=e.data.get(s.dataId).values,a=Xy(i,o);return e.makeTensorInfo(s.shape,"int32",a)}var dP={kernelName:Pp,backendName:"cpu",kernelFunc:WJ};var UJ=Et(Ms,r=>Math.tan(r)),hP={kernelName:Ms,backendName:"cpu",kernelFunc:UJ};var HJ=Et(Ls,r=>Math.tanh(r)),gP={kernelName:Ls,backendName:"cpu",kernelFunc:HJ};function qJ(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{reps:s}=n;ot(o,"tile");let i=Yy(e.bufferSync(o),s);return e.makeTensorInfo(i.shape,i.dtype,i.values)}var xP={kernelName:jn,backendName:"cpu",kernelFunc:qJ};function KJ(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{k:s,sorted
`),s=o.length.toString().length+2,i=o.map((p,m)=>x.rightPad((m+1).toString(),s)+p),a=0;for(let p=0;p<i.length;p++)a=Math.max(i[p].length,a);let u=i.slice(0,n-1),l=i.slice(n-1,n),c=i.slice(n);console.log(u.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${x.rightPad(l[0],a)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join(`
`))}function BS(r){return ul(r,()=>r.createProgram(),"Unable to create WebGLProgram.")}function VS(r,t){if(vt(r,()=>r.linkProgram(t)),r.getProgramParameter(t,r.LINK_STATUS)===!1)throw console.log(r.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function rg(r,t){if(vt(r,()=>r.validateProgram(t)),r.getProgramParameter(t,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function GS(r,t){let e=ul(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return vt(r,()=>r.bindBuffer(r.ARRAY_BUFFER,e)),vt(r,()=>r.bufferData(r.ARRAY_BUFFER,t,r.STATIC_DRAW)),e}function WS(r,t){let e=ul(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return vt(r,()=>r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e)),vt(r,()=>r.bufferData(r.ELEMENT_ARRAY_BUFFER,t,r.STATIC_DRAW)),e}function mQ(){return G().getNumber("WEBGL_VERSION")===2?1:4}function US(r){return ul(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function HS(r,t){let e=G().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(r<=0||t<=0){let n=`[${r}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(r>e||t>e){let n=`[${r}x${t}]`,o=`[${e}x${e}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+o+".")}}function qS(r){return ul(r,()=>r.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function lb(r,t,e,n,o,s,i){let a=r.getAttribLocation(t,e);return a===-1?!1:(vt(r,()=>r.bindBuffer(r.ARRAY_BUFFER,n)),vt(r,()=>r.vertexAttribPointer(a,o,r.FLOAT,!1,s,i)),vt(r,()=>r.enableVertexAttribArray(a)),!0)}function TP(r,t,e){EP(r,e),vt(r,()=>r.activeTexture(r.TEXTURE0+e)),vt(r,()=>r.bindTexture(r.TEXTURE_2D,t))}function fQ(r,t){EP(r,t),vt(r,()=>r.activeTexture(r.TEXTURE0+t)),vt(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function KS(r,t,e){return ul(r,()=>r.getUniformLocation(t,e),'uniform "'+e+'" not present in program.')}function jS(r,t,e){return r.getUniformLocation(t,e)}function XS(r,t,e,n){vt(r,()=>TP(r,t,n)),vt(r,()=>r.uniform1i(e,n))}function dQ(r){vt(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,null)),vt(r,()=>r.viewport(0,0,r.canvas.width,r.canvas.height)),vt(r,()=>r.scissor(0,0,r.canvas.width,r.canvas.height))}function ng(r,t,e){vt(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,e)),vt(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t,0))}function ub(r,t){vt(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,t)),vt(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0))}function Gm(r){let t=r.checkFramebufferStatus(r.FRAMEBUFFER);if(t!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+_P(r,t))}function _P(r,t){switch(t){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 ${t}`}}function ul(r,t,e){let n=vt(r,()=>t());if(n==null)throw new Error(e);return n}function EP(r,t){let e=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+r.TEXTURE0;if(n<r.TEXTURE0||n>e){let o=`[gl.TEXTURE0, gl.TEXTURE${e}]`;throw new Error(`textureUnit must be in ${o}.`)}}function cl(r,t=2){return x.sizeFromShape(r.slice(0,r.length-t))}function pl(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 og(r){let t=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(t=[cl(r),...pl(r)]),t}function YS(r,t=!1){let e=G().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(e=e*2,r=r.map((o,s)=>s>=r.length-2?x.nearestLargerEven(r[s]):r[s]),r.length===1&&(r=[2,r[0]])),r.length!==2&&(r=x.squeezeShape(r).newShape);let n=x.sizeFromShape(r);if(r.length<=1&&n<=e)return[1,n];if(r.length===2&&r[0]<=e&&r[1]<=e)return r;if(r.length===3&&r[0]*r[1]<=e&&r[2]<=e)return[r[0]*r[1],r[2]];if(r.length===3&&r[0]<=e&&r[1]*r[2]<=e)return[r[0],r[1]*r[2]];if(r.length===4&&r[0]*r[1]
bool isnan_custom(float val) {
uint floatToUint = floatBitsToUint(val);
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
#define isnan(value) isnan_custom(value)
`,u="",l=`
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
`):(r="",t="attribute",e="varying",n="varying",o="texture2D",s="gl_FragColor",i="",a=`
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
`,u=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
`,l=`
int round(float value) {
return int(floor(value + 0.5));
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
`),{version:r,attribute:t,varyingVs:e,varyingFs:n,texture2D:o,output:s,defineOutput:i,defineSpecialNaN:a,defineSpecialInf:u,defineRound:l}}function li(r,t,e="index"){let n=x.computeStrides(t);return n.map((o,s)=>{let i=`int ${r[s]} = ${e} / ${o}`,a=s===n.length-1?`int ${r[s+1]} = ${e} - ${r[s]} * ${o}`:`index -= ${r[s]} * ${o}`;return`${i}; ${a};`}).join("")}function Ac(r,t,e="index"){let n=x.computeStrides(t);return n.map((o,s)=>{let i=`int ${r[s]} = ${e} / outShapeStrides[${s}]`,a=s===n.length-1?`int ${r[s+1]} = ${e} - ${r[s]} * outShapeStrides[${s}]`:`index -= ${r[s]} * outShapeStrides[${s}]`;return`${i}; ${a};`}).join("")}function yQ(r,t){let e=r.length,n=r.map(s=>`${t}[${s}]`),o=new Array(e-1);o[e-2]=n[e-1];for(let s=e-3;s>=0;--s)o[s]=`(${o[s+1]} * ${n[s+1]})`;return o}function AP(r,t,e="index"){let n=r.map((s,i)=>i),o=yQ(n,t);return o.map((s,i)=>{let a=`int ${r[i]} = ${e} / ${o[i]}`,u=i===o.length-1?`int ${r[i+1]} = ${e} - ${r[i]} * ${o[i]}`:`index -= ${r[i]} * ${o[i]}`;return`${a}; ${u};`}).join("")}function Um(r){let t=x.computeStrides(r).map(e=>e.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}function Hm(){return`
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
`}var pb=`
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:DP}=k;function $P(r,t,e){let n=[];if(r.forEach(f=>{let d=x.sizeFromShape(f.shapeInfo.logicalShape);if(f.shapeInfo.isUniform?n.push(`uniform float ${f.name}${d>1?`[${d}]`:""};`):(n.push(`uniform sampler2D ${f.name};`),n.push(`uniform int offset${f.name};`)),e.enableShapeUniforms){let{uniformShape:h}=mb(e.packedInputs,f.shapeInfo.logicalShape,f.shapeInfo.texShape);switch(h.length){case 1:n.push(`uniform int ${f.name}Shape;`);break;case 2:n.push(`uniform ivec2 ${f.name}Shape;`);break;case 3:n.push(`uniform ivec3 ${f.name}Shape;`);break;case 4:n.push(`uniform ivec4 ${f.name}Shape;`);break;default:break}n.push(`uniform ivec2 ${f.name}TexShape;`)}}),e.enableShapeUniforms){switch(t.logicalShape.length){case 1:n.push("uniform int outShape;");break;case 2:n.push("uniform ivec2 outShape;"),n.push("uniform int outShapeStrides;");break;case 3:n.push("uniform ivec3 outShape;"),n.push("uniform ivec2 outShapeStrides;");break;case 4:n.push("uniform ivec4 outShape;"),n.push("uniform ivec3 outShapeStrides;");break;default:break}n.push("uniform ivec2 outTexShape;")}e.customUniforms&&e.customUniforms.forEach(f=>{n.push(`uniform ${f.type} ${f.name}${f.arrayIndex?`[${f.arrayIndex}]`:""};`)});let o=n.join(`
`),s=r.map(f=>bQ(f,t,e.packedInputs,e.enableShapeUniforms)).join(`
`),i=t.texShape,a=He(),u=CQ(a),l,c,p=kQ(a);return t.isPacked?(l=wQ(t.logicalShape,i,e.enableShapeUniforms),c=SQ(a)):(l=vQ(t.logicalShape,i,e.enableShapeUniforms),c=IQ(a)),e.packedInputs&&(p+=EQ),[p,u,c,o,l,s,e.userCode].join(`
`)}function Km(r,t=!1){let e=r.shapeInfo.logicalShape;switch(e.length){case 0:return VQ(r,t);case 1:return WQ(r,t);case 2:return HQ(r,t);case 3:return KQ(r,t);case 4:return XQ(r,t);case 5:return YQ(r);case 6:return ZQ(r);default:throw new Error(`${e.length}-D input sampling is not yet supported`)}}function RP(r,t){switch(r.shapeInfo.logicalShape.length){case 0:return BQ(r);case 1:return GQ(r,t);case 2:return UQ(r,t);case 3:return qQ(r,t);default:return jQ(r,t)}}function bQ(r,t,e=!1,n){let o="";e?o+=RP(r,n):o+=Km(r,n);let s=r.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(e?o+=JQ(r,t):o+=QQ(r,t)),o}function wQ(r,t,e){switch(r.length){case 0:return FP();case 1:return AQ(r,t,e);case 2:return LQ(r,t,e);case 3:return $Q(r,t,e);default:return FQ(r,t,e)}}function vQ(r,t,e){switch(r.length){case 0:return FP();case 1:return DQ(r,t,e);case 2:return zQ(r,t,e);case 3:return RQ(r,t,e);case 4:return OQ(r,t,e);case 5:return PQ(r,t);case 6:return MQ(r,t);default:throw new Error(`${r.length}-D output sampling is not yet supported`)}}function CQ(r){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${r.texture2D}(textureSampler, uv).r;
}
`}function IQ(r){return`
void setOutput(float val) {
${r.output} = vec4(val, 0, 0, 0);
}
`}function SQ(r){return`
void setOutput(vec4 val) {
${r.output} = val;
}
`}function kQ(r){return`${r.version}
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;
2021-06-04 14:54:48 +02:00
};
2022-03-07 19:17:31 +01:00
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
2021-06-04 14:54:48 +02:00
};
2022-03-07 19:17:31 +01:00
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;
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
return res;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
//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);
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${NQ}
${TQ}
${_Q}
`}var NQ=`
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);
}
`,TQ=`
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);
}
`,_Q=`
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);
}
`,EQ=`
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);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`;function FP(){return`
int getOutputCoords() {
return 0;
}
`}function AQ(r,t,e){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?e?`
int getOutputCoords() {
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
2021-03-26 15:26:02 +01:00
}
2022-03-07 19:17:31 +01:00
`:`
int getOutputCoords() {
return 2 * int(resultUV.x * ${n[1]}.0);
}
2022-03-07 19:17:31 +01:00
`:n[1]===1?e?`
int getOutputCoords() {
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
int getOutputCoords() {
return 2 * int(resultUV.y * ${n[0]}.0);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:e?`
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(${n[0]}, ${n[1]}));
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
}
`}function DQ(r,t,e){return t[0]===1?e?`
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`:t[1]===1?e?`
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
2020-12-15 14:15:43 +01:00
}
2022-03-07 19:17:31 +01:00
`:`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:e?`
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(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
`}function $Q(r,t,e){if(e)return`
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 n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],o=Math.ceil(r[2]/2),s=o*Math.ceil(r[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${o});
int c = imod(index, ${o}) * 2;
return ivec3(b, r, c);
}
`}function RQ(r,t,e){if(e)return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${Ac(["r","c","d"],r)}
return ivec3(r, c, d);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`;let n=li(["r","c","d"],r);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
return ivec3(r, c, d);
}
`}function FQ(r,t,e){if(e)return`
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 n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],o=Math.ceil(r[r.length-1]/2),s=o*Math.ceil(r[r.length-2]/2),i=s,a="",u="b, r, c";for(let l=2;l<r.length-1;l++)i*=r[r.length-l-1],a=`
int b${l} = index / ${i};
index -= b${l} * ${i};
`+a,u=`b${l}, `+u;return`
ivec${r.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
${a}
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${o});
int c = imod(index, ${o}) * 2;
return ivec${r.length}(${u});
}
`}function OQ(r,t,e){if(e)return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${Ac(["r","c","d","d2"],r)}
return ivec4(r, c, d, d2);
}
`;let n=li(["r","c","d","d2"],r);return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
return ivec4(r, c, d, d2);
}
`}function PQ(r,t){let e=li(["r","c","d","d2","d3"],r);return`
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${e}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`}function MQ(r,t){let e=li(["r","c","d","d2","d3","d4"],r);return`
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${e}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function LQ(r,t,e){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(x.arraysEqual(r,t))return e?`
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]));
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`;let o=Math.ceil(r[1]/2);return e?`
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(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int r = 2 * (index / ${o});
int c = imod(index, ${o}) * 2;
return ivec2(r, c);
}
`}function zQ(r,t,e){return x.arraysEqual(r,t)?e?`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:r[1]===1?e?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:r[0]===1?e?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:e?`
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(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${r[1]};
int c = index - r * ${r[1]};
return ivec2(r, c);
}
`}function Dc(r){return`offset${r}`}function BQ(r){let t=r.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),n=He();return`
vec4 ${e}() {
return ${n.texture2D}(${t}, halfCR);
}
`}function VQ(r,t){let e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`float ${n}() {return ${e};}`;let[o,s]=r.shapeInfo.texShape;if(o===1&&s===1)return`
float ${n}() {
return sampleTexture(${e}, halfCR);
2021-03-26 15:26:02 +01:00
}
2022-03-07 19:17:31 +01:00
`;let i=Dc(e);if(t)return`
float ${n}() {
vec2 uv = uvFromFlat(${e}TexShape[0], ${e}TexShape[1], ${i});
return sampleTexture(${e}, uv);
}
`;let[a,u]=r.shapeInfo.texShape;return`
float ${n}() {
vec2 uv = uvFromFlat(${a}, ${u}, ${i});
return sampleTexture(${e}, uv);
}
`}function GQ(r,t){let e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),o=r.shapeInfo.texShape,s=He();if(t)return`
vec4 ${n}(int index) {
ivec2 packedTexShape = ivec2(ceil(float(${e}TexShape[0]) / 2.0), ceil(float(${e}TexShape[1]) / 2.0));
vec2 uv = packedUVfrom1D(
packedTexShape[0], packedTexShape[1], index);
return ${s.texture2D}(${e}, uv);
}
`;let i=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];return`
vec4 ${n}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${s.texture2D}(${e}, uv);
}
`}function WQ(r,t){let e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`
float ${n}(int index) {
${jm(r)}
}
`;let o=r.shapeInfo.texShape,s=o[0],i=o[1];if(i===1&&s===1)return`
float ${n}(int index) {
return sampleTexture(${e}, halfCR);
}
`;let a=Dc(e);return i===1?t?`
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / float(${e}TexShape[0]));
return sampleTexture(${e}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${s}.0);
return sampleTexture(${e}, uv);
}
`:s===1?t?`
float ${n}(int index) {
vec2 uv = vec2((float(index + ${a}) + 0.5) / float(${e}TexShape[1]), 0.5);
return sampleTexture(${e}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = vec2((float(index + ${a}) + 0.5) / ${i}.0, 0.5);
return sampleTexture(${e}, uv);
}
`:t?`
float ${n}(int index) {
vec2 uv = uvFromFlat(${e}TexShape[0], ${e}TexShape[1], index + ${a});
return sampleTexture(${e}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = uvFromFlat(${s}, ${i}, index + ${a});
return sampleTexture(${e}, uv);
}
`}function UQ(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r.shapeInfo.texShape,i=s[0],a=s[1],u=He();if(s!=null&&x.arraysEqual(e,s))return t?`
vec4 ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return ${u.texture2D}(${n}, uv);
}
`:`
vec4 ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${i}.0);
return ${u.texture2D}(${n}, uv);
}
`;if(t)return`
vec4 ${o}(int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${n}Shape[1]) / 2.0));
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
return ${u.texture2D}(${n}, uv);
}
`;let l=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],c=Math.ceil(e[1]/2);return`
vec4 ${o}(int row, int col) {
vec2 uv = packedUVfrom2D(${c}, ${l[0]}, ${l[1]}, row, col);
return ${u.texture2D}(${n}, uv);
}
`}function HQ(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r.shapeInfo.texShape;if(s!=null&&x.arraysEqual(e,s)){if(t)return`
float ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`;let m=s[0],f=s[1];return`
float ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${f}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
`}let{newShape:i,keptDims:a}=x.squeezeShape(e),u=i;if(u.length<e.length){let m=Xm(r,u),f=["row","col"];return`
${Km(m,t)}
float ${o}(int row, int col) {
return ${o}(${Ym(f,a)});
}
`}if(r.shapeInfo.isUniform)return`
float ${o}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${e[1]}, 1)));
${jm(r)}
}
`;let l=s[0],c=s[1],p=Dc(n);return c===1?t?`
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${n}Shape[1], 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / float(${n}TexShape[0]));
return sampleTexture(${n}, uv);
}
`:`
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${e[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
return sampleTexture(${n}, uv);
}
`:l===1?t?`
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${n}Shape[1], 1, 1));
vec2 uv = vec2((index + 0.5) / float(${n}TexShape[1]), 0.5);
return sampleTexture(${n}, uv);
}
`:`
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${e[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
return sampleTexture(${n}, uv);
}
`:t?`
float ${o}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${n}Shape[1] + col + ${p};
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
float ${o}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${e[1]} + col + ${p};
vec2 uv = uvFromFlat(${l}, ${c}, index);
return sampleTexture(${n}, uv);
}
`}function qQ(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(e[0]===1){let m=e.slice(1),f=[1,2],d=Xm(r,m),h=["b","row","col"];return`
${RP(d,t)}
vec4 ${o}(int b, int row, int col) {
return ${o}(${Ym(h,f)});
}
`}let a=He();if(t)return`
vec4 ${o}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${n}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${a.texture2D}(${n}, uv);
}
`;let u=i[0],l=i[1],c=Math.ceil(e[2]/2),p=c*Math.ceil(e[1]/2);return`
vec4 ${o}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${u}, ${l}, ${p}, ${c}, b, row, col);
return ${a.texture2D}(${n}, uv);
}
`}function KQ(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e[1]*e[2],i=e[2],{newShape:a,keptDims:u}=x.squeezeShape(e),l=a;if(l.length<e.length){let h=Xm(r,l),g=["row","col","depth"];return`
${Km(h,t)}
float ${o}(int row, int col, int depth) {
return ${o}(${Ym(g,u)});
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`}if(r.shapeInfo.isUniform)return`
float ${o}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${s}, ${i}, 1)));
${jm(r)}
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`;let c=r.shapeInfo.texShape,p=c[0],m=c[1],f=r.shapeInfo.flatOffset;if(m===s&&f==null)return t?`
float ${o}(int row, int col, int depth) {
int stride1 = ${n}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
float ${o}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${m}.0, ${p}.0);
return sampleTexture(${n}, uv);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`;if(m===i&&f==null)return t?`
float ${o}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${n}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
float ${o}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${e[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${m}.0, ${p}.0);
return sampleTexture(${n}, uv);
}
`;let d=Dc(n);return t?`
float ${o}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = ${n}Shape[1] * ${n}Shape[2];
int stride1 = ${n}Shape[2];
int index = row * ${s} + col * ${i} + depth + ${d};
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
return sampleTexture(${n}, uv);
}
`:`
float ${o}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${s} + col * ${i} + depth + ${d};
vec2 uv = uvFromFlat(${p}, ${m}, index);
return sampleTexture(${n}, uv);
}
`}function jQ(r,t){let e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),o=He();if(t)return`
vec4 ${n}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${e}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${e}Shape[2]) / 2.0));
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${e}Shape[1];
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${e}TexShape[0]) / 2.0), ceil(float(${e}TexShape[1]) / 2.0));
int texR = index / packedTexShape[1];
int texC = index - texR * packedTexShape[1];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${o.texture2D}(${e}, uv);
}
`;let s=r.shapeInfo.logicalShape,i=s.length,a=r.shapeInfo.texShape,u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],l=u[0],c=u[1],p=Math.ceil(s[i-1]/2),m=p*Math.ceil(s[i-2]/2),f="int b, int row, int col",d=`b * ${m} + (row / 2) * ${p} + (col / 2)`;for(let h=2;h<i-1;h++)f=`int b${h}, `+f,m*=s[i-h-1],d=`b${h} * ${m} + `+d;return`
vec4 ${n}(${f}) {
int index = ${d};
int texR = index / ${c};
int texC = index - texR * ${c};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${l});
return ${o.texture2D}(${e}, uv);
}
`}function XQ(r,t){let e=r.shapeInfo.logicalShape,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e[3],i=e[2]*s,a=e[1]*i,{newShape:u,keptDims:l}=x.squeezeShape(e);if(u.length<e.length){let b=Xm(r,u),w=["row","col","depth","depth2"];return`
${Km(b,t)}
float ${o}(int row, int col, int depth, int depth2) {
return ${o}(${Ym(w,l)});
}
`}if(r.shapeInfo.isUniform)return`
float ${o}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${a}, ${i}, ${s}, 1)));
${jm(r)}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`;let c=r.shapeInfo.flatOffset,p=r.shapeInfo.texShape,m=p[0],f=p[1],d=`int stride2 = ${n}Shape[3];`,h=`int stride1 = ${n}Shape[2] * stride2;`,g=`int stride0 = ${n}Shape[1] * stride1;`;if(f===a&&c==null)return t?`
float ${o}(int row, int col, int depth, int depth2) {
${d}
${h}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
float ${o}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${i}, ${s}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${m}.0);
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`;if(f===s&&c==null)return t?`
float ${o}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${n}Shape[1] * ${n}Shape[2], ${n}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`:`
float ${o}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${e[1]*e[2]}, ${e[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${m}.0);
return sampleTexture(${n}, uv);
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
`;let y=Dc(n);return t?`
float ${o}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
${d}
${h}
${g}
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2;
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${y});
return sampleTexture(${n}, uv);
}
`:`
float ${o}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${i} +
depth * ${s} + depth2;
vec2 uv = uvFromFlat(${m}, ${f}, index + ${y});
return sampleTexture(${n}, uv);
}
`}function YQ(r){let t=r.shapeInfo.logicalShape,e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),o=t[4],s=t[3]*o,i=t[2]*s,a=t[1]*i,{newShape:u,keptDims:l}=x.squeezeShape(t);if(u.length<t.length){let h=Xm(r,u),g=["row","col","depth","depth2","depth3"];return`
${Km(h)}
float ${n}(int row, int col, int depth, int depth2, int depth3) {
return ${n}(${Ym(g,l)});
}
`}if(r.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${a}, ${i}, ${s}, ${o})) +
depth3;
${jm(r)}
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`;let c=r.shapeInfo.flatOffset,p=r.shapeInfo.texShape,m=p[0],f=p[1];if(f===a&&c==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${i}, ${s}, ${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${m}.0);
return sampleTexture(${e}, uv);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`;if(f===o&&c==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${m}.0);
return sampleTexture(${e}, uv);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`;let d=Dc(e);return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${i} + depth * ${s} +
depth2 * ${o} + depth3 + ${d};
vec2 uv = uvFromFlat(${m}, ${f}, index);
return sampleTexture(${e}, uv);
}
`}function ZQ(r){let t=r.shapeInfo.logicalShape,e=r.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),{newShape:o,keptDims:s}=x.squeezeShape(t);if(o.length<t.length){let g=Xm(r,o),y=["row","col","depth","depth2","depth3","depth4"];return`
${Km(g)}
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${n}(${Ym(y,s)});
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`}let i=t[5],a=t[4]*i,u=t[3]*a,l=t[2]*u,c=t[1]*l;if(r.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${c}, ${l}, ${u}, ${a})) +
dot(
vec2(depth3, depth4),
vec2(${i}, 1)));
${jm(r)}
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`;let p=r.shapeInfo.flatOffset,m=r.shapeInfo.texShape,f=m[0],d=m[1];if(d===c&&p==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${l}, ${u}, ${a}, ${i})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${f}.0);
return sampleTexture(${e}, uv);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`;if(d===i&&p==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${f}.0);
return sampleTexture(${e}, uv);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`;let h=Dc(e);return`
float ${n}(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 * ${c} + col * ${l} + depth * ${u} +
depth2 * ${a} + depth3 * ${i} + depth4 + ${h};
vec2 uv = uvFromFlat(${f}, ${d}, index);
return sampleTexture(${e}, uv);
}
`}function jm(r){let t=r.name,e=x.sizeFromShape(r.shapeInfo.logicalShape);return e<2?`return ${t};`:`
for (int i = 0; i < ${e}; i++) {
if (i == index) {
return ${t}[i];
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
}
`}function JQ(r,t){let e=r.name,n=e.charAt(0).toUpperCase()+e.slice(1),o="get"+n+"AtOutCoords",s=r.shapeInfo.logicalShape.length,i=t.logicalShape.length,a=DP(r.shapeInfo.logicalShape,t.logicalShape),u=Ht(i),l=i-s,c,p=["x","y","z","w","u","v"];s===0?c="":i<2&&a.length>=1?c="coords = 0;":c=a.map(b=>`coords.${p[b+l]} = 0;`).join(`
`);let m="";i<2&&s>0?m="coords":m=r.shapeInfo.logicalShape.map((b,w)=>`coords.${p[w+l]}`).join(", ");let f="return outputValue;",h=x.sizeFromShape(r.shapeInfo.logicalShape)===1,y=x.sizeFromShape(t.logicalShape)===1;if(s===1&&!h&&!y)f=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(h&&!y)i===1?f=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:f=`
return vec4(outputValue.x);
`;else if(a.length){let b=s-2,w=s-1;a.indexOf(b)>-1&&a.indexOf(w)>-1?f="return vec4(outputValue.x);":a.indexOf(b)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(w)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${o}() {
${u} coords = getOutputCoords();
${c}
vec4 outputValue = get${n}(${m});
${f}
}
`}function QQ(r,t){let e=r.name,n=e.charAt(0).toUpperCase()+e.slice(1),o="get"+n+"AtOutCoords",s=t.texShape,i=r.shapeInfo.texShape,a=r.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!r.shapeInfo.isUniform&&a===u&&r.shapeInfo.flatOffset==null&&x.arraysEqual(i,s))return`
float ${o}() {
return sampleTexture(${e}, resultUV);
}
`;let l=Ht(u),c=DP(r.shapeInfo.logicalShape,t.logicalShape),p=u-a,m,f=["x","y","z","w","u","v"];a===0?m="":u<2&&c.length>=1?m="coords = 0;":m=c.map(h=>`coords.${f[h+p]} = 0;`).join(`
`);let d="";return u<2&&a>0?d="coords":d=r.shapeInfo.logicalShape.map((h,g)=>`coords.${f[g+p]}`).join(", "),`
float ${o}() {
${l} coords = getOutputCoords();
${m}
return get${n}(${d});
}
`}function Ht(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 mb(r,t,e){let{newShape:n,keptDims:o}=x.squeezeShape(t),s=t.length,i=r&&s===3&&t[0]===1,a=i?t.slice(1):n,u=!r&&s>1&&!x.arraysEqual(t,e)&&n.length<s||i;return{useSqueezeShape:u,uniformShape:u?a:t,keptDims:o}}function Xm(r,t){let e=JSON.parse(JSON.stringify(r));return e.shapeInfo.logicalShape=t,e}function Ym(r,t){return t.map(e=>r[e]).join(", ")}function PP(r,t,e,n){let o=e.map((v,I)=>{let E={logicalShape:v.shape,texShape:v.isUniform?null:v.texData.texShape,isUniform:v.isUniform,isPacked:v.isUniform?!1:v.texData.isPacked,flatOffset:null};return v.texData!=null&&v.texData.slice!=null&&v.texData.slice.flatOffset>0&&(E.flatOffset=v.texData.slice.flatOffset),{name:t.variableNames[I],shapeInfo:E}}),s=o.map(v=>v.shapeInfo),i={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},a=$P(o,i,t),u=zS(r.gl,a),l=r.createProgram(u),c=null,p=r.getUniformLocation(l,"NAN",!1);G().getNumber("WEBGL_VERSION")===1&&(c=r.getUniformLocation(l,"INFINITY",!1));let m=!1,f={},d={},h={};for(let v=0;v<t.variableNames.length;v++){let I=t.variableNames[v];f[I]=r.getUniformLocation(l,I,m),f[`offset${I}`]=r.getUniformLocation(l,`offset${I}`,m),t.enableShapeUniforms&&(d[`${I}Shape`]=r.getUniformLocation(l,`${I}Shape`,m),h[`${I}TexShape`]=r.getUniformLocation(l,`${I}TexShape`,m))}let g,y,b;t.enableShapeUniforms&&(g=r.getUniformLocation(l,"outShape",m),b=r.getUniformLocation(l,"outShapeStrides",m),y=r.getUniformLocation(l,"outTexShape",m));let w=[];return t.customUniforms&&t.customUniforms.forEach((v,I)=>{w[I]=r.getUniformLocation(l,v.name,m)}),{program:t,fragmentShader:u,source:a,webGLProgram:l,uniformLocations:f,customUniformLocations:w,inShapeInfos:s,outShapeInfo:i,infLoc:c,nanLoc:p,inShapesLocations:d,inTexShapesLocations:h,outShapeLocation:g,outShapeStridesLocation:b,outTexShapeLocation:y}}function OP(r,t){if(r.length!==t.length)throw Error(`Binary was compiled with ${r.length} inputs, but was executed with ${t.length} inputs`);r.forEach((e,n)=>{let o=e.logicalShape,s=t[n],i=s.shape;if(!x.arraysEqual(o,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${o} and ${i} must match`);if(e.isUniform&&s.isUniform)return;let a=e.texShape,u=s.isUniform?null:s.texData.texShape;if(!x.arraysEqual(a,u))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${u} must match`)})}function MP(r,t,e,n,o){t.program.enableShapeUniforms||(OP(t.inShapeInfos,e),OP([t.outShapeInfo],[n]));let s=n.texData.texture,i=n.texData.texShape;n.texData.isPacked?r.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):r.setOutputMatrixTexture(s.texture,i[0],i[1]),r.setProgram(t.webGLProgram),G().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&r.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&r.gl.uniform1f(t.nanLoc,NaN),e.forEach((u,l)=>{let c=t.program.variableNames[l],p=t.uniformLocations[c],m=t.uniformLocations[`offset${c}`],f=t.inShapesLocations[`${c}Shape`],d=t.inTexShapesLocations[`${c}TexShape`];if(f){let{uniformShape:h}=mb(t.program.packedInputs,u.shape,u.texData.texShape);switch(h.length){case 1:r.gl.uniform1iv(f,new Int32Array(h));break;case 2:r.gl.uniform2iv(f,new Int32Array(h));break;case 3:r.gl.uniform3iv(f,new Int32Array(h));break;case 4:r.gl.uniform4iv(f,new Int32Array(h));break;default:break}}if(d&&r.gl.uniform2i(d,u.texData.texShape[0],u.texData.texShape[1]),p!=null){if(u.isUniform){if(x.sizeFromShape(u.shape)<2)r.gl.uniform1f(p,u.uniformValues[0]);else{let h=u.uniformValues;h instanceof Float32Array||(h=new Float32Array(h)),r.gl.uniform1fv(p,h)}return}u.texData.slice!=null&&m!=null&&r.gl.uniform1i(m,u.texData.slice.flatOffset),r.setInputMatrixTexture(u.texData.texture.texture,p,l)}});let a=t.outShapeLocation;if(a)switch(n.shape.length){case 1:r.gl.uniform1iv(a,new Int32Array(n.shape));break;case 2:r.gl.uniform2iv(a,new Int32Array(n.s
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?Ac(["r","c","d"],t):li(["r","c","d"],t)}
return ivec3(r, c, d);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
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);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
${e.output} = result;
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`}};var ok=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=nu.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let e=He();this.outputShape=t,this.enableShapeUniforms=De(this.outputShape.length),this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?Ac(["r","c","d"],t):li(["r","c","d"],t)}
return ivec3(r, c, d);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
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));
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
${e.output} = result;
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`}};var sk=class{constructor(t){this.variableNames=["A"],this.outTexUsage=Ur.DOWNLOAD;let e=He();this.outputShape=t,this.userCode=`
${pb}
void main() {
float x = getAAtOutCoords();
${e.output} = encode_float(x);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`}};var ik=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ur.DOWNLOAD;let e=He();this.outputShape=t,this.userCode=`
${pb}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${e.output} = encode_float(x);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`}};var ak=class{constructor(t,e=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=He();this.outputShape=t,this.enableShapeUniforms=De(this.outputShape.length);let o="result";e&&(o="floor(result * 255. + 0.5)"),this.userCode=`
${this.enableShapeUniforms?Hm():Um(t)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int 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]);
vec4 values = ${n.texture2D}(A, uv);
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
2021-12-06 12:34:50 +01:00
} else {
2022-03-07 19:17:31 +01:00
result = values[3];
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
${n.output} = vec4(${o}, 0., 0., 0.);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`}};var lk=class{constructor(t,e=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=He();this.outputShape=t,this.enableShapeUniforms=De(this.outputShape.length);let o="",s="result";e&&(s="floor(result * 255. + 0.5)");for(let i=0;i<=1;i++)for(let a=0;a<=1;a++){let u=i*2+a;o+=`
localCoords = coords;
if(localCoords[2] + ${a} < ${this.enableShapeUniforms?"outShape[2]":`${t[2]}`}) {
localCoords[2] += ${a};
if (localCoords[1] + ${i} < ${this.enableShapeUniforms?"outShape[1]":`${t[1]}`}) {
localCoords[1] += ${i};
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 = ${n.texture2D}(A, uv);
if (offset == 0) {
result[${u}] = values[0];
} else if (offset == 1) {
result[${u}] = values[1];
} else if (offset == 2) {
result[${u}] = values[2];
} else {
result[${u}] = values[3];
2021-12-06 12:34:50 +01:00
}
}
}
2022-03-07 19:17:31 +01:00
`}this.userCode=`
${this.enableShapeUniforms?Hm():Um(t)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${o}
${n.output} = ${s};
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`}};var kk={};Xt(kk,{bindVertexProgramAttributeStreams:()=>xk,createBufferFromOutputTexture:()=>wk,createFloat16MatrixTexture:()=>fk,createFloat16PackedMatrixTexture:()=>gk,createFloat32MatrixTexture:()=>mk,createIndexBuffer:()=>pk,createPackedMatrixTexture:()=>hk,createUnsignedBytesMatrixTexture:()=>dk,createVertexBuffer:()=>ck,createVertexShader:()=>uk,downloadByteEncodedFloatMatrixFromOutputTexture:()=>Ck,downloadFloat32MatrixFromBuffer:()=>vk,downloadMatrixFromPackedOutputTexture:()=>Sk,downloadPackedMatrixFromBuffer:()=>Ik,getInternalFormatForFloat16MatrixTexture:()=>db,getInternalFormatForFloat16PackedMatrixTexture:()=>xb,getInternalFormatForFloat32MatrixTexture:()=>fb,getInternalFormatForPackedMatrixTexture:()=>gb,getInternalFormatForUnsignedBytesMatrixTexture:()=>hb,uploadDenseMatrixToTexture:()=>yk,uploadPixelDataToTexture:()=>bk});function uk(r){let t=He(),e=`${t.version}
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;return LS(r,e)}function ck(r){let t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return GS(r,t)}function pk(r){let t=new Uint16Array([0,1,2,2,1,3]);return WS(r,t)}function sg(r,t,e,n,o,s){HS(t,e);let i=US(r),a=r.TEXTURE_2D;return vt(r,()=>r.bindTexture(a,i)),vt(r,()=>r.texParameteri(a,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)),vt(r,()=>r.texParameteri(a,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)),vt(r,()=>r.texParameteri(a,r.TEXTURE_MIN_FILTER,r.NEAREST)),vt(r,()=>r.texParameteri(a,r.TEXTURE_MAG_FILTER,r.NEAREST)),G().getNumber("WEBGL_VERSION")===1?vt(r,()=>r.texImage2D(a,0,n,t,e,0,o,s,null)):vt(r,()=>r.texStorage2D(a,1,n,t,e)),vt(r,()=>r.bindTexture(r.TEXTURE_2D,null)),{texture:i,texShape:[e,t]}}function fb(r){return r.internalFormatFloat}function mk(r,t,e,n){let[o,s]=Ec(t,e);return sg(r,o,s,fb(n),n.textureFormatFloat,r.FLOAT)}function db(r){return r.internalFormatHalfFloat}function fk(r,t,e,n){let[o,s]=Ec(t,e);return sg(r,o,s,db(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function hb(r){return r.downloadTextureFormat}function dk(r,t,e,n){let[o,s]=Ec(t,e);return sg(r,o,s,hb(n),r.RGBA,r.UNSIGNED_BYTE)}function gb(r){return r.internalFormatPackedFloat}function hk(r,t,e,n){let[o,s]=Ui(t,e);return sg(r,o,s,gb(n),r.RGBA,r.FLOAT)}function xb(r){return r.internalFormatPackedHalfFloat}function gk(r,t,e,n){let[o,s]=Ui(t,e);return sg(r,o,s,xb(n),r.RGBA,n.textureTypeHalfFloat)}function xk(r,t,e){return vt(r,()=>r.bindBuffer(r.ARRAY_BUFFER,e)),lb(r,t,"clipSpacePos",e,3,20,0)&&lb(r,t,"uv",e,2,20,12)}function yk(r,t,e,n,o,s){vt(r,()=>r.bindTexture(r.TEXTURE_2D,t));let i,a,u;o instanceof Uint8Array?(i=new Uint8Array(e*n*4),a=r.UNSIGNED_BYTE,u=r.RGBA):(i=new Float32Array(e*n*4),a=r.FLOAT,u=s.internalFormatPackedFloat),i.set(o),G().getNumber("WEBGL_VERSION")===2?vt(r,()=>r.texSubImage2D(r.TEXTURE_2D,0,0,0,e,n,r.RGBA,a,i)):vt(r,()=>r.texImage2D(r.TEXTURE_2D,0,u,e,n,0,r.RGBA,a,i)),vt(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function bk(r,t,e){vt(r,()=>r.bindTexture(r.TEXTURE_2D,t)),e.data instanceof Uint8Array?G().getNumber("WEBGL_VERSION")===2?vt(r,()=>r.texSubImage2D(r.TEXTURE_2D,0,0,0,e.width,e.height,r.RGBA,r.UNSIGNED_BYTE,e.data)):vt(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e.width,e.height,0,r.RGBA,r.UNSIGNED_BYTE,e.data)):G().getNumber("WEBGL_VERSION")===2?vt(r,()=>r.texSubImage2D(r.TEXTURE_2D,0,0,0,r.RGBA,r.UNSIGNED_BYTE,e)):vt(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e)),vt(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function wk(r,t,e,n){let o=r.createBuffer();vt(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,o));let a=4*4*t*e;return vt(r,()=>r.bufferData(r.PIXEL_PACK_BUFFER,a,r.STREAM_READ)),vt(r,()=>r.readPixels(0,0,e,t,r.RGBA,r.FLOAT,0)),vt(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,null)),o}function vk(r,t,e){let n=r,o=new Float32Array(e);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,o),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),o}function Ck(r,t,e,n){let[o,s]=Ec(t,e),i=4,a=new Uint8Array(SP(t*e,i));return vt(r,()=>r.readPixels(0,0,o,s,n.downloadTextureFormat,r.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function Ik(r,t,e,n,o,s,i,a){let u=r,l=new Float32Array(kP(s,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function Sk(r,t,e){let n=new Float32Array(t*e*4);return vt(r,()=>r.readPixels(0,0,e,t,r.RGBA,r.FLOAT,n)),n}var Zm=class{constructor(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let e=G().getNumber("WEBGL_VERSION");t!=null?(this.gl=t,FS(e,t)):this.gl=Vn(e);let n="WEBGL_color_buffer_float",o="EXT_color_buffer_half_float";if(G().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",i="OES_texture_half_float";if(this.textureFloatExtension=Vm(this.gl,s),Gn(this.gl,i))this.textureHalfFloatExtension=Vm(this.gl,i);else if(G().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`;else{let e=tr("rc",this.rank),n=Ht(this.rank),o=this.getOutOfBoundsCondition(e),s=this.getSetup(e),i=this.getOutput(e);this.userCode=`
void main() {
${n} rc = getOutputCoords();
if(${o}) {
setOutput(vec4(0));
2021-12-06 12:34:50 +01:00
} else {
2022-03-07 19:17:31 +01:00
${s}
setOutput(vec4(${i}));
2021-12-06 12:34:50 +01:00
}
}
2022-03-07 19:17:31 +01:00
`}}getSourceCoordsArr(t){let e=[];for(let n=0;n<=1;n++)for(let o=0;o<=1;o++){let s=`${n===0?"r":"rp1"}, ${o===0?"c":"cp1"}`;for(let i=2;i<this.rank;i++)s=`${t[t.length-1-i]},`+s;e.push(s)}return e}getOutOfBoundsCondition(t){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let e="";for(let n=this.rank-2;n<this.rank;n++)e+=`${t[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(e+="||");return e}getSetup(t){if(this.rank===1)return"";let e=t.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],o=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
int r = ${e[0]};
int c = ${e[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${n};
bool rEdge = rp1 >= ${o};
`}getOutput(t){let e=this.getSourceCoordsArr(t);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${e[0]}),
cEdge ? 0. : getA(${e[1]}),
rEdge ? 0. : getA(${e[2]}),
rEdge || cEdge ? 0. : getA(${e[3]})`}};var ig=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=t,this.enableShapeUniforms=De(this.outputShape.length);let n="";for(let o=0;o<4;o++){let s="thisRC = rc;";o%2===1&&(s+="thisRC.z += 1;"),o>1&&(s+="thisRC.y += 1;"),n+=`
${s}
${o>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[${o}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${o>0?"}":""}
`}this.userCode=`
${ntt(e,this.enableShapeUniforms)}
${this.enableShapeUniforms?Hm():Um(t)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${this.enableShapeUniforms?"outShape[1]":t[1]};
int cols = ${this.enableShapeUniforms?"outShape[2]":t[2]};
${n}
setOutput(result);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`}};function ntt(r,t){return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t?AP(["r","c","d"],"inputShape"):li(["r","c","d"],r)}
return ivec3(r, c, d);
}
`}var _k=class{constructor(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(t,e,n){let o=kM(e,n),s=NM(t,o,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let i=SM(t,o,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=i,this.log();let u=this.freeTextures[s].shift();return this.usedTextures[s].push(u),u}let a;return o===Rr.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===Rr.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===Rr.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===Rr.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===Rr.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[s].push(a),this.numUsedTextures++,this._numBytesAllocated+=i,this.log(),a}releaseTexture(t,e,n,o){if(this.freeTextures==null)return;let s=kM(n,o),i=NM(e,s,o);i in this.freeTextures||(this.freeTextures[i]=[]);let a=SM(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,o),u=G().get("WEBGL_DELETE_TEXTURE_THRESHOLD");u!==-1&&this._numBytesAllocated>u?(this.gpgpu.deleteMatrixTexture(t.texture),this._numBytesAllocated-=a):(this.freeTextures[i].push(t),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;let l=this.usedTextures[i],c=l.indexOf(t);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(c,1),this.log()}log(){if(!this.logEnabled)return;let t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${t})`);let e=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*e)}%)`)}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 t in this.freeTextures)this.freeTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});for(let t in this.usedTextures)this.usedTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function ott(r,t){let e=r;if(t===e.R32F)return 4;if(t===e.R16F)return 2;if(t===e.RGBA32F)return 16;if(t===r.RGBA)return 16;if(t===e.RGBA16F)return 8;if(t===e.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function SM(r,t,e,n,o){let s=stt(t,n),i;if(o){let[u,l]=Ui(r[0],r[1]);i=u*l}else{let[u,l]=Ec(r[0],r[1]);i=u*l}let a=ott(e,s);return i*a}function stt(r,t){switch(r){case Rr.PACKED_2X2_FLOAT32:return gb(t);case Rr.PACKED_2X2_FLOAT16:return xb(t);case Rr.UNPACKED_FLOAT32:return fb(t);case Rr.UNPACKED_FLOAT16:return db(t);case Rr.PACKED_4X1_UNSIGNED_BYTE:return hb(t);default:throw new Error(`Unknown physical texture type ${r}`)}}function itt(r){return G().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?Rr.PACKED_2X2_FLOAT32:Rr.UNPACKED_FLOAT32:r?Rr.PACKED_2X2_FLOAT16:Rr.UNPACKED_FLOAT16}function kM(r,t){if(r===Ur.UPLOAD)return Rr.PACKED_2X2_FLOAT32;if(r===Ur.RENDER||r==null)return itt(t);if(r===Ur.DOWNLOAD||r===Ur.PIXELS)return Rr.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${r}`)}function NM(r,t,e){return`${r[0]}_${r[1]}_${t}_${e}`}var wn=class{constructor(t,e){this.variableNames=["A"],this.outputShape=t,this.enableShapeUniforms=De(this.outputShape.length),this.userCode=`
float unaryOperation(float x) {
${e}
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
`}},dr="if (isnan(x)) return x;",TM="return x;",Ek="return abs(x);";var _M="return (x >= 0.0) ? x : (exp(x) - 1.0);",EM=dr+`
return (x < 0.0) ? 0.0 : x;
`,AM=dr+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,Rc="return x;",DM="return 1.0 / (1.0 + exp(-1.0 * x));";var RM="return x;",FM=`
vec4 result;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
return result;
`,OM=`
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
return result;
`,PM=`
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
return result;
`,MM="return 1.0 / (1.0 + exp(-1.0 * x));",$o=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.enableShapeUniforms=De(this.outputShape.length),this.userCode=`
vec4 unaryOperation(vec4 x) {
${e}
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
setOutput(y);
}
`}};var Ak=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t,this.enableShapeUniforms=De(this.outputShape.length);let e=t.length,n=tr("rc",e),o=Ht(e),s=IM(e,n),i=n.slice(-2),a=e<=1?"rc":`vec2(${i.join(",")})`;this.userCode=`
void main() {
${o} rc = getOutputCoords();
vec4 packedInput = getA(${s});
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
setOutput(getChannel(packedInput, ${a}));
2021-10-22 15:06:43 +02:00
}
2022-03-07 19:17:31 +01:00
`}};var ltt=Vr.whereImpl,utt=1e-7,ctt=1e-4,vb={};function ptt(r){return r in vb||(vb[r]={}),vb[r]}var mtt=G().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),ftt=600;function dtt(){return G().global.screen==null?1024:G().global.screen.height*G().global.screen.width*window.devicePixelRatio*ftt/1024/1024}var Fc=class extends pi{constructor(t){super();if(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,!G().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let e;if(t!=null){if(t instanceof Zm)e=t;else{let n=Vn(G().getNumber("WEBGL_VERSION"),t);e=new Zm(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=Vn(G().getNumber("WEBGL_VERSION"));e=new Zm(n),this.binaryCache=ptt(G().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=e,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new _k(this.gpgpu),this.numMBBeforeWarning=dtt(),this.texData=new bl(this,po())}nextDataId(){return Fc.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(t,e,n){if((G().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||G().getBool("DEBUG"))&&this.checkNumericalProblems(t),n==="complex64"&&t!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let o={id:this.nextDataId()};return this.texData.set(o,{shape:e,dtype:n,values:t,usage:Ur.UPLOAD,refCount:1}),o}refCount(t){return this.texData.has(t)?this.texData.get(t).refCount:0}incRef(t){let e=this.texData.get(t);e.refCount++}decRef(t){if(this.texData.has(t)){let e=this.texData.get(t);e.refCount--}}move(t,e,n,o,s){if(G().getBool("DEBUG")&&this.checkNumericalProblems(e),o==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:o,values:e,usage:Ur.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}readSync(t){let e=this.texData.get(t),{values:n,dtype:o,complexTensorInfos:s,slice:i,shape:a,isPacked:u}=e;if(i!=null){let m;u?m=new $o(a,Rc):m=new wn(a,Rc);let f=this.runWebGLProgram(m,[{dataId:t,shape:a,dtype:o}],o),d=this.readSync(f.dataId);return this.disposeIntermediateTensorInfo(f),d}if(n!=null)return this.convertAndCacheOnCPU(t);if(o==="string")return n;let l=this.activeTimers!=null,c;l&&(c=x.now());let p;if(o==="complex64"){let m=this.readSync(s.real.dataId),f=this.readSync(s.imag.dataId);p=k.mergeRealAndImagArrays(m,f)}else p=this.getValuesFromTexture(t);return l&&(this.downloadWaitMs+=x.now()-c),this.convertAndCacheOnCPU(t,p)}async read(t){if(this.pendingRead.has(t)){let d=this.pendingRead.get(t);return new Promise(h=>d.push(h))}let e=this.texData.get(t),{values:n,shape:o,slice:s,dtype:i,complexTensorInfos:a,isPacked:u}=e;if(s!=null){let d;u?d=new $o(o,Rc):d=new wn(o,Rc);let h=this.runWebGLProgram(d,[{dataId:t,shape:o,dtype:i}],i),g=this.read(h.dataId);return this.disposeIntermediateTensorInfo(h),g}if(n!=null)return this.convertAndCacheOnCPU(t);if(G().getBool("DEBUG")&&!G().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&G().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,c;if(i!=="complex64"&&G().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(t);let d=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(d.texture.texture,...tg(o))}this.pendingRead.set(t,[]),i!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(i==="complex64"){let d=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),h=d[0],g=d[1];p=k.mergeRealAndImagArrays(h,g)}else if(l==null)p=this.getValuesFromTexture(t);else{let d=x.sizeFromShape(o);p=this.gpgpu.downloadFloat32MatrixFromBuffer(l,d)}if(c!=null&&this.disposeIntermediateTensorInfo(c),l!=null){let d=this.gpgpu.gl;vt(d,()=>d.deleteBuffer(l))}let m=this.convertAndCacheOnCPU(t,p),f=this.pendingRead.get(t);return this.pendingRead.delete(t
if (isnan(a)) return a;
if (isnan(b)) return b;
`;var Ro=class{constructor(t,e,n){this.variableNames=["A","B"],this.outputShape=k.assertAndGetBroadcastShape(e,n),this.enableShapeUniforms=De(this.outputShape.length),this.userCode=`
float binaryOperation(float a, float b) {
${t}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
2021-10-22 15:06:43 +02:00
}
2022-03-07 19:17:31 +01:00
`}};var su=`
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`;var ui=class{constructor(t,e,n,o=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=k.assertAndGetBroadcastShape(e,n);let s=this.outputShape.length;this.enableShapeUniforms=De(s);let i="";if(o)if(s===0||x.sizeFromShape(this.outputShape)===1)i=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else if(i=`
${Ht(s)} coords = getOutputCoords();
`,s===1)this.enableShapeUniforms?i+=`
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`:i+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{let u=tr("coords",s);this.enableShapeUniforms?i+=`
bool nextRowOutOfBounds =
(${u[s-2]} + 1) >= outShape[${s} - 2];
bool nextColOutOfBounds =
(${u[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;
`:i+=`
bool nextRowOutOfBounds =
(${u[s-2]} + 1) >= ${this.outputShape[s-2]};
bool nextColOutOfBounds =
(${u[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) {
${t}
2021-04-01 19:39:54 +02:00
}
void main() {
2022-03-07 19:17:31 +01:00
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
vec4 result = binaryOperation(a, b);
${i}
2021-04-01 19:39:54 +02:00
setOutput(result);
}
2022-03-07 19:17:31 +01:00
`}};function er(r){let{inputs:t,backend:e}=r,{x:n}=t;return e.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var BM={kernelName:so,backendName:"webgl",kernelFunc:er};function Dn(r){let{inputs:t,backend:e}=r,{real:n,imag:o}=t,s=e.makeTensorInfo(n.shape,"complex64"),i=e.texData.get(s.dataId),a=er({inputs:{x:n},backend:e}),u=er({inputs:{x:o},backend:e});return i.complexTensorInfos={real:a,imag:u},s}var VM={kernelName:pp,backendName:"webgl",kernelFunc:Dn};var Dk="return (a < 0.) ? b * a : a;",$k=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function gtt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{alpha:s}=n,i=e.makeTensorInfo([],"float32",x.createScalarValue(s,"float32")),a=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ui($k,o.shape,i.shape):new Ro(Dk,o.shape,i.shape),u=e.runWebGLProgram(a,[o,i],"float32");return e.disposeIntermediateTensorInfo(i),u}var GM={kernelName:cs,backendName:"webgl",kernelFunc:gtt};var Rk="return (a < 0.) ? b * a : a;",Fk=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function xtt(r){let{inputs:t,backend:e}=r,{x:n,alpha:o}=t,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ui(Fk,n.shape,o.shape):new Ro(Rk,n.shape,o.shape);return e.runWebGLProgram(s,[n,o],"float32")}var WM={kernelName:Is,backendName:"webgl",kernelFunc:xtt};var Fo="if (isnan(x)) return x;",UM=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,HM=`
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`;function Ct({opSnippet:r,packedOpSnippet:t,cpuKernelImpl:e,dtype:n}){return({inputs:o,backend:s})=>{let{x:i}=o,a=s,u=n||i.dtype;if(a.shouldExecuteOnCPU([i])&&e!=null){let p=a.texData.get(i.dataId),m=e(p.values,u);return a.makeTensorInfo(i.shape,u,m)}let l=G().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,c;return l?c=new $o(i.shape,t):c=new wn(i.shape,r),a.runWebGLProgram(c,[i],u)}}function le({opSnippet:r,packedOpSnippet:t,checkOutOfBounds:e=!1,supportsComplex:n=!1,cpuKernelImpl:o,dtype:s}){return({inputs:i,backend:a})=>{let{a:u,b:l}=i,c=a;if(n&&u.dtype==="complex64"){let d=c.texData.get(u.dataId),h=c.texData.get(l.dataId),[g,y]=[[d.complexTensorInfos.real,h.complexTensorInfos.real],[d.complexTensorInfos.imag,h.complexTensorInfos.imag]].map(w=>{let[v,I]=w,E={dataId:v.dataId,dtype:v.dtype,shape:u.shape},D={dataId:I.dataId,dtype:I.dtype,shape:l.shape},$=new Ro(r,u.shape,l.shape);return c.runWebGLProgram($,[E,D],yr(v.dtype,I.dtype))}),b=Dn({inputs:{real:g,imag:y},backend:c});return c.disposeIntermediateTensorInfo(g),c.disposeIntermediateTensorInfo(y),b}let p=s||yr(u.dtype,l.dtype);if((u.dtype==="string"||l.dtype==="string"||c.shouldExecuteOnCPU([u,l]))&&o!=null){let d=c.texData.get(u.dataId).values,h=c.texData.get(l.dataId).values,g=u.dtype==="string"?k.fromUint8ToStringArray(d):d,y=u.dtype==="string"?k.fromUint8ToStringArray(h):h,[b,w]=o(u.shape,l.shape,g,y,p),v=c.makeTensorInfo(w,p),I=c.texData.get(v.dataId);return I.values=b,v}let m=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,f;return m?f=new ui(t,u.shape,l.shape,e):f=new Ro(r,u.shape,l.shape),c.runWebGLProgram(f,[u,l],p)}}function iu(r,t=!1){if(r==="linear")return t?RM:TM;if(r==="relu")return t?OM:EM;if(r==="elu")return t?FM:_M;if(r==="relu6")return t?PM:AM;if(r==="prelu")return t?Fk:Rk;if(r==="leakyrelu")return t?$k:Dk;if(r==="sigmoid")return t?MM:DM;throw new Error(`Activation ${r} has not been implemented for the WebGL backend.`)}var ag=class{constructor(t,e,n,o=!1,s=!1,i=!1,a=null,u=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=De(this.outputShape.length);let c=o?t[1]:t[2],p=Math.ceil(c/2),m=o?"i * 2, rc.y":"rc.y, i * 2",f=s?"rc.z, i * 2":"i * 2, rc.z",d=o?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],g="",y="";a&&(u?g=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${a}
}`:l?g=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${a}
}`:g=`vec4 activation(vec4 x) {
${a}
}`,y="result = activation(result);");let b=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),u&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let w="rc.x",v="rc.x";t[0]<e[0]?w=`int(min(float(rc.x), ${t[0]-1}.))`:e[0]<t[0]&&(v=`int(min(float(rc.x), ${e[0]-1}.))`),this.userCode=`
${g}
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = ${p}.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${p}; i++) {
int batchA = ${w};
int batchB = ${v};
vec4 a = getMatrixA(batchA, ${m});
vec4 b = getMatrixB(batchB, ${f});
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${d[0]} * ${h[0]});
result += (${d[1]} * ${h[1]});
}
return result;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${b}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${y}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
setOutput(result);
}
`}};var Ok={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},Ib=class{constructor(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=k.assertAndGetBroadcastShape(e,n),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${t}
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}};var qM="return a * b;";function lg(r){let{inputs:t,backend:e}=r,{a:n,b:o}=t,s=k.upcastType(n.dtype,o.dtype);if(n.dtype==="complex64"){let a=e.texData.get(n.dataId),u=e.texData.get(o.dataId),l=new Ib(Ok.REAL,n.shape,o.shape),c=new Ib(Ok.IMAG,n.shape,o.shape),p=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:n.shape},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:n.shape},{dataId:u.complexTensorInfos.real.dataId,dtype:u.complexTensorInfos.real.dtype,shape:o.shape},{dataId:u.complexTensorInfos.imag.dataId,dtype:u.complexTensorInfos.imag.dtype,shape:o.shape}],m=e.runWebGLProgram(l,p,"float32"),f=e.runWebGLProgram(c,p,"float32"),d=Dn({inputs:{real:m,imag:f},backend:e});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f),d}if(e.shouldExecuteOnCPU([n,o])){let a=e.texData.get(n.dataId),u=e.texData.get(o.dataId),[l,c]=oM(n.shape,o.shape,a.values,u.values,s),p=e.makeTensorInfo(c,s),m=e.texData.get(p.dataId);return m.values=l,p}let i;return G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new ui(qM,n.shape,o.shape):i=new Ro(qM,n.shape,o.shape),e.runWebGLProgram(i,[n,o],s)}var KM={kernelName:bs,backendName:"webgl",kernelFunc:lg};function jM(r,t,e){let n=[cl(r.shape),...pl(r.shape)],o={dtype:r.dtype,shape:n,dataId:r.dataId},s=[cl(t),...pl(t)],i=new ig(s,n),a=!0,u=[n],l=e.runWebGLProgram(i,[o],r.dtype,u,a);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function ut(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{shape:s}=n,i=e,a=x.sizeFromShape(o.shape),u=x.inferFromImplicitShape(s,a),l=x.sizeFromShape(u);x.assert(a===l,()=>`The new shape (${u}) has ${l} elements and the old shape (${o.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);let c=i.texData.get(o.dataId);return c.isPacked&&!ou(o.shape,u)&&!(c.texture!==null&&ou(c.shape,u))?jM(o,u,i):(i.incRef(o.dataId),{dataId:o.dataId,shape:u,dtype:o.dtype})}var XM={kernelName:Ci,backendName:"webgl",kernelFunc:ut};var Sb=class{constructor(t,e){this.variableNames=["x"];let{windowSize:n,batchSize:o,inSize:s,outSize:i}=t;this.outputShape=[o,i];let a=Math.floor(n/4)*4,u=n%4,l="sumValue += dot(values, ones);";if(e!=null){let p=1/e;l=`sumValue += dot(values * ${x.isInt(p)?p.toPrecision(2):p}, ones);`}let c="";s%n>0&&(c=`
if (inIdx < 0 || inIdx >= ${s}) {
return 0.0;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${c}
return getX(batch, inIdx);
2021-04-01 19:39:54 +02:00
}
void main() {
2022-03-07 19:17:31 +01:00
ivec2 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
int batch = coords[0];
2022-03-07 19:17:31 +01:00
int outIdx = coords[1];
int inOffset = outIdx * ${n};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float sumValue = 0.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int i = 0; i < ${a}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${l}
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
int inIdx = inOffset + ${a};
if (${u===1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${l}
} else if (${u===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${l}
} else if (${u===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${l}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput(sumValue);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}};var Pk=class{constructor(t,e){this.variableNames=["x"];let{windowSize:n,batchSize:o,inSize:s,outSize:i}=t;this.outputShape=[o,i];let a="0.0",u="";e==="prod"?a="1.0":e==="min"?(a="1.0 / 1e-20",u="min"):e==="max"&&(a="-1.0 / 1e-20",u="max");let l=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="sum"?l="sumValue":e==="prod"?l="prodValue":e==="all"?l="allValue":e==="any"&&(l="anyValue");let c=Math.floor(n/4)*4,p=n%4,m=`
if (${e==="sum"}) {
sumValue += dot(values, ones);
} else if (${e==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${u}(values, minMaxValue);
if (${e==="min"} || ${e==="max"}) {
minMaxValue = ${u}(values, minMaxValue);
bvec4 isNaN = isnan(values);
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
minMaxValue = vec4(NAN);
}
}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`,f="vec4";e==="all"?(a="1.0",m=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,f="bvec4"):e==="any"&&(a="0.0",m=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,f="bvec4");let d="";s%n>0&&(d=`
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${a};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float getValue(int batch, int inIdx) {
${d}
return getX(batch, inIdx);
}
2021-04-01 19:39:54 +02:00
void main() {
2022-03-07 19:17:31 +01:00
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
vec4 minMaxValue = vec4(${a});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int i = 0; i < ${c}; i += 4) {
int inIdx = inOffset + i;
${f} values = ${f}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${m}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
int inIdx = inOffset + ${c};
if (${p===1}) {
${f} values = ${f}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${m}
} else if (${p===2}) {
${f} values = ${f}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${m}
} else if (${p===3}) {
${f} values = ${f}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${m}
}
setOutput(${l});
}
2022-03-07 19:17:31 +01:00
`}};function btt(r){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let e=t.length?t[t.length-1].outSize:r[1],n=k.computeOptimalWindowSize(e);t.push({inSize:e,windowSize:n,outSize:Math.ceil(e/n)})}return t}function Wn(r,t,e,n){let o=btt(r.shape),s=r;for(let i=0;i<o.length;i++){let{inSize:a,windowSize:u,outSize:l}=o[i],c,p;e==="mean"?c=i===0?new Sb({windowSize:u,inSize:a,batchSize:r.shape[0],outSize:l},a):new Sb({windowSize:u,inSize:a,batchSize:r.shape[0],outSize:l}):c=new Pk({windowSize:u,inSize:a,batchSize:r.shape[0],outSize:l},e),p=s,s=n.runWebGLProgram(c,[s],t),p.dataId!==r.dataId&&n.disposeIntermediateTensorInfo(p)}return s}var Mk=class{constructor(t,e){this.variableNames=["A"];let n=new Array(t.length);for(let i=0;i<n.length;i++)n[i]=t[e[i]];this.outputShape=n,this.rank=n.length;let o=Ht(this.rank),s=wtt(e);this.userCode=`
void main() {
${o} resRC = getOutputCoords();
setOutput(getA(${s}));
}
2022-03-07 19:17:31 +01:00
`}};function wtt(r){let t=r.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t);for(let o=0;o<r.length;o++)n[r[o]]=e[o];return n.join()}var Lk=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(t.length);for(let c=0;c<n.length;c++)n[c]=t[e[c]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let o=Ht(this.rank),s=Nk("rc",this.rank),i=new Array(this.rank);for(let c=0;c<e.length;c++)i[e[c]]=s[c];let a=`vec2(${i.slice(-2).join()})`,u=`++${s[this.rank-1]} < ${n[this.rank-1]}`,l=`getChannel(getA(${i.join()}), ${a})`;this.userCode=`
void main() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${l};
if(${u}) {
result[1] = ${l};
}
2022-03-07 19:17:31 +01:00
--${s[this.rank-1]};
if(++${s[this.rank-2]} < ${n[this.rank-2]}) {
result[2] = ${l};
if(${u}) {
result[3] = ${l};
}
}
setOutput(result);
}
2022-03-07 19:17:31 +01:00
`}};function au(r,t,e){let n=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Lk(r.shape,t):new Mk(r.shape,t);return e.runWebGLProgram(n,[r],r.dtype)}function YM(r,t,e,n){let o=t,s=r.shape.length,i=x.parseAxisParam(o,r.shape),a=i,u=k.getAxesPermutation(a,s),l=u!=null,c=r;l&&(c=au(r,u,n),a=k.getInnerMostAxes(a.length,s)),k.assertAxesAreInnerMostDims("sum",a,s);let[p,m]=k.computeOutAndReduceShapes(c.shape,a),f=p;e&&(f=k.expandShapeToKeepDim(p,i));let d=x.sizeFromShape(m),g=x.sizeFromShape(r.shape)/d,y=ut({inputs:{x:c},attrs:{shape:[g,d]},backend:n}),b=Tu(r.dtype),w=Wn(y,b,"sum",n),v=ut({inputs:{x:w},attrs:{shape:f},backend:n});return n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(w),l&&n.disposeIntermediateTensorInfo(c),v}function Oc(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n;return YM(o,s,i,e)}var ZM={kernelName:Rs,backendName:"webgl",kernelFunc:Oc};function Le(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{perm:s}=n,i=e,a=o.shape.length,u=new Array(a);for(let c=0;c<u.length;c++)u[c]=o.shape[s[c]];let l;if(i.shouldExecuteOnCPU([o])){let p=i.texData.get(o.dataId).values,m=$c(p,o.shape,o.dtype,s,u);l=i.makeTensorInfo(u,o.dtype);let f=i.texData.get(l.dataId);f.values=m}else l=au(o,s,i);return l}var JM={kernelName:zs,backendName:"webgl",kernelFunc:Le};var zk=1e3;function Pc({a:r,b:t,transposeA:e,transposeB:n,backend:o,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:a=0,activation:u=null}){let l=r.shape.length,c=t.shape.length,p=e?r.shape[l-2]:r.shape[l-1],m=n?t.shape[c-1]:t.shape[c-2],f=e?r.shape[l-1]:r.shape[l-2],d=n?t.shape[c-2]:t.shape[c-1],h=r.shape.slice(0,-2),g=t.shape.slice(0,-2),y=x.sizeFromShape(h),b=x.sizeFromShape(g),v=Mr.assertAndGetBroadcastShape(r.shape.slice(0,-2),t.shape.slice(0,-2)).concat([f,d]);x.assert(p===m,()=>`Error in matMul: inner shapes (${p}) and (${m}) of Tensors with shapes ${r.shape} and ${t.shape} and transposeA=${e} and transposeB=${n} must match.`);let I=e?[y,p,f]:[y,f,p],E=n?[b,d,m]:[b,m,d],D=ut({inputs:{x:r},backend:o,attrs:{shape:I}}),$=ut({inputs:{x:t},backend:o,attrs:{shape:E}}),R=[D,$],M=Math.max(y,b),W=e?D.shape[1]:D.shape[2],U=s!=null,q=i!=null,K=u==="leakyrelu",j=u!=null?iu(u,!0):null,Q=U||q||K||j!=null,rt;if((f===1||d===1)&&W>zk&&Q===!1){let nt=D,st=$;e&&(nt=Le({inputs:{x:D},backend:o,attrs:{perm:[0,2,1]}}),R.push(nt)),n&&(st=Le({inputs:{x:$},backend:o,attrs:{perm:[0,2,1]}}),R.push(st));let it=d!==1,ft=d===1,at=nt;it&&(at=ut({inputs:{x:nt},backend:o,attrs:{shape:[M,W,1]}}),R.push(at));let xt=d===1?2:1,dt=st;ft&&(dt=ut({inputs:{x:st},backend:o,attrs:{shape:[M,1,W]}}),R.push(dt));let bt=lg({inputs:{a:at,b:dt},backend:o});rt=Oc({inputs:{x:bt},backend:o,attrs:{axis:xt,keepDims:!0}}),R.push(bt)}else{let nt=yr(r.dtype,t.dtype),st=new ag(I,E,[M,f,d],e,n,U,j,q,K),it=[D,$];if(s!=null&&it.push(s),q&&it.push(i),K){let ft=o.makeTensorInfo([],"float32",x.createScalarValue(a,"float32"));it.push(ft),R.push(ft)}rt=o.runWebGLProgram(st,it,nt)}let X=ut({inputs:{x:rt},backend:o,attrs:{shape:v}});R.push(rt);for(let nt of R)o.disposeIntermediateTensorInfo(nt);return X}function vtt(r){let{inputs:t,backend:e,attrs:n}=r,{a:o,b:s,bias:i,preluActivationWeights:a}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=n;return Pc({a:o,b:s,transposeA:u,transposeB:l,backend:e,bias:i,preluActivationWeights:a,leakyreluAlpha:p,activation:c})}var QM={kernelName:Ei,backendName:"webgl",kernelFunc:vtt};var tL="return abs(x);";function Ctt(r){let{inputs:t,backend:e}=r,{x:n}=t;if(e.shouldExecuteOnCPU([n])&&n.dtype!=="complex64"){let s=e.texData.get(n.dataId),i=bb(s.values);return e.makeTensorInfo(n.shape,n.dtype,i)}let o;return G().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new $o(n.shape,tL):o=new wn(n.shape,tL),e.runWebGLProgram(o,[n],n.dtype)}var eL={kernelName:di,backendName:"webgl",kernelFunc:Ctt};var Itt=dr+`
if (abs(x) > 1.) {
return NAN;
}
2022-03-07 19:17:31 +01:00
return acos(x);
`,Stt=Ct({opSnippet:Itt}),rL={kernelName:ji,backendName:"webgl",kernelFunc:Stt};var ktt=dr+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,Ntt=Ct({opSnippet:ktt}),nL={kernelName:Xi,backendName:"webgl",kernelFunc:Ntt};var oL="return a + b;",Ttt=le({opSnippet:oL,packedOpSnippet:oL,supportsComplex:!0,cpuKernelImpl:zP}),sL={kernelName:Kn,backendName:"webgl",kernelFunc:Ttt};var Bk=class{constructor(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map((s,i)=>`T${i}`);let n=[];this.variableNames.forEach(s=>{n.push(`float v${s} = get${s}AtOutCoords();`)});let o=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
void main() {
${n.join(`
`)}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float result = ${o};
setOutput(result);
}
`}};var Vk=class{constructor(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map((s,i)=>`T${i}`);let n=[];this.variableNames.forEach(s=>{n.push(`vec4 v${s} = get${s}AtOutCoords();`)});let o=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
void main() {
${n.join(`
`)}
2022-01-14 16:04:13 +01:00
2022-03-07 19:17:31 +01:00
vec4 result = ${o};
setOutput(result);
}
`}};function kb(r){let{inputs:t,backend:e}=r,n=t;if(n.length===1)return er({inputs:{x:n[0]},backend:e});if(n.length>G().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(n.length/2),l=kb({inputs:n.slice(0,u),backend:e}),c=kb({inputs:n.slice(u),backend:e});return kb({inputs:[l,c],backend:e})}let o=n.map(u=>u.dtype).reduce((u,l)=>yr(u,l)),s=n.map(u=>u.shape),a=G().getBool("WEBGL_PACK")?new Vk(n[0].shape,s):new Bk(n[0].shape,s);return e.runWebGLProgram(a,n,o)}var iL={kernelName:qo,backendName:"webgl",kernelFunc:kb};function _tt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n,a=o.shape.length,u=x.parseAxisParam(s,o.shape),l=u,c=k.getAxesPermutation(l,a),p=o;c!=null&&(p=Le({inputs:{x:o},backend:e,attrs:{perm:c}}),l=k.getInnerMostAxes(l.length,a)),k.assertAxesAreInnerMostDims("all",l,a);let[m,f]=k.computeOutAndReduceShapes(p.shape,l),d=x.sizeFromShape(f),h=ut({inputs:{x:p},backend:e,attrs:{shape:[-1,d]}}),g=Wn(h,h.dtype,"all",e),y;if(i){let b=k.expandShapeToKeepDim(m,u);y=ut({inputs:{x:g},backend:e,attrs:{shape:b}})}else y=ut({inputs:{x:g},backend:e,attrs:{shape:m}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(g),c!=null&&e.disposeIntermediateTensorInfo(p),y}var aL={kernelName:Yi,backendName:"webgl",kernelFunc:_tt};function Ett(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n,a=o.shape.length,u=x.parseAxisParam(s,o.shape),l=u,c=k.getAxesPermutation(l,a),p=o;c!=null&&(p=Le({inputs:{x:o},backend:e,attrs:{perm:c}}),l=k.getInnerMostAxes(l.length,a)),k.assertAxesAreInnerMostDims("any",l,a);let[m,f]=k.computeOutAndReduceShapes(p.shape,l),d=x.sizeFromShape(f),h=ut({inputs:{x:p},backend:e,attrs:{shape:[-1,d]}}),g=Wn(h,h.dtype,"any",e),y;if(i){let b=k.expandShapeToKeepDim(m,u);y=ut({inputs:{x:g},backend:e,attrs:{shape:b}})}else y=ut({inputs:{x:g},backend:e,attrs:{shape:m}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(g),c!=null&&e.disposeIntermediateTensorInfo(p),y}var lL={kernelName:Zi,backendName:"webgl",kernelFunc:Ett};var Gk=class{constructor(t,e,n){this.variableNames=["A"];let{windowSize:o,batchSize:s,outSize:i}=t;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,i];let a=e==="max"?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${o};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int i = 0; i < ${o}; i++) {
int inIdx = ${u};
float candidate = getA(batch, inIdx);
if (candidate ${a} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}};var Wk=class{constructor(t,e,n,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,x.assert(t.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let s=t[t.length-1],i=Math.ceil(s/e);this.outputShape=t.slice(0,-1),i>1&&this.outputShape.push(i),o||this.variableNames.push("bestIndicesA");let a=this.outputShape,u=a.length,l=Ht(u),c=tr("coords",u),p,m;if(i===1){m=u+1;let $=Ht(m);p=`
${$} sourceLocR = ${$}(${c.join()}, 0);
++${c[u-1]};
${$} sourceLocG = ${$}(${c.join()}, 0);
++${c[u-2]};
${$} sourceLocA = ${$}(${c.join()}, 0);
--${c[u-1]};
${$} sourceLocB = ${$}(${c.join()}, 0);
--${c[u-2]};`}else m=u,p=`
${l} sourceLocR = coords;
++${c[u-1]};
${l} sourceLocG = coords;
++${c[u-2]};
${l} sourceLocA = coords;
--${c[u-1]};
${l} sourceLocB = coords;
--${c[u-2]};`;let f=["x","y","z","w","u","v"].slice(0,m),d="."+f[m-1],h=f.map($=>"int "+$),g=tr("sourceLocR",m-1).concat("inIdx.r"),y=tr("sourceLocG",m-1).concat("inIdx.g"),b=tr("sourceLocB",m-1).concat("inIdx.b"),w=tr("sourceLocA",m-1).concat("inIdx.a"),v=n==="max"?"greaterThan":"lessThan",I=o?"":`
inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${y.join()}),
getBestIndicesAChannel(${b.join()}),
getBestIndicesAChannel(${w.join()})));`,E=`vec4(
getAChannel(${g.join()}),
hasNextCol ? getAChannel(${y.join()}) : 0.,
hasNextRow ? getAChannel(${b.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,D=o?"":`
float getBestIndicesAChannel(${h.join()}) {
return getChannel(getBestIndicesA(${f.join()}),
vec2(${f.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${h.join()}) {
return getChannel(getA(${f.join()}),
vec2(${f.slice(-2).join()}));
}
${D}
void main() {
${l} coords = getOutputCoords();
bool hasNextCol = ${c[u-1]} < ${a[u-1]-1};
bool hasNextRow = ${c[u-2]} < ${a[u-2]-1};
${p}
ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
sourceLocB${d}, sourceLocA${d}) * ${e};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${E};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int i = 0; i < ${e}; i++) {
inIdx = srcIdx;
${I}
vec4 candidate = ${E};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${v}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +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);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function uL(r,t,e,n=null){let o=t.shape[0],s=t.shape[1];n!=null&&(o=n.shape[0],s=n.shape[1]);let i=k.computeOptimalWindowSize(s),a={windowSize:i,inSize:s,batchSize:o,outSize:Math.ceil(s/i)},u=new Gk(a,e,n==null),l=[t];n!=null&&l.push(n);let c=r.runWebGLProgram(u,l,"int32");if(c.shape[1]===1)return c;let p=uL(r,t,e,c);return r.disposeIntermediateTensorInfo(c),p}function cL(r,t,e,n=null){let o=n!=null?n.shape:t.shape,s=o[o.length-1],i=k.computeOptimalWindowSize(s),a=new Wk(o,i,e,n==null),u=n==null?[t]:[t,n],l=r.runWebGLProgram(a,u,"int32");if(l.shape.length===t.shape.length){let c=cL(r,t,e,l);return r.disposeIntermediateTensorInfo(l),c}return l}function Nb(r,t,e,n){let o=[e];if(k.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),o,t.shape.length),!G().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],i=r.texData.get(t.dataId),a=i!==null&&i.isPacked,u=t;a&&(u=r.unpackTensor(t),s.push(u));let[l,c]=k.computeOutAndReduceShapes(u.shape,o),p=x.sizeFromShape(c),m=ut({inputs:{x:u},backend:r,attrs:{shape:[-1,p]}});s.push(m);let f=uL(r,m,n);s.push(f);let d=ut({inputs:{x:f},backend:r,attrs:{shape:l}});return s.forEach(h=>r.disposeIntermediateTensorInfo(h)),d}return cL(r,t,n)}function Att(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s}=n,i=x.parseAxisParam(s,o.shape),a=k.getAxesPermutation(i,o.shape.length),u=o,l=[];a!=null&&(u=Le({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(u),i=k.getInnerMostAxes(i.length,u.shape.length)),k.assertAxesAreInnerMostDims("argMax",[i[0]],u.shape.length);let c=Nb(e,u,i[0],"max");return l.forEach(p=>e.disposeIntermediateTensorInfo(p)),c}var pL={kernelName:Ko,backendName:"webgl",kernelFunc:Att};function Dtt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s}=n,i=x.parseAxisParam(s,o.shape),a=k.getAxesPermutation(i,o.shape.length),u=o,l=[];a!=null&&(u=Le({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(u),i=k.getInnerMostAxes(i.length,u.shape.length)),k.assertAxesAreInnerMostDims("argMin",[i[0]],u.shape.length);let c=Nb(e,u,i[0],"min");return l.forEach(p=>e.disposeIntermediateTensorInfo(p)),c}var mL={kernelName:wl,backendName:"webgl",kernelFunc:Dtt};var $tt=dr+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,Rtt=Ct({opSnippet:$tt}),fL={kernelName:Ji,backendName:"webgl",kernelFunc:Rtt};var Ftt=dr+"return log(x + sqrt(x * x + 1.0));",Ott=Ct({opSnippet:Ftt}),dL={kernelName:Qi,backendName:"webgl",kernelFunc:Ott};var Ptt=dr+`
return atan(x);
`,Mtt=Ct({opSnippet:Ptt}),hL={kernelName:ta,backendName:"webgl",kernelFunc:Mtt};var Ltt=UM+`
return atan(a, b);
`,ztt=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+HM+`
return result;
`,Btt=le({opSnippet:Ltt,packedOpSnippet:ztt}),gL={kernelName:ra,backendName:"webgl",kernelFunc:Btt};var Vtt=dr+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Gtt=Ct({opSnippet:Vtt}),xL={kernelName:ea,backendName:"webgl",kernelFunc:Gtt};var Hi=class{constructor(t,e,n,o=!1,s=!1){if(this.variableNames=["x"],e==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let i=t.filterWidth,a=t.strideHeight,u=t.strideWidth,l=t.dilationHeight,c=t.dilationWidth,p=t.effectiveFilterHeight,m=t.effectiveFilterWidth,f=t.padInfo.top,d=t.padInfo.left;this.outputShape=t.outShape;let h=e==="avg",g=`((batch * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + d`,y=`(xR * ${t.inWidth} + xC) * ${t.inChannels} + d`,b="0.0";if(h||(b="-1.0 / 1e-20"),n){let $=">=";this.userCode=`
const ivec2 strides = ivec2(${a}, ${u});
const ivec2 pads = ivec2(${f}, ${d});
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// 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;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${p};
wR += ${l}) {
int xR = xRCorner + wR;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${m};
wC += ${c}) {
int xC = xCCorner + wC;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float value = getX(batch, xR, xC, d);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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 ${$} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${o?s?g:y:`wR * ${m} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}let w="max",v=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(v="avgValue / count");let I=Math.floor(i/4)*4,E=i%4,D=`
if (${h}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${w}(values, minMaxValue);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`;this.userCode=`
const ivec2 strides = ivec2(${a}, ${u});
const ivec2 pads = ivec2(${f}, ${d});
const float initializationValue = ${b};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float count = 0.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${t.inWidth}) {
return initializationValue;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
count += 1.0;
return getX(batch, xR, xC, d);
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${b});
float avgValue = 0.0;
count = 0.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${p};
wR += ${l}) {
int xR = xRCorner + wR;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${I}; wC += 4) {
int xC = xCCorner + wC * ${c};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
getValue(batch, xR, xC + 3 * ${c}, d)
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${D}
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
int xC = xCCorner + ${I};
if (${E===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${D}
} else if (${E===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${D}
} else if (${E===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
initializationValue
);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${D}
2021-04-01 19:39:54 +02:00
}
}
2022-03-07 19:17:31 +01:00
setOutput(${v});
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}},Mc=class{constructor(t,e,n,o=!1,s=!1){if(this.variableNames=["x"],e==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let i=t.filterWidth,a=t.strideDepth,u=t.strideHeight,l=t.strideWidth,c=t.dilationDepth,p=t.dilationHeight,m=t.dilationWidth,f=t.effectiveFilterDepth,d=t.effectiveFilterHeight,h=t.effectiveFilterWidth,g=t.padInfo.front,y=t.padInfo.top,b=t.padInfo.left;this.outputShape=t.outShape;let w=e==="avg",v="0.0";if(w||(v="-1.0 / 1e-20"),n){let M=">=";this.userCode=`
const ivec3 strides =
ivec3(${a}, ${u}, ${l});
const ivec3 pads = ivec3(${g}, ${y}, ${b});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wD = 0; wD < ${f};
wD += ${c}) {
int xD = xDCorner + wD;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xD < 0 || xD >= ${t.inDepth}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${h};
wC += ${m}) {
int xC = xCCorner + wC;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float value = getX(batch, xD, xR, xC, ch);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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 ${M} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${o?s?`(((batch * ${t.inDepth} + xD) * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`((xD * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`wD * ${d} * ${h} +
wR * ${h} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}let I="max",E=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(E="avgValue / count");let D=Math.floor(i/4)*4,$=i%4,R=`
if (${w}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${I}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${a}, ${u}, ${l});
const ivec3 pads = ivec3(${g}, ${y}, ${b});
const float initializationValue = ${v};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float count = 0.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${t.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${v});
float avgValue = 0.0;
count = 0.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wD = 0; wD < ${f};
wD += ${c}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${t.inDepth}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${D}; wC += 4) {
int xC = xCCorner + wC * ${m};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +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),
getValue(batch, xD, xR, xC + 3 * ${m}, ch)
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${R}
}
int xC = xCCorner + ${D};
if (${$===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${R}
} else if (${$===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${m}, ch),
initializationValue,
initializationValue
);
${R}
} else if (${$===3}) {
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
);
${R}
}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput(${E});
2021-04-01 19:39:54 +02:00
}
}
2022-03-07 19:17:31 +01:00
`}};function Wtt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t;ai(o,"avgPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:u}=n,l=1;x.assert(k.eitherStridesOrDilationsAreOne(i,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);let c=k.computePool2DInfo(o.shape,s,i,l,a,u);if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))return er({inputs:{x:o},backend:e});let p=new Hi(c,"avg",!1);return e.runWebGLProgram(p,[o],"float32")}var yL={kernelName:jo,backendName:"webgl",kernelFunc:Wtt};function Utt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{filterSize:s,strides:i,pad:a,dimRoundingMode:u,dataFormat:l}=n,c=[1,1,1],p=k.computePool3DInfo(o.shape,s,i,c,a,u,l),m=new Mc(p,"avg",!1);return e.runWebGLProgram(m,[o],"float32")}var bL={kernelName:vl,backendName:"webgl",kernelFunc:Utt};var Uk=class{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;let e=t.filterHeight,n=t.filterWidth,o=t.strideHeight,s=t.strideWidth,i=t.dilationHeight,a=t.dilationWidth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=u-1-t.padInfo.top,p=l-1-t.padInfo.left,m=1/(e*n);this.userCode=`
const ivec2 pads = ivec2(${c}, ${p});
const float avgMultiplier = float(${m});
2021-12-06 12:34:50 +01:00
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2022-03-07 19:17:31 +01:00
int b = coords[0];
int d = coords[3];
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// 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 < ${u};
wR += ${i}) {
float dyR = float(dyRCorner + wR) / ${o}.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${l};
wC+= ${a}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float dyValue = getDy(b, idyR, idyC, d);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
dotProd += dyValue * avgMultiplier;
2021-04-01 19:39:54 +02:00
}
}
2022-03-07 19:17:31 +01:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}},Hk=class{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;let e=t.filterDepth,n=t.filterHeight,o=t.filterWidth,s=t.strideDepth,i=t.strideHeight,a=t.strideWidth,u=t.dilationDepth,l=t.dilationHeight,c=t.dilationWidth,p=t.effectiveFilterDepth,m=t.effectiveFilterHeight,f=t.effectiveFilterWidth,d=p-1-t.padInfo.front,h=m-1-t.padInfo.top,g=f-1-t.padInfo.left,y=1/(e*n*o);this.userCode=`
const ivec3 pads = ivec3(${d}, ${h}, ${g});
const float avgMultiplier = float(${y});
2021-12-06 12:34:50 +01:00
2021-04-01 19:39:54 +02:00
void main() {
2022-03-07 19:17:31 +01:00
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// 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;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wD = 0; wD < ${p};
wD += ${u}) {
float dyD = float(dyDCorner + wD) / ${s}.0;
if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
continue;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
int idyD = int(dyD);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${m};
wR += ${l}) {
float dyR = float(dyRCorner + wR) / ${i}.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
fract(dyR) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
2022-03-07 19:17:31 +01:00
int idyR = int(dyR);
for (int wC = 0; wC < ${f};
wC += ${c}) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
2021-04-01 19:39:54 +02:00
}
}
2022-03-07 19:17:31 +01:00
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function Htt(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,i=s,{filterSize:a,strides:u,pad:l,dimRoundingMode:c}=n,p=[1,1,1],m=k.computePool3DInfo(i.shape,a,u,p,l,c),f=new Hk(m);return e.runWebGLProgram(f,[o],i.dtype)}var wL={kernelName:lp,backendName:"webgl",kernelFunc:Htt};function qtt(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,i=s;ai([o,s],"avgPoolGrad");let{filterSize:a,strides:u,pad:l}=n,c=k.computePool2DInfo(i.shape,a,u,1,l),p=new Uk(c);return e.runWebGLProgram(p,[o],i.dtype)}var vL={kernelName:ap,backendName:"webgl",kernelFunc:qtt};function Ktt(r){let{inputs:t,backend:e,attrs:n}=r,{a:o,b:s}=t,{transposeA:i,transposeB:a}=n;return Pc({a:o,b:s,transposeA:i,transposeB:a,backend:e})}var CL={kernelName:Xo,backendName:"webgl",kernelFunc:Ktt};var qk=class{constructor(t,e,n,o,s,i){this.outputShape=[],this.variableNames=["x","mean","variance"],k.assertAndGetBroadcastShape(t,e),k.assertAndGetBroadcastShape(t,n);let a="0.0";o!=null&&(k.assertAndGetBroadcastShape(t,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let u="1.0";s!=null&&(k.assertAndGetBroadcastShape(t,s),this.variableNames.push("scale"),u="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${a};
float scale = ${u};
float inv = scale * inversesqrt(variance + float(${i}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}};var Kk=class{constructor(t,e,n,o,s,i){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],k.assertAndGetBroadcastShape(t,e),k.assertAndGetBroadcastShape(t,n);let a="vec4(0.0)";o!=null&&(k.assertAndGetBroadcastShape(t,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let u="vec4(1.0)";s!=null&&(k.assertAndGetBroadcastShape(t,s),this.variableNames.push("scale"),u="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
void main() {
vec4 offset = ${a};
vec4 scale = ${u};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec4 inv = scale * inversesqrt(variance + vec4(${i}));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
setOutput((x - mean) * inv + offset);
}
`}};var jtt=({inputs:r,backend:t,attrs:e})=>{let{x:n,mean:o,variance:s,offset:i,scale:a}=r;x.assert(o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),x.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),x.assert(a==null||o.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:u}=e;u==null&&(u=.001);let l=[n,o,s],c=null;i!=null&&(c=i.shape,l.push(i));let p=null;a!=null&&(p=a.shape,l.push(a));let m=G().getBool("WEBGL_PACK_NORMALIZATION")?new Kk(n.shape,o.shape,s.shape,c,p,u):new qk(n.shape,o.shape,s.shape,c,p,u);return t.runWebGLProgram(m,l,l[0].dtype)},IL={kernelName:ls,backendName:"webgl",kernelFunc:jtt};var Xk=class{constructor(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;let e=Ht(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=Xtt(this.rank),o,s=t.map((i,a)=>`sourceLoc.${jk[a]} = start[${a}] + coords.${jk[a]};`);o=`
${e} sourceLoc;
${e} coords = getOutputCoords();
${s.join(`
`)}
`,this.userCode=`
void main() {
${o}
setOutput(getSource(${n}));
}
`}},jk=["x","y","z","w","u","v"];function Xtt(r){if(r===1)return"sourceLoc";if(r<=6)return jk.slice(0,r).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}var Yk=class{constructor(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let e=Ht(this.rank),n=tr("coords",this.rank),o=tr("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${o.slice(-2).join()})`,i=`getChannel(getSource(${o.join()}), ${s})`,a=`
result.x = ${i};
if (++${n[this.rank-1]} < ${t[this.rank-1]}) {
++${o[this.rank-1]};
result.y = ${i};
--${o[this.rank-1]};
}
`,u=this.rank===1?"":`
--${n[this.rank-1]};
if (++${n[this.rank-2]} < ${t[this.rank-2]}) {
++${o[this.rank-2]};
result.z = ${i};
if (++${n[this.rank-1]} < ${t[this.rank-1]}) {
++${o[this.rank-1]};
result.w = ${i};
}
}
`,l=this.rank<=4?`sourceLoc = coords +
${e}(${t.map((c,p)=>`start[${p}]`).join()});`:t.map((c,p)=>`${o[p]} = ${n[p]} + start[${p}];`).join(`
`);this.userCode=`
void main() {
${e} coords = getOutputCoords();
${e} sourceLoc;
${l}
vec4 result = vec4(0.);
${a}
${u}
setOutput(result);
}
`}};function Ytt(r,t,e,n){let o=n.texData.get(r.dataId),s=n.makeTensorInfo(e,r.dtype),i=n.texData.get(s.dataId);Object.assign(i,o),i.refCount=1,i.shape=e,i.dtype=r.dtype;let a=Ve.computeFlatOffset(t,x.computeStrides(r.shape));o.slice&&(a+=o.slice.flatOffset),i.slice={flatOffset:a,origDataId:o.slice&&o.slice.origDataId||r.dataId};let u=n.dataRefCount.get(i.slice.origDataId)||1;return n.dataRefCount.set(i.slice.origDataId,u+1),s}function ci(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{begin:s,size:i}=n,[a,u]=Ve.parseSliceParams(o,s,i);if(Ve.assertParamsValid(o,a,u),x.sizeFromShape(u)===0)return e.makeTensorInfo(u,o.dtype,[]);if(e.shouldExecuteOnCPU([o])||o.dtype==="string"){let p=e.texData.get(o.dataId),m=pM(p.values,a,u,o.shape,o.dtype);return e.makeTensorInfo(u,o.dtype,m)}let{isPacked:l}=e.texData.get(o.dataId),c=Ve.isSliceContinous(o.shape,a,u);if(l||!c){let p=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Yk(u):new Xk(u),m=[a];return e.runWebGLProgram(p,[o],o.dtype,m)}return e.uploadToGPU(o.dataId),Ytt(o,a,u,e)}var SL={kernelName:Si,backendName:"webgl",kernelFunc:ci};var Ztt=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockShape:s,crops:i}=n;x.assert(o.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let a=s.reduce((b,w)=>b*w),u=k.getReshaped(o.shape,s,a),l=k.getPermuted(u.length,s.length),c=k.getReshapedPermuted(o.shape,s,a),p=k.getSliceBeginCoords(i,s.length),m=k.getSliceSize(c,i,s.length),f=[],d=ut({inputs:{x:o},backend:e,attrs:{shape:u}}),h=Le({inputs:{x:d},backend:e,attrs:{perm:l}}),g=ut({inputs:{x:h},backend:e,attrs:{shape:c}}),y=ci({inputs:{x:g},backend:e,attrs:{begin:p,size:m}});return f.push(d),f.push(h),f.push(g),f.forEach(b=>e.disposeIntermediateTensorInfo(b)),y},kL={kernelName:hi,backendName:"webgl",kernelFunc:Ztt};function Jtt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,weights:s}=t,{size:i}=n,a=e.readSync(o.dataId),u=e.readSync(s.dataId),l=yb(a,u,s.dtype,s.shape,i);return e.makeTensorInfo([i],s.dtype,l)}var NL={kernelName:up,backendName:"webgl",kernelFunc:Jtt};function Qtt(r){let{inputs:t,backend:e}=r,{s0:n,s1:o}=t,s=e.readSync(n.dataId),i=e.readSync(o.dataId),a=k.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return e.makeTensorInfo([a.length],"int32",Int32Array.from(a))}var TL={kernelName:cp,backendName:"webgl",kernelFunc:Qtt};var tet="return float(a != b);",Zk=le({opSnippet:tet,cpuKernelImpl:iM,dtype:"bool"}),_L={kernelName:ba,backendName:"webgl",kernelFunc:Zk};function ml(r){let{inputs:t,backend:e}=r,{input:n}=t,o=e.texData.get(n.dataId);return er({inputs:{x:o.complexTensorInfos.real},backend:e})}var EL={kernelName:Ap,backendName:"webgl",kernelFunc:ml};var eet="return float(int(x));";function AL(r,t){let e=new wn(r.shape,eet),n=t.runWebGLProgram(e,[r],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function Jk(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{dtype:s}=n;if(s==="complex64"){if(o.dtype==="complex64")return er({inputs:{x:o},backend:e});let i=ye(o.shape),a=Jk({inputs:{x:o},backend:e,attrs:{dtype:"float32"}}),u=Dn({inputs:{real:a,imag:i},backend:e});return i.dispose(),e.disposeIntermediateTensorInfo(a),u}if(o.dtype==="complex64"){let i=ml({inputs:{input:o},backend:e}),a=Jk({inputs:{x:i},backend:e,attrs:{dtype:s}});return e.disposeIntermediateTensorInfo(i),a}if(!x.hasEncodingLoss(o.dtype,s)){let i=er({inputs:{x:o},backend:e});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return AL(o,e);if(s==="bool"){let i=e.makeTensorInfo([],"bool",x.getTypedArrayFromDType("bool",1)),u=Zk({inputs:{a:o,b:i},backend:e});return e.disposeIntermediateTensorInfo(i),u}throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${s}`)}var DL={kernelName:no,backendName:"webgl",kernelFunc:Jk};var $L="return ceil(x);",ret=Ct({opSnippet:$L,packedOpSnippet:$L,cpuKernelImpl:VP}),RL={kernelName:Yo,backendName:"webgl",kernelFunc:ret};var Qk=class{constructor(t){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,this.userCode=`
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`}};var tN=class{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,this.userCode=`
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`}};function net(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{clipValueMin:s,clipValueMax:i}=n,a;G().getBool("WEBGL_PACK_CLIP")?a=new tN(o.shape):a=new Qk(o.shape);let u=[[s],[i]];return e.runWebGLProgram(a,[o],o.dtype,u)}var FL={kernelName:oo,backendName:"webgl",kernelFunc:net};var eN=class{constructor(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=`
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 OL(r,t){return{dataId:t.dataId,dtype:t.dtype,shape:r.shape}}function oet(r){let{inputs:t,backend:e}=r,{x:n}=t,o=e.texData.get(n.dataId),s=new eN(n.shape),i=[OL(n,o.complexTensorInfos.real),OL(n,o.complexTensorInfos.imag)];return e.runWebGLProgram(s,i,i[0].dtype)}var PL={kernelName:Cl,backendName:"webgl",kernelFunc:oet};var rN=class{constructor(t){this.outputShape=[],this.outputShape=k.computeOutShape(t,1),this.variableNames=t.map((i,a)=>`T${a}`);let e=new Array(t.length-1);e[0]=t[0][1];for(let i=1;i<e.length;i++)e[i]=e[i-1]+t[i][1];let n=[`if (yC < ${e[0]}) setOutput(getT0(yR, yC));`];for(let i=1;i<e.length;i++){let a=e[i-1];n.push(`else if (yC < ${e[i]}) setOutput(getT${i}(yR, yC-${a}));`)}let o=e.length,s=e[e.length-1];n.push(`else setOutput(getT${o}(yR, yC-${s}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${n.join(`
`)}
}
`}};var nN=class{constructor(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=k.computeOutShape(t,e);let n=this.outputShape,o=n.length,s=Ht(o),i=tr("coords",o),a=["x","y","z","w","u","v"].slice(0,o);this.variableNames=t.map((h,g)=>`T${g}`);let u=new Array(t.length-1);u[0]=t[0][e];for(let h=1;h<u.length;h++)u[h]=u[h-1]+t[h][e];let l=a[e],c=a.slice(-2),p=a.join(),m=`if (${l} < ${u[0]}) {
return getChannel(
getT0(${p}), vec2(${c.join()}));
}`;for(let h=1;h<u.length;h++){let g=u[h-1];m+=`
if (${l} < ${u[h]} && ${l} >= ${u[h-1]}) {
return getChannel(
getT${h}(${Tb(a,l,g)}),
vec2(${Tb(c,l,g)}));
}`}let f=u.length,d=u[u.length-1];m+=`
return getChannel(
getT${f}(${Tb(a,l,d)}),
vec2(${Tb(c,l,d)}));`,this.userCode=`
float getValue(${a.map(h=>"int "+h)}) {
${m}
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
${s} coords = getOutputCoords();
vec4 result = vec4(getValue(${i}), 0., 0., 0.);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${i[o-1]} = ${i[o-1]} + 1;
if (${i[o-1]} < ${n[o-1]}) {
result.g = getValue(${i});
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${i[o-2]} = ${i[o-2]} + 1;
if (${i[o-2]} < ${n[o-2]}) {
result.a = getValue(${i});
}
${i[o-1]} = ${i[o-1]} - 1;
if (${i[o-2]} < ${n[o-2]} &&
${i[o-1]} < ${n[o-1]}) {
result.b = getValue(${i});
}
setOutput(result);
}
`}};function Tb(r,t,e){let n=r.indexOf(t);return r.map((s,i)=>i===n?`${s} - ${e}`:s).join()}function Lc(r){let{inputs:t,backend:e}=r,{input:n}=t,o=e.texData.get(n.dataId);return er({inputs:{x:o.complexTensorInfos.imag},backend:e})}var ML={kernelName:Ip,backendName:"webgl",kernelFunc:Lc};function zc(r,t,e){let n=r[0].dtype;if(n==="complex64"){let c=r.map(h=>ml({inputs:{input:h},backend:e})),p=r.map(h=>Lc({inputs:{input:h},backend:e})),m=zc(c,t,e),f=zc(p,t,e),d=Dn({inputs:{real:m,imag:f},backend:e});return c.forEach(h=>e.disposeIntermediateTensorInfo(h)),p.forEach(h=>e.disposeIntermediateTensorInfo(h)),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f),d}let o=e.shouldExecuteOnCPU(r);if(n==="string"&&(o=!0),o){let c=r.map(y=>{let b=x.sizeFromShape(y.shape.slice(t));return ut({inputs:{x:y},backend:e,attrs:{shape:[-1,b]}})}),p=c.map(y=>({vals:e.readSync(y.dataId),shape:y.shape})),m=k.computeOutShape(c.map(y=>y.shape),1),f=c[0].shape[0]===1,d=GP(p,m,n,f),h=k.computeOutShape(r.map(y=>y.shape),t),g=e.makeTensorInfo(h,n,d);return c.forEach(y=>e.disposeIntermediateTensorInfo(y)),g}if(r.length>G().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(r.length/2),p=zc(r.slice(0,c),t,e),m=zc(r.slice(c),t,e),f=zc([p,m],t,e);return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(m),f}if(G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&r[0].shape.length>1){let c=new nN(r.map(p=>p.shape),t);return e.runWebGLProgram(c,r,n)}let{tensors2D:s,outShape:i}=set(r,t,e),a=new rN(s.map(c=>c.shape)),u=e.runWebGLProgram(a,s,n);s.forEach(c=>e.disposeIntermediateTensorInfo(c));let l=ut({inputs:{x:u},attrs:{shape:i},backend:e});return e.disposeIntermediateTensorInfo(u),l}function set(r,t,e){let n=k.computeOutShape(r.map(s=>s.shape),t);return{tensors2D:r.map(s=>ut({inputs:{x:s},attrs:{shape:[-1,x.sizeFromShape(s.shape.slice(t))]},backend:e})),outShape:n}}function oN(r){let{inputs:t,backend:e,attrs:n}=r,{axis:o}=n,s=x.parseAxisParam(o,t[0].shape)[0],i=k.computeOutShape(t.map(l=>l.shape),s);if(x.sizeFromShape(i)===0)return e.makeTensorInfo(i,t[0].dtype,[]);let a=t.filter(l=>x.sizeFromShape(l.shape)>0);if(a.length===1)return er({inputs:{x:a[0]},backend:e});let u=a.map(l=>l.shape);return k.assertParamsConsistent(u,s),zc(a,s,e)}var LL={kernelName:gi,backendName:"webgl",kernelFunc:oN};var ug=class{constructor(t,e=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"],this.outputShape=t.outShape;let i=t.padInfo.top,a=t.padInfo.left,u=t.strideHeight,l=t.strideWidth,c=t.dilationHeight,p=t.dilationWidth,m=t.filterHeight,f=t.filterWidth,d=Math.floor(t.inChannels/4)*4,h=t.inChannels%4,g=t.dataFormat==="channelsLast",y=g?1:2,b=g?2:3,w=g?3:1,v="",I="";n&&(o?v=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?v=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}`:v=`
float activation(float x) {
${n}
}
`,I="result = activation(result);");let E=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${v}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
const ivec2 strides = ivec2(${u}, ${l});
const ivec2 pads = ivec2(${i}, ${a});
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2022-03-07 19:17:31 +01:00
int batch = coords[0];
int d2 = coords[${w}];
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
ivec2 xRCCorner =
ivec2(coords[${y}], coords[${b}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
2021-04-01 19:39:54 +02:00
// ? = to be determined. : = across all values in that axis.
2021-03-31 13:01:22 +02:00
float dotProd = 0.0;
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${c};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2021-04-01 19:39:54 +02:00
continue;
}
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${f}; wC++) {
int xC = xCCorner + wC * ${p};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2021-04-01 19:39:54 +02:00
continue;
}
2022-03-07 19:17:31 +01:00
for (int d1 = 0; d1 < ${d}; d1 += 4) {
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)
);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
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);
}
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (${h===1}) {
if (${g}) {
dotProd +=
getX(batch, xR, xC, ${d}) *
getW(wR, wC, ${d}, d2);
} else {
dotProd +=
getX(batch, ${d}, xR, xC) *
getW(wR, wC, ${d}, d2);
}
} else if (${h===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${d}, d2),
getW(wR, wC, ${d} + 1, d2)
);
if (${g}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${d}),
getX(batch, xR, xC, ${d} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${d}, xR, xC),
getX(batch, ${d} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${h===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${d}, d2),
getW(wR, wC, ${d} + 1, d2),
getW(wR, wC, ${d} + 2, d2)
);
if (${g}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${d}),
getX(batch, xR, xC, ${d} + 1),
getX(batch, xR, xC, ${d} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${d}, xR, xC),
getX(batch, ${d} + 1, xR, xC),
getX(batch, ${d} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
2021-04-01 19:39:54 +02:00
}
}
2022-03-07 19:17:31 +01:00
float result = dotProd;
${E}
${I}
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}},sN=class{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;let e=t.padInfo.front,n=t.padInfo.top,o=t.padInfo.left,s=t.strideDepth,i=t.strideHeight,a=t.strideWidth,u=t.dilationDepth,l=t.dilationHeight,c=t.dilationWidth,p=t.filterDepth,m=t.filterHeight,f=t.filterWidth,d=Math.floor(t.inChannels/4)*4,h=t.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${s}, ${i}, ${a});
const ivec3 pads = ivec3(${e}, ${n}, ${o});
2021-04-01 19:39:54 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
2022-03-07 19:17:31 +01:00
int d2 = coords.u;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
2021-04-01 19:39:54 +02:00
float dotProd = 0.0;
2022-03-07 19:17:31 +01:00
for (int wF = 0; wF < ${p}; wF++) {
int xF = xFCorner + wF * ${u};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xF < 0 || xF >= ${t.inDepth}) {
2021-04-01 19:39:54 +02:00
continue;
}
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${l};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2021-04-01 19:39:54 +02:00
continue;
}
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${f}; wC++) {
int xC = xCCorner + wC * ${c};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2021-04-01 19:39:54 +02:00
continue;
}
2022-03-07 19:17:31 +01:00
for (int d1 = 0; d1 < ${d}; d1 += 4) {
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)
);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (${h===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${d}) *
getW(wF, wR, wC, ${d}, d2);
} else if (${h===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${h===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1),
getX(batch, xF, xR, xC, ${d} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2),
getW(wF, wR, wC, ${d} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
}
}
}
setOutput(dotProd);
}
2022-03-07 19:17:31 +01:00
`}};var iN=class{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"},{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=t,this.enableShapeUniforms=De(this.outputShape.length);let{dataFormat:n}=e,o=He(),s=n==="channelsLast",i=s?0:1,a=s?1:2,u=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${t[1]} && pos < ${t[0]}) {`,l="";for(let c=0;c<=1;c++)for(let p=0;p<=1;p++)l+=`
blockIndex = rc.y + ${p};
pos = rc.x + ${c};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${u}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if(d0 < inputShape[${i}] && 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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if(d1 < inputShape[${a}] && d1 >= 0) {
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
ch = imod(pos, inChannels);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (${s}) {
innerDims = vec2(d1, ch);
result[${c*2+p}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${c*2+p}] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2022-03-07 19:17:31 +01:00
ivec2 rc = getOutputCoords();
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
vec4 result = vec4(0);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${l}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
${o.output} = result;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function _b({x:r,filter:t,convInfo:e,backend:n,bias:o=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:a=null}){let u=r.shape,l=n.texData.get(r.dataId),c=e.inChannels,p=u[0]*u[1]*u[2],m=e.outChannels,f=e.dataFormat==="channelsLast",d=!1,h=!1,g,y=[];if(!((p===1||m===1)&&c>zk)&&l.isPacked&&f&&l.texture!=null&&u[2]%2!==0&&x.arraysEqual(l.shape.slice(-3),u.slice(-3))){let v=u[0]*u[1]*(u[2]+1),I={dataId:r.dataId,shape:[1,v,e.inChannels],dtype:r.dtype},E=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,x.assert(ou(l.shape,I.shape),()=>`packed reshape ${l.shape} to ${I.shape} isn't free`);let D=ut({inputs:{x:t},backend:n,attrs:{shape:[1,e.inChannels,e.outChannels]}});y.push(D);let $=Pc({a:I,b:D,backend:n,transposeA:d,transposeB:h,bias:o,activation:a,preluActivationWeights:s,leakyreluAlpha:i}),R=n.texData.get($.dataId);x.assert(R.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=E,R.shape=e.outShape,g=er({inputs:{x:$},backend:n}),g.shape=e.outShape,y.push($)}else{let v=f?u[0]*u[1]*u[2]:u[0]*u[2]*u[3],I=ut({inputs:{x:r},backend:n,attrs:{shape:[1,v,e.inChannels]}}),E=ut({inputs:{x:t},backend:n,attrs:{shape:[1,e.inChannels,e.outChannels]}}),D=Pc({a:I,b:E,transposeA:d,transposeB:h,backend:n,bias:o,activation:a,preluActivationWeights:s,leakyreluAlpha:i});g=ut({inputs:{x:D},backend:n,attrs:{shape:e.outShape}}),y.push(I),y.push(E),y.push(D)}for(let v of y)n.disposeIntermediateTensorInfo(v);return g}function Eb({x:r,filter:t,convInfo:e,backend:n,bias:o=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:a=null}){let{filterWidth:u,filterHeight:l,inChannels:c,outWidth:p,outHeight:m,dataFormat:f}=e,d=f==="channelsLast",h=u*l*c,g=m*p,y=[h,g],b=!0,w=!1,v=[],I=ut({inputs:{x:r},backend:n,attrs:{shape:r.shape.slice(1)}}),E=ut({inputs:{x:t},backend:n,attrs:{shape:[1,h,x.sizeFromShape(t.shape)/h]}});v.push(I),v.push(E);let D=new iN(y,e),$=[I.shape,[e.padInfo.top,e.padInfo.left],[e.strideHeight,e.strideWidth],[e.dilationHeight,e.dilationWidth],[e.inChannels],[e.filterWidth*e.inChannels],[e.outWidth]],R=n.runWebGLProgram(D,[I],"float32",$),M=ut({inputs:{x:R},backend:n,attrs:{shape:[1,y[0],y[1]]}});v.push(R),v.push(M);let W=o!=null,U=s!=null,q=a==="leakyrelu",K=a?iu(a,!0):null,j=new ag(M.shape,E.shape,[1,g,e.outChannels],b,w,W,K,U,q),Q=[M,E];if(o&&Q.push(o),U&&Q.push(s),q){let st=n.makeTensorInfo([],"float32",x.createScalarValue(i,"float32"));Q.push(st),v.push(st)}let rt=n.runWebGLProgram(j,Q,"float32"),X=d?[1,m,p,e.outChannels]:[1,e.outChannels,m,p],nt=ut({inputs:{x:rt},backend:n,attrs:{shape:X}});v.push(rt);for(let st of v)n.disposeIntermediateTensorInfo(st);return nt}function iet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dataFormat:u,dilations:l,dimRoundingMode:c}=n,p=k.convertConv2DDataFormat(u),m=k.computeConv2DInfo(o.shape,s.shape,i,l,a,c,!1,p),f;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"))f=_b({x:o,filter:s,convInfo:m,backend:e});else if(G().getBool("WEBGL_CONV_IM2COL")&&o.shape[0]===1)f=Eb({x:o,filter:s,convInfo:m,backend:e});else{let h=new ug(m);f=e.runWebGLProgram(h,[o,s],"float32")}let d=ut({inputs:{x:f},backend:e,attrs:{shape:m.outShape}});return e.disposeIntermediateTensorInfo(f),d}var zL={kernelName:Zo,backendName:"webgl",kernelFunc:iet};var aN=class{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideHeight,n=t.strideWidth,o=t.padInfo.top,s=t.padInfo.left,i=t.dataFormat==="channelsLast";this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int b = 0; b < ${t.batchSize}; b++) {
for (int yR = 0; yR < ${t.outHeight}; yR++) {
int xR = wR + yR * ${e} - ${o};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int yC = 0; yC < ${t.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${s};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (${i}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
2022-01-14 16:04:13 +01:00
2022-03-07 19:17:31 +01:00
}
}
}
setOutput(dotProd);
}
`}},lN=class{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterHeight,n=t.filterWidth,o=t.strideHeight,s=t.strideWidth,i=t.dataFormat==="channelsLast",a=e-1-t.padInfo.top,u=n-1-t.padInfo.left,l=i?1:2,c=i?2:3,p=i?3:1;this.userCode=`
const ivec2 pads = ivec2(${a}, ${u});
2022-01-14 16:04:13 +01:00
2022-03-07 19:17:31 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${p}];
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
ivec2 dyCorner = ivec2(coords[${l}], coords[${c}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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 < ${e}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
int wRPerm = ${e} - 1 - wR;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
int wCPerm = ${n} - 1 - wC;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int d2 = 0; d2 < ${t.outChannels}; d2++) {
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (${i}) {
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;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
}
2021-04-01 19:39:54 +02:00
}
}
2022-03-07 19:17:31 +01:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}},uN=class{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideDepth,n=t.strideHeight,o=t.strideWidth,s=t.padInfo.front,i=t.padInfo.top,a=t.padInfo.left;this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2022-03-07 19:17:31 +01:00
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float dotProd = 0.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int b = 0; b < ${t.batchSize}; b++) {
for (int yF = 0; yF < ${t.outDepth}; yF++) {
int xF = wF + yF * ${e} - ${s};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xF < 0 || xF >= ${t.inDepth}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int yR = 0; yR < ${t.outHeight}; yR++) {
int xR = wR + yR * ${n} - ${i};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int yC = 0; yC < ${t.outWidth}; yC++) {
int xC = wC + yC * ${o} - ${a};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}},cN=class{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterDepth,n=t.filterHeight,o=t.filterWidth,s=t.strideDepth,i=t.strideHeight,a=t.strideWidth,u=e-1-t.padInfo.front,l=n-1-t.padInfo.top,c=o-1-t.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${u}, ${l}, ${c});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float dotProd = 0.0;
for (int wF = 0; wF < ${e}; wF++) {
float dyF = float(dyFCorner + wF) / ${s}.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (dyF < 0.0 || dyF >= ${t.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
int wFPerm = ${e} - 1 - wF;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${i}.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
int wRPerm = ${n} - 1 - wR;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${a}.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
int wCPerm = ${o} - 1 - wC;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int d2 = 0; d2 < ${t.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function aet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,pad:a,dataFormat:u,dimRoundingMode:l,filterShape:c}=n,p=k.convertConv2DDataFormat(u),m=k.computeConv2DInfo(o.shape,c,i,1,a,l,!1,p),f=new aN(m);return e.runWebGLProgram(f,[o,s],"float32")}var BL={kernelName:mp,backendName:"webgl",kernelFunc:aet};function uet(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{inputShape:i,strides:a,pad:u,dataFormat:l,dimRoundingMode:c}=n,p=k.convertConv2DDataFormat(l),m=k.computeConv2DInfo(i,s.shape,a,1,u,c,!1,p),f=new lN(m);return e.runWebGLProgram(f,[o,s],"float32")}var VL={kernelName:Jo,backendName:"webgl",kernelFunc:uet};function cet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u}=n,l=k.computeConv3DInfo(o.shape,s.shape,i,u,a),c=new sN(l);return e.runWebGLProgram(c,[o,s],"float32")}var GL={kernelName:Il,backendName:"webgl",kernelFunc:cet};function pet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,pad:a,filterShape:u}=n,l=k.computeConv3DInfo(o.shape,u,i,1,a),c=new uN(l);return e.runWebGLProgram(c,[o,s],"float32")}var WL={kernelName:fp,backendName:"webgl",kernelFunc:pet};function met(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{pad:i,strides:a,inputShape:u}=n,l=k.computeConv3DInfo(u,s.shape,a,1,i),c=new cN(l);return e.runWebGLProgram(c,[o,s],"float32")}var UL={kernelName:dp,backendName:"webgl",kernelFunc:met};var fet=Fo+`
return cos(x);
`,det=Ct({opSnippet:fet}),HL={kernelName:Qo,backendName:"webgl",kernelFunc:det};var het=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,get=Ct({opSnippet:het}),qL={kernelName:ts,backendName:"webgl",kernelFunc:get};var pN=class{constructor(t,e,n,o,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[i,a,u,l]=t,[c]=e,[p,m]=n;this.outputShape=[c,p,m,l];let f=o==="bilinear"?1:0,[d,h]=[`${a-1}.0`,`${u-1}.0`],[g,y,b]=p>1?[`${(a-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[w,v,I]=m>1?[`${(u-1)/(m-1)}`,"(x2-x1) * width_ratio",`x1*${h} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${h}`];this.userCode=`
const float height_ratio = float(${g});
const float width_ratio = float(${w});
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
2022-03-07 19:17:31 +01:00
int y = coords[1];
int x = coords[2];
2021-04-01 19:39:54 +02:00
int d = coords[3];
2022-03-07 19:17:31 +01:00
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${i}) {
return;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float height_scale = ${y};
float width_scale = ${v};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float in_y = ${b};
if( in_y < 0.0 || in_y > ${d} ) {
setOutput(float(${s}));
return;
}
float in_x = ${I};
if( in_x < 0.0 || in_x > ${h} ) {
setOutput(float(${s}));
return;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${f} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
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);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
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);
}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}};var xet=r=>{let{inputs:t,backend:e,attrs:n}=r,{image:o,boxes:s,boxInd:i}=t,{cropSize:a,method:u,extrapolationValue:l}=n,c=new pN(o.shape,s.shape,a,u,l);return e.runWebGLProgram(c,[o,s,i],"float32")},KL={kernelName:na,backendName:"webgl",kernelFunc:xet};var Ab=class{constructor(t,e,n){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=t;let o=t.length,s=e?"0.0":`getX(${jL(o,"coords")})`,i=t[t.length-1],a="",u="";e?(a=n?`end != ${i-1}`:"end != 0",u=n?"end + 1":"end - 1"):(a=n?`end + pow2 < ${i}`:"end >= pow2",u=n?"end + pow2":"end - pow2"),this.userCode=`
void main() {
${Ht(o)} coords = getOutputCoords();
int end = ${XL(o,"coords")};
float val = ${s};
int pow2 = int(pow(2.0, index));
if (${a}) {
int idx = ${u};
${XL(o,"coords")} = idx;
val += getX(${jL(o,"coords")});
}
setOutput(val);
}
`}};function jL(r,t){if(r===1)return`${t}`;if(r===2)return`${t}.x, ${t}.y`;if(r===3)return`${t}.x, ${t}.y, ${t}.z`;if(r===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${r} is not yet supported`)}function XL(r,t){if(r===1)return`${t}`;if(r===2)return`${t}.y`;if(r===3)return`${t}.z`;if(r===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${r} is not yet supported`)}function yet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,exclusive:i,reverse:a}=n,u=o.shape.length,l=k.getAxesPermutation([s],u),c=o;l!=null&&(c=Le({inputs:{x:o},backend:e,attrs:{perm:l}}));let p=k.getInnerMostAxes(1,u)[0];if(p!==u-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${o.shape.length-1} but got axis=${s}`);let m=c.shape[p],f=er({inputs:{x:c},backend:e});for(let d=0;d<=Math.ceil(Math.log2(m))-1;d++){let h=new Ab(c.shape,!1,a),g=[[d]],y=f;f=e.runWebGLProgram(h,[f],f.dtype,g),e.disposeIntermediateTensorInfo(y)}if(i){let d=new Ab(c.shape,i,a),h=f;f=e.runWebGLProgram(d,[f],f.dtype),e.disposeIntermediateTensorInfo(h)}if(l!=null){let d=k.getUndoAxesPermutation(l),h=Le({inputs:{x:f},backend:e,attrs:{perm:d}});return e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(c),h}return f}var YL={kernelName:es,backendName:"webgl",kernelFunc:yet};function bet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,weights:s}=t,{size:i,binaryOutput:a}=n;if(o.shape.length===1){let u=e.readSync(o.dataId),l=e.readSync(s.dataId),c=yb(u,l,s.dtype,s.shape,i);return e.makeTensorInfo([i],s.dtype,c)}else if(o.shape.length===2){let u=e.bufferSync(o),l=e.bufferSync(s),c=BP(u,l,i,a);return e.makeTensorInfo(c.shape,s.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}var ZL={kernelName:hp,backendName:"webgl",kernelFunc:bet};var mN=class{constructor(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
int in_h = h / ${e};
int offset_h = imod(h, ${e});
int in_w = w / ${e};
int offset_w = imod(w, ${e});
int offset_d = (offset_h * ${e} + offset_w) *
${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 wet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockSize:s,dataFormat:i}=n,a=o.shape[0],u=i==="NHWC"?o.shape[1]:o.shape[2],l=i==="NHWC"?o.shape[2]:o.shape[3],c=i==="NHWC"?o.shape[3]:o.shape[1],p=u*s,m=l*s,f=c/(s*s),d=i==="NHWC"?[a,p,m,f]:[a,f,p,m],h=new mN(d,s,i);return e.runWebGLProgram(h,[o],o.dtype)}var JL={kernelName:oa,backendName:"webgl",kernelFunc:wet};var cg=class{constructor(t,e=!1,n=null,o=!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=t.outShape,this.enableShapeUniforms=De(this.outputShape.length);let i=t.filterHeight,a=t.filterWidth,u=t.outChannels/t.inChannels,l="",c="";n&&(o?l=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?l=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}`:l=`
float activation(float x) {
${n}
}
`,c="result = activation(result);");let p=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${l}
2021-12-06 12:34:50 +01:00
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2022-03-07 19:17:31 +01:00
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${u};
int q = d2 - d1 * ${u};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// 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 < ${i}; wR++) {
int xR = xRCorner + wR * dilations[0];
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= inDims[0]) {
continue;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${a}; wC++) {
int xC = xCCorner + wC * dilations[1];
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xC < 0 || xC >= inDims[1]) {
continue;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float result = dotProd;
${p}
${c}
setOutput(result);
}
`}};var pg=class{constructor(t,e=!1,n=null,o=!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=t.outShape,this.enableShapeUniforms=De(this.outputShape.length);let i=t.outChannels/t.inChannels,a=t.padInfo.left,u=t.strideWidth,l=t.dilationWidth,c=t.filterHeight,p=t.filterWidth,m=p,f=`
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;for(let y=0;y<p;y++)f+=`
vec4 xTexelC${y*2};
int xTexelC${y*2}Ready;
vec4 xTexelC${y*2+1};
int xTexelC${y*2+1}Ready;
vec4 xC${y};`;f+=`
for (int r = 0; r < ${c}; r++) {
`;for(let y=0;y<p;y++)f+=`
xTexelC${y*2} = vec4(0.0);
xTexelC${y*2}Ready = 0;
xTexelC${y*2+1} = vec4(0.0);
xTexelC${y*2+1}Ready = 0;
xC${y} = vec4(0.0);`;f+=`
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;for(let y=0;y<(m+1)/2;y++){let b=y*2;if(f+=`
xC = xCCorner + ${b*l};
`,u===1){if(b<p&&(a%2===1?(f+=`
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// 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;
}
`,l===1&&b>0?f+=`
xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy);
`:f+=`
xCOffset = xC + 1 - 2;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
xC${b} = vec4(previous.zw, xTexelC${b}.xy);
} else {
xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
}
`):f+=`
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;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
xC${b} = xTexelC${b};
`,b+1<p)){let w=a%2===0?x.nearestLargerEven(l):l;l%2===0&&a%2===1||l%2!==0&&a%2!==1?(f+=`
xCOffset = xC + imod(pads[1], 2) + ${w};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// 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;
}
`,l>1&&(f+=`
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
xTexelC${b}Ready = 1;
}
`),f+=`
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy);
`):w===1?f+=`
xC${b+1} = xTexelC${b};
`:f+=`
xCOffset = xC + ${w};
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;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
xC${b+1} = xTexelC${b+1};
`}}else b<p&&(a%2===1?(f+=`
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;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
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;
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
xC${b} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
`,b+1<p&&(f+=`
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);
`)):(f+=`
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;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
xC${b} = vec4(
xTexelC${b}.xy, xTexelC${b+1}.xy);
`,b+1<p&&(f+=`
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
`)));b<p&&(f+=`
wTexel = getW(r, ${b}, d1, q);
dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
`,b+1<p&&(f+=`
wTexel = getW(r, ${b+1}, d1, q);
dotProd += xC${b+1} * vec4(wTexel.xz, wTexel.xz);
`))}f+=`
}
`,f+=`
}
`;let d="",h="";n&&(o?d=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?d=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${n}
}`:d=`vec4 activation(vec4 x) {
${n}
}`,h="result = activation(result);");let g=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${d}
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2022-03-07 19:17:31 +01:00
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${i};
int q = d2 - d1 * ${i};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${f}
2021-04-30 18:01:04 +02:00
2022-03-07 19:17:31 +01:00
vec4 result = dotProd - vec4(0.000000000000001);
${g}
${h}
setOutput(result);
2021-04-30 18:01:04 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function vet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u,dimRoundingMode:l}=n,c=u;c==null&&(c=[1,1]),x.assert(k.eitherStridesOrDilationsAreOne(i,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`);let p=k.computeConv2DInfo(o.shape,s.shape,i,c,a,l,!0),m;G().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels===1?m=new pg(p):m=new cg(p);let f=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return e.runWebGLProgram(m,[o,s],"float32",f)}var QL={kernelName:rs,backendName:"webgl",kernelFunc:vet};var fN=class{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideHeight,n=t.strideWidth,o=t.padInfo.top,s=t.padInfo.left,i=t.outChannels/t.inChannels;this.userCode=`
2021-04-30 18:01:04 +02:00
void main() {
ivec4 coords = getOutputCoords();
2022-03-07 19:17:31 +01:00
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${i} + dm;
2021-04-30 18:01:04 +02:00
2022-03-07 19:17:31 +01:00
float dotProd = 0.0;
2021-04-30 18:01:04 +02:00
2022-03-07 19:17:31 +01:00
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${t.batchSize}; b++) {
for (int yR = 0; yR < ${t.outHeight}; yR++) {
int xR = wR + yR * ${e} - ${o};
2021-04-30 18:01:04 +02:00
2022-03-07 19:17:31 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
continue;
}
2021-04-30 18:01:04 +02:00
2022-03-07 19:17:31 +01:00
for (int yC = 0; yC < ${t.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${s};
2021-04-30 18:01:04 +02:00
2022-03-07 19:17:31 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`}},dN=class{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterHeight,n=t.filterWidth,o=t.strideHeight,s=t.strideWidth,i=e-1-t.padInfo.top,a=n-1-t.padInfo.left,u=t.outChannels/t.inChannels;this.userCode=`
const ivec2 pads = ivec2(${i}, ${a});
2021-12-06 12:34:50 +01:00
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2022-03-07 19:17:31 +01:00
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float dotProd = 0.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${e}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
2022-03-07 19:17:31 +01:00
int idyR = int(dyR);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
int wRPerm = ${e} - 1 - wR;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
2022-03-07 19:17:31 +01:00
int idyC = int(dyC);
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
int wCPerm = ${n} - 1 - wC;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${u}; dm++) {
int d2 = d1 * ${u} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}};function Cet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,dy:s}=t,{strides:i,dilations:a,pad:u,dimRoundingMode:l,filterShape:c}=n,p=k.computeConv2DInfo(o.shape,c,i,a,u,l,!0),m=new fN(p);return e.runWebGLProgram(m,[o,s],"float32")}var tz={kernelName:gp,backendName:"webgl",kernelFunc:Cet};function Iet(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,filter:s}=t,{strides:i,dilations:a,pad:u,dimRoundingMode:l,inputShape:c}=n,p=k.computeConv2DInfo(c,s.shape,i,a,u,l,!0),m=new dN(p);return e.runWebGLProgram(m,[o,s],"float32")}var ez={kernelName:xp,backendName:"webgl",kernelFunc:Iet};var hN=class{constructor(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`}};function ket(r){let{inputs:t,backend:e}=r,{x:n}=t,o=[...n.shape,...n.shape],s=x.sizeFromShape(n.shape),i=ut({inputs:{x:n},backend:e,attrs:{shape:[s]}}),a=new hN(s),u=e.runWebGLProgram(a,[i],i.dtype),l=ut({inputs:{x:u},backend:e,attrs:{shape:o}});return e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(u),l}var rz={kernelName:yp,backendName:"webgl",kernelFunc:ket};var gN=class{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;let{inHeight:e,inWidth:n,padInfo:o,strideHeight:s,strideWidth:i,filterHeight:a,filterWidth:u,dilationHeight:l,dilationWidth:c}=t,{top:p,left:m}=o;this.userCode=`
const ivec2 strides = ivec2(${s}, ${i});
const ivec2 pads = ivec2(${p}, ${m});
const float neg_infinity = -3.4e38;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
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;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float curVal = neg_infinity;
for (int h = 0; h < ${a}; h++) {
int hIn = hBeg + h * ${l};
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
if (hIn >= 0 && hIn < ${e}) {
for (int w = 0; w < ${u}; w++) {
int wIn = wBeg + w * ${c};
if (wIn >= 0 && wIn < ${n}) {
float xVal = getX(batch, hIn, wIn, d1);
float wVal = getW(h, w, d1);
float val = xVal + wVal;
if (val > curVal) {
curVal = val;
}
}
2021-04-01 19:39:54 +02:00
}
}
}
2022-03-07 19:17:31 +01:00
float result = curVal;
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function Net(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s}=t,{strides:i,pad:a,dilations:u}=n,l=k.computeDilation2DInfo(o.shape,s.shape,i,a,"NHWC",u),c,p=new gN(l);c=e.runWebGLProgram(p,[o,s],"float32");let m=ut({inputs:{x:c},backend:e,attrs:{shape:l.outShape}});return e.disposeIntermediateTensorInfo(c),m}var nz={kernelName:Sl,backendName:"webgl",kernelFunc:Net};function Tet(r){let{inputs:t,backend:e,attrs:n}=r,{equation:o}=n,s=t,{allDims:i,summedDims:a,idDims:u}=k.decodeEinsumEquation(o,s.length);k.checkEinsumDimSizes(i.length,u,s);let{path:l,steps:c}=k.getEinsumComputePath(a,u),p=c.length,m=null,f=i.length,d=[];for(let h=0;h<p;++h){for(let g of c[h]){let{permutationIndices:y,expandDims:b}=k.getEinsumPermutation(f,u[g]),w;k.isIdentityPermutation(y)?w=s[g]:(w=Le({inputs:{x:s[g]},backend:e,attrs:{perm:y}}),d.push(w));let v=w.shape.slice();for(let I=0;I<b.length;++I)v.splice(b[I],0,1);x.arraysEqual(w.shape,v)||(w=ut({inputs:{x:w},backend:e,attrs:{shape:v}}),d.push(w)),m===null?m=w:(m=lg({inputs:{a:w,b:m},backend:e}),d.push(m))}h<p-1&&(l[h]>=0&&(m=Oc({inputs:{x:m},backend:e,attrs:{axis:l[h]-(i.length-f),keepDims:!1}}),d.push(m)),f--)}for(let h of d)h!==m&&e.disposeIntermediateTensorInfo(h);return m}var oz={kernelName:bp,backendName:"webgl",kernelFunc:Tet};var _et="return (x >= 0.0) ? x : (exp(x) - 1.0);",Eet=`
vec4 result;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
return result;
`,Aet=Ct({opSnippet:_et,packedOpSnippet:Eet}),sz={kernelName:os,backendName:"webgl",kernelFunc:Aet};var Det="return (b >= 1.0) ? a : a * (b + 1.0);",$et=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,Ret=r=>{let{inputs:t,backend:e}=r,{dy:n,y:o}=t,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ui($et,n.shape,o.shape):new Ro(Det,n.shape,o.shape);return e.runWebGLProgram(s,[n,o],n.dtype)},iz={kernelName:wp,backendName:"webgl",kernelFunc:Ret};var Fet=`
return vec4(equal(a, b));
`,Oet="return float(a == b);",Pet=le({opSnippet:Oet,packedOpSnippet:Fet,dtype:"bool",cpuKernelImpl:WP}),az={kernelName:ia,backendName:"webgl",kernelFunc:Pet};var Met=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${k.ERF_P};
float a1 = ${k.ERF_A1};
float a2 = ${k.ERF_A2};
float a3 = ${k.ERF_A3};
float a4 = ${k.ERF_A4};
float a5 = ${k.ERF_A5};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +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));
`,Let=Ct({opSnippet:Met}),lz={kernelName:sa,backendName:"webgl",kernelFunc:Let};var zet=Fo+`
return exp(x);
`,Bet=`
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;
`,xN=Ct({opSnippet:zet,packedOpSnippet:Bet,cpuKernelImpl:UP,dtype:"float32"}),uz={kernelName:ss,backendName:"webgl",kernelFunc:xN};function Db(r){let{inputs:t,attrs:e,backend:n}=r,{dim:o}=e,{input:s}=t,i=s.shape.length,a=s.shape.slice(),u=o;return o<0&&(x.assert(-(i+1)<=o,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),u=i+o+1),a.splice(u,0,1),ut({inputs:{x:s},backend:n,attrs:{shape:a}})}var cz={kernelName:xi,backendName:"webgl",kernelFunc:Db};var pz="return exp(x) - 1.0;",Vet=Ct({opSnippet:pz,packedOpSnippet:pz,cpuKernelImpl:HP}),mz={kernelName:aa,backendName:"webgl",kernelFunc:Vet};var $b=class{constructor(t,e,n){this.variableNames=["real","imag"];let o=e[1];this.outputShape=e;let s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,i=n?`${o}.0`:"1.0",a;if(t==="real")a="return real * expR - imag * expI;";else if(t==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${t}.`);this.userCode=`
const float exponentMultiplier = ${s};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${a}
2021-03-26 15:26:02 +01:00
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${o});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${o}; 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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
result +=
unaryOpComplex(real, expR, imag, expI) / ${i};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}};function Rb(r,t,e){let n=e.texData.get(r.dataId),o=x.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],i=o/s,a=ut({inputs:{x:r},backend:e,attrs:{shape:[i,s]}}),u=a.shape,l=new $b("real",u,t),c=new $b("imag",u,t),p=[{dataId:n.complexTensorInfos.real.dataId,dtype:n.complexTensorInfos.real.dtype,shape:u},{dataId:n.complexTensorInfos.imag.dataId,dtype:n.complexTensorInfos.imag.dtype,shape:u}],m=e.runWebGLProgram(l,p,"float32"),f=e.runWebGLProgram(c,p,"float32"),d=Dn({inputs:{real:m,imag:f},backend:e});e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f);let h=ut({inputs:{x:d},backend:e,attrs:{shape:r.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(d),h}function Get(r){let{inputs:t,backend:e}=r,{input:n}=t;return Rb(n,!1,e)}var fz={kernelName:vp,backendName:"webgl",kernelFunc:Get};var yN=class{constructor(t,e){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=t,this.userCode=`
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`}};function fl(r){let{backend:t,attrs:e}=r,{shape:n,value:o}=e,{dtype:s}=e;if(s=s||x.inferDtype(o),s==="string"){let i=x.getArrayFromDType(s,x.sizeFromShape(n));return i.fill(o),t.makeTensorInfo(n,s,i)}else{let i=new yN(n,o),a=[[o]];return t.runWebGLProgram(i,[],s,a)}}var dz={kernelName:kl,backendName:"webgl",kernelFunc:fl};var bN=class{constructor(t){this.variableNames=["Image"],this.outputShape=[];let e=t[2];this.outputShape=t,this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
2022-03-07 19:17:31 +01:00
int coordX = ${e} - x - 1;
float outputValue;
if(coordX >= 0 && coordX < ${e}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
2021-04-01 19:39:54 +02:00
}
setOutput(outputValue);
}
2022-03-07 19:17:31 +01:00
`}};var hz={kernelName:la,backendName:"webgl",kernelFunc:({inputs:r,backend:t})=>{let{image:e}=r,n=t,o=new bN(e.shape);return n.runWebGLProgram(o,[e],e.dtype)}};var gz="return floor(x);",Wet=Ct({opSnippet:gz,packedOpSnippet:gz,cpuKernelImpl:qP}),xz={kernelName:is,backendName:"webgl",kernelFunc:Wet};var Uet=`
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;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`,Het=`
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
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);
`,qet=le({opSnippet:Uet,packedOpSnippet:Het,dtype:"int32"}),yz={kernelName:as,backendName:"webgl",kernelFunc:qet};var wN=class{constructor(t){this.variableNames=["A"];let e=He(),[n,o]=t;this.outputShape=t,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${o}.0, ${n}.0);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec4 values = ${e.texture2D}(A, uv);
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;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
setOutput(floor(value * 255.0 + 0.5));
}
`}};var vN=class{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let e=He(),[n,o]=t;this.outputShape=t,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
2021-03-31 13:01:22 +02:00
2022-03-07 19:17:31 +01:00
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(${o}.0, ${n}.0);
vec4 values = ${e.texture2D}(A, uv);
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;
2020-12-15 14:15:43 +01:00
}
2022-03-07 19:17:31 +01:00
result[row * 2 + col] = floor(value * 255.0 + 0.5);
2021-03-31 13:01:22 +02:00
}
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${e.output} = result;
}
`}};var bz={kernelName:bf,backendName:"webgl",kernelFunc:Ket},Jm;function Ket(r){let{inputs:t,backend:e,attrs:n}=r,{pixels:o}=t,{numChannels:s}=n,i=typeof HTMLVideoElement!="undefined"&&o instanceof HTMLVideoElement,a=typeof HTMLImageElement!="undefined"&&o instanceof HTMLImageElement,[u,l]=i?[o.videoWidth,o.videoHeight]:[o.width,o.height],c=[l,u],p=[l,u,s];(a||i)&&(Jm==null&&(Jm=document.createElement("canvas").getContext("2d")),Jm.canvas.width=u,Jm.canvas.height=l,Jm.drawImage(o,0,0,u,l),o=Jm.canvas);let m=e.makeTensorInfo(c,"int32");e.texData.get(m.dataId).usage=Ur.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(m.dataId),o);let f=G().getBool("WEBGL_PACK")?new vN(p):new wN(p),d=e.runWebGLProgram(f,[m],"int32");return e.disposeData(m.dataId),d}function jet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=k.convertConv2DDataFormat(c),g=k.computeConv2DInfo(o.shape,s.shape,u,p,l,m,!1,h),y,b=[];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"))y=_b({x:o,filter:s,convInfo:g,backend:e,bias:i,activation:f,preluActivationWeights:a,leakyreluAlpha:d});else if(G().getBool("WEBGL_CONV_IM2COL")&&o.shape[0]===1)y=Eb({x:o,filter:s,convInfo:g,backend:e,bias:i,activation:f,preluActivationWeights:a,leakyreluAlpha:d});else{let v=i!=null,I=a!=null,E=f==="leakyrelu",D=f?iu(f,!1):null,$=new ug(g,v,D,I,E),R=[o,s];if(i&&R.push(i),a&&R.push(a),E){let M=e.makeTensorInfo([],"float32",x.createScalarValue(d,"float32"));R.push(M),b.push(M)}y=e.runWebGLProgram($,R,"float32")}let w=ut({inputs:{x:y},backend:e,attrs:{shape:g.outShape}});return b.push(y),b.forEach(v=>e.disposeIntermediateTensorInfo(v)),w}var wz={kernelName:Ai,backendName:"webgl",kernelFunc:jet};function Xet(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=t,{strides:u,pad:l,dilations:c,dimRoundingMode:p,activation:m,leakyreluAlpha:f}=n,d=[],h=c;h==null&&(h=[1,1]),x.assert(k.eitherStridesOrDilationsAreOne(u,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${h}'`);let g=k.computeConv2DInfo(o.shape,s.shape,u,h,l,p,!0),y=G().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,b=m?iu(m,y):null,w=[o,s],v=i!=null,I=a!=null,E=m==="leakyrelu";if(v&&w.push(i),I&&w.push(a),E){let M=e.makeTensorInfo([],"float32",x.createScalarValue(f,"float32"));w.push(M),d.push(M)}let D;y?D=new pg(g,v,b,I,E):D=new cg(g,v,b,I,E);let $=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],R=e.runWebGLProgram(D,w,"float32",$);return d.forEach(M=>e.disposeIntermediateTensorInfo(M)),R}var vz={kernelName:Di,backendName:"webgl",kernelFunc:Xet};var CN=class{constructor(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;let o=Ht(e.length),s=Ht(n.length),i=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${o} strides = ${o}(${this.strides});
void main() {
${s} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${i};
}
setOutput(getX(flattenIndex, coords[1]));
2021-03-31 13:01:22 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function Yet(r){let{inputs:t,backend:e}=r,{params:n,indices:o}=t,s=o.shape,i=s[s.length-1],a=x.sizeFromShape(n.shape),[u,l,c,p]=k.prepareAndValidate(n,o),m=ut({inputs:{x:o},backend:e,attrs:{shape:[l,i]}}),f=ut({inputs:{x:n},backend:e,attrs:{shape:[x.sizeFromShape(n.shape)/c,c]}});if(e.shouldExecuteOnCPU([n,o])||n.dtype==="string"){let y=e.readSync(o.dataId),b=e.bufferSync(n),w=KP(y,b,n.dtype,l,i,c,p,n.shape,a);return e.makeTensorInfo(u,n.dtype,w.values)}let d=new CN(i,p,[l,c]),h=e.runWebGLProgram(d,[f,m],f.dtype),g=ut({inputs:{x:h},backend:e,attrs:{shape:u}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(h),g}var Cz={kernelName:ua,backendName:"webgl",kernelFunc:Yet};var IN=class{constructor(t,e){this.variableNames=["A","indices"],this.outputShape=e,this.rank=e.length;let n=Ht(this.rank),o=Zet(t,2);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
int index = int(getIndices(resRC.x, resRC.z));
float inBounds = (index >= 0) && (index < ${t[2]}) ? 1.0 : 0.0;
setOutput(inBounds * getA(${o}));
2021-03-31 13:01:22 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function Zet(r,t){let e=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let o=0;o<r.length;o++)o===2?n.push("index"):n.push(`${e[o]}`);return n.join()}function SN(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,indices:s}=t,{axis:i,batchDims:a}=n,u=x.parseAxisParam(i,o.shape)[0];if(G().get("DEBUG")){let b=e.readSync(s.dataId),w=o.shape[u];for(let v=0;v<b.length;++v){let I=b[v];x.assert(I<=w-1&&I>=0,()=>`GatherV2: the index value ${I} is not in [0, ${w-1}]`)}}let l=k.segment_util.collectGatherOpShapeInfo(o,s,u,a),c=x.sizeFromShape(s.shape),p=[],m=ut({inputs:{x:o},backend:e,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}}),f=ut({inputs:{x:s},backend:e,attrs:{shape:[l.batchSize,c/l.batchSize]}});p.push(m),p.push(f);let d=[l.batchSize,l.outerSize,c/l.batchSize,l.sliceSize];if(e.shouldExecuteOnCPU([o,s])||o.dtype==="string"){let b=e.bufferSync(f),w=e.bufferSync(m),v=jP(w,b,d);return p.forEach(I=>e.disposeIntermediateTensorInfo(I)),e.makeTensorInfo(l.outputShape,v.dtype,v.values)}let h=new IN(m.shape,d),g=e.runWebGLProgram(h,[m,f],m.dtype);p.push(g);let y=ut({inputs:{x:g},backend:e,attrs:{shape:l.outputShape}});return p.forEach(b=>e.disposeIntermediateTensorInfo(b)),y}var Iz={kernelName:yi,backendName:"webgl",kernelFunc:SN};var Jet="return float(a > b);",Qet=`
return vec4(greaterThan(a, b));
`,trt=le({opSnippet:Jet,packedOpSnippet:Qet,cpuKernelImpl:XP,dtype:"bool"}),Sz={kernelName:ca,backendName:"webgl",kernelFunc:trt};var ert="return float(a >= b);",rrt=`
return vec4(greaterThanEqual(a, b));
`,nrt=le({opSnippet:ert,packedOpSnippet:rrt,dtype:"bool",cpuKernelImpl:YP}),kz={kernelName:us,backendName:"webgl",kernelFunc:nrt};function ort(r){let{inputs:t,backend:e}=r,{input:n}=t;return Rb(n,!0,e)}var Nz={kernelName:Cp,backendName:"webgl",kernelFunc:ort};var srt="return float(!isnan(x) && !isinf(x));",irt=Ct({opSnippet:srt,dtype:"bool"}),Tz={kernelName:pa,backendName:"webgl",kernelFunc:irt};var art="return float(isinf(x));",lrt=Ct({opSnippet:art,dtype:"bool"}),_z={kernelName:ma,backendName:"webgl",kernelFunc:lrt};var urt="return float(isnan(x));",crt=Ct({opSnippet:urt,dtype:"bool"}),Ez={kernelName:fa,backendName:"webgl",kernelFunc:crt};var prt="return float(a < b);",mrt=`
return vec4(lessThan(a, b));
`,frt=le({opSnippet:prt,packedOpSnippet:mrt,cpuKernelImpl:ZP,dtype:"bool"}),Az={kernelName:da,backendName:"webgl",kernelFunc:frt};var drt="return float(a <= b);",hrt=`
return vec4(lessThanEqual(a, b));
`,grt=le({opSnippet:drt,packedOpSnippet:hrt,cpuKernelImpl:JP,dtype:"bool"}),Dz={kernelName:ha,backendName:"webgl",kernelFunc:grt};function xrt(r){let{backend:t,attrs:e}=r,{start:n,stop:o,num:s}=e,i=QP(n,o,s);return t.makeTensorInfo([i.length],"float32",i)}var $z={kernelName:Sp,backendName:"webgl",kernelFunc:xrt};var yrt=Fo+`
return x < 0.0 ? 0./0. : log(x);
`,brt=`
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;
`,wrt=Ct({opSnippet:yrt,packedOpSnippet:brt,cpuKernelImpl:tM}),Rz={kernelName:ps,backendName:"webgl",kernelFunc:wrt};var vrt=Fo+`
return log(1.0 + x);
`,Crt=Ct({opSnippet:vrt}),Fz={kernelName:ga,backendName:"webgl",kernelFunc:Crt};var Irt="return float(a >= 1.0 && b >= 1.0);",Srt=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,krt=le({opSnippet:Irt,packedOpSnippet:Srt,dtype:"bool"}),Oz={kernelName:xa,backendName:"webgl",kernelFunc:krt};var Nrt="return float(!(x >= 1.0));",Trt=Ct({opSnippet:Nrt}),Pz={kernelName:bu,backendName:"webgl",kernelFunc:Trt};var _rt="return float(a >= 1.0 || b >= 1.0);",Ert=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,Art=le({opSnippet:_rt,packedOpSnippet:Ert,dtype:"bool"}),Mz={kernelName:wu,backendName:"webgl",kernelFunc:Art};var kN=class{constructor(t,e,n,o,s){this.variableNames=["x"],this.outputShape=[];let i=e,a=t[3]-1;this.outputShape=t;let u,l=`float(${n}) + float(${o}) * sum`;s===.5?u=`inversesqrt(${l})`:s===1?u=`1.0/(${l})`:u=`exp(log(${l}) * float(-${s}));`,this.userCode=`
2021-03-31 13:01:22 +02:00
void main() {
2022-03-07 19:17:31 +01:00
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 = -${i}; j <= ${i}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${a}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
2021-03-31 13:01:22 +02:00
}
2022-03-07 19:17:31 +01:00
float val = x * ${u};
setOutput(val);
2021-03-31 13:01:22 +02:00
}
2022-03-07 19:17:31 +01:00
`}};var NN=class{constructor(t,e,n,o,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let i=e,a=t[3]-1;this.outputShape=t;let u,l=`float(${n}) + float(${o}) * sum`;s===.5?u=`inversesqrt(${l})`:s===1?u=`1.0/(${l})`:u=`exp(log(${l}) * float(-${s}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
2022-01-14 16:04:13 +01:00
2022-03-07 19:17:31 +01:00
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
);
2022-01-14 16:04:13 +01:00
2022-03-07 19:17:31 +01:00
int firstChannel = d - ${i};
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));
}
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${i}; j <= ${i}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a}));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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 * ${u};
setOutput(result);
}
`}};var Drt=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{depthRadius:s,bias:i,alpha:a,beta:u}=n,l=G().getBool("WEBGL_PACK_NORMALIZATION")?new NN(o.shape,s,i,a,u):new kN(o.shape,s,i,a,u);return e.runWebGLProgram(l,[o],o.dtype)},Lz={kernelName:Nl,backendName:"webgl",kernelFunc:Drt};var TN=class{constructor(t,e,n,o,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=o,this.beta=s,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${e})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${e} + 1)));
2021-03-31 13:01:22 +02:00
2022-03-07 19:17:31 +01:00
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
2021-03-31 13:01:22 +02:00
2022-03-07 19:17:31 +01:00
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;
}
}
2021-03-31 13:01:22 +02:00
2022-03-07 19:17:31 +01:00
norm = float(${o}) * norm + float(${n});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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(${o})
* float(${s})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ 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 $rt=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o,y:s,dy:i}=t,{depthRadius:a,bias:u,alpha:l,beta:c}=n,p=new TN(o.shape,a,u,l,c);return e.runWebGLProgram(p,[o,s,i],o.dtype)},zz={kernelName:kp,backendName:"webgl",kernelFunc:$rt};function Bz(r,t,e,n){let o=x.sizeFromShape(t),i=x.sizeFromShape(r.shape)/o,a=ut({inputs:{x:r},attrs:{shape:[i,o]},backend:n}),u=Wn(a,r.dtype,"max",n),l=ut({inputs:{x:u},attrs:{shape:e},backend:n});return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(u),l}function _N(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{reductionIndices:s,keepDims:i}=n,a=o.shape.length,u=x.parseAxisParam(s,o.shape),l=u,c=k.getAxesPermutation(l,a),p=c!=null,m=e.shouldExecuteOnCPU([o]),f=o;if(p){if(m){let w=e.texData.get(f.dataId).values,v=new Array(a);for(let D=0;D<v.length;D++)v[D]=o.shape[c[D]];let I=$c(w,o.shape,o.dtype,c,v);f=e.makeTensorInfo(v,o.dtype);let E=e.texData.get(f.dataId);E.values=I}else f=au(o,c,e);l=k.getInnerMostAxes(l.length,a)}k.assertAxesAreInnerMostDims("max",l,a);let[d,h]=k.computeOutAndReduceShapes(f.shape,l),g=d;i&&(g=k.expandShapeToKeepDim(d,u));let y;if(m){let w=e.texData.get(f.dataId).values,v=eM(w,x.sizeFromShape(h),g,o.dtype);y=e.makeTensorInfo(g,o.dtype);let I=e.texData.get(y.dataId);I.values=v}else y=Bz(f,h,g,e);return p&&e.disposeIntermediateTensorInfo(f),y}var Vz={kernelName:ms,backendName:"webgl",kernelFunc:_N};var Rrt=Cb+`
return max(a, b);
`,Frt=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+su+`
2021-04-01 19:39:54 +02:00
return result;
2022-03-07 19:17:31 +01:00
`,Ort=le({opSnippet:Rrt,packedOpSnippet:Frt,cpuKernelImpl:rM}),Gz={kernelName:fs,backendName:"webgl",kernelFunc:Ort};function Prt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t;ai(o,"maxPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:u}=n,l=1;x.assert(k.eitherStridesOrDilationsAreOne(i,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);let c=k.computePool2DInfo(o.shape,s,i,l,a,u);if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))return er({inputs:{x:o},backend:e});let p=new Hi(c,"max",!1);return e.runWebGLProgram(p,[o],o.dtype)}var Wz={kernelName:ds,backendName:"webgl",kernelFunc:Prt};function Mrt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{filterSize:s,strides:i,pad:a,dataFormat:u,dimRoundingMode:l}=n,c=[1,1,1],p=k.computePool3DInfo(o.shape,s,i,c,a,l,u),m=new Mc(p,"max",!1);return e.runWebGLProgram(m,[o],o.dtype)}var Uz={kernelName:Tl,backendName:"webgl",kernelFunc:Mrt};var EN=class{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;let e=t.strideHeight,n=t.strideWidth,o=t.dilationHeight,s=t.effectiveFilterHeight,i=t.effectiveFilterWidth,a=s-1-t.padInfo.top,u=i-1-t.padInfo.left,l=s*i-1;this.userCode=`
const ivec2 pads = ivec2(${a}, ${u});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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 += ${o}) {
float dyR = float(dyRCorner + wR) / ${e}.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${i}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${i} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}},AN=class{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;let e=t.strideDepth,n=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,i=t.dilationHeight,a=t.dilationWidth,u=t.effectiveFilterDepth,l=t.effectiveFilterHeight,c=t.effectiveFilterWidth,p=u-1-t.padInfo.front,m=l-1-t.padInfo.top,f=c-1-t.padInfo.left,d=u*l*c-1;this.userCode=`
const ivec3 pads = ivec3(${p}, ${m}, ${f});
2020-12-15 14:15:43 +01:00
2021-03-26 15:26:02 +01:00
void main() {
2022-03-07 19:17:31 +01:00
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wD = 0; wD < ${u};
wD += ${s}) {
float dyD = float(dyDCorner + wD) / ${e}.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wR = 0; wR < ${l};
wR += ${i}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int wC = 0; wC < ${c};
wC += ${a}) {
float dyC = float(dyCCorner + wC) / ${o}.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${d} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
2021-07-29 15:05:49 +02:00
2022-03-07 19:17:31 +01:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${l} * ${c} +
wR * ${c} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2021-07-29 15:05:49 +02:00
2022-03-07 19:17:31 +01:00
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}};function Lrt(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s}=t,i=s,{filterSize:a,strides:u,pad:l,dimRoundingMode:c}=n,p=[1,1,1],m=k.computePool3DInfo(i.shape,a,u,p,l,c),f=new Mc(m,"max",!0),d=e.runWebGLProgram(f,[i],i.dtype),h=new AN(m),g=e.runWebGLProgram(h,[o,d],i.dtype);return e.disposeIntermediateTensorInfo(d),g}var Hz={kernelName:Tp,backendName:"webgl",kernelFunc:Lrt};function zrt(r){let{inputs:t,backend:e,attrs:n}=r,{dy:o,input:s,output:i}=t,a=s;ai([s,i],"maxPoolGrad");let{filterSize:u,strides:l,pad:c,dimRoundingMode:p}=n,m=k.computePool2DInfo(a.shape,u,l,1,c,p),f=!0,d=new Hi(m,"max",f),h=e.runWebGLProgram(d,[a],a.dtype),g=new EN(m),y=e.runWebGLProgram(g,[o,h],a.dtype);return e.disposeIntermediateTensorInfo(h),y}var qz={kernelName:Np,backendName:"webgl",kernelFunc:zrt};function Kz(r,t,e,n){let o=new Hi(e,"max",!1),s=n.runWebGLProgram(o,[r],"float32");o=new Hi(e,"max",!0,!0,t);let i=n.runWebGLProgram(o,[r],"float32");return[s,i]}var jz={kernelName:_p,backendName:"webgl",kernelFunc:({inputs:r,attrs:t,backend:e})=>{let{x:n}=r,{filterSize:o,strides:s,pad:i,includeBatchInIndex:a}=t,u=e;x.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);let l=[1,1];x.assert(k.eitherStridesOrDilationsAreOne(s,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${l}'`);let c=k.computePool2DInfo(n.shape,o,s,l,i),[p,m]=Kz(n,a,c,u);return[p,m]}};function Xz(r,t,e,n){let o=x.sizeFromShape(t),i=x.sizeFromShape(r.shape)/o,a=ut({inputs:{x:r},attrs:{shape:[i,o]},backend:n}),u=Wn(a,"float32","mean",n),l=ut({inputs:{x:u},attrs:{shape:e},backend:n});return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(u),l}var Yz={kernelName:hs,backendName:"webgl",kernelFunc:({inputs:r,attrs:t,backend:e})=>{let{x:n}=r,{keepDims:o,axis:s}=t,i=e,a=n.shape.length,u=x.parseAxisParam(s,n.shape),l=u,c=k.getAxesPermutation(l,a),p=c!=null,m=i.shouldExecuteOnCPU([n]),f=[],d=n;if(p){if(m){let v=i.texData.get(d.dataId).values,I=new Array(a);for(let $=0;$<I.length;$++)I[$]=n.shape[c[$]];let E=$c(v,n.shape,n.dtype,c,I);d=i.makeTensorInfo(I,n.dtype);let D=i.texData.get(d.dataId);D.values=E}else d=au(n,c,i);f.push(d),l=k.getInnerMostAxes(l.length,a)}k.assertAxesAreInnerMostDims("sum",l,a);let[h,g]=k.computeOutAndReduceShapes(d.shape,l),y=h;o&&(y=k.expandShapeToKeepDim(h,u));let b=Xz(d,g,y,i);for(let w of f)i.disposeIntermediateTensorInfo(w);return b}};function Brt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n,a=o.shape.length,u=x.parseAxisParam(s,o.shape),l=u,c=k.getAxesPermutation(l,a),p=o;c!=null&&(p=Le({inputs:{x:o},backend:e,attrs:{perm:c}}),l=k.getInnerMostAxes(l.length,o.shape.length)),k.assertAxesAreInnerMostDims("min",l,a);let[m,f]=k.computeOutAndReduceShapes(p.shape,l),d=x.sizeFromShape(f),h=ut({inputs:{x:p},backend:e,attrs:{shape:[-1,d]}}),g=Wn(h,h.dtype,"min",e),y;if(i){let b=k.expandShapeToKeepDim(m,u);y=ut({inputs:{x:g},backend:e,attrs:{shape:b}})}else y=ut({inputs:{x:g},backend:e,attrs:{shape:m}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(g),c!=null&&e.disposeIntermediateTensorInfo(p),y}var Zz={kernelName:gs,backendName:"webgl",kernelFunc:Brt};var Vrt=Cb+`
return min(a, b);
`,Grt=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+su+`
return result;
`,Wrt=le({opSnippet:Vrt,packedOpSnippet:Grt,cpuKernelImpl:nM}),Jz={kernelName:xs,backendName:"webgl",kernelFunc:Wrt};var DN=class{constructor(t,e,n){this.variableNames=["x"],this.outputShape=e.map((c,p)=>c[0]+t[p]+c[1]);let o=t.length,s=Ht(o),i=e.map(c=>c[0]).join(","),a=e.map((c,p)=>c[0]+t[p]).join(","),u=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o),l=n==="reflect"?0:1;if(o===1){this.userCode=`
int start = ${i};
int end = ${a};
2021-07-29 15:05:49 +02:00
2022-03-07 19:17:31 +01:00
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${l};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${l};
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${s} start = ${s}(${i});
${s} end = ${s}(${a});
2021-07-29 15:05:49 +02:00
2022-03-07 19:17:31 +01:00
void main() {
${s} outC = getOutputCoords();
for (int i = 0; i < ${o}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${l};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};
}
}
${s} coords = outC - start;
setOutput(getX(${u}));
}
`}};var $N=class{constructor(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((d,h)=>d[0]+t[h]+d[1]);let o=t.length,s=Ht(o),i=e.map(d=>d[0]).join(","),a=e.map((d,h)=>d[0]+t[h]).join(","),u=tr("rc",o),l=tr("source",o),c=`${u[o-1]} < ${this.outputShape[o-1]}`,p=o===1?"source":`vec2(${l.slice(-2).join()})`,m=n==="reflect"?0:1,f="";if(o===1){let d=`
${s} source = rc;
if (source < start) {
source = start * 2 - source - ${m};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${m};
}
source -= start;
`;f=`
${s} rc = outputLoc;
${d}
result[0] = getChannel(getX(${l.join()}), ${p});
${u[o-1]} += 1;
if(${c}) {
${d}
result[1] = getChannel(getX(${l.join()}), ${p});
}
`}else{let d=`
${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;
`;f=`
${s} rc = outputLoc;
${d}
result[0] = getChannel(getX(${l.join()}), ${p});
${u[o-1]} += 1;
if(${c}) {
${d}
result[1] = getChannel(getX(${l.join()}), ${p});
}
rc = outputLoc;
${u[o-2]} += 1;
if(${u[o-2]} < ${this.outputShape[o-2]}) {
${d}
result[2] = getChannel(getX(${l.join()}), ${p});
${u[o-1]} += 1;
if(${c}) {
${d}
result[3] = getChannel(getX(${l.join()}), ${p});
}
}
`}this.userCode=`
const ${s} start = ${s}(${i});
const ${s} end = ${s}(${a});
2021-07-29 15:05:49 +02:00
2022-03-07 19:17:31 +01:00
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${f}
setOutput(result);
}
`}};var Urt=({inputs:r,backend:t,attrs:e})=>{let{x:n}=r,{paddings:o,mode:s}=e,i=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new $N(n.shape,o,s):new DN(n.shape,o,s);return t.runWebGLProgram(i,[n],n.dtype)},Qz={kernelName:ys,backendName:"webgl",kernelFunc:Urt};var Hrt=`if (b == 0.0) return NAN;
return mod(a, b);`,qrt=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+su+`
return result;
`,Krt=le({opSnippet:Hrt,packedOpSnippet:qrt}),t3={kernelName:ya,backendName:"webgl",kernelFunc:Krt};var RN=class{constructor(t,e,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[t,n],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
2021-07-29 15:05:49 +02:00
2022-03-07 19:17:31 +01:00
float r = random(seed);
float cdf = 0.0;
2021-07-29 15:05:49 +02:00
2022-03-07 19:17:31 +01:00
for (int i = 0; i < ${e-1}; i++) {
cdf += getProbs(batch, i);
2021-07-29 15:05:49 +02:00
2022-03-07 19:17:31 +01:00
if (r < cdf) {
setOutput(float(i));
return;
}
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// If no other event happened, last event happened.
setOutput(float(${e-1}));
}
`}};var jrt=`
if (a == b) {
return 1.0;
};
return a / b;`,Xrt=`
// 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.;
2021-07-29 15:05:49 +02:00
}
2022-03-07 19:17:31 +01:00
if(a.y == b.y) {
result.y = 1.;
2021-07-29 15:05:49 +02:00
}
2022-03-07 19:17:31 +01:00
if(a.z == b.z) {
result.z = 1.;
2021-07-29 15:05:49 +02:00
}
2022-03-07 19:17:31 +01:00
if(a.w == b.w) {
result.w = 1.;
2021-07-29 15:05:49 +02:00
}
2022-03-07 19:17:31 +01:00
return result;
`,FN=le({opSnippet:jrt,packedOpSnippet:Xrt,checkOutOfBounds:!0}),e3={kernelName:ns,backendName:"webgl",kernelFunc:FN};var r3="return a - b;",ON=le({opSnippet:r3,packedOpSnippet:r3,supportsComplex:!0,cpuKernelImpl:bM}),n3={kernelName:Ps,backendName:"webgl",kernelFunc:ON};function PN(r){let{inputs:t,backend:e,attrs:n}=r,{logits:o}=t,{dim:s}=n,i=x.parseAxisParam([s],o.shape),a=_N({inputs:{x:o},backend:e,attrs:{reductionIndices:i,keepDims:!1}}),u=k.expandShapeToKeepDim(a.shape,i),l=ut({inputs:{x:a},backend:e,attrs:{shape:u}}),c=ON({inputs:{a:o,b:l},backend:e}),p=xN({inputs:{x:c},backend:e}),m=Oc({inputs:{x:p},backend:e,attrs:{axis:i,keepDims:!1}}),f=ut({inputs:{x:m},backend:e,attrs:{shape:u}}),d=FN({inputs:{a:p,b:f},backend:e});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(c),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(f),d}var o3={kernelName:Fs,backendName:"webgl",kernelFunc:PN};function Yrt(r){let{inputs:t,backend:e,attrs:n}=r,{logits:o}=t,{numSamples:s,seed:i,normalized:a}=n,u=a?o:PN({inputs:{logits:o},backend:e,attrs:{dim:o.shape.length-1}}),l=u.shape[0],c=u.shape[1],p=new RN(l,c,s),m=[[i]],f=e.runWebGLProgram(p,[u],"int32",m);return a||e.disposeIntermediateTensorInfo(u),f}var s3={kernelName:Ep,backendName:"webgl",kernelFunc:Yrt};var Zrt=dr+`
return -x;
`,Jrt=`
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 Qrt(r){let{inputs:t,backend:e}=r,{x:n}=t;if(e.shouldExecuteOnCPU([n])){let s=e.texData.get(n.dataId),[i,a]=sM(s.values,n.shape,n.dtype);return e.makeTensorInfo(a,n.dtype,i)}let o;return G().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new $o(n.shape,Jrt):o=new wn(n.shape,Zrt),e.runWebGLProgram(o,[n],n.dtype)}var i3={kernelName:bi,backendName:"webgl",kernelFunc:Qrt};var tnt=Vr.nonMaxSuppressionV3Impl;function ent(r){k.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:e,attrs:n}=r,{boxes:o,scores:s}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:u}=n,l=e.readSync(o.dataId),c=e.readSync(s.dataId),{selectedIndices:p}=tnt(l,c,i,a,u);return e.makeTensorInfo([p.length],"int32",new Int32Array(p))}var a3={kernelName:wa,backendName:"webgl",kernelFunc:ent};var rnt=Vr.nonMaxSuppressionV4Impl;function nnt(r){k.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:e,attrs:n}=r,{boxes:o,scores:s}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:u,padToMaxOutputSize:l}=n,c=e.readSync(o.dataId),p=e.readSync(s.dataId),{selectedIndices:m,validOutputs:f}=rnt(c,p,i,a,u,l);return[e.makeTensorInfo([m.length],"int32",new Int32Array(m)),e.makeTensorInfo([],"int32",new Int32Array([f]))]}var l3={kernelName:va,backendName:"webgl",kernelFunc:nnt};var ont=Vr.nonMaxSuppressionV5Impl;function snt(r){k.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:e,attrs:n}=r,{boxes:o,scores:s}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:u,softNmsSigma:l}=n,c=e.readSync(o.dataId),p=e.readSync(s.dataId),m=i,f=a,d=u,h=l,{selectedIndices:g,selectedScores:y}=ont(c,p,m,f,d,h);return[e.makeTensorInfo([g.length],"int32",new Int32Array(g)),e.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var u3={kernelName:Ca,backendName:"webgl",kernelFunc:snt};var MN=class{constructor(t,e,n,o){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${o}), float(${n}),
float(index == coords.y)));
}
`}};var int=r=>{let{inputs:t,backend:e,attrs:n}=r,{indices:o}=t,{depth:s,onValue:i,offValue:a}=n,u=x.sizeFromShape(o.shape),l=new MN(u,s,i,a),c=ut({inputs:{x:o},backend:e,attrs:{shape:[u]}}),p=e.runWebGLProgram(l,[c],o.dtype);e.disposeIntermediateTensorInfo(c);let m=[...o.shape,s],f=ut({inputs:{x:p},backend:e,attrs:{shape:m}});return e.disposeIntermediateTensorInfo(p),f},c3={kernelName:ws,backendName:"webgl",kernelFunc:int};function mg(r){let{inputs:t,backend:e}=r,{x:n}=t;if(n.dtype==="complex64"){let o=ml({inputs:{input:n},backend:e}),s=mg({inputs:{x:o},backend:e}),i=Lc({inputs:{input:n},backend:e}),a=mg({inputs:{x:i},backend:e}),u=Dn({inputs:{real:s,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),u}else return fl({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:e})}var p3={kernelName:_i,backendName:"webgl",kernelFunc:mg};function m3(r){let{inputs:t,backend:e}=r,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let o=ml({inputs:{input:n},backend:e}),s=m3({inputs:{x:o},backend:e}),i=Lc({inputs:{input:n},backend:e}),a=mg({inputs:{x:i},backend:e}),u=Dn({inputs:{real:s,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),u}else return fl({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:e})}var f3={kernelName:wi,backendName:"webgl",kernelFunc:m3};function ant(r){let{inputs:t,backend:e,attrs:n}=r,{axis:o}=n;if(t.length===1)return Db({inputs:{input:t[0]},backend:e,attrs:{dim:o}});let s=t[0].shape,i=t[0].dtype;t.forEach(c=>{x.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),x.assert(i===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let a=[],u=t.map(c=>{let p=Db({inputs:{input:c},backend:e,attrs:{dim:o}});return a.push(p),p}),l=oN({inputs:u,backend:e,attrs:{axis:o}});return a.forEach(c=>e.disposeIntermediateTensorInfo(c)),l}var d3={kernelName:vi,backendName:"webgl",kernelFunc:ant};var LN=class{constructor(t,e,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((l,c)=>l[0]+t[c]+l[1]);let o=t.length,s=Ht(o),i=e.map(l=>l[0]).join(","),a=e.map((l,c)=>l[0]+t[c]).join(","),u=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o);if(o===1){this.userCode=`
int start = ${i};
int end = ${a};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${s} start = ${s}(${i});
${s} end = ${s}(${a});
void main() {
${s} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${s} coords = outC - start;
setOutput(getX(${u}));
}
}
`}};var zN=class{constructor(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((h,g)=>h[0]+t[g]+h[1]);let o=t.length,s=Ht(o),i=e.map(h=>h[0]).join(","),a=e.map((h,g)=>h[0]+t[g]).join(","),u=tr("rc",o),l=tr("source",o),c=`${u[o-1]} < ${this.outputShape[o-1]}`,p=o===1?"source":`vec2(${l.slice(-2).join()})`,m=[`${s} rc = outputLoc;`,`${u[o-1]} += 1;
if(${c}) {
`,o===1?"":`}
rc = outputLoc;
${u[o-2]} += 1;
if(${u[o-2]} < ${this.outputShape[o-2]}) {`,o===1?"":` ${u[o-1]} += 1;
if(${c}) {`],f=o===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="";for(let h=0,g=o===1?2:4;h<g;h++)d+=`
${m[h]}
if (${f}) {
result[${h}] = float(value);
} else {
${s} source = rc - start;
result[${h}] = getChannel(getX(${l.join()}), ${p});
}
`;d+=o===1?"} ":"}}",this.userCode=`
const ${s} start = ${s}(${i});
const ${s} end = ${s}(${a});
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${d}
setOutput(result);
}
`}};var BN=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{paddings:s,constantValue:i}=n;if(x.sizeFromShape(o.shape)===0){let l=s.map((c,p)=>c[0]+o.shape[p]+c[1]);return fl({backend:e,attrs:{shape:l,value:i,dtype:o.dtype}})}let a=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new zN(o.shape,s,i):new LN(o.shape,s,i),u=[[i]];return e.runWebGLProgram(a,[o],o.dtype,u)},h3={kernelName:vs,backendName:"webgl",kernelFunc:BN};var lnt=`
if(a < 0.0 && floor(b) < b){
return NAN;
2021-07-29 15:05:49 +02:00
}
2022-03-07 19:17:31 +01:00
if (b == 0.0) {
return 1.0;
2021-07-29 15:05:49 +02:00
}
2022-03-07 19:17:31 +01:00
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
`,unt=`
// 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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
`+su+`
return result;
`,cnt=le({opSnippet:lnt,packedOpSnippet:unt}),g3={kernelName:Cs,backendName:"webgl",kernelFunc:cnt};function pnt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{axis:s,keepDims:i}=n,a=o.shape.length,u=[],l=x.parseAxisParam(s,o.shape),c=l,p=k.getAxesPermutation(c,a),m=o;p!=null&&(m=Le({inputs:{x:o},backend:e,attrs:{perm:p}}),c=k.getInnerMostAxes(c.length,a),u.push(m)),k.assertAxesAreInnerMostDims("prod",c,a);let f;if(e.shouldExecuteOnCPU([m])){let d=e.texData.get(m.dataId).values,{outVals:h,outShape:g,outDtype:y}=aM(m.shape,m.dtype,d,c);f=e.makeTensorInfo(g,y,h)}else{let[d,h]=k.computeOutAndReduceShapes(m.shape,c),g=x.sizeFromShape(h),y=ut({inputs:{x:m},backend:e,attrs:{shape:[-1,g]}}),b=Tu(o.dtype),w=Wn(y,b,"prod",e);f=ut({inputs:{x:w},backend:e,attrs:{shape:d}}),u.push(y),u.push(w)}if(i){u.push(f);let d=k.expandShapeToKeepDim(f.shape,l);f=ut({inputs:{x:f},backend:e,attrs:{shape:d}})}return u.forEach(d=>e.disposeIntermediateTensorInfo(d)),f}var x3={kernelName:Ia,backendName:"webgl",kernelFunc:pnt};var VN=r=>{let{backend:t,attrs:e}=r,{start:n,stop:o,step:s,dtype:i}=e,a=lM(n,o,s,i);return t.makeTensorInfo([a.length],i,a)},y3={kernelName:_l,backendName:"webgl",kernelFunc:VN};var mnt="return 1.0 / x;",fnt=Ct({opSnippet:mnt}),b3={kernelName:Sa,backendName:"webgl",kernelFunc:fnt};var dnt=dr+`
return (x < 0.0) ? 0.0 : x;
`,hnt=`
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
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;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
return result;
`,gnt=Ct({opSnippet:dnt,packedOpSnippet:hnt}),w3={kernelName:Ss,backendName:"webgl",kernelFunc:gnt};var xnt=dr+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,ynt=`
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;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
return result;
`,bnt=Ct({opSnippet:xnt,packedOpSnippet:ynt}),v3={kernelName:Ns,backendName:"webgl",kernelFunc:bnt};var GN=class{constructor(t,e,n,o,s){this.variableNames=["A"],this.outputShape=[];let[i,a,u,l]=t;this.outputShape=[i,e,n,l];let c=[o&&e>1?a-1:a,o&&n>1?u-1:u],p=[o&&e>1?e-1:e,o&&n>1?n-1:n],m;s?m="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":m="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${c[0]/p[0]},
${c[1]/p[1]});
const vec2 inputShapeRC = vec2(${a}.0, ${u}.0);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Fractional source index.
vec2 sourceFracIndexRC = ${m};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
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);
2021-03-31 13:01:22 +02:00
}
2022-03-07 19:17:31 +01:00
`}};var WN=class{constructor(t,e,n,o,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[i,a,u,l]=t;this.outputShape=[i,e,n,l];let c=[o&&e>1?a-1:a,o&&n>1?u-1:u],p=[o&&e>1?e-1:e,o&&n>1?n-1:n],m;s?m="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":m="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${c[0]/p[0]},
${c[1]/p[1]},
${c[1]/p[1]});
const vec3 inputShapeRC = vec3(${a}.0, ${u}.0,
${u}.0);
2022-03-07 19:17:31 +01:00
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
2021-04-01 19:39:54 +02:00
}
2021-04-01 19:39:54 +02:00
void main() {
2022-03-07 19:17:31 +01:00
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);
2022-03-07 19:17:31 +01:00
// Fractional source index.
vec3 sourceFracIndexRC = ${m};
2022-03-07 19:17:31 +01:00
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2022-03-07 19:17:31 +01:00
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${l-1};
bool hasNextRow = coords.z < ${n-1};
2022-03-07 19:17:31 +01:00
// 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);
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
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);
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
setOutput(newValue);
2021-12-01 21:37:52 +01:00
}
2022-03-07 19:17:31 +01:00
`}};function wnt(r){let{inputs:t,backend:e,attrs:n}=r,{images:o}=t,{alignCorners:s,halfPixelCenters:i,size:a}=n,[u,l]=a,c=G().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new WN(o.shape,u,l,s,i):new GN(o.shape,u,l,s,i);return e.runWebGLProgram(c,[o],"float32")}var C3={kernelName:ks,backendName:"webgl",kernelFunc:wnt};var UN=class{constructor(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;let[,o,s]=e,[,i,a]=t,u=[n&&i>1?o-1:o,n&&a>1?s-1:s],l=[n&&i>1?i-1:i,n&&a>1?a-1:a],c=u[0]/l[0],p=u[1]/l[1],m=1/c,f=1/p,d=Math.ceil(m)*2+2,h=Math.ceil(f)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float accumulator = 0.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
const float heightScale = float(${c});
const float widthScale = float(${p});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
const float invHeightScale = float(${m});
const float invWidthScale = float(${f});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
const int winHeight = int(${d});
const int winWidth = int(${h});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${i}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${a}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${o-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
2021-07-29 15:05:49 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function vnt(r){let{inputs:t,backend:e,attrs:n}=r,{images:o,dy:s}=t,{alignCorners:i}=n,a=new UN(s.shape,o.shape,i);return e.runWebGLProgram(a,[s],s.dtype)}var I3={kernelName:$p,backendName:"webgl",kernelFunc:vnt};var HN=class{constructor(t,e,n,o,s){this.variableNames=["A"],this.outputShape=[];let[i,a,u,l]=t;this.outputShape=[i,e,n,l];let c=[o&&e>1?a-1:a,o&&n>1?u-1:u],p=[o&&e>1?e-1:e,o&&n>1?n-1:n],m=o?"0.5":"0.0",f;s?f="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":f="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${c[0]/p[0]},
${c[1]/p[1]});
const vec2 inputShapeRC = vec2(${a}.0, ${u}.0);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Fractional source index.
vec2 sourceFracIndexRC = ${f};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
setOutput(newValue);
}
`}};var qN=class{constructor(t,e,n,o,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[i,a,u,l]=t;this.outputShape=[i,e,n,l];let c=[o&&e>1?a-1:a,o&&n>1?u-1:u],p=[o&&e>1?e-1:e,o&&n>1?n-1:n],m=o?"0.5":"0.0",f;s?f="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":f="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${c[0]/p[0]},
${c[1]/p[1]},
${c[1]/p[1]});
const vec3 inputShapeRC = vec3(${a}.0, ${u}.0,
${u}.0);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Fractional source index.
vec3 sourceFracIndexRC = ${f};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${l-1};
bool hasNextRow = coords.z < ${n-1};
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
setOutput(newValue);
}
`}};function Cnt(r){let{inputs:t,backend:e,attrs:n}=r,{images:o}=t,{alignCorners:s,halfPixelCenters:i,size:a}=n,[u,l]=a,c=G().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new qN(o.shape,u,l,s,i):new HN(o.shape,u,l,s,i);return e.runWebGLProgram(c,[o],o.dtype)}var S3={kernelName:El,backendName:"webgl",kernelFunc:Cnt};var KN=class{constructor(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;let[,o,s]=e,[,i,a]=t,u=[n&&i>1?o-1:o,n&&a>1?s-1:s],l=[n&&i>1?i-1:i,n&&a>1?a-1:a],c=u[0]/l[0],p=u[1]/l[1],m=1/c,f=1/p,d=Math.ceil(m)*2+2,h=Math.ceil(f)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float accumulator = 0.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
const float heightScale = float(${c});
const float widthScale = float(${p});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
const float invHeightScale = float(${m});
const float invWidthScale = float(${f});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
const int winHeight = int(${d});
const int winWidth = int(${h});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${i}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${a}) {
continue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float sourceFracRow =
float(${u[0]}) *
(float(dyR) / float(${l[0]}));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float sourceFracCol =
float(${u[1]}) *
(float(dyC) / float(${l[1]}));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
int sourceNearestRow = int(min(
float(int(${o}) - 1),
${n} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
int sourceNearestCol = int(min(
float(int(${s}) - 1),
${n} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}};function Int(r){let{inputs:t,backend:e,attrs:n}=r,{images:o,dy:s}=t,{alignCorners:i}=n,a=new KN(s.shape,o.shape,i);return e.runWebGLProgram(a,[s],s.dtype)}var k3={kernelName:Dp,backendName:"webgl",kernelFunc:Int};var jN=class{constructor(t,e){this.variableNames=["x"];let n=t.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=t,n===1){this.userCode=`
void main() {
int coord = getOutputCoords();
setOutput(getX(${t[0]} - coord - 1));
}
`;return}let o=a=>e.indexOf(a)!==-1&&t[a]!==1?`${t[a]} - coords[${a}] - 1`:`coords[${a}]`,s=t.map((a,u)=>o(u)).join(","),i=Ht(n);this.userCode=`
void main() {
${i} coords = getOutputCoords();
setOutput(getX(${s}));
}
`}};var XN=class{constructor(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=t.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=t;let o=tr("rc",n),s=`${o[n-1]} + 1 < ${this.outputShape[n-1]}`,i=`${o[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Ht(n);n===1?this.userCode=`
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${t[0]} - rc - 1),
${t[0]} - rc - 1);
if(${s}){
result.g = getChannel(getX(${t[0]} - (rc + 1) - 1),
${t[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
${a} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${u(o.slice())};
if(${s}){
result.g = ${l(o.slice())};
}
if(${i}) {
result.b = ${c(o.slice())};
if(${s}) {
result.a = ${p(o.slice())};
}
}
setOutput(result);
}
`;function u(d){return m(d)}function l(d){return d[n-1]="("+d[n-1]+" + 1)",m(d)}function c(d){return d[n-2]="("+d[n-2]+" + 1)",m(d)}function p(d){return d[n-1]="("+d[n-1]+" + 1)",d[n-2]="("+d[n-2]+" + 1)",m(d)}function m(d){let h=t.map((b,w)=>f(w,d)),g=h.join(","),y=h.slice(-2).join(",");return`getChannel(getX(${g}), vec2(${y}))`}function f(d,h){return e.indexOf(d)!==-1&&t[d]!==1?`${t[d]} - ${h[d]} - 1`:`${h[d]}`}}};function Snt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{dims:s}=n,i=o.shape.length,a=x.parseAxisParam(s,o.shape);if(i===0)return er({inputs:{x:o},backend:e});let u=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new XN(o.shape,a):new jN(o.shape,a);return e.runWebGLProgram(u,[o],o.dtype)}var N3={kernelName:Ts,backendName:"webgl",kernelFunc:Snt};var YN=class{constructor(t,e){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=t[1],o=t[2];this.outputShape=t;let s="";typeof e=="number"?s=`float outputValue = ${e.toFixed(2)};`:s=`
vec3 fill = vec3(${e.join(",")});
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 < ${o} && coordY >= 0 && coordY < ${n}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}};var T3={kernelName:Fa,backendName:"webgl",kernelFunc:({inputs:r,attrs:t,backend:e})=>{let{image:n}=r,{radians:o,fillValue:s,center:i}=t,a=e,u=new YN(n.shape,s),[l,c]=k.getImageCenter(i,n.shape[1],n.shape[2]),p=[[l,c,Math.sin(o),Math.cos(o)]];return a.runWebGLProgram(u,[n],n.dtype,p)}};var knt=`
// 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;
2021-04-01 19:39:54 +02:00
}
}
2022-03-07 19:17:31 +01:00
`,Nnt=Ct({opSnippet:knt}),_3={kernelName:_s,backendName:"webgl",kernelFunc:Nnt};var Tnt="return inversesqrt(x);",_nt=Ct({opSnippet:Tnt,cpuKernelImpl:uM}),E3={kernelName:Es,backendName:"webgl",kernelFunc:_nt};var fg=class{constructor(t,e,n,o,s,i,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;let u=Ht(s.length),l=Ht(i.length),c="";n===1?c="i":n===2&&(c="i, j");let p=`getIndices(${c})`,m="";o===1?m="i":o===2&&(m="i, coords[1]");let f=`getUpdates(${m})`,d=e>1?"strides[j]":"strides";this.userCode=`
${u} strides = ${u}(${s});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
${l} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${t}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${e}; j++) {
int index = round(${p});
flattenedIndex += index * ${d};
}
if (flattenedIndex == coords[0]) {
sum += ${f};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`}};function Ent(r){let{inputs:t,backend:e,attrs:n}=r,{indices:o,updates:s}=t,{shape:i}=n,{sliceRank:a,numUpdates:u,sliceSize:l,strides:c,outputSize:p}=k.calculateShapes(s,o,i),m=[p/l,l];if(p===0)return e.makeTensorInfo(i,o.dtype);let f=ut({inputs:{x:o},backend:e,attrs:{shape:[u,a]}}),d=ut({inputs:{x:s},backend:e,attrs:{shape:[u,l]}}),h=e.makeTensorInfo([],"float32",new Float32Array([0])),g=new fg(u,a,f.shape.length,d.shape.length,c,m),y=e.runWebGLProgram(g,[d,f,h],d.dtype),b=ut({inputs:{x:y},backend:e,attrs:{shape:i}});return e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(y),e.disposeIntermediateTensorInfo(h),b}var A3={kernelName:ka,backendName:"webgl",kernelFunc:Ent};var ZN=class{constructor(t,e,n){this.variableNames=["c","a","b"],this.outputShape=e;let o,s;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)s="resRC",o="resRC";else{let a=["resRC.x","resRC.y","resRC.z","resRC.w"],u=[],l=[];for(let c=0;c<e.length;c++)l.push(`${a[c]}`),c<t&&u.push(`${a[c]}`);o=u.join(),s=l.join()}let i=Ht(n);this.userCode=`
void main() {
${i} resRC = getOutputCoords();
float cVal = getC(${o});
if (cVal >= 1.0) {
setOutput(getA(${s}));
} else {
setOutput(getB(${s}));
}
}
`}};function Ant(r){let{inputs:t,backend:e}=r,{condition:n,t:o,e:s}=t,i=new ZN(n.shape.length,o.shape,o.shape.length);return e.runWebGLProgram(i,[n,o,s],yr(o.dtype,s.dtype))}var D3={kernelName:Ii,backendName:"webgl",kernelFunc:Ant};var Dnt=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${k.SELU_SCALEALPHA};
float scale = ${k.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`,$nt=Ct({opSnippet:Dnt}),$3={kernelName:Na,backendName:"webgl",kernelFunc:$nt};var Rnt=Fo+`
return 1.0 / (1.0 + exp(-1.0 * x));
`,Fnt=`
vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
bvec4 isNaN = isnan(x);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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;
2021-12-06 12:34:50 +01:00
2021-04-01 19:39:54 +02:00
return result;
2022-03-07 19:17:31 +01:00
`,Ont=Ct({opSnippet:Rnt,packedOpSnippet:Fnt,cpuKernelImpl:cM}),R3={kernelName:Ds,backendName:"webgl",kernelFunc:Ont};var Pnt=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,Mnt=Ct({opSnippet:Pnt}),F3={kernelName:_a,backendName:"webgl",kernelFunc:Mnt};var Lnt=Fo+`
return sin(x);
`,znt=Ct({opSnippet:Lnt}),O3={kernelName:As,backendName:"webgl",kernelFunc:znt};var Bnt=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,Vnt=Ct({opSnippet:Bnt}),P3={kernelName:Ta,backendName:"webgl",kernelFunc:Vnt};var Gnt=`
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
bool too_large = x > -threshold;
bool too_small = x < threshold;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float result;
float exp_x = exp(x);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (too_large){
result = x;
2021-03-26 15:26:02 +01:00
}
2022-03-07 19:17:31 +01:00
else if (too_small){
result = exp_x;
2021-03-26 15:26:02 +01:00
}
2022-03-07 19:17:31 +01:00
else{
result = log(exp_x + 1.0);
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
return result;
`,Wnt=Ct({opSnippet:Gnt}),M3={kernelName:Ea,backendName:"webgl",kernelFunc:Wnt};var Unt=r=>{let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{blockShape:s,paddings:i}=n;x.assert(o.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let a=s.reduce((y,b)=>y*b),u=[[0,0]];u.push(...i);for(let y=1+s.length;y<o.shape.length;++y)u.push([0,0]);let l=[],c=BN({inputs:{x:o},backend:e,attrs:{paddings:u,constantValue:0}}),p=k.getReshaped(c.shape,s,a,!1),m=k.getPermuted(p.length,s.length,!1),f=k.getReshapedPermuted(c.shape,s,a,!1),d=ut({inputs:{x:c},backend:e,attrs:{shape:p}}),h=Le({inputs:{x:d},backend:e,attrs:{perm:m}}),g=ut({inputs:{x:h},backend:e,attrs:{shape:f}});return l.push(c),l.push(d),l.push(h),l.forEach(y=>e.disposeIntermediateTensorInfo(y)),g},L3={kernelName:ki,backendName:"webgl",kernelFunc:Unt};function Hnt(r){let{inputs:t,backend:e}=r,{indices:n,values:o,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${n.shape}`);if(o.shape.length!==1)throw new Error(`Values must be a vector, saw:
${o.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${i.shape}`);let a=e.readSync(n.dataId),u=e.readSync(o.dataId),l=e.readSync(s.dataId),c=e.readSync(i.dataId)[0],[p,m,f,d,h]=mM(a,n.shape,n.dtype,u,o.dtype,l,c);return[e.makeTensorInfo(m,n.dtype,p),e.makeTensorInfo([m[0]],o.dtype,f),e.makeTensorInfo([d.length],"bool",new Uint8Array(d.map(g=>Number(g)))),e.makeTensorInfo([h.length],n.dtype,new Int32Array(h))]}var z3={kernelName:Al,backendName:"webgl",kernelFunc:Hnt};function qnt(r){let{inputs:t,backend:e}=r,{inputIndices:n,inputShape:o,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${n.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${o.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(e.readSync(o.dataId)),a=e.readSync(n.dataId),u=Array.from(e.readSync(s.dataId)),[l,c,p]=fM(a,n.shape,n.dtype,i,u);return[e.makeTensorInfo(c,n.dtype,l),e.makeTensorInfo([p.length],s.dtype,new Int32Array(p))]}var B3={kernelName:Aa,backendName:"webgl",kernelFunc:qnt};function Knt(r){let{inputs:t,backend:e}=r,{data:n,indices:o,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);let i=e.readSync(n.dataId),a=e.readSync(o.dataId),u=e.readSync(s.dataId),[l,c]=wb(i,n.shape,n.dtype,a,u,!0);return e.makeTensorInfo(c,n.dtype,l)}var V3={kernelName:Dl,backendName:"webgl",kernelFunc:Knt};function jnt(r){let{inputs:t,backend:e}=r,{data:n,indices:o,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);let i=e.readSync(n.dataId),a=e.readSync(o.dataId),u=e.readSync(s.dataId),[l,c]=wb(i,n.shape,n.dtype,a,u);return e.makeTensorInfo(c,n.dtype,l)}var G3={kernelName:$l,backendName:"webgl",kernelFunc:jnt};function Xnt(r){let{inputs:t,backend:e,attrs:n}=r,{sparseIndices:o,sparseValues:s,defaultValue:i}=t,{outputShape:a}=n,{sliceRank:u,numUpdates:l,strides:c,outputSize:p}=k.calculateShapes(s,o,a),m=!1,f=new fg(l,u,o.shape.length,s.shape.length,c,[p,1],m),d=e.runWebGLProgram(f,[s,o,i],s.dtype),h=ut({inputs:{x:d},backend:e,attrs:{shape:a}});return e.disposeIntermediateTensorInfo(d),h}var W3={kernelName:Rp,backendName:"webgl",kernelFunc:Xnt};function Ynt(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{numOrSizeSplits:s,axis:i}=n,a=x.parseAxisParam(i,o.shape)[0],u=k.prepareSplitSize(o,s,a),l=o.shape.length,c=new Array(l).fill(0),p=o.shape.slice();return u.map(m=>{let f=[...p];f[a]=m;let d=ci({inputs:{x:o},backend:e,attrs:{begin:c,size:f}});return c[a]+=m,d})}var U3={kernelName:Ni,backendName:"webgl",kernelFunc:Ynt};var H3="return sqrt(x);",Znt=Ct({opSnippet:H3,packedOpSnippet:H3,cpuKernelImpl:dM}),q3={kernelName:$s,backendName:"webgl",kernelFunc:Znt};var Jnt="return x * x;",Qnt=Ct({opSnippet:Jnt}),K3={kernelName:Rl,backendName:"webgl",kernelFunc:Qnt};var j3="return (a - b) * (a - b);",tot=le({opSnippet:j3,packedOpSnippet:j3}),X3={kernelName:Os,backendName:"webgl",kernelFunc:tot};function eot({inputs:r,attrs:t,backend:e}){let{x:n}=r,o=dr+`
return x > 0.0 ? 1.0 : float(${t.alpha});
`,s=new wn(n.shape,o);return e.runWebGLProgram(s,[n],n.dtype)}var Y3={kernelName:io,backendName:"webgl",kernelFunc:eot};var JN=class{constructor(t,e,n){this.variableNames=["x"],this.outputShape=n;let o=n.length,s=Ht(n.length),i=Ht(n.length),a="";if(o===1)a="coords * strides + begin";else{let u=0;a=n.map((l,c)=>(u++,n.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${u-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
${s} begin = ${s}(${t});
${s} strides = ${s}(${e});
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
void main() {
${i} coords = getOutputCoords();
setOutput(getX(${a}));
}
`}};function rot(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{begin:s,end:i,strides:a,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=n,{finalShapeSparse:f,finalShape:d,isIdentity:h,sliceDim0:g,isSimpleSlice:y,begin:b,end:w,strides:v}=Ve.sliceInfo(o.shape,s,i,a,u,l,c,p,m),I;if(h)I=ut({inputs:{x:o},backend:e,attrs:{shape:d}});else if(g||y){x.assert(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);let D=Ve.computeOutShape(b,w,v),$=ci({inputs:{x:o},backend:e,attrs:{begin:b,size:D}});I=ut({inputs:{x:$},backend:e,attrs:{shape:d}}),e.disposeIntermediateTensorInfo($)}else if(e.shouldExecuteOnCPU([o])){let $=e.readSync(o.dataId),R=It(o.shape,o.dtype,$),M=hM(f,R,v,b);I=e.makeTensorInfo(d,o.dtype,M.values)}else{let $=new JN(b,v,f);I=e.runWebGLProgram($,[o],o.dtype)}let E=ut({inputs:{x:I},backend:e,attrs:{shape:d}});return e.disposeIntermediateTensorInfo(I),E}var Z3={kernelName:Da,backendName:"webgl",kernelFunc:rot};function not(r){let{inputs:t,backend:e,attrs:n}=r,{separator:o,nGramWidths:s,leftPad:i,rightPad:a,padWidth:u,preserveShortSequences:l}=n,{data:c,dataSplits:p}=t,m=e.readSync(c.dataId),f=e.readSync(p.dataId),[d,h]=gM(m,f,o,s,i,a,u,l);return[e.makeTensorInfo([d.length],"string",d),e.makeTensorInfo(p.shape,"int32",h)]}var J3={kernelName:Fp,backendName:"webgl",kernelFunc:not};function oot(r){let{inputs:t,backend:e,attrs:n}=r,{skipEmpty:o}=n,{input:s,delimiter:i}=t;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(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let a=e.readSync(s.dataId),u=e.readSync(i.dataId)[0],[l,c,p]=xM(a,u,o),m=c.length;return[e.makeTensorInfo([m,2],"int32",l),e.makeTensorInfo([m],"string",c),e.makeTensorInfo([2],"int32",new Int32Array(p))]}var Q3={kernelName:Op,backendName:"webgl",kernelFunc:oot};function sot(r){let{inputs:t,backend:e,attrs:n}=r,{numBuckets:o}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");let i=e.readSync(s.dataId),a=yM(i,o);return e.makeTensorInfo(s.shape,"int32",a)}var tB={kernelName:Pp,backendName:"webgl",kernelFunc:sot};var iot="return tan(x);",aot=Ct({opSnippet:iot}),eB={kernelName:Ms,backendName:"webgl",kernelFunc:aot};var lot=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,uot=Ct({opSnippet:lot}),rB={kernelName:Ls,backendName:"webgl",kernelFunc:uot};var QN=class{constructor(t,e){this.variableNames=["A"];let n=new Array(t.length);for(let i=0;i<n.length;i++)n[i]=t[i]*e[i];this.outputShape=n,this.rank=n.length;let o=Ht(this.rank),s=cot(t);this.userCode=`
void main() {
${o} resRC = getOutputCoords();
setOutput(getA(${s}));
}
`}};function cot(r){let t=r.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${r[0]})`;let e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[];for(let o=0;o<r.length;o++)n.push(`imod(${e[o]}, ${r[o]})`);return n.join()}function tT(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{reps:s}=n;if(o.dtype==="string"||o.shape.length>5){let u=e.readSync(o.dataId),l=o.dtype==="string"?u.map(m=>x.decodeString(m)):u,c=It(o.shape,o.dtype,l),p=wM(c,s);return e.makeTensorInfo(p.shape,p.dtype,p.values)}let i=new QN(o.shape,s);return e.runWebGLProgram(i,[o],o.dtype)}var nB={kernelName:jn,backendName:"webgl",kernelFunc:tT};var eT=class{constructor(t){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=t,this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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.
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
int i = isFirstInPair ? elemIdx : elemIdx - inc;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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;
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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));
}
}
`}},rT=class{constructor(t){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=t,this.userCode=`
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];
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
// 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.
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
float x0 = getX(batch, i0);
float x1 = i1 < n ? getX(batch, i1) : x0;
setOutput(x0 >= x1 ? float(i0) : float(i1));
}
`}};function Bc(r,t){t!==null&&r.disposeIntermediateTensorInfo(t)}function oB(r){let t=1;for(;t<r;)t*=2;return t}function pot(r){let{inputs:t,backend:e,attrs:n}=r,{x:o}=t,{k:s,sorted:i}=n,a=G().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),u=G().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=o.shape,c=l[l.length-1];if(e.shouldExecuteOnCPU([o])||c<a||s>u){let M=e.readSync(o.dataId),[W,U]=vM(M,l,o.dtype,s,i);return[e.makeTensorInfo(W.shape,W.dtype,W.values),e.makeTensorInfo(U.shape,U.dtype,U.values)]}if(s===0)return l[l.length-1]=0,[e.makeTensorInfo(l,o.dtype,[]),e.makeTensorInfo(l,"int32",[])];if(c===1)return[o,fl({attrs:{shape:l,dtype:"int32",value:0},backend:e})];let p=e.texData.get(o.dataId),m=p!==null&&p.isPacked,f=m?e.unpackTensor(o):o,h=x.sizeFromShape(l)/c,g=ut({inputs:{x:f},attrs:{shape:[h,c]},backend:e});m&&Bc(e,f);let y=oB(s),b=oB(c),w=null,v=()=>w===null?[g,g]:[g,w],I=(M,W,U)=>{let q=v(),K=new eT(U),Q=[[c],[w===null?1:0],[Number.NEGATIVE_INFINITY],[M],[W]],rt=w;w=e.runWebGLProgram(K,q,"int32",Q),Bc(e,rt)};for(let M=1;M<y;M*=2){let W=M*2;for(let U=M;U>=1;U/=2)I(W,U,[h,b])}for(let M=b;M>y;M/=2){let W=v(),U=new rT([h,M/2]),K=[[c],[w===null?1:0],[y]],j=w;w=e.runWebGLProgram(U,W,"int32",K),Bc(e,j);let Q=y/2,rt=Q*2;for(let X=Q;X>=1;X/=2)I(rt,X,w.shape)}let E=w;w=ci({inputs:{x:w},backend:e,attrs:{begin:0,size:[h,s]}}),Bc(e,E);let D=SN({inputs:{x:g,indices:w},backend:e,attrs:{axis:1,batchDims:1}});Bc(e,g);let $=l.slice(0,-1);$.push(s),E=w,w=ut({inputs:{x:w},attrs:{shape:$},backend:e}),Bc(e,E);let R=D;return D=ut({inputs:{x:D},attrs:{shape:$},backend:e}),Bc(e,R),[D,w]}var sB={kernelName:$a,backendName:"webgl",kernelFunc:pot};var nT=class{constructor(t,e,n,o,s,i){this.variableNames=["Image","Transforms"],this.outputShape=i;let a=n==="nearest"?1:2,u;switch(o){case"constant":u=1;break;case"reflect":u=2;break;case"wrap":u=3;break;case"nearest":u=4;break;default:u=1;break}this.userCode=`
float mapCoord(float outCoord, float len) {
float inCoord = outCoord;
if(${u} == 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 (${u} == 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 (${u} == 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 < ${t} && 0 <= coordX && coordX < ${e}) {
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = float(${s});
}
return outputValue;
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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(${e}));
float mapY = mapCoord(inY, float(${t}));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
if (${a} == 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 mot(r){let{inputs:t,backend:e,attrs:n}=r,{image:o,transforms:s}=t,{interpolation:i,fillMode:a,fillValue:u,outputShape:l}=n,[c,p,m,f]=o.shape,[d,h]=l!=null?l:[p,m],g=[c,d,h,f],y=new nT(p,m,i,a,u,g);return e.runWebGLProgram(y,[o,s],"float32")}var iB={kernelName:Ra,backendName:"webgl",kernelFunc:mot};function fot(r){let{inputs:t,attrs:e,backend:n}=r,{axis:o}=e,{x:s}=t;ai(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=n.readSync(s.dataId),{outputValues:a,outputShape:u,indices:l}=CM(i,o,s.shape,s.dtype);return[n.makeTensorInfo(u,s.dtype,a),n.makeTensorInfo([l.length],"int32",l)]}var aB={kernelName:Mp,backendName:"webgl",kernelFunc:fot};function dot(r){let{inputs:t,backend:e,attrs:n}=r,{value:o}=t,{axis:s}=n;s<0&&(s+=o.shape.length);let i=o,a=i.shape.length,u=o.shape[s],l=new Array(a-1),c=0;for(let h=0;h<a;h++)h!==s&&(l[c++]=i.shape[h]);let p=[],m=new Array(a).fill(0),f=i.shape.slice();f[s]=1;let d=new Array(u);for(let h=0;h<d.length;h++){m[s]=h;let g=ci({inputs:{x:i},backend:e,attrs:{begin:m,size:f}}),y=ut({inputs:{x:g},backend:e,attrs:{shape:l}});d[h]=y,p.push(g)}return p.forEach(h=>e.disposeIntermediateTensorInfo(h)),d}var lB={kernelName:Ti,backendName:"webgl",kernelFunc:dot};var oT=class{constructor(t,e){this.variableNames=["x","segmentIds"];let n=t.windowSize,o=t.batchSize,s=t.inSize,i=t.numSegments,a=i*Math.ceil(s/n);this.outputShape=[o,a];let u="0.0",l="sumValue",c=Math.floor(n/4)*4,p=n%4,m=`
sumValue += dot(values, segFilter);
`,f="";s%n>0&&(f=`
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
`);let d="";s%n>0&&(d=`
if (inIdx < 0 || inIdx >= ${s}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${u};
2021-12-09 20:22:22 +01:00
2022-03-07 19:17:31 +01:00
float getValue(int batch, int inIdx) {
${f}
return getX(batch, inIdx);
}
2021-12-09 20:22:22 +01:00
2022-03-07 19:17:31 +01:00
float getSegmentIdAtIndex(int inIdx) {
${d}
return getSegmentIds(inIdx);
}
2021-12-09 20:22:22 +01:00
2022-03-07 19:17:31 +01:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${i})) * float(${n}));
int currentSeg = int(mod(float(outIdx), float(${i})));
2021-12-09 20:22:22 +01:00
2022-03-07 19:17:31 +01:00
float sumValue = 0.0;
2021-12-09 20:22:22 +01:00
2022-03-07 19:17:31 +01:00
for (int i = 0; i < ${c}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
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
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${m}
}
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
int inIdx = inOffset + ${c};
if (${p===1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${m}
} else if (${p===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${m}
} else if (${p===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
2021-12-06 12:34:50 +01:00
2022-03-07 19:17:31 +01:00
${m}
}
setOutput(${l});
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
`}};function hot(r){let{inputs:t,backend:e,attrs:n}=r,{x:o,segmentIds:s}=t,{numSegments:i}=n,a=o.shape.length,u=[],l=0,c=k.getAxesPermutation([l],a),p=o;c!=null&&(p=Le({inputs:{x:o},backend:e,attrs:{perm:c}}),u.push(p),l=k.getInnerMostAxes(1,a)[0]);let m=k.segment_util.computeOutShape(p.shape,l,i),f=x.sizeFromShape([p.shape[l]]),d=ut({inputs:{x:p},backend:e,attrs:{shape:[-1,f]}});u.push(d);let h=Tu(o.dtype),g=(v,I,E,D,$)=>{let R=v.shape[0],M=v.shape[1],W=k.segment_util.segOpComputeOptimalWindowSize(M,$),U={windowSize:W,inSize:M,batchSize:R,numSegments:$},q=new oT(U,I),K=e.compileAndRun(q,[v,E],D);if(u.push(K),K.shape[1]===$)return K;let j=VN({backend:e,attrs:{start:0,stop:$,step:1,dtype:"float32"}}),Q=tT({inputs:{x:j},backend:e,attrs:{reps:[M/W]}});return u.push(j),u.push(Q),g(K,I,Q,D,$)},y=g(d,"unsortedSegmentSum",s,h,i),b=ut({inputs:{x:y},backend:e,attrs:{shape:m}}),w=b;if(c!=null){u.push(b);let v=k.getUndoAxesPermutation(c);w=Le({inputs:{x:w},backend:e,attrs:{perm:v}})}return u.forEach(v=>e.disposeIntermediateTensorInfo(v)),w}var uB={kernelName:Fl,backendName:"webgl",kernelFunc:hot};var got=[QM,eL,rL,nL,sL,iL,aL,lL,pL,mL,fL,dL,hL,gL,xL,yL,bL,wL,vL,CL,IL,kL,NL,TL,DL,RL,FL,VM,PL,LL,zL,BL,VL,GL,WL,UL,HL,qL,KL,YL,ZL,JL,QL,tz,ez,rz,nz,oz,sz,iz,az,lz,uz,cz,mz,fz,dz,hz,xz,yz,bz,wz,vz,Cz,Iz,Sz,kz,BM,Nz,ML,Tz,_z,Ez,GM,Az,Dz,$z,Rz,Fz,Oz,Pz,Mz,Lz,zz,Vz,Gz,Wz,Uz,Hz,qz,jz,Yz,Zz,Jz,Qz,t3,s3,KM,i3,a3,l3,u3,_L,c3,f3,d3,h3,g3,WM,x3,y3,EL,e3,b3,w3,v3,XM,C3,I3,S3,k3,N3,T3,_3,E3,A3,D3,$3,R3,F3,O3,P3,SL,o3,M3,L3,z3,B3,V3,G3,W3,U3,q3,K3,X3,Y3,Z3,J3,Q3,tB,n3,ZM,eB,rB,nB,sB,iB,JM,aB,lB,uB,p3];for(let r of got)vu(r);var Zt;(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"})(Zt||(Zt={}));var lu;(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"})(lu||(lu={}));var cB;function xot(r){cB=r.wasm.cwrap(Ei,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function yot(r){let{inputs:t,backend:e,attrs:n}=r,{a:o,b:s,bias:i,preluActivationWeights:a}=t;if(o.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=n,m=e.dataIdMap.get(o.dataId).id,f=e.dataIdMap.get(s.dataId).id,d=0;if(i!=null){let $=e.dataIdMap.get(i.dataId);if($.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${$.shape.length}.`);d=$.id}let h=a==null?0:e.dataIdMap.get(a.dataId).id,g=lu[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let y=u?o.shape[2]:o.shape[1],b=l?s.shape[1]:s.shape[2],w=Mr.assertAndGetBroadcastShape(o.shape.slice(0,-2),s.shape.slice(0,-2)),v=e.makeOutput([...w,y,b],o.dtype),I=e.dataIdMap.get(v.dataId).id,E=new Uint8Array(new Int32Array(o.shape).buffer),D=new Uint8Array(new Int32Array(s.shape).buffer);return cB(m,E,o.shape.length,f,D,s.shape.length,u,l,g,d,h,p||0,I),v}var pB={kernelName:Ei,backendName:"wasm",setupFunc:xot,kernelFunc:yot};function ue(r,t){let e;function n(s){e=s.wasm.cwrap(r,null,["number","number","number"])}function o(s){let{backend:i,inputs:{x:a}}=s,u=i.dataIdMap.get(a.dataId).id,l=i.makeOutput(a.shape,t||a.dtype),c=i.dataIdMap.get(l.dataId).id;return x.sizeFromShape(l.shape)===0||e(u,Zt[a.dtype],c),l}return{kernelName:r,backendName:"wasm",setupFunc:n,kernelFunc:o}}var mB=ue(di);function Ce(r,t,e){let n;function o(i){n=i.wasm.cwrap(r,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:a,inputs:u}=i,{a:l,b:c}=u,p=a.dataIdMap.get(l.dataId).id,m=a.dataIdMap.get(c.dataId).id,f=e!=null?e:l.dtype,d=k.assertAndGetBroadcastShape(l.shape,c.shape),h=a.makeOutput(d,f);if(x.sizeFromShape(d)===0)return h;let g=new Uint8Array(new Int32Array(l.shape).buffer),y=new Uint8Array(new Int32Array(c.shape).buffer),b=a.dataIdMap.get(h.dataId)
${n.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
${o.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=t.dataIdMap.get(n.dataId).id,a=t.dataIdMap.get(o.dataId).id,u=t.dataIdMap.get(s.dataId).id,l=n.shape[0],c=x.sizeFromShape(s.shape),p=t.makeOutput([l,c],n.dtype),m=t.dataIdMap.get(p.dataId).id,f=t.makeOutput([c],s.dtype),d=t.dataIdMap.get(f.dataId).id,h=t.makeOutput([3],"int32"),g=t.dataIdMap.get(h.dataId).id;kG(i,a,u,l,m,d,g);let y=t.readSync(h.dataId),b;switch(y[0]){case 0:{b=k.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(y[1],y[2]);break}case 1:{b=k.getSparseReshapeNegativeOutputDimErrorMessage(y[1],y[2]);break}case 2:b=k.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let w=Array.from(t.readSync(o.dataId)),v=Array.from(t.readSync(f.dataId));b=k.getSparseReshapeInputOutputMultipleErrorMessage(w,v);break}case 4:{let w=Array.from(t.readSync(o.dataId)),v=Array.from(t.readSync(f.dataId));b=k.getSparseReshapeInputOutputMismatchErrorMessage(w,v);break}default:b=""}if(t.disposeData(h.dataId),b)throw t.disposeData(p.dataId),t.disposeData(f.dataId),new Error(b);return[p,f]}var NG={kernelName:Aa,backendName:"wasm",setupFunc:git,kernelFunc:xit};var TG;function Pb(r){TG=r.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function Mb(r,t){let{backend:e,inputs:n}=r,{data:o,indices:s,segmentIds:i}=n,a=s.shape[0],u=e.readSync(i.dataId,a-1,a)[0],c=a>0?u+1:0;if(c<0)throw new Error(k.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=o.shape.slice();p[0]=c;let m=e.dataIdMap.get(o.dataId).id,f=e.dataIdMap.get(s.dataId).id,d=e.dataIdMap.get(i.dataId).id,h=e.makeOutput(p,o.dtype),g=e.dataIdMap.get(h.dataId).id,y=e.makeOutput([4],"int32"),b=e.dataIdMap.get(y.dataId).id;TG(m,Zt[o.dtype],o.shape[0],f,d,g,b,t,0);let w=e.readSync(y.dataId),v;switch(w[0]){case 0:{v=k.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{v=k.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:v=k.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(w[1],w[2]);break;case 3:v=k.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(w[1],w[2],w[3]);break;default:v=""}if(e.disposeData(y.dataId),v)throw e.disposeData(h.dataId),new Error(v);return h}function yit(r){return Mb(r,!0)}var _G={kernelName:Dl,backendName:"wasm",setupFunc:Pb,kernelFunc:yit};function bit(r){return Mb(r,!1)}var EG={kernelName:$l,backendName:"wasm",setupFunc:Pb,kernelFunc:bit};function wit(r){let{inputs:t,attrs:e,backend:n}=r,{x:o}=t,{numOrSizeSplits:s,axis:i}=e,a=x.parseAxisParam(i,o.shape)[0],u=k.prepareSplitSize(o,s,a),l=new Array(o.shape.length).fill(0),c=o.shape.slice();return u.map(p=>{let m=[...c];m[a]=p;let f=Oo({inputs:{x:o},attrs:{begin:l,size:m},backend:n});return l[a]+=p,f})}var AG={kernelName:Ni,backendName:"wasm",kernelFunc:wit};var DG=ue($s);var $G=ue(Rl);var vit=!0,RG=Ce(Os,vit);var FG;function Cit(r){FG=r.wasm.cwrap(io,null,["number","number","number","number"])}function Iit(r){let{backend:t,inputs:e,attrs:n}=r,{alpha:o}=n,{x:s}=e,i=t.dataIdMap.get(s.dataId).id,a=t.makeOutput(s.shape,s.dtype),u=t.dataIdMap.get(a.dataId).id;return FG(i,o,Zt[s.dtype],u),a}var OG={kernelName:io,backendName:"wasm",setupFunc:Cit,kernelFunc:Iit};var PG;function Sit(r){PG=r.wasm.cwrap(Da,null,["number","array","number","array","array","array","array","array","number","number"])}function kit(r){let{backend:t,inputs:e,attrs:n}=r,{x:o}=e,{begin:s,end:i,strides:a,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=n,{finalShapeSparse:f,finalShape:d,isIdentity:h,sliceDim0:g,isSimpleSlice:y,begin:b,end:w,strides:v}=Ve.sliceInfo(o.shape,s,i,a,u,l,c,p,m),I;if(h)I=cr({inputs:{x:o},backend:t,attrs:{shape:d}});else if(g||y){x.assert(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);let E=Ve.computeOutShape(b,w,v),D=Oo({inputs:{x:o},backend:t,attrs:{begin:b,size:E}});I=cr({inputs:{x:D},backend:t,attrs:{shape:d}}),t.disposeData(D.dataId)}else{let E=t.makeOutput(f,"float32"),D=
");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.onmessage=(e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;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).then(function(instance){Module=instance})}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["__emscripten_thread_exit"](result)}}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==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else if(e.data.cmd==="processProxyingQueue"){if(Module["_pthread_self"]()){Module["_emscripten_proxy_execute_queue"](e.data.queue)}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}});`;var oW=gu(rW());var Vb=class extends pi{constructor(t){super();this.wasm=t,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(iW),hT=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new bl(this,po())}write(t,e,n){let o={id:this.dataIdNextNumber++};return this.move(o,t,e,n,1),o}numDataIds(){return this.dataIdMap.numDataIds()}async time(t){let e=x.now();return t(),{kernelMs:x.now()-e}}move(t,e,n,o,s){let i=this.dataIdNextNumber++;if(o==="string"){let c=e;this.dataIdMap.set(t,{id:i,stringBytes:c,shape:n,dtype:o,memoryOffset:null,refCount:s});return}let a=x.sizeFromShape(n),u=a*x.bytesPerElement(o),l=this.wasm._malloc(u);this.dataIdMap.set(t,{id:i,memoryOffset:l,shape:n,dtype:o,refCount:s}),this.wasm.tfjs.registerTensor(i,a,l),e!=null&&this.wasm.HEAPU8.set(new Uint8Array(e.buffer,e.byteOffset,u),l)}async read(t){return this.readSync(t)}readSync(t,e,n){let{memoryOffset:o,dtype:s,shape:i,stringBytes:a}=this.dataIdMap.get(t);if(s==="string")return(e==null||e===0)&&(n==null||n>=a.length)?a:a.slice(e,n);e=e||0,n=n||x.sizeFromShape(i);let u=x.bytesPerElement(s),l=this.wasm.HEAPU8.slice(o+e*u,o+n*u);return zit(l.buffer,s)}disposeData(t,e=!1){if(this.dataIdMap.has(t)){let n=this.dataIdMap.get(t);if(n.refCount--,!e&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(t)}return!0}refCount(t){return this.dataIdMap.has(t)?this.dataIdMap.get(t).refCount:0}incRef(t){let e=this.dataIdMap.get(t);e!=null&&e.refCount++}floatPrecision(){return 32}getMemoryOffset(t){return this.dataIdMap.get(t).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(t,e,n){let o;if(n==null)o=this.write(null,t,e);else{let s=this.dataIdNextNumber++;o={id:s},this.dataIdMap.set(o,{id:s,memoryOffset:n,shape:t,dtype:e
2021-04-26 20:45:49 +02:00
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
2021-04-30 18:01:04 +02:00
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
2022-01-14 16:04:13 +01:00
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2022 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
2021-04-30 18:01:04 +02:00
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
2021-08-31 18:21:57 +02:00
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
2021-04-26 20:45:49 +02:00
/** @license See the LICENSE file. */