2021-09-08 19:51:28 +02:00
/ *
2020-12-02 22:46:41 +01:00
Face - API
homepage : < https : //github.com/vladmandic/face-api>
author : < https : //github.com/vladmandic>'
2021-09-08 19:51:28 +02:00
* /
2020-12-02 22:46:41 +01:00
2022-05-24 13:16:42 +02:00
var PA = Object . defineProperty ; var OA = ( e => typeof require != "undefined" ? require : typeof Proxy != "undefined" ? new Proxy ( e , { get : ( t , n ) => ( typeof require != "undefined" ? require : t ) [ n ] } ) : e ) ( function ( e ) { if ( typeof require != "undefined" ) return require . apply ( this , arguments ) ; throw new Error ( 'Dynamic require of "' + e + '" is not supported' ) } ) ; var ob = ( e , t ) => { for ( var n in t ) PA ( e , n , { get : t [ n ] , enumerable : ! 0 } ) } ; var ze = { } ; ob ( ze , { Abs : ( ) => Tl , Acos : ( ) => _l , Acosh : ( ) => Cl , AdadeltaOptimizer : ( ) => gf , AdagradOptimizer : ( ) => yf , AdamOptimizer : ( ) => bf , AdamaxOptimizer : ( ) => xf , Add : ( ) => hs , AddN : ( ) => vi , All : ( ) => El , Any : ( ) => Fl , ArgMax : ( ) => wi , ArgMin : ( ) => cc , Asin : ( ) => Al , Asinh : ( ) => $l , Atan : ( ) => Dl , Atan2 : ( ) => Ml , Atanh : ( ) => Rl , AvgPool : ( ) => ki , AvgPool3D : ( ) => dc , AvgPool3DGrad : ( ) => lm , AvgPoolGrad : ( ) => om , BackendWasm : ( ) => WE , BatchMatMul : ( ) => Ii , BatchToSpaceND : ( ) => Pl , Bincount : ( ) => um , BroadcastArgs : ( ) => pm , BroadcastTo : ( ) => dI , Callback : ( ) => xN , CallbackList : ( ) => I2 , Cast : ( ) => Si , Ceil : ( ) => Ni , ClipByValue : ( ) => ms , Complex : ( ) => cm , ComplexAbs : ( ) => hc , Concat : ( ) => Ol , Conv2D : ( ) => Ti , Conv2DBackpropFilter : ( ) => dm , Conv2DBackpropInput : ( ) => _i , Conv3D : ( ) => mc , Conv3DBackpropFilterV2 : ( ) => hm , Conv3DBackpropInputV2 : ( ) => mm , Cos : ( ) => Ci , Cosh : ( ) => Ei , CropAndResize : ( ) => zl , Cumprod : ( ) => Ll , Cumsum : ( ) => Fi , CustomCallback : ( ) => N2 , DataStorage : ( ) => rm , DenseBincount : ( ) => fm , DepthToSpace : ( ) => Bl , DepthwiseConv2dNative : ( ) => Ai , DepthwiseConv2dNativeBackpropFilter : ( ) => gm , DepthwiseConv2dNativeBackpropInput : ( ) => ym , Diag : ( ) => bm , Dilation2D : ( ) => fc , Dilation2DBackpropFilter : ( ) => Fh , Dilation2DBackpropInput : ( ) => Eh , ENV : ( ) => Tx , EarlyStopping : ( ) => vN , Einsum : ( ) => xm , Elu : ( ) => Di , EluGrad : ( ) => vm , Environment : ( ) => pI , Equal : ( ) => Vl , Erf : ( ) => Wl , Exp : ( ) => Ri , ExpandDims : ( ) => Ul , Expm1 : ( ) => Gl , FFT : ( ) => wm , Fill : ( ) => gc , FlipLeftRight : ( ) => Hl , Floor : ( ) => Mi , FloorDiv : ( ) => Pi , FromPixels : ( ) => Ah , FusedBatchNorm : ( ) => Oi , FusedConv2D : ( ) => ai , FusedDepthwiseConv2D : ( ) => ri , GPGPUContext : ( ) => Sh , GatherNd : ( ) => ql , GatherV2 : ( ) => jl , GraphModel : ( ) => o0 , Greater : ( ) => Kl , GreaterEqual : ( ) => Li , History : ( ) => S2 , IFFT : ( ) => km , Identity : ( ) => zi , Imag : ( ) => Im , InputSpec : ( ) => Bt , IsFinite : ( ) => Xl , IsInf : ( ) => Yl , IsNan : ( ) => Ql , KernelBackend : ( ) => pc , LRN : ( ) => xc , LRNGrad : ( ) => Nm , LayerVariable : ( ) => g2 , LayersModel : ( ) => _r , LeakyRelu : ( ) => Bi , Less : ( ) => Jl , LessEqual : ( ) => Zl , LinSpace : ( ) => Sm , Log : ( ) => Wi , Log1p : ( ) => eu , LogSoftmax : ( ) => hI , LogicalAnd : ( ) => tu , LogicalNot : ( ) => yc , LogicalOr : ( ) => bc , LowerBound : ( ) => $$ , MathBackendWebGL : ( ) => Gf , Max : ( ) => Vi , MaxPool : ( ) => Gi , MaxPool3D : ( ) => vc , MaxPool3DGrad : ( ) => _m , MaxPoolGrad : ( ) => Tm , MaxPoolWithArgmax : ( ) => Cm , Maximum : ( ) => Ui , Mean : ( ) => Hi , Min : ( ) => ji , Minimum : ( ) => qi , MirrorPad : ( ) => Ki , Mod : ( ) => nu , MomentumOptimizer : ( ) => vf , Multinomial : ( ) => Em , Multiply : ( ) => Xi , Neg : ( ) => au , NonMaxSuppressionV3 : ( ) => su , NonMaxSuppressionV4 : ( ) => iu , NonMaxSuppressionV5 : ( ) => ou , NotEqual : ( ) => ru , OP _SCOPE _SUFFIX : ( ) => II , OneHot : ( ) => Yi , OnesLike : ( ) => lu , Optimizer : ( ) => $r , OptimizerConstructors : ( ) => qr , Pack : ( ) => uu , PadV2 : ( ) => Qi , Pool : ( ) => D$ , Pow : ( ) => Ji , Prelu : ( ) => Zi , Prod : ( ) => eo , RMSPropOptimizer : ( ) => wf , RNN : ( ) => fr , Range : ( ) => wc , Rank : ( ) => Nb , Real : ( ) => Fm , RealDiv : ( ) => $i , Reciprocal : ( ) => pu , Reduction : ( ) => kn , Relu : ( ) => to , Relu6 : ( ) => ao , Reshape : ( ) => cu , ResizeBilinear : ( ) => no , ResizeBilinearGrad : ( ) => $m , ResizeNearestNeighbor : ( ) => kc , ResizeNearestNeighborGrad : ( ) => Am , Reverse : ( ) => ro , RotateWithOffset : ( ) => _u , Round : ( ) => so , Rsqrt : ( ) => io , SGDOptimizer : ( ) => Hc , ScatterNd : ( ) => du , SearchSorted : ( ) => Dm , Select : ( ) => hu , Selu : ( ) => mu , Sequential : ( ) => bl , Sigmoid : ( ) => lo , Sign : ( ) => yu , Sin : ( ) => oo , Sinh : ( ) => gu , Slice : ( ) => fu , Softmax : ( ) => co , Softplus : ( ) => bu , SpaceToBatchND : ( ) => xu , SparseFillEmptyRows : ( ) => Ic , SparseReshape : ( ) => wu , SparseSegmentMean : ( ) => Sc , SparseSegmentSum : ( ) => Nc , SparseToDense : ( ) => Rm , SplitV : ( ) => vu , Sqrt : ( ) => uo , Square : ( ) => Tc , SquaredDifference : ( ) => ho , Step : ( ) => gs , StridedSlice : ( ) => ku , StringNGrams : ( ) => Mm , StringSplit : ( ) => Pm , StringToHashBucketFast : ( ) => Om , Sub : ( ) => mo , Sum : ( ) => po , SymbolicTensor : ( ) => Ua , Tan : ( ) => fo , Tanh : ( ) => go , Tensor : ( ) => Fe , TensorBuffer : ( ) => qt , Tile : ( ) => fs , TopK : ( ) => Iu , Transform : ( ) => Su , Transpose : ( ) => Nr , Unique : ( ) => Lm , Unpack : ( ) => Nu , UnsortedSegmentSum : ( ) => _c , UpperBound : ( ) => R$ , Variable : ( ) => as , ZerosLike : ( ) => Tu , _FusedMatMul : ( ) => ni , abs : ( ) => zt , acos : ( ) => Vx , acosh : ( ) => Ux , add : ( ) => J , addN : ( ) => rS , all : ( ) => Gm , any : ( ) => Jp , argMax : ( ) => oi , argMin : ( ) => Gx , asin : ( ) => Hx , asinh : ( ) => jx , atan : (
2022-03-07 19:17:31 +01:00
` ),ee=N=>j.writeSync(2,N+ `
2022-05-24 13:16:42 +02:00
` ));var re=c.print||Z,Y=c.printErr||ee;Object.assign(c,g),g=null,c.arguments&&(y=c.arguments),c.thisProgram&&(b=c.thisProgram),c.quit&&(x=c.quit);var ie=4;function ae(N){ae.shown||(ae.shown={}),ae.shown[N]||(ae.shown[N]=1,Y(N))}function le(N,D){if(typeof WebAssembly.Function=="function"){for(var U={i:"i32",j:"i64",f:"f32",d:"f64"},Q={parameters:[],results:D[0]=="v"?[]:[U[D[0]]]},pe=1;pe<D.length;++pe)Q.parameters.push(U[D[pe]]);return new WebAssembly.Function(Q,N)}var he=[1,0,1,96],ve=D.slice(0,1),_e=D.slice(1),Ct={i:127,j:126,f:125,d:124};he.push(_e.length);for(var pe=0;pe<_e.length;++pe)he.push(Ct[_e[pe]]);ve=="v"?he.push(0):he=he.concat([1,Ct[ve]]),he[1]=he.length-2;var La=new Uint8Array([0,97,115,109,1,0,0,0].concat(he,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0])),za=new WebAssembly.Module(La),nh=new WebAssembly.Instance(za,{e:{f:N}}),Cp=nh.exports.f;return Cp}var ue=[],ke;function ye(){if(ue.length)return ue.pop();try{oa.grow(1)}catch(N){throw N instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":N}return oa.length-1}function Ie(N,D){for(var U=N;U<N+D;U++){var Q=Uo(U);Q&&ke.set(Q,U)}}var Ee=0, $ e=N=>{Ee=N},Be=Atomics.load,je=Atomics.store,st=Atomics.compareExchange,et;c.wasmBinary&&(et=c.wasmBinary);var tt=c.noExitRuntime||!0;typeof WebAssembly!="object"&&Bo("no native wasm support detected");var Te,gt,ct=!1,yn;function Qt(N,D){N||Bo(D)}function Dn(N){var D=c["_"+N];return D}function Gt(N,D,U,Q,pe){var he={string:function(la){var Yo=0;if(la!=null&&la!==0){var S1=(la.length<<2)+1;Yo=Xo(S1),Rs(la,Yo,S1)}return Yo},array:function(la){var Yo=Xo(la.length);return xr(la,Yo),Yo}};function ve(la){return D==="string"?ia(la):D==="boolean"?Boolean(la):la}var _e=Dn(N),Ct=[],La=0;if(Q)for(var za=0;za<Q.length;za++){var nh=he[U[za]];nh?(La===0&&(La=sb()),Ct[za]=nh(Q[za])):Ct[za]=Q[za]}var Cp=_e.apply(null,Ct);function MA(la){return La!==0&&Jd(La),ve(la)}return Cp=MA(Cp),Cp}function Jt(N,D,U,Q){U=U||[];var pe=U.every(function(ve){return ve==="number"}),he=D!=="string";return he&&pe&&!Q?Dn(N):function(){return Gt(N,D,U,arguments,Q)}}var Da=1;function Rn(N){var D=new TextDecoder(N);this.decode=U=>(U.buffer instanceof SharedArrayBuffer&&(U=new Uint8Array(U)),D.decode.call(D,U))}var Ht=typeof TextDecoder!="undefined"?new Rn("utf8"):void 0;function sa(N,D,U){for(var Q=D+U,pe=D;N[pe]&&!(pe>=Q);)++pe;if(pe-D>16&&N.subarray&&Ht)return Ht.decode(N.subarray(D,pe));for(var he="";D<pe;){var ve=N[D++];if(!(ve&128)){he+=String.fromCharCode(ve);continue}var _e=N[D++]&63;if((ve&224)==192){he+=String.fromCharCode((ve&31)<<6|_e);continue}var Ct=N[D++]&63;if((ve&240)==224?ve=(ve&15)<<12|_e<<6|Ct:ve=(ve&7)<<18|_e<<12|Ct<<6|N[D++]&63,ve<65536)he+=String.fromCharCode(ve);else{var La=ve-65536;he+=String.fromCharCode(55296|La>>10,56320|La&1023)}}return he}function ia(N,D){return N?sa(i(),N,D):""}function Vr(N,D,U,Q){if(!(Q>0))return 0;for(var pe=U,he=U+Q-1,ve=0;ve<N.length;++ve){var _e=N.charCodeAt(ve);if(_e>=55296&&_e<=57343){var Ct=N.charCodeAt(++ve);_e=65536+((_e&1023)<<10)|Ct&1023}if(_e<=127){if(U>=he)break;D[U++]=_e}else if(_e<=2047){if(U+1>=he)break;D[U++]=192|_e>>6,D[U++]=128|_e&63}else if(_e<=65535){if(U+2>=he)break;D[U++]=224|_e>>12,D[U++]=128|_e>>6&63,D[U++]=128|_e&63}else{if(U+3>=he)break;D[U++]=240|_e>>18,D[U++]=128|_e>>12&63,D[U++]=128|_e>>6&63,D[U++]=128|_e&63}}return D[U]=0,U-pe}function Rs(N,D,U){return Vr(N,i(),D,U)}function kd(N){for(var D=0,U=0;U<N.length;++U){var Q=N.charCodeAt(U);Q>=55296&&Q<=57343&&(Q=65536+((Q&1023)<<10)|N.charCodeAt(++U)&1023),Q<=127?++D:Q<=2047?D+=2:Q<=65535?D+=3:D+=4}return D}var Ur=typeof TextDecoder!="undefined"?new Rn("utf-16le"):void 0;function xr(N,D){s().set(N,D)}function gp(N,D,U){for(var Q=0;Q<N.length;++Q)s()[D++>>0]=N.charCodeAt(Q);U||(s()[D>>0]=0)}function Lo(N,D){return N%D>0&&(N+=D-N%D),N}var bn,Id,Sd,yp,Nd,Td,r1,_d,Cd;_&&(bn=c.buffer);function Ra(N){bn=N,c.HEAP8=Id=new Int8Array(N),c.HEAP16=yp=new Int16Array(N),c.HEAP32=Td=new Int32Array(N),c.HEAPU8=Sd=new Uint8Array(N),c.HEAPU16=Nd=new Uint16Array(N),c.HEAPU32=r1=new Uint32Array(N),c.HEAPF32=_d=new Float32Array(N),c.HEAPF64=Cd=n
2022-03-07 19:17:31 +01:00
` )),l.join( `
2022-05-24 13:16:42 +02:00
` )}function Z $ (e,t,n,a){let r=bt(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?Rp(e):e;if(o>1)for(let u=0;u<r/s;u++){let p=u*s;for(let d=0;d<s;d++)i[d]=Math.max(i[d],Dp(l[p+d],0,n).length)}return i}function Dp(e,t,n){let a;return Array.isArray(e)?a= ` $ { parseFloat ( e [ 0 ] . toFixed ( ub ) ) } + $ { parseFloat ( e [ 1 ] . toFixed ( ub ) ) } j ` :Yr(e)?a= ` '${e}' ` :n==="bool"?a=yI(e):a=parseFloat(e.toFixed(ub)).toString(),Up(a,t)}function yI(e){return e===0?"false":"true"}function fh(e,t,n,a,r,s=!0){let i=n==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(n==="complex64"){let f=Rp(e);return[Dp(f[0],0,n)]}return n==="bool"?[yI(e[0])]:[e[0].toString()]}if(l===1){if(o>C1){let g=Ep*i,y=Array.from(e.slice(0,g)),b=Array.from(e.slice((o-Ep)*i,o*i));return n==="complex64"&&(y=Rp(y),b=Rp(b)),["["+y.map((x,v)=>Dp(x,r[v],n)).join(", ")+", ..., "+b.map((x,v)=>Dp(x,r[o-Ep+v],n)).join(", ")+"]"]}let f=n==="complex64"?Rp(e):Array.from(e);return["["+f.map((g,y)=>Dp(g,r[y],n)).join(", ")+"]"]}let u=t.slice(1),p=a.slice(1),d=a[0]*i,c=[];if(o>C1){for(let f=0;f<Ep;f++){let g=f*d,y=g+d;c.push(...fh(e.slice(g,y),u,n,p,r,!1))}c.push("...");for(let f=o-Ep;f<o;f++){let g=f*d,y=g+d;c.push(...fh(e.slice(g,y),u,n,p,r,f===o-1))}}else for(let f=0;f<o;f++){let g=f*d,y=g+d;c.push(...fh(e.slice(g,y),u,n,p,r,f===o-1))}let h=l===2?",":"";c[0]="["+c[0]+h;for(let f=1;f<c.length-1;f++)c[f]=" "+c[f]+h;let m= ` ,
2022-03-07 19:17:31 +01:00
` ;for(let f=2;f<l;f++)m+= `
2022-05-24 13:16:42 +02:00
` ;return c[c.length-1]=" "+c[c.length-1]+"]"+(s?"":m),c}function Rp(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var qt=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=bt(e),n!=null){let a=n.length;R(a===this.size,()=> ` Length of values '${a}' does not match the size inferred by the shape '${this.size}' . ` )}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||aI(t,this.size),this.strides=Nl(e)}set(e,...t){t.length===0&&(t=[0]),R(t.length===this.rank,()=> ` The number of provided coordinates ( $ { t . length } ) must match the rank ( $ { this . rank } ) ` );let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let a of e){if(a<0||a>=this.shape[t]){let r= ` Requested out of range element at $ { e } . Buffer shape = $ { this . shape } ` ;throw new Error(r)}t++}let n=e[e.length-1];for(let a=0;a<e.length-1;++a)n+=this.strides[a]*e[a];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Ba().makeTensor(this.values,this.shape,this.dtype)}},Ba=null,el=null,eD=null;function tD(e){Ba=e}function nD(e){el=e}function aD(e){eD=e}var Fe=class{constructor(e,t,n,a){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=bt(e),this.strides=Nl(e),this.dataId=n,this.id=a,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return el.buffer(this.shape,this.dtype,e)}bufferSync(){return el.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return rl(this.shape,e,this.dtype==="complex64")}arraySync(){return rl(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Ba().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>Rh(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Ba().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Ba().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Rh(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await Ba().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Ba().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return el.print(this,e)}clone(){return this.throwIfDisposed(),el.clone(this)}toString(e=!1){let t=this.dataSync();return J $ (t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),el.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Ba().makeVariable(this,e,t,n)}};Object.defineProperty(Fe,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function ne(){return _x("Tensor",()=>Fe)}ne();var as=class extends Fe{constructor(e,t,n,a){super(e.shape,e.dtype,e.dataId,a),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error( ` dtype of the new value ( $ { e . dtype } ) and previous value ( $ { this . dtype } ) must match ` );if(!ds(e.shape,this.shape))throw new Error( ` shape of the new value ( $ { e . shape } ) and previous value ( $ { this . shape } ) must match ` );Ba().disposeTensor(this),this.dataId=e.dataId,Ba().incRef(this,null)}dispose(){Ba().disposeVariable(this),this.isDisposedInternal=!0}};Ob
Manifest JSON has weights with names : $ { o . join ( ", " ) } . ` )}let l=r.reduce((h,m,f)=>(m&&h.push(f),h),[]),u=[];l.forEach(h=>{t[h].paths.forEach(m=>{let f=n+(n.endsWith("/")?"":"/")+m;u.push(f)})});let p=await e(u),d={},c=0;return l.forEach(h=>{let m=t[h].paths.length,f=0;for(let x=0;x<m;x++)f+=p[c+x].byteLength;let g=new ArrayBuffer(f),y=new Uint8Array(g),b=0;for(let x=0;x<m;x++){let v=new Uint8Array(p[c+x]);y.set(v,b),b+=v.byteLength}s[h].forEach(x=>{let v=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),k=SI(v,[x.manifestEntry]);for(let T in k)d[T]=k[T]}),c+=m}),d}}var eR="application/octet-stream",tR="application/json",Dx=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(R(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of ` fetch ` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=X().platform.fetch,R(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&R(e.length===2,()=> ` URL paths for http must have a length of 2 , ( actual length is $ { e . length } ) . ` ),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],a=NI(e,n);t.body.append("model.json",new Blob([JSON.stringify(a)],{type:tR}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:eR}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo: $ c(e),responses:[r]};throw new Error( ` BrowserHTTPRequest . save ( ) failed due to HTTP response status $ { r . status } . ` )}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error( ` Request to $ { this . path } failed with status code $ { e . status } . Please verify this URL points to the model JSON of the model to load . ` );let t;try{t=await e.json()}catch(r){let s= ` Failed to parse model JSON of response from $ { this . path } . ` ;throw this.path.endsWith(".pb")?s+=" 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.":s+=" Please make sure the server is serving valid JSON for this request.",new Error(s)}let n=t.modelTopology,a=t.weightsManifest;if(n==null&&a==null)throw new Error( ` The JSON from HTTP path $ { this . path } contains neither model topology or manifest for weights . ` );return $ x(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,a]=nR(t),r=this.weightPathPrefix||n,s=[];for(let u of e)s.push(...u.weights);let i=[],o=[];for(let u of e)for(let p of u.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(p)):i.push(r+p+a);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await RI(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,Ax(l)]}};Dx.URL_SCHEME_REGEX=/^https?: \/ \/ /;function nR(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),a=e.substring(0,t),r=n>t?e.substring(n):"";return[a+"/",r]}function Mb(e){return e.match(Dx.URL_SCHEME_REGEX)!=null}var PI=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(a=>Mb(a)):n=Mb(e),n)return Rx(e,t)}return null};Dt.registerSaveRouter(PI);Dt.registerLoadRouter(PI);function Rx(e,t){return new Dx(e,t)}function aR(e,t){return Rx(e,t)}var db=class{
2022-03-07 19:17:31 +01:00
Actual : $ { r } .
Expected : $ { s } . ` );for(let i=0;i<s.length;++i){let o=r[i],l=s[i];if(!n(o,l))throw new Error( ` Arrays differ : actual [ $ { i } ] = $ { o } , expected [ $ { i } ] = $ { l } .
Actual : $ { r } .
2022-05-24 13:16:42 +02:00
Expected : $ { s } . ` )}}function qR(e,t){e().then(()=>t.fail(),()=>t())}function KR(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Yr(e)||Yr(e[0])||Yr(t)||Yr(t[0])?Ob(e,n,(a,r)=>a==r):Ob(e,t,(a,r)=>Wx(a,r,0))}function XR(e,t,n){if(n==null&&(n=Bx()),!Wx(e,t,n))throw new Error( ` Numbers differ : actual === $ { e } , expected === $ { t } ` )}function Wx(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function YR(e,t,n){for(let a=0;a<e.length;a++)if(e[a]<t||e[a]>n)throw new Error( ` Value out of range : $ { e [ a ] } low : $ { t } , high : $ { n } ` )}function QR(e,t){let n=new Float32Array(e),a=new Float32Array(t);if(n.length!==a.length)throw new Error( ` Expected ArrayBuffer to be of length $ { a . length } , but it was $ { n . length } ` );for(let r=0;r<a.length;r++)if(n[r]!==a[r])throw new Error( ` Expected ArrayBuffer value at $ { r } to be $ { a [ r ] } but got $ { n [ r ] } instead ` )}function aS(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?aS(n):e[t]=Fc(n)}return e}var JR="3.18.0";function ZR(e,t){let n=F(e,"a","add"),a=F(t,"b","add");[n,a]=At(n,a);let r={a:n,b:a};return L.runKernel(hs,r)}var J=z({add_:ZR});function eM(e,t){let n=F(e,"a","floorDiv"),a=F(t,"b","floorDiv");[n,a]=At(n,a);let r={a:n,b:a};return L.runKernel(Pi,r)}var Um=z({floorDiv_:eM});function tM(e,t){let n=F(e,"a","div"),a=F(t,"b","div");if([n,a]=At(n,a),n.dtype==="int32"&&a.dtype==="int32")return Um(n,a);let r={a:n,b:a},s={};return L.runKernel( $ i,r,s)}var fe=z({div_:tM});function nM(e,t){let n=F(e,"a","mul"),a=F(t,"b","mul");[n,a]=At(n,a);let r={a:n,b:a};return L.runKernel(Xi,r)}var B=z({mul_:nM});function aM(e){let t=F(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return L.runKernel(hc,n)}else{let n={x:t};return L.runKernel(Tl,n)}}var zt=z({abs_:aM});function rM(e){let t={x:F(e,"x","acos")};return L.runKernel(_l,t)}var Vx=z({acos_:rM});function sM(e){let t={x:F(e,"x","acosh")};return L.runKernel(Cl,t)}var Ux=z({acosh_:sM});function iM(e){R(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),R(e.length>=1,()=> ` Must pass at least one tensor to tf . addN ( ) , but got $ { e . length } ` );let t=e.map((r,s)=>F(r, ` tensors$ { s } ` ,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!ds(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return L.runKernel(vi,a)}var rS=z({addN_:iM});function oM(e,t=null,n=!1){let a={x:F(e,"x","all","bool")},r={axis:t,keepDims:n};return L.runKernel(El,a,r)}var Gm=z({all_:oM});function lM(e,t=null,n=!1){let a={x:F(e,"x","any","bool")},r={axis:t,keepDims:n};return L.runKernel(Fl,a,r)}var Jp=z({any_:lM});function uM(e,t=0){let n={x:F(e,"x","argMax")},a={axis:t};return L.runKernel(wi,n,a)}var oi=z({argMax_:uM});function pM(e,t=0){let n={x:F(e,"x","argMin")},a={axis:t};return L.runKernel(cc,n,a)}var Gx=z({argMin_:pM});function cM(e){let t={x:F(e,"x","asin")};return L.runKernel(Al,t)}var Hx=z({asin_:cM});function dM(e){let t={x:F(e,"x","asinh")};return L.runKernel( $ l,t)}var jx=z({asinh_:dM});function hM(e){let t={x:F(e,"x","atan")};return L.runKernel(Dl,t)}var qx=z({atan_:hM});function mM(e,t){let n=F(e,"a","atan2"),a=F(t,"b","atan2");[n,a]=At(n,a);let r={a:n,b:a};return L.runKernel(Ml,r)}var Kx=z({atan2_:mM});function fM(e){let t={x:F(e,"x","atanh")};return L.runKernel(Rl,t)}var Xx=z({atanh_:fM});function gM(e,t,n,a,r="NHWC",s){let i=e[3],o=[...t,i],l=oS(r);return Rc(e,o,n,s,a,null,null,l)}function sS(e,t,n,a,r,s,i="channelsLast"){let[o,l]=Oh(t),u;if(i==="channelsLast")u=[o,l,e[3],e[3]];else if(i==="channelsFirst")u=[o,l,e[1],e[1]];else throw new Error( ` Unknown dataFormat $ { i } ` );return Rc(e,u,n,a,r,s,!1,i)}function yM(e,t,n,a,r,s,i="NDHWC"){let[o,l,u]=Lb(t),p,d;if(i==="NDHWC")d="channelsLast",p=[o,l,u,e[4],e[4]];else if(i==="NCDHW")d="channelsFirst",p=[o,l,u,e[1],e[1]];else throw new Error( ` Unknown dataFormat $ { i } ` );return iS(e,p,n,a,r,!1,d,s)}function Rc(e,t,n,a,r,s,i=!1,o="channelsLast"){let[l,u,p,d]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,p,d]=e;
with dtype $ { s . dtype } . ` )}),n.length===1)return Tr(n[0]);let a=n,r={axis:t};return L.runKernel(Ol,a,r)}var Ze=z({concat_:NM});function TM(e){let t={x:F(e,"x","sigmoid","float32")};return L.runKernel(lo,t)}var ha=z({sigmoid_:TM});function _M(e,t,n){let a=F(e,"x","slice","string_or_numeric");if(a.rank===0)throw new Error("Slicing scalar is not possible");let r={x:a},s={begin:t,size:n};return L.runKernel(fu,r,s)}var He=z({slice_:_M});function CM(e){let t={x:F(e,"x","tanh","float32")};return L.runKernel(go,t)}var li=z({tanh_:CM});function EM(e,t,n,a,r,s){let i=F(e,"forgetBias","basicLSTMCell"),o=F(t,"lstmKernel","basicLSTMCell"),l=F(n,"lstmBias","basicLSTMCell"),u=F(a,"data","basicLSTMCell"),p=F(r,"c","basicLSTMCell"),d=F(s,"h","basicLSTMCell"),c=Ze([u,d],1),h=De(c,o),m=J(h,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],b=He(m,[0,0],y),x=He(m,[0,g],y),v=He(m,[0,g*2],y),k=He(m,[0,g*3],y),T=J(B(ha(b),li(x)),B(p,ha(J(i,v)))),_=B(li(T),ha(k));return[T,_]}var FM=z({basicLSTMCell_:EM});function AM(e,t,n){let a=F(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);R(a.rank>=1+t.length,()=> ` input rank is $ { a . rank } but should be > than blockShape . length $ { t . length } ` ),R(n.length===t.length,()=> ` crops . length is $ { n . length } but should be equal to blockShape . length $ { t . length } ` ),R(a.shape[0]%r===0,()=> ` input tensor batch is $ { a . shape [ 0 ] } but is not divisible by the product of the elements of blockShape $ { t . join ( " * " ) } === $ { r } ` );let s={x:a},i={blockShape:t,crops:n};return L.runKernel(Pl,s,i)}var Mc=z({batchToSpaceND_:AM});function $ M(e){let t;return e.rank===0||e.rank===1?t=W(e,[1,1,1,e.size]):e.rank===2?t=W(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function DM(e,t,n,a,r,s){s==null&&(s=.001);let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(n,"variance","batchNorm"),u;r!=null&&(u=F(r,"scale","batchNorm"));let p;a!=null&&(p=F(a,"offset","batchNorm")),R(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),R(p==null||o.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),R(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let d={x: $ M(i),scale:u,offset:p,mean:o,variance:l},c={varianceEpsilon:s},h=L.runKernel(Oi,d,c);return W(h,i.shape)}var Er=z({batchNorm_:DM});function RM(e,t,n,a,r,s){let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(n,"variance","batchNorm"),u;r!=null&&(u=F(r,"scale","batchNorm"));let p;return a!=null&&(p=F(a,"offset","batchNorm")),R(i.rank===2,()=> ` Error in batchNorm2D : x must be rank 2 but got rank $ { i . rank } . ` ),R(o.rank===2||o.rank===1,()=> ` Error in batchNorm2D : mean must be rank 2 or rank 1 but got rank $ { o . rank } . ` ),R(l.rank===2||l.rank===1,()=> ` Error in batchNorm2D : variance must be rank 2 or rank 1 but got rank $ { l . rank } . ` ),u!=null&&R(u.rank===2||u.rank===1,()=> ` Error in batchNorm2D : scale must be rank 2 or rank 1 but got rank $ { u . rank } . ` ),p!=null&&R(p.rank===2||p.rank===1,()=> ` Error in batchNorm2D : offset must be rank 2 or rank 1 but got rank $ { p . rank } . ` ),Er(i,o,l,p,u,s)}var lS=z({batchNorm2d_:RM});function MM(e,t,n,a,r,s){let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(n,"variance","batchNorm"),u;r!=null&&(u=F(r,"scale","batchNorm"));let p;return a!=null&&(p=F(a,"offset","batchNorm")),R(i.rank===3,()=> ` Error in batchNorm3D : x must be rank 3 but got rank $ { i . rank } . ` ),R(o.rank===3||o.rank===1,()=> ` Error in batchNorm3D : mean must be rank 3 or rank 1 but got rank $ { o . rank } . ` ),R(l.rank===3||l.rank===1,()=> ` Error in batchNorm3D : variance must be rank 3 or rank 1 but got rank $ { l . rank } . ` ),u!=null&&R(u.rank===3||u.rank===1,()=> ` Error in batchNorm3D : scale must be rank 3 or rank 1 but got rank $ { u . rank } . ` ),p!=null&&R(p.rank===3||p.rank===1,()=> ` Error in batchNorm3D : offset must be rank 3 or rank 1 but got rank $ { p . rank } . ` ),Er(i,o,l,p,u,s)}var uS=z({batchNorm3d_:MM});function PM(e,t,n,a,r,s){let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(n,"variance","batchNorm"),u;r!=null&&(u=F(r,"scale","batchNorm")
2022-03-07 19:17:31 +01:00
$ { r } and $ { t } for depthToSpace with input shape
$ { a . shape } ` ),R(s*t>=0,()=> ` Negative dimension size caused by overflow when multiplying
$ { s } and $ { t } for depthToSpace with input shape
2022-05-24 13:16:42 +02:00
$ { a . shape } ` ),R(i%(t*t)===0,()=> ` Dimension size must be evenly divisible by $ { t * t } but is $ { i } for depthToSpace with input shape $ { a . shape } ` );let o={x:a},l={blockSize:t,dataFormat:n};return L.runKernel(Bl,o,l)}var nv=z({depthToSpace_:rP});function sP(e,t,n,a,r="NHWC",s=[1,1],i){let o=F(e,"x","depthwiseConv2d","float32"),l=F(t,"filter","depthwiseConv2d","float32"),u=o,p=!1;o.rank===3&&(p=!0,u=W(o,[1,o.shape[0],o.shape[1],o.shape[2]])),R(u.rank===4,()=> ` Error in depthwiseConv2d : input must be rank 4 , but got rank $ { u . rank } . ` ),R(l.rank===4,()=> ` Error in depthwiseConv2d : filter must be rank 4 , but got rank $ { l . rank } . ` ),R(u.shape[3]===l.shape[2],()=> ` Error in depthwiseConv2d : number of input channels ( $ { u . shape [ 3 ] } ) must match the inChannels dimension in filter $ { l . shape [ 2 ] } . ` ),Tn("depthwiseConv2d",a,i);let d={x:u,filter:l},c={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},h=L.runKernel(Ai,d,c);return p?W(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var xs=z({depthwiseConv2d_:sP});function iP(e){let t={x:F(e,"x","diag")};return L.runKernel(bm,t)}var oP=z({diag_:iP});function lP(e,t,n,a,r=[1,1],s="NHWC"){let i=F(e,"x","dilation2d"),o=F(t,"filter","dilation2d");R(i.rank===3||i.rank===4,()=> ` Error in dilation2d : input must be rank 3 or 4 , but got rank $ { i . rank } . ` ),R(o.rank===3,()=> ` Error in dilation2d : filter must be rank 3 , but got rank $ { o . rank } . ` ),R(s==="NHWC",()=> ` Error in dilation2d : Only NHWC is currently supported , but got dataFormat of $ { s } ` );let l=i,u=!1;i.rank===3&&(l=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);let p={x:l,filter:o},d={strides:n,pad:a,dilations:r},c=L.runKernel(fc,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var av=z({dilation2d_:lP});function uP(e,t){let n=F(e,"a","equal","string_or_numeric"),a=F(t,"b","equal","string_or_numeric");[n,a]=At(n,a),ut(n.shape,a.shape);let r={a:n,b:a};return L.runKernel(Vl,r)}var Jn=z({equal_:uP});function pP(e,t,n){let a=F(t,"a","where"),r=F(n,"b","where"),s=F(e,"condition","where","bool"),i=ut(ut(s.shape,a.shape),r.shape),o=ol(s,i),l=ol(a,i),u=ol(r,i),p={condition:o,t:l,e:u};return L.runKernel(hu,p)}var fn=z({where_:pP});function cP(e){let t={x:F(e,"x","zerosLike")};return L.runKernel(Tu,t)}var Ke=z({zerosLike_:cP});function dP(e,t){let n=F(e,"a","div"),a=F(t,"b","div");[n,a]=At(n,a);let r=fe(n,a),s=Ke(r),i=Jn(a,s);return fn(i,s,r)}var rv=z({divNoNan_:dP});function hP(e,t){let n=F(e,"t1","dot"),a=F(t,"t2","dot");R((n.rank===1||n.rank===2)&&(a.rank===1||a.rank===2),()=> ` Error in dot : inputs must all be rank 1 or 2 , but got ranks $ { n . rank } and $ { a . rank } . ` );let r=n.rank===1?n.size:n.shape[1],s=a.rank===1?a.size:a.shape[0];if(R(r===s,()=> ` Error in dot : inner dimensions of inputs must match , but got $ { r } and $ { s } . ` ),n.rank===1&&a.rank===1){let i=W(n,[1,-1]),o=W(a,[-1,1]),l=De(i,o);return W(l,[])}else if(n.rank===1&&a.rank===2){let i=W(n,[1,-1]),o=W(a,[a.shape[0],a.shape[1]]),l=De(i,o);return W(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=W(a,[-1,1]),o=De(n,i);return W(o,[o.size])}else{let i=W(a,[a.shape[0],a.shape[1]]);return De(n,i)}}var xS=z({dot_:hP});function mP(e,...t){let n=t.map((r,s)=>F(r, ` tensors$ { s } ` ,"einsum")),a={equation:e};return L.runKernel(xm,n,a)}var vS=z({einsum_:mP});function fP(e){let t={x:F(e,"x","elu","float32")};return L.runKernel(Di,t)}var Eu=z({elu_:fP});function gP(e){let t=F(e,"x","erf");R(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be ` int32 ` or ` float32 ` ."),t.dtype==="int32"&&(t=oe(t,"float32"));let n={x:t};return L.runKernel(Wl,n)}var sv=z({erf_:gP});function iv(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function wS(e,t,n){let a=e.length+t.length,r=[],s=0,i=0;for(let o=0;o<a;o++)n.indexOf(o)===-1?r.push(e[s++]):r.push(t[i++]);return r}function kS(e,t){let n=[],a=e.length;for(let s=0;s<a;s++)t.indexOf(s)===-1&&n.push(e[s]);let r=t.map(s=>e[s]);return[n,r]}function ui(e,t){let n=t.map(a=>1);return wS(e,n,t)}function yP(e,t,n){R(iv(t,n),()=> ` $ { e } supports only inner - most axes for now . Got axes $ { t } and rank - $ { n } input . ` )}function IS(e,t){if(iv(e,t))return null;let n
rank $ { s . rank } . ` ),R(ul(t),()=> ` Error in localResponseNormalization : depthRadius must be an integer but got depthRadius $ { t } . ` );let i=s,o=!1;s.rank===3&&(o=!0,i=W(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:n,alpha:a,beta:r},p=L.runKernel(xc,l,u);return o?W(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var dv=z({localResponseNormalization_:VP});function UP(e){let t={x:F(e,"x","log","float32")};return L.runKernel(Wi,t)}var Zn=z({log_:UP});function GP(e){let t={x:F(e,"x","log1p")};return L.runKernel(eu,t)}var zc=z({log1p_:GP});function HP(e){return R(ns(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let a=F(t,"x","tf.grad","string_or_numeric"),r=n!=null?F(n,"dy","tf.grad"):null;return L.tidy(()=>{let{value:s,grads:i}=L.gradients(()=>e(a),[a],r);return r!=null&&Nn(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Ym(i),i[0]})}}function jP(e){return R(ns(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{R(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of ` Tensor ` s or ` TensorLike ` s");let a=Qp(t,"args","tf.grads","string_or_numeric"),r=n!=null?F(n,"dy","tf.grads"):null;return L.tidy(()=>{let{value:s,grads:i}=L.gradients(()=>e(...a),a,r);return r!=null&&Nn(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ym(i),i})}}function qP(e){return R(ns(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{R(t instanceof Fe,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),R(n==null||n instanceof Fe,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:r}=L.gradients(()=>e(t),[t],n);return Ym(a),{grad:a[0],value:r}}}function KP(e){return R(ns(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{R(Array.isArray(t)&&t.every(r=>r instanceof Fe),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),R(n==null||n instanceof Fe,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=L.gradients(()=>e(...t),t,n);return n!=null&&Nn(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ym(a.grads),a}}function CS(e,t){R(ns(e),()=>"The f passed in variableGrads(f) must be a function"),R(t==null||Array.isArray(t)&&t.every(u=>u instanceof as),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in L.registeredVariables)t.push(L.registeredVariables[u])}let a=n?t.filter(u=>!u.trainable):null,r=t.length;t=t.filter(u=>u.trainable),R(t.length>0,()=> ` variableGrads ( ) expects at least one of the input variables to be trainable , but none of the $ { r } variables is trainable . ` );let s=!0,{value:i,grads:o}=L.gradients(e,t,null,s);R(o.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),R(i.rank===0,()=> ` The f passed in variableGrads ( f ) must return a scalar , but it returned a rank - $ { i . rank } tensor ` );let l={};return t.forEach((u,p)=>{o[p]!=null&&(l[u.name]=o[p])}),a!=null&&a.forEach(u=>l[u.name]=null),{value:i,grads:l}}function ur(e){return L.customGrad(e)}function Ym(e){if(e.filter(t=>t==null).length>0)throw new Error( ` Cannot compute gradient of y = f ( x ) with respect to x . Make sure that
the f you passed encloses all operations that lead from x to y . ` )}function XP(e){let t={x:F(e,"x","softplus")};return L.runKernel(bu,t)}var bo=z({softplus_:XP});function YP(e){let t=F(e,"x","logSigmoid");return ur(n=>({value:wt(bo(wt(n))),gradFunc:a=>B(a,ha(wt(n)))}))(t)}var ES=z({logSigmoid_:YP});function QP(e,t){let n=F(e,"a","sub"),a=F(t,"b","sub");[n,a]=At(n,a);let r={a:n,b:a};return L.runKernel(mo,r)}var ce=z({sub_:QP});function JP(e,t=-1){let n=F(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error( ` Log Softmax along a non - last dimension is not yet supported . Logits was rank $ { n . rank } and axis was $ { t } ` );return ur((a,r)=>{let s=Sa(a,t,!0),i=ce(a,s),o=ce(oe(i,"float32"),Zn(be(gn(i),t,!0)));return r([o]),{value:o,gradFunc:(l,u)=>{let[p]=u,d=!0,c=gn(p);return ce(l,B(be(l,t,d),c))}}})(n)}var Qm=z({logSoftmax_:JP});function ZP(e,t=null,n=!1){let a=F(e,"x","logSumExp"),r=_a(t,a.shape),s=Sa(a,r,!0),i=ce(a,s),o=gn(i),l=be(o,r),u=Zn(l),p=J(W(s,u.shape),u);if(n){let d=ui(p.shape,r);return W(p,d)}return p}var hv=z({logSumExp_:ZP});function eO(e,t){let n=F(e,"a","logicalAnd","bool"),a=F(t,"b","logicalAnd","bool");ut(n.shape,a.shape);let r={a:n,b:a};return L.runKernel(tu,r)}var Ta=z({logicalAnd_:eO});function tO(e){let t={x:F(e,"x","logicalNot","bool")};return L.runKernel(yc,t)}var Bc=z({logicalNot_:tO});function nO(e,t){let n=F(e,"a","logicalOr","bool"),a=F(t,"b","logicalOr","bool");ut(n.shape,a.shape);let r={a:n,b:a};return L.runKernel(bc,r)}var Jm=z({logicalOr_:nO});function aO(e,t){let n=F(e,"a","logicalXor","bool"),a=F(t,"b","logicalXor","bool");return ut(n.shape,a.shape),Ta(Jm(e,t),Bc(Ta(e,t)))}var FS=z({logicalXor_:aO}),rh=2147483648;function rO(e,t,n="left"){let a=F(e,"sortedSequence","searchSorted"),r=F(t,"values","searchSorted"),s=a.shape[a.shape.length-1],i=r.shape[r.shape.length-1],o=W(a,[-1,s]),l=W(r,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(bt(l.shape)>=rh)throw new Error( ` values tensor size must less than $ { rh } ` );if(o.shape[1]>=rh)throw new Error( ` trailing dim _size must less than $ { rh } for int32 output type , was $ { o . shape [ 1 ] } ` );let u={sortedSequence:o,values:l},p={side:n};return L.runKernel(Dm,u,p)}var mv=z({searchSorted_:rO});function AS(e,t){return mv(e,t,"left")}function sO(e,t,n,a,r){let s=F(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),R(o.rank===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { o . rank } . ` ),R(dr(n,i),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { n } and dilations '${i}' ` ),Tn("maxPool",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r},d=L.runKernel(Gi,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Pt=z({maxPool_:sO});function iO(e,t=[1,1,1],n,a,r,s="NDHWC"){let i=F(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),R(o.rank===5,()=> ` Error in maxPool3d : x must be rank 5 but got rank $ { o . rank } . ` ),R(s==="NDHWC",()=> ` Error in maxPool3d : Only NDHWC is currently supported , but got dataFormat of $ { s } ` ),Tn("maxPool3d",a,r);let u={x:o},p={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},d=L.runKernel(vc,u,p);return l?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var fv=z({maxPool3d_:iO});function oO(e,t,n,a,r=!1){let s={x:F(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:a,includeBatchInIndex:r},o=L.runKernel(Cm,s,i);return{result:o[0],indexes:o[1]}}var $ S=z({maxPoolWithArgmax_:oO});function lO(e,t){let n=F(e,"a","maximum"),a=F(t,"b","maximum");[n,a]=At(n,a),n.dtype==="bool"&&(n=oe(n,"int32"),a=oe(a,"int32")),ut(n.shape,a.shape);let r={a:n,b:a};return L.runKernel(Ui,r)}var hr=z({maximum_:lO});function uO(e,t=null,n=!1){let a={x:F(e,"x","mean")},r={axis:t,keepDims:n};return L.runKernel(Hi,a,r)}var Et=z({mean_:uO});function St(e,t="float32"){if(t==="complex64"){let a=St(e,"float32"),r=St(e,"float32");return Cr(a,r)}let n=im(b
$ { r . 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(o.rank!==0)throw new Error( ` Default value should be a scalar but received shape $ { o . shape } ` );let l={indices:r,values:s,denseShape:i,defaultValue:o},u=L.runKernel(Ic,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var hz=z({sparseFillEmptyRows_:dz});function mz(e,t,n){let a=F(e,"inputIndices","sparseReshape","int32"),r=F(t,"inputShape","sparseReshape","int32"),s=F(n,"newShape","sparseReshape","int32");if(a.rank!==2)throw new Error( ` Input indices should be Tensor2D but received shape
$ { a . shape } ` );if(r.rank!==1)throw new Error( ` Input shape should be Tensor1D but received shape $ { r . shape } ` );if(s.rank!==1)throw new Error( ` New shape should be Tensor1D but received shape $ { s . shape } ` );let i={inputIndices:a,inputShape:r,newShape:s},o=L.runKernel(wu,i);return{outputIndices:o[0],outputShape:o[1]}}var fz=z({sparseReshape_:mz});function gz(e,t,n){let a=F(e,"data","sparseSegmentMean"),r=F(t,"indices","sparseSegmentMean","int32"),s=F(n,"segmentIds","sparseSegmentMean","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error( ` Indices should be Tensor1D but received shape
2022-03-07 19:17:31 +01:00
$ { r . shape } ` );if(s.rank!==1)throw new Error( ` Segment ids should be Tensor1D but received shape
2022-05-24 13:16:42 +02:00
$ { s . shape } ` );let i={data:a,indices:r,segmentIds:s};return L.runKernel(Sc,i)}var yz=z({sparseSegmentMean_:gz});function bz(e,t,n){let a=F(e,"data","sparseSegmentSum"),r=F(t,"indices","sparseSegmentSum","int32"),s=F(n,"segmentIds","sparseSegmentSum","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error( ` Indices should be Tensor1D but received shape
2022-03-07 19:17:31 +01:00
$ { r . shape } ` );if(s.rank!==1)throw new Error( ` Segment ids should be Tensor1D but received shape
2022-05-24 13:16:42 +02:00
$ { s . shape } ` );let i={data:a,indices:r,segmentIds:s};return L.runKernel(Nc,i)}var xz=z({sparseSegmentSum_:bz});function vz(e,t,n,a,r,s,i,o){let l=F(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error( ` Data must be a vector , saw : $ { l . shape } ` );let u=F(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let p={separator:n,nGramWidths:a,leftPad:r,rightPad:s,padWidth:i,preserveShortSequences:o},d={data:l,dataSplits:u},c=L.runKernel(Mm,d,p);return{nGrams:c[0],nGramsSplits:c[1]}}var wz=z({stringNGrams_:vz});function kz(e,t,n=!0){let a=F(e,"input","stringSplit","string"),r=F(t,"delimiter","stringSplit","string");if(a.rank!==1)throw new Error( ` Input should be Tensor1D but received shape $ { a . shape } ` );if(r.rank!==0)throw new Error( ` Delimiter should be a scalar but received shape $ { r . shape } ` );let s={skipEmpty:n},i={input:a,delimiter:r},o=L.runKernel(Pm,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var Iz=z({stringSplit_:kz});function Sz(e,t){let n=F(e,"input","stringToHashBucketFast","string"),a={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return L.runKernel(Om,r,a)}var Nz=z({stringToHashBucketFast_:Sz}),Tz={fft:Uc,ifft:fl,rfft:Gc,irfft:uf},_z={hammingWindow:aL,hannWindow:jS,frame:qS,stft:oL},Ln={flipLeftRight:cL,grayscaleToRGB:hL,resizeNearestNeighbor:JS,resizeBilinear:QS,rotateWithOffset:fL,cropAndResize:uL,nonMaxSuppression:yL,nonMaxSuppressionAsync:NL,nonMaxSuppressionWithScore:_L,nonMaxSuppressionWithScoreAsync:EL,nonMaxSuppressionPadded:AL,nonMaxSuppressionPaddedAsync:DL,threshold:LL,transform:BL},ZS={bandPart:VL,gramSchmidt:GL,qr:jL},Cz={absoluteDifference:XL,computeWeightedLoss:Ar,cosineDistance:QL,hingeLoss:ZL,huberLoss:tz,logLoss:az,meanSquaredError:sz,sigmoidCrossEntropy:lz,softmaxCrossEntropy:cz},Mp={sparseFillEmptyRows:hz,sparseReshape:fz,sparseSegmentMean:yz,sparseSegmentSum:xz},yh={stringNGrams:wz,stringSplit:Iz,stringToHashBucketFast:Nz}, $ r=class extends eS{minimize(e,t=!1,n){let{value:a,grads:r}=this.computeGradients(e,n);if(n!=null){let s=n.map(i=>({name:i.name,tensor:r[i.name]}));this.applyGradients(s)}else this.applyGradients(r);return Re(r),t?a:(a.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return CS(e,t)}dispose(){this.iterations_!=null&&Re(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:we(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error( ` setWeights ( ) is not implemented for this optimizer class $ { this . getClassName ( ) } ` )}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty( $ r,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var gf=class extends $ r{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=L.registeredVariables[t],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName: ` $ { t } / accum _grad ` ,variable:O(()=>Ke(a).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName: ` $ { t } / accum _var ` ,variable:O(()=>Ke(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;O(()=>{let l=J(B(i,this.rho),B(lt(s),1-this.rho)),u=B(fe(un(J(o,this.epsilon)),un(J(i,this.epsilon))),s),p=J(B(o,this.rho),B(lt(u),1-this.rho));i.assign(l),o.assign(p);let d=J(B(u,-this.learningRate),a);a.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpda
indices . shape [ 0 ] = $ { e } ` }function lB(e,t){return ` indices ( $ { e } , 0 ) is invalid : $ { t } < 0 ` }function uB(e,t,n){return ` indices ( $ { e } , 0 ) is invalid : $ { t } >= $ { n } ` }function pB(e,t){return ` only one output dimension may be - 1 , not both $ { e } and $ { t } ` }function cB(e,t){return ` size $ { e } must be non - negative , not $ { t } ` }function dB(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function hB(e,t){let n=bt(e),a=bt(t);return ` Input to reshape is a SparseTensor with $ { n }
dense values , but the requested shape requires a multiple of $ { a } . inputShape = $ { e } outputShape = $ { t } ` }function mB(e,t){let n=bt(e),a=bt(t);return ` Input to reshape is a tensor with $ { n } dense values , but the requested shape has $ { a } . inputShape = $ { e } outputShape = $ { t } ` }function fB(){return"segment ids must be >= 0"}function gB(){return"segment ids are not increasing"}function yB(e,t){return ` Segment id $ { e } out of range [ 0 , $ { t } ) , possibly because segmentIds input is not sorted . ` }function bB(e,t,n){return ` Bad : indices [ $ { e } ] == $ { t } out of range [ 0 , $ { n } ) ` }var n2={};Me(n2,{collectGatherOpShapeInfo:()=>wB,computeOutShape:()=>vB,segOpComputeOptimalWindowSize:()=>xB});function xB(e,t){let n=!1,a;for(e<=Dv?(a=e,n=!0):a=Ch(e,Math.floor(Math.sqrt(e)));!n;)a>t||a===e?n=!0:a=Ch(e,a+1);return a}function vB(e,t,n){let a=[],r=e.length;for(let s=0;s<r;s++)s!==t?a.push(e[s]):a.push(n);return a}function wB(e,t,n,a){let r=t.shape.length,s=e.shape.length;if(a!==0&&(a<-r||a>r))throw new Error( ` Expect batchDims in the range of [ - $ { r } , $ { r } ] , but got $ { a } ` );if(a<0&&(a+=r),a>s)throw new Error( ` batchDims ( $ { a } ) must be less than rank ( x ) (
$ { s } ) . ` );if(n<a)throw new Error( ` batchDims ( $ { a } ) must be less than or equal to axis ( $ { n } ) . ` );for(let d=0;d<a;++d)if(e.shape[d]!==t.shape[d])throw new Error( ` x . shape [ $ { d } ] : $ { e . shape [ d ] } should be equal to indices . shape [ $ { d } ] : $ { t . shape [ d ] } . ` );let i=e.shape[n],o=[],l=1,u=1,p=1;for(let d=0;d<a;++d)o.push(e.shape[d]),l*=e.shape[d];for(let d=a;d<n;d++)o.push(e.shape[d]),u*=e.shape[d];for(let d=a;d<r;d++)o.push(t.shape[d]);for(let d=n+1;d<s;d++)o.push(e.shape[d]),p*=e.shape[d];return{batchSize:l,sliceSize:p,outerSize:u,dimSize:i,outputShape:o}}function kB(e){try{return e.map(t=>Rh(t))}catch(t){throw new Error( ` Failed to decode encoded string bytes into utf - 8 , error : $ { t } ` )}}function IB(e){return e.map(t=>Fc(t))}var mr={};Me(mr,{nonMaxSuppressionV3Impl:()=>KS,nonMaxSuppressionV4Impl:()=>XS,nonMaxSuppressionV5Impl:()=>YS,whereImpl:()=>zS});var a2={kernelName:Tl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>B(e,Ru(oe(n,"float32"),-1))}}},SB={kernelName:_l,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=lt(oe(n,"float32")),r=un(ce(we(1),a));return wt(fe(e,r))}}}},NB={kernelName:Cl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=un(ce(lt(oe(n,"float32")),1));return fe(e,a)}}}},TB={kernelName:hs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ut(n.shape,a.shape);return{a:()=>{let s=e,i=Vt(n.shape,r);return i.length>0&&(s=be(s,i)),W(s,n.shape)},b:()=>{let s=e,i=Vt(a.shape,r);return i.length>0&&(s=be(s,i)),W(s,a.shape)}}}},_B={kernelName:vi,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((a,r)=>{n[r]=()=>e.clone()}),n}},CB={kernelName:wi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ke(n)}}},EB={kernelName:cc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ke(n)}}},FB={kernelName:Al,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,un(ce(we(1),lt(oe(n,"float32")))))}}},AB={kernelName: $ l,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=un(J(we(1),lt(oe(n,"float32"))));return fe(e,a)}}}}, $ B={kernelName:Ml,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=ut(n.shape,a.shape);return{a:()=>{let s=J(lt(n),lt(a)),i=B(e,fe(a,s)),o=Vt(n.shape,r);return o.length>0&&(i=be(i,o)),W(i,n.shape)},b:()=>{let s=J(lt(n),lt(a)),i=wt(B(e,fe(n,s))),o=Vt(a.shape,r);return o.length>0&&(i=be(i,o)),W(i,a.shape)}}}},DB={kernelName:Dl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,J(lt(oe(n,"float32")),1))}}},RB={kernelName:Rl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,ce(we(1),lt(oe(n,"float32"))))}}};function MB(e,t,n,a,r,s){let i=F(e,"dy","avgPool3dGrad"),o=F(t,"input","avgPool3dGrad"),l=i,u=o,p=!1;o.rank===4&&(p=!0,l=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),R(l.rank===5,()=> ` Error in avgPool3dGrad : dy must be rank 5 but got rank $ { l . rank } . ` ),R(u.rank===5,()=> ` Error in avgPool3dGrad : input must be rank 5 but got rank $ { u . rank } . ` ),Tn("avgPool3dGrad",r,s);let d={dy:l,input:u},c={filterSize:n,strides:a,pad:r,dimRoundingMode:s},h=L.runKernel(lm,d,c);return p?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var PB=z({avgPool3dGrad_:MB}),OB={kernelName:dc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i,dimRoundingMode:o}=n;return{x:()=>PB(e,a,r,s,i,o)}}};function LB(e,t,n,a,r){let s=F(e,"dy","avgPoolGrad"),i=F(t,"input","avgPoolGrad");R(i.rank===s.rank,()=> ` Rank of input ( $ { i . rank } ) does not match rank of dy ( $ { s . rank } ) ` );let o=i,l=s,u=!1;i.rank===3&&(u=!0,o=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=W(s,[1,s.shape[0],s.shape[1],s.shape[2]])),R(l.rank===4,()=> ` Error in avgPoolGrad : dy must be rank 4 but got rank $ { l . rank } . ` ),R(o.rank===4,()=> ` Error in avgPoolGrad : input must be rank 4 but got rank $ { o . rank } . ` );let p={dy:l,input:o},d={filterSize:n,strides:a,pad:r},c=L.runKernel(om,p,d);return u?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var zB=z({avgPoolGrad_:LB}),BB={kernelName:ki,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i}=n;return{x:()=>zB(e,a,r,s,i)}}},WB={kernelName:Ii,i
2022-03-07 19:17:31 +01:00
1. The $ { a } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2. The custom $ { a } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );return i}else{let s=e;if(s.className==null||s.config==null)throw new H( ` $ { a } : Improper config format : $ { JSON . stringify ( s ) } .
2022-04-05 13:38:11 +02:00
'className' and 'config' must set . ` );let i=s.className,o,l;if(i in n?[o,l]=n[i]:i in va?[o,l]=va.className:i in t&&([o,l]=t[i]),o==null)throw new H( ` Unknown $ { a } : $ { i } . This may be due to one of the following reasons :
2022-03-07 19:17:31 +01:00
1. The $ { a } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2022-05-24 13:16:42 +02:00
2. The custom $ { a } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );if(l!=null){let u={};for(let h of Object.keys(va))u[h]=va[h];for(let h of Object.keys(n))u[h]=n[h];let p=s.config;p.customObjects=u;let d=Object.assign({},va);for(let h of Object.keys(n))va[h]=n[h];zb(s.config);let c=l(o,s.config,n,r);return va=Object.assign({},d),c}else{let u=Object.assign({},va);for(let d of Object.keys(n))va[d]=n[d];let p=new o(s.config);return va=Object.assign({},u),p}}}function C4(e,t){return e<t?-1:e>t?1:0}function sh(e,t){return-1*C4(e,t)}function es(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function E4(e){if(e==null)throw new H( ` Invalid value in obj : $ { JSON . stringify ( e ) } ` );for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function vo(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new H( ` $ { n } is not a valid $ { t } . Valid values are $ { e } or null / undefined . ` )}function Mv(e,t,n=0,a=1/0){return rr(n>=0),rr(a>=n),Array.isArray(e)&&e.length>=n&&e.length<=a&&e.every(r=>typeof r===t)}function nn(e,t){Array.isArray(e)?(w.assert(e.length>0,()=> ` $ { t } is unexpectedly an empty array . ` ),e.forEach((n,a)=>nn(n, ` element $ { a + 1 } of $ { t } ` ))):w.assert(Number.isInteger(e)&&e>0,()=> ` Expected $ { t } to be a positive integer , but got $ { o2 ( e ) } . ` )}function o2(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>o2(t)).join(",")+"]":typeof e=="string"? ` "${e}" ` : ` $ { e } ` }function F4(e,t,n){let a=n!=null?n():w.now(),r;return(...s)=>{let i=n!=null?n():w.now();return i-a<t||(a=i,r=e(...s)),r}}function l2(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}var A4=0;function u2(){return A4++}var ih={};function kf(e=""){return e in ih||(ih[e]=0),ih[e]+=1,e+ih[e].toString()}var $ 4=["channelsFirst","channelsLast"],D4=["nearest","bilinear"],R4=["valid","same","causal"],M4=["max","avg"],P4=["sum","mul","concat","ave"],Qo=new Map;function Ot(e){vo( $ 4,"DataFormat",e)}function O4(e){vo(D4,"InterpolationFormat",e)}function ya(e){vo(R4,"PaddingMode",e)}function p2(e){vo(M4,"PoolMode",e)}var Gp=[],q1="/";function Zs(e,t){Gp.push(e);try{let n=t();return Gp.pop(),n}catch(n){throw Gp.pop(),n}}function L4(){return Gp.length===0?"":Gp.join(q1)+q1}function c2(e){if(!h2(e))throw new Error("Not a valid tensor name: '"+e+"'");return L4()+e}function d2(e){if(!h2(e))throw new Error("Not a valid tensor name: '"+e+"'");Qo.has(e)||Qo.set(e,0);let t=Qo.get(e);if(Qo.set(e,Qo.get(e)+1),t>0){let n= ` $ { e } _$ { t } ` ;return Qo.set(n,1),n}else return e}var z4=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9 \. _ \/ ]* $ /);function h2(e){return!!e.match(z4)}function B4(e){return e===parseInt(e.toString(),10)}function ts(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let a=1;for(let r=t;r<n;++r)a*=e[r];return a}function gl(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){let a=e[n];a<t&&(t=a)}return t}function is(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){let a=e[n];a>t&&(t=a)}return t}function Ka(e,t){if(t<e)throw new H( ` end ( $ { t } ) < begin ( $ { e } ) is forbidden . ` );let n=[];for(let a=e;a<t;++a)n.push(a);return n}var mb;function jt(){return mb==null&&(mb=BI().epsilon()),mb}function Xa(){return"channelsLast"}function If(e,t){return oe(e,t)}function qc(e,t=-1){let n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),W(e,n)}function W4(e,t){return O(()=>{if(e.shape.length!==2)throw new H( ` repeat ( ) expects a rank - 2 tensor , but received a rank - $ { e . shape . length } tensor . ` );let n=qc(e,1);return Bb(n,[1,t,1])})}function V4(e){let t=[ts(e.shape)];return W(e,t)}function U4(e){if(e.rank<=1)throw new H( ` batchFlatten requires a minimum rank of 2. Got rank : $ { e . rank } . ` );let t=[e.shape[0],ts(e.shape,1)];return W(e,t)}function ei(e,t,n){return O(()=>{switch(e.rank){case 1:return lf(e,t,n);case 2:return kv(e,[t,0],[n,e.shape[1]]);case 3:return Du(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return tc(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return He(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);cas
2022-05-18 14:36:05 +02:00
because the value dtype is $ { t . dtype } , but TensorArray dtype is $ { this . dtype } . ` );if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Ia(this.elementShape,t.shape, ` TensorArray $ { this . name } : Could not write to TensorArray index $ { e } . ` ),n.read)throw new Error( ` TensorArray $ { this . name } : Could not write to TensorArray index $ { e } , because it has already been read . ` );if(n.written)throw new Error( ` TensorArray $ { this . name } : Could not write to TensorArray index $ { e } , because it has already been written . ` );n.tensor=t,tn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error( ` TensorArray $ { this . name } : could not write multiple tensors , because the index size : $ { e . length } is not the same as tensors size : $ { t . length } . ` );e.forEach((n,a)=>this.write(n,t[a]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but gather requested dtype $ { t } ` );if(e)e=e.slice(0,this.size());else{e=[];for(let a=0;a<this.size();a++)e.push(a)}if(e.length===0)return Qn([],[0].concat(this.elementShape));let n=this.readMany(e);return Ia(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Mt(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but concat requested dtype $ { e } ` );if(this.size()===0)return Qn([],[0].concat(this.elementShape));let t=[];for(let a=0;a<this.size();a++)t.push(a);let n=this.readMany(t);return Ia(this.elementShape,n[0].shape, ` TensorArray shape mismatch : tensor array shape ( $ { this . elementShape } ) vs first tensor shape ( $ { n [ 0 ] . shape } ) ` ),Ze(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but tensor has dtype $ { t . dtype } ` );if(e.length!==t.shape[0])throw new Error( ` Expected len ( indices ) == tensor . shape [ 0 ] , but saw : $ { e . length } vs . $ { t . shape [ 0 ] } ` );let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error( ` Max index must be < array size ( $ { n } vs . $ { this . maxSize } ) ` );this.writeMany(e,ht(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but tensor has dtype $ { t . dtype } ` );let n=0,a=e.map(o=>(n+=o,n));if(n!==t.shape[0])throw new Error( ` Expected sum of lengths to be equal to
2022-03-07 19:17:31 +01:00
tensor . shape [ 0 ] , but sum of lengths is
2022-05-24 13:16:42 +02:00
$ { n } , and tensor 's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray' s size is not equal to the size of lengths ( $ { this . maxSize } vs . $ { e . length } ) , and the TensorArray is not marked as dynamically resizeable ` );let r=n===0?0:t.size/n,s=[];O(()=>{t=W(t,[1,n,r]);for(let o=0;o<e.length;++o){let l=o===0?0:a[o-1],u=[0,l,0],p=[1,e[o],r];s[o]=W(He(t,u,p),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},xl=class{constructor(e,t,n,a=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(r=>{if(n!==r.dtype)throw new Error( ` Invalid data types ; op elements $ { n } , but list elements $ { r . dtype } ` );Ia(t,r.shape,"TensorList shape mismatch: "),tn(r)}),this.idTensor=we(0),this.maxNumElements=a,tn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new xl([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , 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 . ` );Ia(e,this.elementShape,"TensorList shape mismatch: ");let a=Ap(this.elementShape,this.tensors,e);return O(()=>{let r=this.tensors.map(s=>W(s,a));return Mt(r,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , but list elements $ { this . elementDtype } ` );if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Ap(this.elementShape,this.tensors,e),a=this.tensors.pop();return Ia(a.shape,e,"TensorList shape mismatch: "),W(a,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { e . dtype } , but list elements $ { this . elementDtype } ` );if(Ia(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");tn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error( ` TensorListResize expects size to be non - negative . Got : $ { e } ` );if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error( ` TensorListResize input size $ { e } is greater maxNumElement $ { this . maxNumElements } . ` );let t=new xl([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { n } , but list elements $ { this . elementDtype } ` );if(e<0||e>this.tensors.length)throw new Error( ` Trying to access element $ { e } in a list with $ { this . tensors . length } elements . ` );if(this.tensors[e]==null)throw new Error( ` element at index $ { e } is null . ` );Ia(this.tensors[e].shape,t,"TensorList shape mismatch: ");let a=Ap(this.elementShape,this.tensors,t);return W(this.tensors[e],a)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t . dtype } , but list elements $ { this . elementDtype } ` );if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error( ` Trying to set element $ { e } in a list with max $ { this . maxNumElements } elements . ` );Ia(this.elementShape,t.shape,"TensorList shape mismatch: "),tn(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , but list elements $ { this . elementDtype } ` );Ia(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let a=Ap(this.elementShape,this.tensors,n);return e.length===0?Qn([],[0].concat(a)):O(()=>{let r=e.map(s=>W(this.tensors[s],a));return Mt(r,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error( ` TensorList dtype is $ { this . elementDtype } but concat requested dtype $ { e } ` );Ia(this.elementShape,t,"TensorList shape mismatch: ");let n=Ap(this.elementShape,this.tensors,t);return this.size()===0?Q
2022-03-07 19:17:31 +01:00
tensor . shape [ 0 ] , but sum of lengths is
2022-05-24 13:16:42 +02:00
$ { a } , and tensor ' s shape is : $ { e . shape } ` );let s=e.shape.slice(1),i=sx(s,n),o=a===0?0:e.size/a,l=O(()=>{let p=[];e=W(e,[1,a,o]);for(let d=0;d<t.length;++d){let c=d===0?0:r[d-1],h=[0,c,0],m=[1,t[d],o];p[d]=W(He(e,h,m),i)}return e.dispose(),p}),u=new xl([],n,e.dtype,t.length);for(let p=0;p<l.length;p++)u.setItem(p,l[p]);return u}var H6=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let a=I("thenBranch",e,t,n),r=I("elseBranch",e,t,n),s=I("cond",e,t,n),i=I("args",e,t,n);return(await s.data())[0]?n.functionMap[a].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let a=I("body",e,t,n),r=I("cond",e,t,n),s=I("args",e,t,n),i=await n.functionMap[r].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),o=s.map(p=>p.id),l=await i[0].data();i.forEach(p=>{!p.kept&&o.indexOf(p.id)===-1&&p.dispose()});let u=s;for(;l[0];){let p=u;u=await n.functionMap[a].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);let d=u.map(h=>h.id);p.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let c=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await c[0].data(),c.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return u}case"LoopCond":{let a=I("pred",e,t,n);return[kr(a)]}case"Switch":{let a=I("pred",e,t,n),r=I("data",e,t,n);return r.kept||(r=kr(r)),(await a.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let a=e.inputNames.find(r=>In(r,t,n)!==void 0);if(a){let r=In(a,t,n);return[kr(r)]}return}case"Enter":{let a=I("frameName",e,t,n),r=I("tensor",e,t,n);return n.enterFrame(a),[kr(r)]}case"Exit":{let a=I("tensor",e,t,n);return n.exitFrame(),[kr(a)]}case"NextIteration":{let a=I("tensor",e,t,n);return n.nextIteration(),[kr(a)]}case"TensorArrayV3":{let a=I("size",e,t,n),r=I("dtype",e,t,n),s=I("elementShape",e,t,n),i=I("dynamicSize",e,t,n),o=I("clearAfterRead",e,t,n),l=I("identicalElementShapes",e,t,n),u=I("name",e,t,n),p=new B6(u,r,a,s,l,i,o);return n.addTensorArray(p),[p.idTensor,we(1)]}case"TensorArrayWriteV3":{let a=I("tensorArrayId",e,t,n),r=I("index",e,t,n),s=I("tensor",e,t,n),i=n.getTensorArray(a.id);return i.write(r,s),[i.idTensor]}case"TensorArrayReadV3":{let a=I("tensorArrayId",e,t,n),r=I("index",e,t,n);return[n.getTensorArray(a.id).read(r)]}case"TensorArrayGatherV3":{let a=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),s=I("dtype",e,t,n);return[n.getTensorArray(a.id).gather(r,s)]}case"TensorArrayScatterV3":{let a=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),s=I("tensor",e,t,n),i=n.getTensorArray(a.id);return i.scatter(r,s),[i.idTensor]}case"TensorArrayConcatV3":{let a=I("tensorArrayId",e,t,n),r=n.getTensorArray(a.id),s=I("dtype",e,t,n);return[r.concat(s)]}case"TensorArraySplitV3":{let a=I("tensorArrayId",e,t,n),r=I("tensor",e,t,n),s=I("lengths",e,t,n),i=n.getTensorArray(a.id);return i.split(s,r),[i.idTensor]}case"TensorArraySizeV3":{let a=I("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return[we(r.size(),"int32")]}case"TensorArrayCloseV3":{let a=I("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let a=I("tensorListId",e,t,n),r=I("index",e,t,n),s=I("tensor",e,t,n),i=n.getTensorList(a.id);return i.setItem(r,s),[i.idTensor]}case"TensorListGetItem":{let a=I("tensorListId",e,t,n),r=I("index",e,t,n),s=I("elementShape",e,t,n),i=I("elementDType",e,t,n);return[n.getTensorList(a.id).getItem(r,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let a=I("indices",e,t,n),r=I("tensor",e,t,n),s=I("elementShape",e,t,n),i=I("numElements",e,t,n),o=U6(r,a,s,i);return n.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let a=I("elementShape",e,t,n),r=I("elementDType",e,t,n),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=I(s,e,t,n),o=V6(a,r,i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{let a=I("tensorListId",e,t,n),r=I("indices",e,t,n),s=I("elementShape",e,t,n),i=I("elementDType",e,t,n);return[n.getTensor
$ { e } ` );let a;return this.size===1/0||this.size==null?a=this.size:t?a=Math.ceil(this.size/e):a=Math.floor(this.size/e),qn(async()=>(await n.iterator()).columnMajorBatch(e,t,jH),a)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,qn(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,qn(async()=>(await t.iterator()).filter(a=>O(()=>e(a))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return qn(async()=>(await t.iterator()).map(n=>O(()=>e(n))),this.size)}mapAsync(e){let t=this;return qn(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError(" ` Dataset . prefetch ( ) ` requires bufferSize to be specified.");let t=this;return qn(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,qn(async()=>{let a=u0(async()=>({value:await t.iterator(),done:!1}));return FH(a.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,qn(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<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 a = this , r = kH . alea ( t || w . now ( ) . toString ( ) ) ; return qn ( async ( ) => { let s = r . int32 ( ) ; return n && ( s += r . int32 ( ) ) , ( await a . iterator ( ) ) . shuffle ( e , s . toString ( ) ) } , this . size ) } take ( e ) { let t = this , n ; return this . size != null && this . size > e ? n = e : this . size != null && this . size <= e ? n = this . size : n = null , qn ( async ( ) => ( await t . iterator ( ) ) . take ( e ) , 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 ( ) } } ; Lu . MAX _BUFFER _SIZE = 1e4 ; function qn ( e , t = null ) { return new class extends Lu { constructor ( ) { super ( ... arguments ) , this . size = t } async iterator ( ) { return e ( ) } } } function GH ( e ) { return qn ( async ( ) => XN ( e ) , e . length ) } function HH ( e ) { if ( ! vl ( e ) ) throw new Error ( "The argument to zip() must be an object or array." ) ; let t ; if ( Array . isArray ( e ) ) for ( let n = 0 ; n < e . length ; n ++ ) t = t == null ? e [ n ] . size : Math . min ( t , e [ n ] . size ) ; else if ( e instanceof Object ) for ( let n in e ) t = t == null ? e [ n ] . size : Math . min ( t , e [ n ] . size ) ; return qn ( async ( ) => { let n = await qN ( e , a => { if ( a instanceof Lu ) return { value : a . iterator ( ) , recurse : ! 1 } ; if ( vl ( a ) ) return { value : null , recurse : ! 0 } ; throw new Error ( "Leaves of the structure passed to zip() must be Datasets, not primitives." ) } ) ; return AH ( n , Jr . SHORTEST ) } , t ) } function jH ( e ) { if ( e === null ) return null ; let t = e [ 0 ] ; return TH ( t ) ? { value : qH ( e ) , recurse : ! 1 } : { value : null , recurse : ! 0 } } function qH ( e ) { if ( e . length === 0 ) throw new Error ( "Can't make a batch of zero elements." ) ; return e [ 0 ] instanceof Fe ? Mt ( e ) : Qn ( e ) } var JN = class extends Lu { constructor ( e ) { super ( ) , this . input = e } async iterator ( ) { return ( await this . input . iterator ( ) ) . decodeUTF8 ( ) . split ( `
` ).map(e=>(e.endsWith(" \r ")&&(e=e.slice(0,-1)),e))}},ph='"', $ p=Symbol("out"),wk=Symbol("field"),ch=Symbol("quote"),xb=Symbol("quoteafterquote"),kk=Symbol("quoteinquote"),ZN=class extends Lu{constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new JN(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(w.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&w.assert(e.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 ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((a,r)=>(a[r]=a[r]+1||1,a),{}),n=Object.keys(t).filter(a=>t[a]>1);if(w.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let a of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(a)===-1)throw new Error('The key "'+a+'" 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 t=e.value;return this.parseRow(t,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},a={};for(let r=0;r<this.fullColumnNames.length;r++){let s=this.fullColumnNames[r],i=this.columnConfigs?this.columnConfigs[s]:null;if(!(this.configuredColumnsOnly&&!i)){let o=t[r],l=null;if(o==="")if(i&&i.default!==void 0)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error( ` Required column $ { s } is empty in this line : $ { e } ` );l=void 0}else{let u=Number(o);if(isNaN(u))i&&i.dtype==="bool"?l=this.getBoolean(o):l=o;else if(!i||!i.dtype)l=u;else switch(i.dtype){case"float32":l=u;break;case"int32":l=Math.floor(u);break;case"bool":l=this.getBoolean(o);break;default:l=u}}i&&i.isLabel?a[s]=l:n[s]=l}}return Object.keys(a).length===0?n:{xs:n,ys:a}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],a=0,r=e.length,s= $ p;for(let i=0;i<r;i++)switch(s){case $ p:switch(e.charAt(i)){case ph:a=i+1,s=ch;break;case this.delimiter:if(a=i+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),s= $ p;break;default:s=wk,a=i;break}break;case wk:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i)),s= $ p,a=i+1;break;default:}break;case ch:switch(e.charAt(i)){case ph:s=xb;break;default:}break;case xb:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i-1)),s= $ p,a=i+1;break;case ph:s=ch;break;default:s=kk;break}break;case kk:switch(e.charAt(i)){case ph:s=ch;break;default:}break;default:}if(s===xb?n.push(e.substring(a,r-1)):n.push(e.substring(a)),t&&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}},eT=class extends rn{constructor(e){super(),this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error( ` Invalid fftSi
2022-03-07 19:17:31 +01:00
=== === === === === === === === === =
2022-05-18 14:36:05 +02:00
Hi , looks like you are running TensorFlow . js in Node . js . To speed things up dramatically , install our node backend , visit https : //github.com/tensorflow/tfjs-node for more details.
2022-05-24 13:16:42 +02:00
=== === === === === === === === === = ` ));let a={id:this.nextDataId()};return this.data.set(a,{values:e,dtype:n,refCount:1}),a}makeTensorInfo(e,t,n){let a;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let r=n.map(s=>w.encodeString(s));a=this.write(r,e,t)}else a=this.write(n,e,t);return{dataId:a,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,a,r){this.data.set(e,{values:t,dtype:a,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let a=this.readSync(n.real.dataId),r=this.readSync(n.imag.dataId);return C.mergeRealAndImagArrays(a,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let n=t.map(a=>w.decodeString(a));return Ve(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ve(e.shape,e.dtype,t)}makeOutput(e,t,n){return ar().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){xe([e],"where");let t=this.readSync(e.dataId);return oj(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};c0.nextDataId=0;var lT={};Me(lT,{addImpl:()=>pT,bincountImpl:()=>h0,bincountReduceImpl:()=>cT,ceilImpl:()=>dT,concatImpl:()=>m0,equalImpl:()=>hT,expImpl:()=>fT,expm1Impl:()=>yT,floorImpl:()=>bT,gatherNdImpl:()=>xT,gatherV2Impl:()=>vT,greaterEqualImpl:()=>kT,greaterImpl:()=>wT,lessEqualImpl:()=>ST,lessImpl:()=>IT,linSpaceImpl:()=>NT,logImpl:()=>TT,maxImpl:()=>_T,maximumImpl:()=>CT,minimumImpl:()=>ET,multiplyImpl:()=>f0,negImpl:()=>FT,notEqualImpl:()=>AT,prodImpl:()=> $ T,rangeImpl:()=>y0,rsqrtImpl:()=>DT,scatterImpl:()=>al,sigmoidImpl:()=>Xj,simpleAbsImpl:()=>uT,sliceImpl:()=>Qh,sparseFillEmptyRowsImpl:()=>MT,sparseReshapeImpl:()=>PT,sparseSegmentReductionImpl:()=>b0,sqrtImpl:()=>Jj,squaredDifferenceImpl:()=>OT,stridedSliceImpl:()=>LT,stringNGramsImpl:()=>zT,stringSplitImpl:()=>BT,stringToHashBucketFastImpl:()=>WT,subImpl:()=>VT,tileImpl:()=>UT,topKImpl:()=>HT,transposeImpl:()=>g0,uniqueImpl:()=>jT});function uT(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var lj=e=>{let{x:t}=e.inputs,n=e.backend;xe(t,"abs");let a=new Float32Array(w.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return a=uT(r),n.makeOutput(a,t.shape,t.dtype)},uj={kernelName:Tl,backendName:"cpu",kernelFunc:lj};function Ut(e){return(t,n,a,r,s)=>{let i=C.assertAndGetBroadcastShape(t,n),o=i.length,l=w.computeStrides(i),u=w.sizeFromShape(i),p=w.getTypedArrayFromDType(s,u),d=t.length,c=n.length,h=w.computeStrides(t),m=w.computeStrides(n),f=C.getBroadcastDims(t,i),g=C.getBroadcastDims(n,i);if(f.length+g.length===0)for(let y=0;y<p.length;++y)p[y]=e(a[y%a.length],r[y%r.length]);else for(let y=0;y<p.length;++y){let b=w.indexToLoc(y,o,l),x=b.slice(-d);f.forEach(_=>x[_]=0);let v=w.locToIndex(x,d,h),k=b.slice(-c);g.forEach(_=>k[_]=0);let T=w.locToIndex(k,c,m);p[y]=e(a[v],r[T])}return[p,i]}}function Xn(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,o=n.makeTensorInfo(a.shape,"complex64"),l=n.data.get(o.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(a.shape,"float32",s),imag:n.makeTensorInfo(r.shape,"float32",i)},o}var pj={kernelName:cm,backendName:"cpu",kernelFunc:Xn};function Yh(e,t,n="float32"){if(n==="comple
2022-03-07 19:17:31 +01:00
$ { s . shape } ` );if(a.shape.length!==2)throw new Error( ` Indices must be a matrix , saw :
$ { a . shape } ` );if(r.shape.length!==1)throw new Error( ` Values must be a vector , saw :
$ { r . shape } ` );if(i.shape.length!==0)throw new Error( ` Default value must be a scalar , saw :
2022-05-24 13:16:42 +02:00
$ { i . shape } ` );let o=n.data.get(a.dataId).values,l=n.data.get(r.dataId).values,u=n.data.get(s.dataId).values,p=n.data.get(i.dataId).values[0],[d,c,h,m,f]=MT(o,a.shape,a.dtype,l,r.dtype,u,p);return[n.makeTensorInfo(c,a.dtype,d),n.makeTensorInfo([c[0]],r.dtype,h),n.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),n.makeTensorInfo([f.length],a.dtype,new Int32Array(f))]}var TX={kernelName:Ic,backendName:"cpu",kernelFunc:NX};function _X(e){let{inputs:t,backend:n}=e,{inputIndices:a,inputShape:r,newShape:s}=t;if(a.shape.length!==2)throw new Error( ` Input indices should be a matrix but received shape
2022-03-07 19:17:31 +01:00
$ { a . shape } ` );if(r.shape.length!==1)throw new Error( ` Input shape should be a vector but received shape
2022-05-24 13:16:42 +02:00
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Target shape should be a vector but received shape $ { s . shape } ` );let i=Array.from(n.data.get(r.dataId).values),o=n.data.get(a.dataId).values,l=Array.from(n.data.get(s.dataId).values),[u,p,d]=PT(o,a.shape,a.dtype,i,l);return[n.makeTensorInfo(p,a.dtype,u),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}var CX={kernelName:wu,backendName:"cpu",kernelFunc:_X};function EX(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
2022-03-07 19:17:31 +01:00
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
2022-05-24 13:16:42 +02:00
$ { s . shape } ` );if(r.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,p]=b0(i,a.shape,a.dtype,o,l,!0);return n.makeTensorInfo(p,a.dtype,u)}var FX={kernelName:Sc,backendName:"cpu",kernelFunc:EX};function AX(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
2022-03-07 19:17:31 +01:00
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
2022-05-24 13:16:42 +02:00
$ { s . shape } ` );if(r.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,p]=b0(i,a.shape,a.dtype,o,l);return n.makeTensorInfo(p,a.dtype,u)}var $ X={kernelName:Nc,backendName:"cpu",kernelFunc:AX};function DX(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=C.calculateShapes(s,r,o),h=!1,m=n.bufferSync(r),f;switch(s.dtype){case"bool":{let g=n.bufferSync(s),y=Boolean(n.data.get(i.dataId).values[0]);f=al(m,g,o,c,p,u,l,d,y,h);break}case"float32":{let g=n.bufferSync(s),y=n.data.get(i.dataId).values[0];f=al(m,g,o,c,p,u,l,d,y,h);break}case"int32":{let g=n.bufferSync(s),y=n.data.get(i.dataId).values[0];f=al(m,g,o,c,p,u,l,d,y,h);break}case"string":{let g=n.bufferSync(s),y=w.decodeString(n.data.get(i.dataId).values[0]);f=al(m,g,o,c,p,u,l,d,y,h);break}default:throw new Error( ` Unsupported type $ { s . dtype } ` )}return n.makeTensorInfo(o,f.dtype,f.values)}var RX={kernelName:Rm,backendName:"cpu",kernelFunc:DX};function MX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,r.shape)[0],l=C.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),p=r.shape.slice();return l.map(d=>{let c=[...p];c[o]=d;let h=mi({inputs:{x:r},backend:n,attrs:{begin:u,size:c}});return u[o]+=d,h})}var PX={kernelName:vu,backendName:"cpu",kernelFunc:MX},OX={kernelName:Tc,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,a=t;xe(n,"square");let r=a.data.get(n.dataId).values,s=new Float32Array(r.length);for(let i=0;i<r.length;++i){let o=r[i];s[i]=o*o}return{dataId:a.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},LX=ot(gs,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),zX={kernelName:gs,backendName:"cpu",kernelFunc:LX};function BX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:d,shrinkAxisMask:c}=a;xe(r,"stridedSlice");let{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:v}=Kt.sliceInfo(r.shape,s,i,o,l,u,p,d,c),k;if(f)k=xt({inputs:{x:r},backend:n,attrs:{shape:m}});else if(g||y){w.assert(r.shape.length>=1,()=> ` Input must have rank at least 1 , got : $ { r . shape . length } ` );let T=Kt.computeOutShape(b,x,v),_=mi({inputs:{x:r},backend:n,attrs:{begin:b,size:T}});k=xt({inputs:{x:_},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(_)}else{let T=n.bufferSync(r),_=LT(h,T,v,b);k=n.makeTensorInfo(m,_.dtype,_.values)}return k}var WX={kernelName:ku,backendName:"cpu",kernelFunc:BX};function VX(e){let{inputs:t,backend:n,attrs:a}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=a,{data:p,dataSplits:d}=t,c=n.data.get(p.dataId).values,h=n.data.get(d.dataId).values,[m,f]=zT(c,h,r,s,i,o,l,u);return[n.makeTensorInfo([m.length],"string",m),n.makeTensorInfo(d.shape,"int32",f)]}var UX={kernelName:Mm,backendName:"cpu",kernelFunc:VX};function GX(e){let{inputs:t,backend:n,attrs:a}=e,{skipEmpty:r}=a,{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 o=n.data.get(s.dataId).values,l=n.data.get(i.dataId).values[0],[u,p,d]=BT(o,l,r),c=p.length;return[n.makeTensorInfo([c,2],"int32",u),n.makeTensorInfo([c],"string",p),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var HX={kernelName:Pm,backendName:"cpu",kernelFunc:GX};function jX(e){let{inputs:t,backend:n,attrs:a}=e,{numBuckets:r}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let i=n.data.get(s.dataId).values,o=WT(i,r);return n.makeTensorInfo(s.shape,"int32",o)}var qX={kernelName:Om,backendName:"cpu",kernelFunc:jX},KX=ot(fo,e=>Math.tan(e)),XX=
2022-05-18 14:36:05 +02:00
` ),s=r.length.toString().length+2,i=r.map((d,c)=>w.rightPad((c+1).toString(),s)+d),o=0;for(let d=0;d<i.length;d++)o=Math.max(i[d].length,o);let l=i.slice(0,a-1),u=i.slice(a-1,a),p=i.slice(a);console.log(l.join( `
2022-03-07 19:17:31 +01:00
` )),console.log(t.split( `
2022-05-18 14:36:05 +02:00
` )[0]),console.log( ` % c $ { w . rightPad ( u [ 0 ] , o ) } ` ,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join( `
2022-05-24 13:16:42 +02:00
` ))}function f_(e){return Dr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function g_(e,t){if(ge(e,()=>e.linkProgram(t)),!X().get("ENGINE_COMPILE_ONLY")&&e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function xh(e,t){if(ge(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function y_(e,t){let n=Dr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return ge(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),ge(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function b_(e,t){let n=Dr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return ge(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),ge(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function N7(){return X().getNumber("WEBGL_VERSION")===2?1:4}function x_(e){return Dr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function v_(e,t){let n=X().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let a= ` [ $ { e } x$ { t } ] ` ;throw new Error("Requested texture size "+a+" is invalid.")}if(e>n||t>n){let a= ` [ $ { e } x$ { t } ] ` ,r= ` [ $ { n } x$ { n } ] ` ;throw new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU "+r+".")}}function w_(e){return Dr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function ux(e,t,n,a,r,s,i){let o=e.getAttribLocation(t,n);return o===-1?!1:(ge(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),ge(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),ge(e,()=>e.enableVertexAttribArray(o)),!0)}function k_(e,t,n){__(e,n),ge(e,()=>e.activeTexture(e.TEXTURE0+n)),ge(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function T7(e,t){__(e,t),ge(e,()=>e.activeTexture(e.TEXTURE0+t)),ge(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function I_(e,t,n){return Dr(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function S_(e,t,n){return e.getUniformLocation(t,n)}function N_(e,t,n,a){ge(e,()=>k_(e,t,a)),ge(e,()=>e.uniform1i(n,a))}function _7(e){ge(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),ge(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),ge(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function vh(e,t,n){ge(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),ge(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function px(e,t){ge(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),ge(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Wp(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+T_(e,t))}function T_(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return ` unknown error $ { t } ` }}function Dr(e,t,n){let a=ge(e,()=>t());if(a==null)throw new Error(n);return a}function __(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,a=t+e.TEXTURE0;if(a<e.TEXTURE0||a>n){let r= ` [ gl . TEXTURE0 , gl . TEXTURE$ { n } ] ` ;throw new Error( ` textureUnit must be in $ { r } . ` )}}function fi(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function gi(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function wh(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[fi(e),...gi(e)]),t}function C_(e,t=!1){let n=X().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((r,s)=>s>=e.length-2?w.nearestLargerEven(e[s]):e[s]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let a=w.sizeFromShape(e);if(e.length<=1&&a<=n)return[1,a];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]
2022-03-07 19:17:31 +01:00
bool isnan _custom ( float val ) {
uint floatToUint = floatBitsToUint ( val ) ;
return ( floatToUint & 0x7fffffff u ) > 0x7f800000 u ;
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 )
` ,l="",u= `
# 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
` ):(e="",t="attribute",n="varying",a="varying",r="texture2D",s="gl_FragColor",i="",o= `
# 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
` ,l= `
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
` ,u= `
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-05-24 13:16:42 +02:00
` ),{version:e,attribute:t,varyingVs:n,varyingFs:a,texture2D:r,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function Io(e,t,n="index"){let a=w.computeStrides(t);return a.map((r,s)=>{let i= ` int $ { e [ s ] } = $ { n } / $ { r } ` ,o=s===a.length-1? ` int $ { e [ s + 1 ] } = $ { n } - $ { e [ s ] } * $ { r } ` : ` index -= $ { e [ s ] } * $ { r } ` ;return ` $ { i } ; $ { o } ; ` }).join("")}function Uf(e,t,n="index"){let a=w.computeStrides(t);return a.map((r,s)=>{let i= ` int $ { e [ s ] } = $ { n } / outShapeStrides [ $ { s } ] ` ,o=s===a.length-1? ` int $ { e [ s + 1 ] } = $ { n } - $ { e [ s ] } * outShapeStrides [ $ { s } ] ` : ` index -= $ { e [ s ] } * outShapeStrides [ $ { s } ] ` ;return ` $ { i } ; $ { o } ; ` }).join("")}function A7(e,t){let n=e.length,a=e.map(s=> ` $ { t } [ $ { s } ] ` ),r=new Array(n-1);r[n-2]=a[n-1];for(let s=n-3;s>=0;--s)r[s]= ` ( $ { r [ s + 1 ] } * $ { a [ s + 1 ] } ) ` ;return r}function $ 7(e,t,n="index"){let a=e.map((s,i)=>i),r=A7(a,t);return r.map((s,i)=>{let o= ` int $ { e [ i ] } = $ { n } / $ { r [ i ] } ` ,l=i===r.length-1? ` int $ { e [ i + 1 ] } = $ { n } - $ { e [ i ] } * $ { r [ i ] } ` : ` index -= $ { e [ i ] } * $ { r [ i ] } ` ;return ` $ { o } ; $ { l } ; ` }).join("")}function N0(e){let t=w.computeStrides(e).map(n=>n.toString());return `
2022-03-07 19:17:31 +01:00
int getFlatIndex ( ivec3 coords ) {
return coords . x * $ { t [ 0 ] } + coords . y * $ { t [ 1 ] } + coords . z ;
}
2022-05-24 13:16:42 +02:00
` }function T0(){return `
2022-03-07 19:17:31 +01:00
int getFlatIndex ( ivec3 coords ) {
return coords . x * outShapeStrides [ 0 ] + coords . y * outShapeStrides [ 1 ] + coords . z ;
}
2022-05-24 13:16:42 +02:00
` }var M_= `
2022-03-07 19:17:31 +01:00
const float FLOAT _MAX = 1.70141184 e38 ;
const float FLOAT _MIN = 1.17549435 e - 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 ;
}
2022-05-24 13:16:42 +02:00
` ,{getBroadcastDims:P_}=C;function D7(e,t,n){let a=[];if(e.forEach(c=>{let h=w.sizeFromShape(c.shapeInfo.logicalShape);if(c.shapeInfo.isUniform?a.push( ` uniform float $ { c . name } $ { h > 1 ? ` [ ${ h } ] ` : "" } ; ` ):(a.push( ` uniform sampler2D $ { c . name } ; ` ),a.push( ` uniform int offset$ { c . name } ; ` )),n.enableShapeUniforms){let{uniformShape:m}=_0(n.packedInputs,c.shapeInfo.logicalShape,c.shapeInfo.texShape);switch(m.length){case 1:a.push( ` uniform int $ { c . name } Shape ; ` );break;case 2:a.push( ` uniform ivec2 $ { c . name } Shape ; ` );break;case 3:a.push( ` uniform ivec3 $ { c . name } Shape ; ` );break;case 4:a.push( ` uniform ivec4 $ { c . name } Shape ; ` );break;default:break}a.push( ` uniform ivec2 $ { c . name } TexShape ; ` )}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:a.push("uniform int outShape;");break;case 2:a.push("uniform ivec2 outShape;"),a.push("uniform int outShapeStrides;");break;case 3:a.push("uniform ivec3 outShape;"),a.push("uniform ivec2 outShapeStrides;");break;case 4:a.push("uniform ivec4 outShape;"),a.push("uniform ivec3 outShapeStrides;");break;default:break}a.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(c=>{a.push( ` uniform $ { c . type } $ { c . name } $ { c . arrayIndex ? ` [ ${ c . arrayIndex } ] ` : "" } ; ` )});let r=a.join( `
` ),s=e.map(c=>R7(c,t,n.packedInputs,n.enableShapeUniforms)).join( `
` ),i=t.texShape,o=Cn(),l=O7(o),u,p,d=B7(o);return t.isPacked?(u=M7(t.logicalShape,i,n.enableShapeUniforms),p=z7(o)):(u=P7(t.logicalShape,i,n.enableShapeUniforms),p=L7(o)),n.packedInputs&&(d+=G7),[d,l,p,r,u,s,n.userCode].join( `
` )}function Vu(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return nY(e,t);case 1:return rY(e,t);case 2:return iY(e,t);case 3:return lY(e,t);case 4:return pY(e,t);case 5:return cY(e);case 6:return dY(e);default:throw new Error( ` $ { n . length } - D input sampling is not yet supported ` )}}function O_(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return tY(e);case 1:return aY(e,t);case 2:return sY(e,t);case 3:return oY(e,t);default:return uY(e,t)}}function R7(e,t,n=!1,a){let r="";n?r+=O_(e,a):r+=Vu(e,a);let s=e.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(n?r+=hY(e,t):r+=mY(e,t)),r}function M7(e,t,n){switch(e.length){case 0:return L_();case 1:return H7(e,t,n);case 2:return Z7(e,t,n);case 3:return q7(e,t,n);default:return X7(e,t,n)}}function P7(e,t,n){switch(e.length){case 0:return L_();case 1:return j7(e,t,n);case 2:return eY(e,t,n);case 3:return K7(e,t,n);case 4:return Y7(e,t,n);case 5:return Q7(e,t);case 6:return J7(e,t);default:throw new Error( ` $ { e . length } - D output sampling is not yet supported ` )}}function O7(e){return `
2022-03-07 19:17:31 +01:00
float sampleTexture ( sampler2D textureSampler , vec2 uv ) {
return $ { e . texture2D } ( textureSampler , uv ) . r ;
}
2022-05-24 13:16:42 +02:00
` }function L7(e){return `
2022-03-07 19:17:31 +01:00
void setOutput ( float val ) {
$ { e . output } = vec4 ( val , 0 , 0 , 0 ) ;
}
2022-05-24 13:16:42 +02:00
` }function z7(e){return `
2022-03-07 19:17:31 +01:00
void setOutput ( vec4 val ) {
$ { e . output } = val ;
}
2022-05-24 13:16:42 +02:00
` }function B7(e){return ` $ { e . version }
2022-03-07 19:17:31 +01:00
precision highp float ;
precision highp int ;
precision highp sampler2D ;
$ { e . varyingFs } vec2 resultUV ;
$ { e . 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 ;
$ { e . defineSpecialNaN }
$ { e . defineSpecialInf }
$ { e . 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 ;
}
//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 ) ;
}
2022-05-24 13:16:42 +02:00
$ { W7 }
$ { V7 }
$ { U7 }
` }var W7= `
2022-03-07 19:17:31 +01:00
vec2 uvFromFlat ( int texNumR , int texNumC , int index ) {
int texR = index / texNumC ;
int texC = index - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
vec2 packedUVfrom1D ( int texNumR , int texNumC , int index ) {
int texelIndex = index / 2 ;
int texR = texelIndex / texNumC ;
int texC = texelIndex - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
2022-05-24 13:16:42 +02:00
` ,V7= `
2022-03-07 19:17:31 +01:00
vec2 packedUVfrom2D ( int texelsInLogicalRow , int texNumR ,
int texNumC , int row , int col ) {
int texelIndex = ( row / 2 ) * texelsInLogicalRow + ( col / 2 ) ;
int texR = texelIndex / texNumC ;
int texC = texelIndex - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
2022-05-24 13:16:42 +02:00
` ,U7= `
2022-03-07 19:17:31 +01:00
vec2 packedUVfrom3D ( int texNumR , int texNumC ,
int texelsInBatch , int texelsInLogicalRow , int b ,
int row , int col ) {
int index = b * texelsInBatch + ( row / 2 ) * texelsInLogicalRow + ( col / 2 ) ;
int texR = index / texNumC ;
int texC = index - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
2022-05-24 13:16:42 +02:00
` ,G7= `
2022-03-07 19:17:31 +01:00
float getChannel ( vec4 frag , vec2 innerDims ) {
vec2 modCoord = mod ( innerDims , 2. ) ;
return modCoord . x == 0. ?
( modCoord . y == 0. ? frag . r : frag . g ) :
( modCoord . y == 0. ? frag . b : frag . a ) ;
2021-12-01 21:37:52 +01: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-05-24 13:16:42 +02:00
` ;function L_(){return `
2022-03-07 19:17:31 +01:00
int getOutputCoords ( ) {
return 0 ;
}
2022-05-24 13:16:42 +02:00
` }function H7(e,t,n){let a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return a[0]===1?n? `
2022-03-07 19:17:31 +01:00
int getOutputCoords ( ) {
return 2 * int ( resultUV . x * ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
` : `
int getOutputCoords ( ) {
return 2 * int ( resultUV . x * $ { a [ 1 ] } . 0 ) ;
2020-12-15 14:15:43 +01:00
}
2022-03-07 19:17:31 +01:00
` :a[1]===1?n? `
int getOutputCoords ( ) {
return 2 * int ( resultUV . y * ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
` : `
int getOutputCoords ( ) {
return 2 * int ( resultUV . y * $ { a [ 0 ] } . 0 ) ;
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
` :n? `
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 ( $ { a [ 0 ] } , $ { a [ 1 ] } ) ) ;
return 2 * ( resTexRC . x * $ { a [ 1 ] } + resTexRC . y ) ;
}
2022-05-24 13:16:42 +02:00
` }function j7(e,t,n){return t[0]===1?n? `
2022-03-07 19:17:31 +01:00
int getOutputCoords ( ) {
return int ( resultUV . x * float ( outTexShape [ 1 ] ) ) ;
2021-04-01 19:39:54 +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?n? `
int getOutputCoords ( ) {
return int ( resultUV . y * float ( outTexShape [ 0 ] ) ) ;
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
` : `
int getOutputCoords ( ) {
return int ( resultUV . y * $ { t [ 0 ] } . 0 ) ;
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
` :n? `
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 ;
}
2022-05-24 13:16:42 +02:00
` }function q7(e,t,n){if(n)return `
2022-03-07 19:17:31 +01:00
ivec3 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
int texelsInLogicalRow = int ( ceil ( float ( outShape [ 2 ] ) / 2.0 ) ) ;
int texelsInBatch = texelsInLogicalRow * int ( ceil ( float ( outShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
int index = resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ;
int b = index / texelsInBatch ;
index -= b * texelsInBatch ;
int r = 2 * ( index / texelsInLogicalRow ) ;
int c = imod ( index , texelsInLogicalRow ) * 2 ;
return ivec3 ( b , r , c ) ;
}
` ;let a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),s=r*Math.ceil(e[1]/2);return `
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { a [ 0 ] } , $ { a [ 1 ] } ) ) ;
int index = resTexRC . x * $ { a [ 1 ] } + resTexRC . y ;
int b = index / $ { s } ;
index -= b * $ { s } ;
int r = 2 * ( index / $ { r } ) ;
int c = imod ( index , $ { r } ) * 2 ;
return ivec3 ( b , r , c ) ;
}
2022-05-24 13:16:42 +02:00
` }function K7(e,t,n){if(n)return `
2022-03-07 19:17:31 +01:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
2022-05-24 13:16:42 +02:00
$ { Uf ( [ "r" , "c" , "d" ] , e ) }
2022-03-07 19:17:31 +01:00
return ivec3 ( r , c , d ) ;
2021-05-18 14:11:17 +02:00
}
2022-05-24 13:16:42 +02:00
` ;let a=Io(["r","c","d"],e);return `
2022-03-07 19:17:31 +01:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { a }
return ivec3 ( r , c , d ) ;
}
2022-05-24 13:16:42 +02:00
` }function X7(e,t,n){if(n)return `
2022-03-07 19:17:31 +01:00
ivec4 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
int index = resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ;
int texelsInLogicalRow = int ( ceil ( float ( outShape [ 3 ] ) / 2.0 ) ) ;
int texelsInBatch = texelsInLogicalRow * int ( ceil ( float ( outShape [ 2 ] ) / 2.0 ) ) ;
int texelsInBatchN = texelsInBatch * outShape [ 1 ] ;
int b2 = index / texelsInBatchN ;
index -= b2 * texelsInBatchN ;
int b = index / texelsInBatch ;
index -= b * texelsInBatch ;
int r = 2 * ( index / texelsInLogicalRow ) ;
int c = imod ( index , texelsInLogicalRow ) * 2 ;
return ivec4 ( b2 , b , r , c ) ;
}
` ;let a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),s=r*Math.ceil(e[e.length-2]/2),i=s,o="",l="b, r, c";for(let u=2;u<e.length-1;u++)i*=e[e.length-u-1],o= `
int b$ { u } = index / $ { i } ;
index -= b$ { u } * $ { i } ;
` +o,l= ` b$ { u } , ` +l;return `
ivec$ { e . length } getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { a [ 0 ] } , $ { a [ 1 ] } ) ) ;
int index = resTexRC . x * $ { a [ 1 ] } + resTexRC . y ;
$ { o }
int b = index / $ { s } ;
index -= b * $ { s } ;
int r = 2 * ( index / $ { r } ) ;
int c = imod ( index , $ { r } ) * 2 ;
return ivec$ { e . length } ( $ { l } ) ;
}
2022-05-24 13:16:42 +02:00
` }function Y7(e,t,n){if(n)return `
2022-03-07 19:17:31 +01:00
ivec4 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
2022-05-24 13:16:42 +02:00
$ { Uf ( [ "r" , "c" , "d" , "d2" ] , e ) }
2022-03-07 19:17:31 +01:00
return ivec4 ( r , c , d , d2 ) ;
}
2022-05-24 13:16:42 +02:00
` ;let a=Io(["r","c","d","d2"],e);return `
2022-03-07 19:17:31 +01:00
ivec4 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { a }
return ivec4 ( r , c , d , d2 ) ;
}
2022-05-24 13:16:42 +02:00
` }function Q7(e,t){let n=Io(["r","c","d","d2","d3"],e);return `
2022-03-07 19:17:31 +01:00
ivec5 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( $ { t [ 0 ] } ,
$ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { n }
ivec5 outShape = ivec5 ( r , c , d , d2 , d3 ) ;
return outShape ;
}
2022-05-24 13:16:42 +02:00
` }function J7(e,t){let n=Io(["r","c","d","d2","d3","d4"],e);return `
2022-03-07 19:17:31 +01:00
ivec6 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { n }
ivec6 result = ivec6 ( r , c , d , d2 , d3 , d4 ) ;
return result ;
}
2022-05-24 13:16:42 +02:00
` }function Z7(e,t,n){let a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.arraysEqual(e,t))return n? `
2022-03-07 19:17:31 +01:00
ivec2 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
return 2 * ivec2 ( resultUV . yx * vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
` : `
ivec2 getOutputCoords ( ) {
return 2 * ivec2 ( resultUV . yx * vec2 ( $ { a [ 0 ] } , $ { a [ 1 ] } ) ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
` ;let r=Math.ceil(e[1]/2);return n? `
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 ( $ { a [ 0 ] } , $ { a [ 1 ] } ) ) ;
int index = resTexRC . x * $ { a [ 1 ] } + resTexRC . y ;
int r = 2 * ( index / $ { r } ) ;
int c = imod ( index , $ { r } ) * 2 ;
return ivec2 ( r , c ) ;
}
2022-05-24 13:16:42 +02:00
` }function eY(e,t,n){return w.arraysEqual(e,t)?n? `
2022-03-07 19:17:31 +01:00
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
` :e[1]===1?n? `
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
` :e[0]===1?n? `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
return ivec2 ( 0 , index ) ;
2020-10-12 20:28:19 +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 ) ;
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
` :n? `
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 / $ { e [ 1 ] } ;
int c = index - r * $ { e [ 1 ] } ;
return ivec2 ( r , c ) ;
}
2022-05-24 13:16:42 +02:00
` }function So(e){return ` offset$ { e } ` }function tY(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),a=Cn();return `
2022-03-07 19:17:31 +01:00
vec4 $ { n } ( ) {
return $ { a . texture2D } ( $ { t } , halfCR ) ;
}
2022-05-24 13:16:42 +02:00
` }function nY(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return ` float $ { a } ( ) { return $ { n } ; } ` ;let[r,s]=e.shapeInfo.texShape;if(r===1&&s===1)return `
2022-03-07 19:17:31 +01:00
float $ { a } ( ) {
return sampleTexture ( $ { n } , halfCR ) ;
2020-10-12 20:28:19 +02:00
}
2022-05-24 13:16:42 +02:00
` ;let i=So(n);if(t)return `
2022-03-07 19:17:31 +01:00
float $ { a } ( ) {
vec2 uv = uvFromFlat ( $ { n } TexShape [ 0 ] , $ { n } TexShape [ 1 ] , $ { i } ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` ;let[o,l]=e.shapeInfo.texShape;return `
float $ { a } ( ) {
vec2 uv = uvFromFlat ( $ { o } , $ { l } , $ { i } ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function aY(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,s=Cn();if(t)return `
2022-03-07 19:17:31 +01:00
vec4 $ { a } ( int index ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { n } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { n } TexShape [ 1 ] ) / 2.0 ) ) ;
vec2 uv = packedUVfrom1D (
packedTexShape [ 0 ] , packedTexShape [ 1 ] , index ) ;
return $ { s . texture2D } ( $ { n } , uv ) ;
}
` ;let i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];return `
vec4 $ { a } ( int index ) {
vec2 uv = packedUVfrom1D (
$ { i [ 0 ] } , $ { i [ 1 ] } , index ) ;
return $ { s . texture2D } ( $ { n } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function rY(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return `
2022-03-07 19:17:31 +01:00
float $ { a } ( int index ) {
2022-05-24 13:16:42 +02:00
$ { Uu ( e ) }
2022-03-07 19:17:31 +01:00
}
` ;let r=e.shapeInfo.texShape,s=r[0],i=r[1];if(i===1&&s===1)return `
float $ { a } ( int index ) {
return sampleTexture ( $ { n } , halfCR ) ;
}
2022-05-24 13:16:42 +02:00
` ;let o=So(n);return i===1?t? `
2022-03-07 19:17:31 +01:00
float $ { a } ( int index ) {
vec2 uv = vec2 ( 0.5 , ( float ( index + $ { o } ) + 0.5 ) / float ( $ { n } TexShape [ 0 ] ) ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` : `
float $ { a } ( int index ) {
vec2 uv = vec2 ( 0.5 , ( float ( index + $ { o } ) + 0.5 ) / $ { s } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` :s===1?t? `
float $ { a } ( int index ) {
vec2 uv = vec2 ( ( float ( index + $ { o } ) + 0.5 ) / float ( $ { n } TexShape [ 1 ] ) , 0.5 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` : `
float $ { a } ( int index ) {
vec2 uv = vec2 ( ( float ( index + $ { o } ) + 0.5 ) / $ { i } . 0 , 0.5 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` :t? `
float $ { a } ( int index ) {
vec2 uv = uvFromFlat ( $ { n } TexShape [ 0 ] , $ { n } TexShape [ 1 ] , index + $ { o } ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` : `
float $ { a } ( int index ) {
vec2 uv = uvFromFlat ( $ { s } , $ { i } , index + $ { o } ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function sY(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=s[0],o=s[1],l=Cn();if(s!=null&&w.arraysEqual(n,s))return t? `
2022-03-07 19:17:31 +01:00
vec4 $ { r } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { a } TexShape [ 1 ] , $ { a } TexShape [ 0 ] ) ;
return $ { l . texture2D } ( $ { a } , uv ) ;
}
` : `
vec4 $ { r } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { o } . 0 , $ { i } . 0 ) ;
return $ { l . texture2D } ( $ { a } , uv ) ;
}
` ;if(t)return `
vec4 $ { r } ( int row , int col ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { a } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { a } TexShape [ 1 ] ) / 2.0 ) ) ;
int valuesPerRow = int ( ceil ( float ( $ { a } Shape [ 1 ] ) / 2.0 ) ) ;
vec2 uv = packedUVfrom2D ( valuesPerRow , packedTexShape [ 0 ] , packedTexShape [ 1 ] , row , col ) ;
return $ { l . texture2D } ( $ { a } , uv ) ;
}
` ;let u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],p=Math.ceil(n[1]/2);return `
vec4 $ { r } ( int row , int col ) {
vec2 uv = packedUVfrom2D ( $ { p } , $ { u [ 0 ] } , $ { u [ 1 ] } , row , col ) ;
return $ { l . texture2D } ( $ { a } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function iY(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape;if(s!=null&&w.arraysEqual(n,s)){if(t)return `
2022-03-07 19:17:31 +01:00
float $ { r } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { a } TexShape [ 1 ] , $ { a } TexShape [ 0 ] ) ;
return sampleTexture ( $ { a } , uv ) ;
}
` ;let c=s[0],h=s[1];return `
float $ { r } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { h } . 0 , $ { c } . 0 ) ;
return sampleTexture ( $ { a } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }let{newShape:i,keptDims:o}=w.squeezeShape(n),l=i;if(l.length<n.length){let c=Gu(e,l),h=["row","col"];return `
$ { Vu ( c , t ) }
2022-03-07 19:17:31 +01:00
float $ { r } ( int row , int col ) {
2022-05-24 13:16:42 +02:00
return $ { r } ( $ { Hu ( h , o ) } ) ;
2022-03-07 19:17:31 +01:00
}
` }if(e.shapeInfo.isUniform)return `
float $ { r } ( int row , int col ) {
int index = round ( dot ( vec2 ( row , col ) , vec2 ( $ { n [ 1 ] } , 1 ) ) ) ;
2022-05-24 13:16:42 +02:00
$ { Uu ( e ) }
2022-03-07 19:17:31 +01:00
}
2022-05-24 13:16:42 +02:00
` ;let u=s[0],p=s[1],d=So(a);return p===1?t? `
2022-03-07 19:17:31 +01:00
float $ { r } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { d } ) , vec3 ( $ { a } Shape [ 1 ] , 1 , 1 ) ) ;
vec2 uv = vec2 ( 0.5 , ( index + 0.5 ) / float ( $ { a } TexShape [ 0 ] ) ) ;
return sampleTexture ( $ { a } , uv ) ;
}
` : `
float $ { r } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { d } ) , vec3 ( $ { n [ 1 ] } , 1 , 1 ) ) ;
vec2 uv = vec2 ( 0.5 , ( index + 0.5 ) / $ { u } . 0 ) ;
return sampleTexture ( $ { a } , uv ) ;
}
` :u===1?t? `
float $ { r } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { d } ) , vec3 ( $ { a } Shape [ 1 ] , 1 , 1 ) ) ;
vec2 uv = vec2 ( ( index + 0.5 ) / float ( $ { a } TexShape [ 1 ] ) , 0.5 ) ;
return sampleTexture ( $ { a } , uv ) ;
}
` : `
float $ { r } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { d } ) , vec3 ( $ { n [ 1 ] } , 1 , 1 ) ) ;
vec2 uv = vec2 ( ( index + 0.5 ) / $ { p } . 0 , 0.5 ) ;
return sampleTexture ( $ { a } , uv ) ;
}
` :t? `
float $ { r } ( int row , int col ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { a } Shape [ 1 ] + col + $ { d } ;
vec2 uv = uvFromFlat ( $ { a } TexShape [ 0 ] , $ { a } TexShape [ 1 ] , index ) ;
return sampleTexture ( $ { a } , uv ) ;
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
` : `
float $ { r } ( int row , int col ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { n [ 1 ] } + col + $ { d } ;
vec2 uv = uvFromFlat ( $ { u } , $ { p } , index ) ;
return sampleTexture ( $ { a } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function oY(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(n[0]===1){let c=n.slice(1),h=[1,2],m=Gu(e,c),f=["b","row","col"];return `
$ { O _ ( m , t ) }
2022-03-07 19:17:31 +01:00
vec4 $ { r } ( int b , int row , int col ) {
2022-05-24 13:16:42 +02:00
return $ { r } ( $ { Hu ( f , h ) } ) ;
2022-03-07 19:17:31 +01:00
}
2022-05-24 13:16:42 +02:00
` }let o=Cn();if(t)return `
2022-03-07 19:17:31 +01:00
vec4 $ { r } ( int b , int row , int col ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { a } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { a } TexShape [ 1 ] ) / 2.0 ) ) ;
int valuesPerRow = int ( ceil ( float ( $ { a } Shape [ 2 ] ) / 2.0 ) ) ;
int texelsInBatch = valuesPerRow * int ( ceil ( float ( $ { a } Shape [ 1 ] ) / 2.0 ) ) ;
vec2 uv = packedUVfrom3D (
packedTexShape [ 0 ] , packedTexShape [ 1 ] , texelsInBatch , valuesPerRow , b , row , col ) ;
return $ { o . texture2D } ( $ { a } , uv ) ;
}
` ;let l=i[0],u=i[1],p=Math.ceil(n[2]/2),d=p*Math.ceil(n[1]/2);return `
vec4 $ { r } ( int b , int row , int col ) {
vec2 uv = packedUVfrom3D (
$ { l } , $ { u } , $ { d } , $ { p } , b , row , col ) ;
return $ { o . texture2D } ( $ { a } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function lY(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=n[1]*n[2],i=n[2],{newShape:o,keptDims:l}=w.squeezeShape(n),u=o;if(u.length<n.length){let f=Gu(e,u),g=["row","col","depth"];return `
$ { Vu ( f , t ) }
2022-03-07 19:17:31 +01:00
float $ { r } ( int row , int col , int depth ) {
2022-05-24 13:16:42 +02:00
return $ { r } ( $ { Hu ( g , l ) } ) ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
` }if(e.shapeInfo.isUniform)return `
float $ { r } ( int row , int col , int depth ) {
int index = round ( dot ( vec3 ( row , col , depth ) ,
vec3 ( $ { s } , $ { i } , 1 ) ) ) ;
2022-05-24 13:16:42 +02:00
$ { Uu ( e ) }
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
` ;let p=e.shapeInfo.texShape,d=p[0],c=p[1],h=e.shapeInfo.flatOffset;if(c===s&&h==null)return t? `
float $ { r } ( int row , int col , int depth ) {
int stride1 = $ { a } Shape [ 2 ] ;
float texR = float ( row ) ;
float texC = dot ( vec2 ( col , depth ) , vec2 ( stride1 , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { a } TexShape [ 1 ] , $ { a } TexShape [ 0 ] ) ;
return sampleTexture ( $ { a } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
` : `
float $ { r } ( 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 ( $ { c } . 0 , $ { d } . 0 ) ;
return sampleTexture ( $ { a } , uv ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
` ;if(c===i&&h==null)return t? `
float $ { r } ( int row , int col , int depth ) {
float texR = dot ( vec2 ( row , col ) , vec2 ( $ { a } Shape [ 1 ] , 1 ) ) ;
float texC = float ( depth ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { a } TexShape [ 1 ] , $ { a } TexShape [ 0 ] ) ;
return sampleTexture ( $ { a } , uv ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
` : `
float $ { r } ( int row , int col , int depth ) {
float texR = dot ( vec2 ( row , col ) , vec2 ( $ { n [ 1 ] } , 1 ) ) ;
float texC = float ( depth ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { c } . 0 , $ { d } . 0 ) ;
return sampleTexture ( $ { a } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` ;let m=So(a);return t? `
2022-03-07 19:17:31 +01:00
float $ { r } ( int row , int col , int depth ) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = $ { a } Shape [ 1 ] * $ { a } Shape [ 2 ] ;
int stride1 = $ { a } Shape [ 2 ] ;
int index = row * $ { s } + col * $ { i } + depth + $ { m } ;
vec2 uv = uvFromFlat ( $ { a } TexShape [ 0 ] , $ { a } TexShape [ 1 ] , index ) ;
return sampleTexture ( $ { a } , uv ) ;
}
` : `
float $ { r } ( int row , int col , int depth ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { s } + col * $ { i } + depth + $ { m } ;
vec2 uv = uvFromFlat ( $ { d } , $ { c } , index ) ;
return sampleTexture ( $ { a } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function uY(e,t){let n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=Cn();if(t)return `
2022-03-07 19:17:31 +01:00
vec4 $ { a } ( int b2 , int b , int row , int col ) {
int valuesPerRow = int ( ceil ( float ( $ { n } Shape [ 3 ] ) / 2.0 ) ) ;
int texelsInBatch = valuesPerRow * int ( ceil ( float ( $ { n } Shape [ 2 ] ) / 2.0 ) ) ;
int index = b * texelsInBatch + ( row / 2 ) * valuesPerRow + ( col / 2 ) ;
texelsInBatch *= $ { n } Shape [ 1 ] ;
index = b2 * texelsInBatch + index ;
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { n } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { n } 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 $ { r . texture2D } ( $ { n } , uv ) ;
}
` ;let s=e.shapeInfo.logicalShape,i=s.length,o=e.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],u=l[0],p=l[1],d=Math.ceil(s[i-1]/2),c=d*Math.ceil(s[i-2]/2),h="int b, int row, int col",m= ` b * $ { c } + ( row / 2 ) * $ { d } + ( col / 2 ) ` ;for(let f=2;f<i-1;f++)h= ` int b$ { f } , ` +h,c*=s[i-f-1],m= ` b$ { f } * $ { c } + ` +m;return `
vec4 $ { a } ( $ { h } ) {
int index = $ { m } ;
int texR = index / $ { p } ;
int texC = index - texR * $ { p } ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { p } , $ { u } ) ;
return $ { r . texture2D } ( $ { n } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function pY(e,t){let n=e.shapeInfo.logicalShape,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=n[3],i=n[2]*s,o=n[1]*i,{newShape:l,keptDims:u}=w.squeezeShape(n);if(l.length<n.length){let b=Gu(e,l),x=["row","col","depth","depth2"];return `
$ { Vu ( b , t ) }
2022-03-07 19:17:31 +01:00
float $ { r } ( int row , int col , int depth , int depth2 ) {
2022-05-24 13:16:42 +02:00
return $ { r } ( $ { Hu ( x , u ) } ) ;
2022-03-07 19:17:31 +01:00
}
` }if(e.shapeInfo.isUniform)return `
float $ { r } ( int row , int col , int depth , int depth2 ) {
int index = round ( dot ( vec4 ( row , col , depth , depth2 ) ,
vec4 ( $ { o } , $ { i } , $ { s } , 1 ) ) ) ;
2022-05-24 13:16:42 +02:00
$ { Uu ( e ) }
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
` ;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,c=d[0],h=d[1],m= ` int stride2 = $ { a } Shape [ 3 ] ; ` ,f= ` int stride1 = $ { a } Shape [ 2 ] * stride2 ; ` ,g= ` int stride0 = $ { a } Shape [ 1 ] * stride1 ; ` ;if(h===o&&p==null)return t? `
float $ { r } ( int row , int col , int depth , int depth2 ) {
$ { m }
$ { f }
float texR = float ( row ) ;
float texC =
dot ( vec3 ( col , depth , depth2 ) ,
vec3 ( stride1 , stride2 , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { a } TexShape [ 1 ] , $ { a } TexShape [ 0 ] ) ;
return sampleTexture ( $ { a } , uv ) ;
2020-12-15 14:15:43 +01:00
}
2022-03-07 19:17:31 +01:00
` : `
float $ { r } ( 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 ( $ { h } . 0 , $ { c } . 0 ) ;
return sampleTexture ( $ { a } , uv ) ;
2020-12-15 14:15:43 +01:00
}
2022-03-07 19:17:31 +01:00
` ;if(h===s&&p==null)return t? `
float $ { r } ( int row , int col , int depth , int depth2 ) {
float texR = dot ( vec3 ( row , col , depth ) ,
vec3 ( $ { a } Shape [ 1 ] * $ { a } Shape [ 2 ] , $ { a } Shape [ 2 ] , 1 ) ) ;
float texC = float ( depth2 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { a } TexShape [ 1 ] , $ { a } TexShape [ 0 ] ) ;
return sampleTexture ( $ { a } , uv ) ;
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
` : `
float $ { r } ( int row , int col , int depth , int depth2 ) {
float texR = dot ( vec3 ( row , col , depth ) ,
vec3 ( $ { n [ 1 ] * n [ 2 ] } , $ { n [ 2 ] } , 1 ) ) ;
float texC = float ( depth2 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { h } . 0 , $ { c } . 0 ) ;
return sampleTexture ( $ { a } , uv ) ;
2020-10-12 20:28:19 +02:00
}
2022-05-24 13:16:42 +02:00
` ;let y=So(a);return t? `
2022-03-07 19:17:31 +01:00
float $ { r } ( int row , int col , int depth , int depth2 ) {
// Explicitly use integer operations as dot() only works on floats.
$ { m }
$ { f }
$ { g }
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2 ;
vec2 uv = uvFromFlat ( $ { a } TexShape [ 0 ] , $ { a } TexShape [ 1 ] , index + $ { y } ) ;
return sampleTexture ( $ { a } , uv ) ;
}
` : `
float $ { r } ( int row , int col , int depth , int depth2 ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { o } + col * $ { i } +
depth * $ { s } + depth2 ;
vec2 uv = uvFromFlat ( $ { c } , $ { h } , index + $ { y } ) ;
return sampleTexture ( $ { a } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function cY(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[4],s=t[3]*r,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:u}=w.squeezeShape(t);if(l.length<t.length){let f=Gu(e,l),g=["row","col","depth","depth2","depth3"];return `
$ { Vu ( f ) }
2022-03-07 19:17:31 +01:00
float $ { a } ( int row , int col , int depth , int depth2 , int depth3 ) {
2022-05-24 13:16:42 +02:00
return $ { a } ( $ { Hu ( g , u ) } ) ;
2022-03-07 19:17:31 +01:00
}
` }if(e.shapeInfo.isUniform)return `
float $ { a } ( int row , int col , int depth , int depth2 , int depth3 ) {
float index = dot (
vec4 ( row , col , depth , depth2 ) ,
vec4 ( $ { o } , $ { i } , $ { s } , $ { r } ) ) +
depth3 ;
2022-05-24 13:16:42 +02:00
$ { Uu ( e ) }
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
` ;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,c=d[0],h=d[1];if(h===o&&p==null)return `
float $ { a } ( int row , int col , int depth , int depth2 , int depth3 ) {
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
vec4 ( $ { i } , $ { s } , $ { r } , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { h } . 0 , $ { c } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
` ;if(h===r&&p==null)return `
float $ { a } ( 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 ( $ { h } . 0 , $ { c } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2021-12-06 12:34:50 +01:00
}
2022-05-24 13:16:42 +02:00
` ;let m=So(n);return `
2022-03-07 19:17:31 +01:00
float $ { a } ( int row , int col , int depth , int depth2 , int depth3 ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { o } + col * $ { i } + depth * $ { s } +
depth2 * $ { r } + depth3 + $ { m } ;
vec2 uv = uvFromFlat ( $ { c } , $ { h } , index ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function dY(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:r,keptDims:s}=w.squeezeShape(t);if(r.length<t.length){let g=Gu(e,r),y=["row","col","depth","depth2","depth3","depth4"];return `
$ { Vu ( g ) }
2022-03-07 19:17:31 +01:00
float $ { a } ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
2022-05-24 13:16:42 +02:00
return $ { a } ( $ { Hu ( y , s ) } ) ;
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
` }let i=t[5],o=t[4]*i,l=t[3]*o,u=t[2]*l,p=t[1]*u;if(e.shapeInfo.isUniform)return `
float $ { a } ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
int index = round ( dot (
vec4 ( row , col , depth , depth2 ) ,
vec4 ( $ { p } , $ { u } , $ { l } , $ { o } ) ) +
dot (
vec2 ( depth3 , depth4 ) ,
vec2 ( $ { i } , 1 ) ) ) ;
2022-05-24 13:16:42 +02:00
$ { Uu ( e ) }
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
` ;let d=e.shapeInfo.flatOffset,c=e.shapeInfo.texShape,h=c[0],m=c[1];if(m===p&&d==null)return `
float $ { a } ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
vec4 ( $ { u } , $ { l } , $ { o } , $ { i } ) ) +
float ( depth4 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { m } . 0 , $ { h } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
` ;if(m===i&&d==null)return `
float $ { a } ( 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 ( $ { m } . 0 , $ { h } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2021-12-06 12:34:50 +01:00
}
2022-05-24 13:16:42 +02:00
` ;let f=So(n);return `
2022-03-07 19:17:31 +01:00
float $ { a } ( 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 * $ { p } + col * $ { u } + depth * $ { l } +
depth2 * $ { o } + depth3 * $ { i } + depth4 + $ { f } ;
vec2 uv = uvFromFlat ( $ { h } , $ { m } , index ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2022-05-24 13:16:42 +02:00
` }function Uu(e){let t=e.name,n=w.sizeFromShape(e.shapeInfo.logicalShape);return n<2? ` return $ { t } ; ` : `
2022-03-07 19:17:31 +01:00
for ( int i = 0 ; i < $ { n } ; i ++ ) {
if ( i == index ) {
return $ { t } [ i ] ;
2021-12-06 12:34:50 +01:00
}
2022-03-07 19:17:31 +01:00
}
2022-05-24 13:16:42 +02:00
` }function hY(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=P_(e.shapeInfo.logicalShape,t.logicalShape),l=mt(i),u=i-s,p,d=["x","y","z","w","u","v"];s===0?p="":i<2&&o.length>=1?p="coords = 0;":p=o.map(g=> ` coords . $ { d [ g + u ] } = 0 ; ` ).join( `
2022-05-18 14:36:05 +02:00
` );let c="";i<2&&s>0?c="coords":c=e.shapeInfo.logicalShape.map((g,y)=> ` coords . $ { d [ y + u ] } ` ).join(", ");let h="return outputValue;",m=w.sizeFromShape(e.shapeInfo.logicalShape)===1,f=w.sizeFromShape(t.logicalShape)===1;if(s===1&&!m&&!f)h= `
2022-03-07 19:17:31 +01:00
return vec4 ( outputValue . xy , outputValue . xy ) ;
` ;else if(m&&!f)i===1?h= `
return vec4 ( outputValue . x , outputValue . x , 0. , 0. ) ;
` :h= `
return vec4 ( outputValue . x ) ;
` ;else if(o.length){let g=s-2,y=s-1;o.indexOf(g)>-1&&o.indexOf(y)>-1?h="return vec4(outputValue.x);":o.indexOf(g)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(y)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return `
vec4 $ { r } ( ) {
$ { l } coords = getOutputCoords ( ) ;
$ { p }
vec4 outputValue = get$ { a } ( $ { c } ) ;
$ { h }
}
2022-05-24 13:16:42 +02:00
` }function mY(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&e.shapeInfo.flatOffset==null&&w.arraysEqual(i,s))return `
2022-03-07 19:17:31 +01:00
float $ { r } ( ) {
return sampleTexture ( $ { n } , resultUV ) ;
}
2022-05-24 13:16:42 +02:00
` ;let u=mt(l),p=P_(e.shapeInfo.logicalShape,t.logicalShape),d=l-o,c,h=["x","y","z","w","u","v"];o===0?c="":l<2&&p.length>=1?c="coords = 0;":c=p.map(f=> ` coords . $ { h [ f + d ] } = 0 ; ` ).join( `
2022-03-07 19:17:31 +01:00
` );let m="";return l<2&&o>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=> ` coords . $ { h [ g + d ] } ` ).join(", "), `
float $ { r } ( ) {
$ { u } coords = getOutputCoords ( ) ;
$ { c }
return get$ { a } ( $ { m } ) ;
}
2022-05-24 13:16:42 +02:00
` }function mt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error( ` GPU for rank $ { e } is not yet supported ` )}function _0(e,t,n){let{newShape:a,keptDims:r}=w.squeezeShape(t),s=t.length,i=e&&s===3&&t[0]===1,o=i?t.slice(1):a,l=!e&&s>1&&!w.arraysEqual(t,n)&&a.length<s||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:r}}function Gu(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Hu(e,t){return t.map(n=>e[n]).join(", ")}function fY(e,t,n,a){let r=n.map((p,d)=>{let c={logicalShape:p.shape,texShape:p.isUniform?null:p.texData.texShape,isUniform:p.isUniform,isPacked:p.isUniform?!1:p.texData.isPacked,flatOffset:null};return p.texData!=null&&p.texData.slice!=null&&p.texData.slice.flatOffset>0&&(c.flatOffset=p.texData.slice.flatOffset),{name:t.variableNames[d],shapeInfo:c}}),s=r.map(p=>p.shapeInfo),i={logicalShape:a.shape,texShape:a.texData.texShape,isUniform:!1,isPacked:a.texData.isPacked,flatOffset:null},o=D7(r,i,t),l=m_(e.gl,o),u=e.createProgram(l);return X().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i},z_(e,t,u))}function z_(e,t,n){let a={},r={},s={},i=[],o,l,u,p=null,d=null;d=e.getUniformLocation(n,"NAN",!1),X().getNumber("WEBGL_VERSION")===1&&(p=e.getUniformLocation(n,"INFINITY",!1));let c=!1;for(let h=0;h<t.variableNames.length;h++){let m=t.variableNames[h];a[m]=e.getUniformLocation(n,m,c),a[ ` offset$ { m } ` ]=e.getUniformLocation(n, ` offset$ { m } ` ,c),t.enableShapeUniforms&&(r[ ` $ { m } Shape ` ]=e.getUniformLocation(n, ` $ { m } Shape ` ,c),s[ ` $ { m } TexShape ` ]=e.getUniformLocation(n, ` $ { m } TexShape ` ,c))}return t.enableShapeUniforms&&(o=e.getUniformLocation(n,"outShape",c),u=e.getUniformLocation(n,"outShapeStrides",c),l=e.getUniformLocation(n,"outTexShape",c)),t.customUniforms&&t.customUniforms.forEach((h,m)=>{i[m]=e.getUniformLocation(n,h.name,c)}),{uniformLocations:a,customUniformLocations:i,infLoc:p,nanLoc:d,inShapesLocations:r,inTexShapesLocations:s,outShapeLocation:o,outShapeStridesLocation:u,outTexShapeLocation:l}}function Nk(e,t){if(e.length!==t.length)throw Error( ` Binary was compiled with $ { e . length } inputs , but was executed with $ { t . length } inputs ` );e.forEach((n,a)=>{let r=n.logicalShape,s=t[a],i=s.shape;if(!w.arraysEqual(r,i))throw Error( ` Binary was compiled with different shapes than the current args . Shapes $ { r } and $ { i } must match ` );if(n.isUniform&&s.isUniform)return;let o=n.texShape,l=s.isUniform?null:s.texData.texShape;if(!w.arraysEqual(o,l))throw Error( ` Binary was compiled with different texture shapes than the current args . Shape $ { o } and $ { l } must match ` )})}function gY(e,t,n,a,r){t.program.enableShapeUniforms||(Nk(t.inShapeInfos,n),Nk([t.outShapeInfo],[a]));let s=a.texData.texture,i=a.texData.texShape;a.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):e.setOutputMatrixTexture(s.texture,i[0],i[1]),e.setProgram(t.webGLProgram),X().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((l,u)=>{let p=t.program.variableNames[u],d=t.uniformLocations[p],c=t.uniformLocations[ ` offset$ { p } ` ],h=t.inShapesLocations[ ` $ { p } Shape ` ],m=t.inTexShapesLocations[ ` $ { p } TexShape ` ];if(h){let{uniformShape:f}=_0(t.program.packedInputs,l.shape,l.texData.texShape);switch(f.length){case 1:e.gl.uniform1iv(h,new Int32Array(f));break;case 2:e.gl.uniform2iv(h,new Int32Array(f));break;case 3:e.gl.uniform3iv(h,new Int32Array(f));break;case 4:e.gl.uniform4iv(h,new Int32Array(f));break;default:break}}if(m&&e.gl.uniform2i(m,l.texData.texShape[0],l.texData.texShape[1]),d!=null){if(l.isUniform){if(w.sizeFromShape(l.shape)<2)e.gl.uniform1f(d,l.uniformValues[0]);else{let f=l.uniformValu
2022-03-07 19:17:31 +01:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2022-05-24 13:16:42 +02:00
$ { this . enableShapeUniforms ? Uf ( [ "r" , "c" , "d" ] , e ) : Io ( [ "r" , "c" , "d" ] , e ) }
2022-03-07 19:17:31 +01:00
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
$ { t . output } = result ;
2021-12-06 12:34:50 +01:00
}
2022-05-24 13:16:42 +02:00
` }},xY=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=sc.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Cn();this.outputShape=e,this.enableShapeUniforms=Hn(this.outputShape.length),this.userCode= `
2022-03-07 19:17:31 +01:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2022-05-24 13:16:42 +02:00
$ { this . enableShapeUniforms ? Uf ( [ "r" , "c" , "d" ] , e ) : Io ( [ "r" , "c" , "d" ] , e ) }
2022-03-07 19:17:31 +01:00
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
$ { t . output } = result ;
2021-12-06 12:34:50 +01:00
}
2022-05-24 13:16:42 +02:00
` }},vY=class{constructor(e){this.variableNames=["A"],this.outTexUsage=ca.DOWNLOAD;let t=Cn();this.outputShape=e,this.userCode= `
$ { M _ }
2022-03-07 19:17:31 +01:00
void main ( ) {
float x = getAAtOutCoords ( ) ;
$ { t . output } = encode _float ( x ) ;
2021-12-06 12:34:50 +01:00
}
2022-05-24 13:16:42 +02:00
` }},wY=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ca.DOWNLOAD;let t=Cn();this.outputShape=e,this.userCode= `
$ { M _ }
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
float x = getChannel ( getAAtOutCoords ( ) , vec2 ( coords . y , coords . z ) ) ;
$ { t . output } = encode _float ( x ) ;
2021-12-06 12:34:50 +01:00
}
2022-05-24 13:16:42 +02:00
` }},kY=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Cn();this.outputShape=e,this.enableShapeUniforms=Hn(this.outputShape.length);let a="result";t&&(a="floor(result * 255. + 0.5)"),this.userCode= `
$ { this . enableShapeUniforms ? T0 ( ) : N0 ( e ) }
2022-03-07 19:17:31 +01:00
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 ( $ { a } , 0. , 0. , 0. ) ;
2021-12-06 12:34:50 +01:00
}
2022-05-24 13:16:42 +02:00
` }},IY=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Cn();this.outputShape=e,this.enableShapeUniforms=Hn(this.outputShape.length);let a="",r="result";t&&(r="floor(result * 255. + 0.5)");for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=s*2+i;a+= `
2022-03-07 19:17:31 +01:00
localCoords = coords ;
if ( localCoords [ 2 ] + $ { i } < $ { this . enableShapeUniforms ? "outShape[2]" : ` ${ e [ 2 ] } ` } ) {
localCoords [ 2 ] += $ { i } ;
if ( localCoords [ 1 ] + $ { s } < $ { this . enableShapeUniforms ? "outShape[1]" : ` ${ e [ 1 ] } ` } ) {
localCoords [ 1 ] += $ { s } ;
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 [ $ { o } ] = values [ 0 ] ;
} else if ( offset == 1 ) {
result [ $ { o } ] = values [ 1 ] ;
} else if ( offset == 2 ) {
result [ $ { o } ] = values [ 2 ] ;
} else {
result [ $ { o } ] = values [ 3 ] ;
2021-12-06 12:34:50 +01:00
}
}
}
2022-03-07 19:17:31 +01:00
` }this.userCode= `
2022-05-24 13:16:42 +02:00
$ { this . enableShapeUniforms ? T0 ( ) : N0 ( e ) }
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
int flatIndex , r , c , offset ;
ivec3 localCoords ;
vec2 uv ;
vec4 values ;
$ { a }
$ { n . output } = $ { r } ;
2021-12-06 12:34:50 +01:00
}
2022-05-24 13:16:42 +02:00
` }},B_={};Me(B_,{bindVertexProgramAttributeStreams:()=>X_,createBufferFromOutputTexture:()=>J_,createFloat16MatrixTexture:()=>H_,createFloat16PackedMatrixTexture:()=>K_,createFloat32MatrixTexture:()=>G_,createIndexBuffer:()=>U_,createPackedMatrixTexture:()=>q_,createUnsignedBytesMatrixTexture:()=>j_,createVertexBuffer:()=>V_,createVertexShader:()=>W_,downloadByteEncodedFloatMatrixFromOutputTexture:()=>eC,downloadFloat32MatrixFromBuffer:()=>Z_,downloadMatrixFromPackedOutputTexture:()=>nC,downloadPackedMatrixFromBuffer:()=>tC,getInternalFormatForFloat16MatrixTexture:()=>E0,getInternalFormatForFloat16PackedMatrixTexture:()=> $ 0,getInternalFormatForFloat32MatrixTexture:()=>C0,getInternalFormatForPackedMatrixTexture:()=>A0,getInternalFormatForUnsignedBytesMatrixTexture:()=>F0,uploadDenseMatrixToTexture:()=>Y_,uploadPixelDataToTexture:()=>Q_});function W_(e){let t=Cn(),n= ` $ { t . version }
2022-03-07 19:17:31 +01:00
precision highp float ;
$ { t . attribute } vec3 clipSpacePos ;
$ { t . attribute } vec2 uv ;
$ { t . varyingVs } vec2 resultUV ;
void main ( ) {
gl _Position = vec4 ( clipSpacePos , 1 ) ;
resultUV = uv ;
2022-05-24 13:16:42 +02:00
} ` ;return h_(e,n)}function V_(e){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 y_(e,t)}function U_(e){let t=new Uint16Array([0,1,2,2,1,3]);return b_(e,t)}function sd(e,t,n,a,r,s){v_(t,n);let i=x_(e),o=e.TEXTURE_2D;return ge(e,()=>e.bindTexture(o,i)),ge(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),ge(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),ge(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),ge(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),X().getNumber("WEBGL_VERSION")===1?ge(e,()=>e.texImage2D(o,0,a,t,n,0,r,s,null)):ge(e,()=>e.texStorage2D(o,1,a,t,n)),ge(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[n,t]}}function C0(e){return e.internalFormatFloat}function G_(e,t,n,a){let[r,s]=rd(t,n);return sd(e,r,s,C0(a),a.textureFormatFloat,e.FLOAT)}function E0(e){return e.internalFormatHalfFloat}function H_(e,t,n,a){let[r,s]=rd(t,n);return sd(e,r,s,E0(a),a.textureFormatFloat,a.textureTypeHalfFloat)}function F0(e){return e.downloadTextureFormat}function j_(e,t,n,a){let[r,s]=rd(t,n);return sd(e,r,s,F0(a),e.RGBA,e.UNSIGNED_BYTE)}function A0(e){return e.internalFormatPackedFloat}function q_(e,t,n,a){let[r,s]=Bu(t,n);return sd(e,r,s,A0(a),e.RGBA,e.FLOAT)}function $ 0(e){return e.internalFormatPackedHalfFloat}function K_(e,t,n,a){let[r,s]=Bu(t,n);return sd(e,r,s, $ 0(a),e.RGBA,a.textureTypeHalfFloat)}function X_(e,t,n){return ge(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),ux(e,t,"clipSpacePos",n,3,20,0)&&ux(e,t,"uv",n,2,20,12)}function Y_(e,t,n,a,r,s){ge(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;r instanceof Uint8Array?(i=new Uint8Array(n*a*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*a*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(r),X().getNumber("WEBGL_VERSION")===2?ge(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA,o,i)):ge(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,a,0,e.RGBA,o,i)),ge(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function Q_(e,t,n){ge(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?X().getNumber("WEBGL_VERSION")===2?ge(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)):ge(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):X().getNumber("WEBGL_VERSION")===2?ge(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)):ge(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),ge(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function J_(e,t,n,a){let r=e.createBuffer();ge(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*n;return ge(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),ge(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),ge(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function Z_(e,t,n){let a=e,r=new Float32Array(n);return a.bindBuffer(a.PIXEL_PACK_BUFFER,t),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,r),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),r}function eC(e,t,n,a){let[r,s]=rd(t,n),i=4,o=new Uint8Array(x7(t*n,i));return ge(e,()=>e.readPixels(0,0,r,s,a.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function tC(e,t,n,a,r,s,i,o){let l=e,u=new Float32Array(v7(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function nC(e,t,n){let a=new Float32Array(t*n*4);return ge(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,a)),a}var Sh=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=X().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,p_(t,e)):this.gl=Ya(t);let n="WEBGL_color_buffer_float",a="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),X().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=Bp(this.gl,r),da(this.gl,s))this.textureHalfFloatExtension=Bp(this.gl,s);else if(X().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environm
2022-03-07 19:17:31 +01:00
void main ( ) {
setOutput ( vec4 ( getA ( ) , 0. , 0. , 0. ) ) ;
2021-12-06 12:34:50 +01:00
}
2022-05-18 14:36:05 +02:00
` ;else{let t=Sn("rc",this.rank),n=mt(this.rank),a=this.getOutOfBoundsCondition(t),r=this.getSetup(t),s=this.getOutput(t);this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { n } rc = getOutputCoords ( ) ;
if ( $ { a } ) {
setOutput ( vec4 ( 0 ) ) ;
2021-12-06 12:34:50 +01:00
} else {
2022-03-07 19:17:31 +01:00
$ { r }
setOutput ( vec4 ( $ { s } ) ) ;
2021-12-06 12:34:50 +01:00
}
}
2022-03-07 19:17:31 +01:00
` }}getSourceCoordsArr(e){let t=[];for(let n=0;n<=1;n++)for(let a=0;a<=1;a++){let r= ` $ { n === 0 ? "r" : "rp1" } , $ { a === 0 ? "c" : "cp1" } ` ;for(let s=2;s<this.rank;s++)r= ` $ { e [ e . length - 1 - s ] } , ` +r;t.push(r)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return ` rc > $ { this . enableShapeUniforms ? "outShape" : this . outputShape [ 0 ] } ` ;let t="";for(let n=this.rank-2;n<this.rank;n++)t+= ` $ { e [ n ] } >= $ { this . enableShapeUniforms ? ` outShape[ ${ n } ] ` : this . outputShape [ n ] } ` ,n<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),n=this.enableShapeUniforms? ` outShape [ $ { this . rank } - 1 ] ` :this.outputShape[this.rank-1],a=this.enableShapeUniforms? ` outShape [ $ { this . rank } - 2 ] ` :this.outputShape[this.rank-2];return `
int r = $ { t [ 0 ] } ;
int c = $ { t [ 1 ] } ;
int rp1 = r + 1 ;
int cp1 = c + 1 ;
bool cEdge = cp1 >= $ { n } ;
bool rEdge = rp1 >= $ { a } ;
` }getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1? ` getA ( rc ) , ( rc + 1 >= $ { this . enableShapeUniforms ? "outShape" : this . outputShape [ 0 ] } ? 0. : getA ( rc + 1 ) ) , 0 , 0 ` : ` getA ( $ { t [ 0 ] } ) ,
cEdge ? 0. : getA ( $ { t [ 1 ] } ) ,
rEdge ? 0. : getA ( $ { t [ 2 ] } ) ,
2022-05-24 13:16:42 +02:00
rEdge || cEdge ? 0. : getA ( $ { t [ 3 ] } ) ` }},oC=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Hn(this.outputShape.length);let n="";for(let a=0;a<4;a++){let r="thisRC = rc;";a%2===1&&(r+="thisRC.z += 1;"),a>1&&(r+="thisRC.y += 1;"),n+= `
2022-03-07 19:17:31 +01:00
$ { r }
$ { a > 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 [ $ { a } ] =
getChannel ( getA ( inputRC . x , inputRC . y , inputRC . z ) , inputRCInnerDims ) ;
$ { a > 0 ? "}" : "" }
` }this.userCode= `
2022-05-24 13:16:42 +02:00
$ { d9 ( t , this . enableShapeUniforms ) }
$ { this . enableShapeUniforms ? T0 ( ) : N0 ( e ) }
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
ivec3 thisRC ;
int rows = $ { this . enableShapeUniforms ? "outShape[1]" : e [ 1 ] } ;
int cols = $ { this . enableShapeUniforms ? "outShape[2]" : e [ 2 ] } ;
$ { n }
setOutput ( result ) ;
2021-12-06 12:34:50 +01:00
}
2022-05-24 13:16:42 +02:00
` }};function d9(e,t){return `
2022-03-07 19:17:31 +01:00
ivec3 inputCoordsFromReshapedOutCoords ( int index ) {
2022-05-24 13:16:42 +02:00
$ { t ? $7 ( [ "r" , "c" , "d" ] , "inputShape" ) : Io ( [ "r" , "c" , "d" ] , e ) }
2022-03-07 19:17:31 +01:00
return ivec3 ( r , c , d ) ;
}
2022-05-24 13:16:42 +02:00
` }var h9=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){let a=_k(t,n),r=Ck(e,a,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=Tk(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[r].shift();return this.usedTextures[r].push(o),o}let i;return a===ln.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===ln.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===ln.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===ln.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===ln.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,n,a){if(this.freeTextures==null)return;let r=_k(n,a),s=Ck(t,r,a);s in this.freeTextures||(this.freeTextures[s]=[]);let i=Tk(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,a),o=X().get("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],u=l.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used", ` $ { this . numFreeTextures } / $ { this . numUsedTextures } ` , ` ( $ { e } ) ` );let t=this._numBytesFree/this._numBytesAllocated;console.log( ` Bytes allocated : $ { this . _numBytesAllocated } ` ),console.log( ` Bytes unused : $ { this . _numBytesFree } ( $ { Math . round ( 100 * t ) } % ) ` )}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function m9(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F||t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error( ` Unknown internal format $ { t } ` )}function Tk(e,t,n,a,r){let s=f9(t,a),i;if(r){let[l,u]=Bu(e[0],e[1]);i=l*u}else{let[l,u]=rd(e[0],e[1]);i=l*u}let o=m9(n,s);return i*o}function f9(e,t){switch(e){case ln.PACKED_2X2_FLOAT32:return A0(t);case ln.PACKED_2X2_FLOAT16:return $ 0(t);case ln.UNPACKED_FLOAT32:return C0(t);case ln.UNPACKED_FLOAT16:return E0(t);case ln.PACKED_4X1_UNSIGNED_BYTE:return F0(t);default:throw new Error( ` Unknown physical texture type $ { e } ` )}}function g9(e){return X().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?ln.PACKED_2X2_FLOAT32:ln.UNPACKED_FLOAT32:e?ln.PACKED_2X2_FLOAT16:ln.UNPACKED_FLOAT16}function _k(e,t){if(e===ca.UPLOAD)return ln.PACKED_2X2_FLOAT32;if(e===ca.RENDER||e==null)return g9(t);if(e===ca.DOWNLOAD||e===ca.PIXELS)return ln.PACKED_4X1_UNSIGNED_BYTE;throw new Error( ` Unknown logical texture type $ { e } ` )}function Ck(e,t,n){return ` $ { e [ 0 ] } _$ { e [ 1 ] } _$ { t } _$ { n } ` }var Sr=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Hn(this.outputShape.length),this.userCode= `
2022-03-07 19:17:31 +01:00
float unaryOperation ( float x ) {
$ { t }
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-05-24 13:16:42 +02:00
` }},Ea="if (isnan(x)) return x;",y9="return x;",Ek="return abs(x);",b9="return (x >= 0.0) ? x : (exp(x) - 1.0);",x9=Ea+ `
2022-03-07 19:17:31 +01:00
return ( x < 0.0 ) ? 0.0 : x ;
2022-05-24 13:16:42 +02:00
` ,v9=Ea+ `
2022-03-07 19:17:31 +01:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2022-05-24 13:16:42 +02:00
` ,Jo="return x;",w9="return 1.0 / (1.0 + exp(-1.0 * x));",k9="return x;",I9= `
2022-03-07 19:17:31 +01:00
vec4 result ;
result . r = ( x . r >= 0.0 ) ? x . r : ( exp ( x . r ) - 1.0 ) ;
result . g = ( x . g >= 0.0 ) ? x . g : ( exp ( x . g ) - 1.0 ) ;
result . b = ( x . b >= 0.0 ) ? x . b : ( exp ( x . b ) - 1.0 ) ;
result . a = ( x . a >= 0.0 ) ? x . a : ( exp ( x . a ) - 1.0 ) ;
return result ;
2022-05-24 13:16:42 +02:00
` ,S9= `
2022-03-07 19:17:31 +01:00
vec4 result = x * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2022-05-24 13:16:42 +02:00
` ,N9= `
2022-03-07 19:17:31 +01:00
vec4 result = min ( x , vec4 ( 6. ) ) * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2022-05-24 13:16:42 +02:00
` ,T9="return 1.0 / (1.0 + exp(-1.0 * x));",Qs=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Hn(this.outputShape.length),this.userCode= `
2022-03-07 19:17:31 +01:00
vec4 unaryOperation ( vec4 x ) {
$ { t }
}
void main ( ) {
vec4 x = getAAtOutCoords ( ) ;
vec4 y = unaryOperation ( x ) ;
setOutput ( y ) ;
}
2022-05-24 13:16:42 +02:00
` }},_9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=Hn(this.outputShape.length);let t=e.length,n=Sn("rc",t),a=mt(t),r=p9(t,n),s=n.slice(-2),i=t<=1?"rc": ` vec2 ( $ { s . join ( "," ) } ) ` ;this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { a } rc = getOutputCoords ( ) ;
vec4 packedInput = getA ( $ { r } ) ;
setOutput ( getChannel ( packedInput , $ { i } ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},C9=mr.whereImpl,E9=1e-7,F9=1e-4,wb={};function A9(e){return e in wb||(wb[e]={}),wb[e]}var $ 9=X().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),D9=600;function R9(){return X().global.screen==null?1024:X().global.screen.height*X().global.screen.width*window.devicePixelRatio*D9/1024/1024}var Gf=class extends pc{constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!X().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof Sh)t=e;else{let n=Ya(X().getNumber("WEBGL_VERSION"),e);t=new Sh(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=Ya(X().getNumber("WEBGL_VERSION"));t=new Sh(n),this.binaryCache=A9(X().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new h9(this.gpgpu),this.numMBBeforeWarning=R9(),this.texData=new rm(this,ar())}nextDataId(){return Gf.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((X().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||X().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a={id:this.nextDataId()};return this.texData.set(a,{shape:t,dtype:n,values:e,usage:ca.UPLOAD,refCount:1}),a}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,a,r){if(X().getBool("DEBUG")&&this.checkNumericalProblems(t),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:a,values:t,usage:ca.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:a,complexTensorInfos:r,slice:s,shape:i,isPacked:o}=t;if(s!=null){let d;o?d=new Qs(i,Jo):d=new Sr(i,Jo);let c=this.runWebGLProgram(d,[{dataId:e,shape:i,dtype:a}],a),h=this.readSync(c.dataId);return this.disposeIntermediateTensorInfo(c),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return n;let l=this.activeTimers!=null,u;l&&(u=w.now());let p;if(a==="complex64"){let d=this.readSync(r.real.dataId),c=this.readSync(r.imag.dataId);p=C.mergeRealAndImagArrays(d,c)}else p=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=w.now()-u),this.convertAndCacheOnCPU(e,p)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(m=>h.push(m))}let t=this.texData.get(e),{values:n,shape:a,slice:r,dtype:s,complexTensorInfos:i,isPacked:o}=t;if(r!=null){let h;o?h=new Qs(a,Jo):h=new Sr(a,Jo);let m=this.runWebGLProgram(h,[{dataId:e,shape:a,dtype:s}],s),f=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),f}if(n!=null)return this.convertAndCacheOnCPU(e);if(X().getBool("DEBUG")&&!X().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&X().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,u;if(s!=="complex64"&&X().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let h=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(h.texture.texture,...dh(a))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(s==="complex64"){let h=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),m=h[0],f=h[1];p=C.mergeRealAndImagArrays(m,f)}else if(l==null)p=this.getValuesFromTexture(e);else{let h=w.sizeFromShape(a);p=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}if(u!=null&&this.disposeIntermediateTensorInfo(u),l!=null){let h=this.gpgpu.gl;ge(h,()=>h.deleteBuffer(l))}let d=this.convertAndCacheOnCPU(e,p),c=this.pendingRead.get(e);return this.pendingRead.delete(e),c.forEach(h=
2022-03-07 19:17:31 +01:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2022-05-24 13:16:42 +02:00
` ,Sl=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=C.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=Hn(this.outputShape.length),this.userCode= `
2022-03-07 19:17:31 +01:00
float binaryOperation ( float a , float b ) {
$ { e }
}
void main ( ) {
float a = getAAtOutCoords ( ) ;
float b = getBAtOutCoords ( ) ;
setOutput ( binaryOperation ( a , b ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},Hf= `
2022-03-07 19:17:31 +01:00
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 ;
2022-05-24 13:16:42 +02:00
` ,id=class{constructor(e,t,n,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=C.assertAndGetBroadcastShape(t,n);let r=this.outputShape.length;this.enableShapeUniforms=Hn(r);let s="";if(a)if(r===0||w.sizeFromShape(this.outputShape)===1)s= `
2022-03-07 19:17:31 +01:00
result . y = 0. ;
result . z = 0. ;
result . w = 0. ;
` ;else if(s= `
2022-05-18 14:36:05 +02:00
$ { mt ( r ) } coords = getOutputCoords ( ) ;
2022-03-07 19:17:31 +01:00
` ,r===1)this.enableShapeUniforms?s+= `
result . y = ( coords + 1 ) >= outShape ? 0. : result . y ;
result . z = 0. ;
result . w = 0. ;
` :s+= `
result . y = ( coords + 1 ) >= $ { this . outputShape [ 0 ] } ? 0. : result . y ;
result . z = 0. ;
result . w = 0. ;
2022-04-01 15:16:17 +02:00
` ;else{let i=Sn("coords",r);this.enableShapeUniforms?s+= `
2022-03-07 19:17:31 +01:00
bool nextRowOutOfBounds =
( $ { i [ r - 2 ] } + 1 ) >= outShape [ $ { r } - 2 ] ;
bool nextColOutOfBounds =
( $ { i [ r - 1 ] } + 1 ) >= outShape [ $ { r } - 1 ] ;
result . y = nextColOutOfBounds ? 0. : result . y ;
result . z = nextRowOutOfBounds ? 0. : result . z ;
result . w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result . w ;
` :s+= `
bool nextRowOutOfBounds =
( $ { i [ r - 2 ] } + 1 ) >= $ { this . outputShape [ r - 2 ] } ;
bool nextColOutOfBounds =
( $ { i [ r - 1 ] } + 1 ) >= $ { this . outputShape [ r - 1 ] } ;
result . y = nextColOutOfBounds ? 0. : result . y ;
result . z = nextRowOutOfBounds ? 0. : result . z ;
result . w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result . w ;
` }this.userCode= `
vec4 binaryOperation ( vec4 a , vec4 b ) {
$ { e }
}
void main ( ) {
vec4 a = getAAtOutCoords ( ) ;
vec4 b = getBAtOutCoords ( ) ;
vec4 result = binaryOperation ( a , b ) ;
$ { s }
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }};function na(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var L9={kernelName:zi,backendName:"webgl",kernelFunc:na};function Is(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.makeTensorInfo(a.shape,"complex64"),i=n.texData.get(s.dataId),o=na({inputs:{x:a},backend:n}),l=na({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},s}var z9={kernelName:cm,backendName:"webgl",kernelFunc:Is},pC="return (a < 0.) ? b * a : a;",cC= `
2022-03-07 19:17:31 +01:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2022-05-24 13:16:42 +02:00
` ;function B9(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a,i=n.makeTensorInfo([],"float32",w.createScalarValue(s,"float32")),o=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new id(cC,r.shape,i.shape):new Sl(pC,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],"float32");return n.disposeIntermediateTensorInfo(i),l}var W9={kernelName:Bi,backendName:"webgl",kernelFunc:B9},dC="return (a < 0.) ? b * a : a;",hC= `
2022-03-07 19:17:31 +01:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2022-05-24 13:16:42 +02:00
` ;function V9(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new id(hC,a.shape,r.shape):new Sl(dC,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],"float32")}var U9={kernelName:Zi,backendName:"webgl",kernelFunc:V9},ju="if (isnan(x)) return x;",G9= `
2022-03-07 19:17:31 +01:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2022-05-24 13:16:42 +02:00
` ,H9= `
2022-03-07 19:17:31 +01:00
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 ;
2022-05-24 13:16:42 +02:00
` ;function Qe({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:a}){return({inputs:r,backend:s})=>{let{x:i}=r,o=s,l=a||i.dtype;if(o.shouldExecuteOnCPU([i])&&n!=null){let d=o.texData.get(i.dataId),c=n(d.values,l);return o.makeTensorInfo(i.shape,l,c)}let u=X().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,p;return u?p=new Qs(i.shape,t):p=new Sr(i.shape,e),o.runWebGLProgram(p,[i],l)}}function pn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:a=!1,cpuKernelImpl:r,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:u}=i,p=o;if(a&&l.dtype==="complex64"){let m=p.texData.get(l.dataId),f=p.texData.get(u.dataId),[g,y]=[[m.complexTensorInfos.real,f.complexTensorInfos.real],[m.complexTensorInfos.imag,f.complexTensorInfos.imag]].map(x=>{let[v,k]=x,T={dataId:v.dataId,dtype:v.dtype,shape:l.shape},_={dataId:k.dataId,dtype:k.dtype,shape:u.shape},E=new Sl(e,l.shape,u.shape);return p.runWebGLProgram(E,[T,_],ma(v.dtype,k.dtype))}),b=Is({inputs:{real:g,imag:y},backend:p});return p.disposeIntermediateTensorInfo(g),p.disposeIntermediateTensorInfo(y),b}let d=s||ma(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||p.shouldExecuteOnCPU([l,u]))&&r!=null){let m=p.texData.get(l.dataId).values,f=p.texData.get(u.dataId).values,g=l.dtype==="string"?C.fromUint8ToStringArray(m):m,y=l.dtype==="string"?C.fromUint8ToStringArray(f):f,[b,x]=r(l.shape,u.shape,g,y,d),v=p.makeTensorInfo(x,d),k=p.texData.get(v.dataId);return k.values=b,v}let c=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return c?h=new id(t,l.shape,u.shape,n):h=new Sl(e,l.shape,u.shape),p.runWebGLProgram(h,[l,u],d)}}function jf(e,t=!1){if(e==="linear")return t?k9:y9;if(e==="relu")return t?S9:x9;if(e==="elu")return t?I9:b9;if(e==="relu6")return t?N9:v9;if(e==="prelu")return t?hC:dC;if(e==="leakyrelu")return t?cC:pC;if(e==="sigmoid")return t?T9:w9;throw new Error( ` Activation $ { e } has not been implemented for the WebGL backend . ` )}var mC=class{constructor(e,t,n,a=!1,r=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=Hn(this.outputShape.length);let u=a?e[1]:e[2],p=Math.ceil(u/2),d=a?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",h=a?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",g="";i&&(o?f= ` vec4 activation ( vec4 a ) {
2022-03-07 19:17:31 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { i }
} ` :l?f= ` vec4 activation ( vec4 a ) {
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { i }
} ` :f= ` vec4 activation ( vec4 x ) {
$ { i }
} ` ,g="result = activation(result);");let y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]<t[0]?b= ` int ( min ( float ( rc . x ) , $ { e [ 0 ] - 1 } . ) ) ` :t[0]<e[0]&&(x= ` int ( min ( float ( rc . x ) , $ { t [ 0 ] - 1 } . ) ) ` ),this.userCode= `
$ { f }
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = $ { p } . 0 ;
vec4 dot2x2ARowBCol ( ivec3 rc ) {
vec4 result = vec4 ( 0 ) ;
for ( int i = 0 ; i < $ { p } ; i ++ ) {
int batchA = $ { b } ;
int batchB = $ { x } ;
vec4 a = getMatrixA ( batchA , $ { d } ) ;
vec4 b = getMatrixB ( batchB , $ { c } ) ;
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += ( $ { h [ 0 ] } * $ { m [ 0 ] } ) ;
result += ( $ { h [ 1 ] } * $ { m [ 1 ] } ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
return result ;
}
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
vec4 result = dot2x2ARowBCol ( rc ) ;
$ { y }
$ { g }
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }},Fk={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},Ak=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=C.assertAndGetBroadcastShape(t,n),this.userCode= `
2022-03-07 19:17:31 +01:00
float binaryOpComplex (
float areal , float aimag , float breal , float bimag ) {
$ { e }
}
void main ( ) {
float areal = getARealAtOutCoords ( ) ;
float aimag = getAImagAtOutCoords ( ) ;
float breal = getBRealAtOutCoords ( ) ;
float bimag = getBImagAtOutCoords ( ) ;
setOutput ( binaryOpComplex ( areal , aimag , breal , bimag ) ) ;
}
2022-05-24 13:16:42 +02:00
` }}, $ k="return a * b;";function R0(e){let{inputs:t,backend:n}=e,{a,b:r}=t,s=C.upcastType(a.dtype,r.dtype);if(a.dtype==="complex64"){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),u=new Ak(Fk.REAL,a.shape,r.shape),p=new Ak(Fk.IMAG,a.shape,r.shape),d=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:a.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:a.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:r.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:r.shape}],c=n.runWebGLProgram(u,d,"float32"),h=n.runWebGLProgram(p,d,"float32"),m=Is({inputs:{real:c,imag:h},backend:n});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),m}if(n.shouldExecuteOnCPU([a,r])){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),[u,p]=GY(a.shape,r.shape,o.values,l.values,s),d=n.makeTensorInfo(p,s),c=n.texData.get(d.dataId);return c.values=u,d}let i;return X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new id( $ k,a.shape,r.shape):i=new Sl( $ k,a.shape,r.shape),n.runWebGLProgram(i,[a,r],s)}var j9={kernelName:Xi,backendName:"webgl",kernelFunc:R0};function q9(e,t,n){let a=[fi(e.shape),...gi(e.shape)],r={dtype:e.dtype,shape:a,dataId:e.dataId},s=[fi(t),...gi(t)],i=new oC(s,a),o=!0,l=[a],u=n.runWebGLProgram(i,[r],e.dtype,l,o);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function me(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=n,o=w.sizeFromShape(r.shape),l=w.inferFromImplicitShape(s,o),u=w.sizeFromShape(l);w.assert(o===u,()=> ` The new shape ( $ { l } ) has $ { u } elements and the old shape ( $ { r . shape } ) has $ { o } elements . The new shape and old shape must have the same number of elements . ` );let p=i.texData.get(r.dataId);return p.isPacked&&!ic(r.shape,l)&&!(p.texture!==null&&ic(p.shape,l))?q9(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var K9={kernelName:cu,backendName:"webgl",kernelFunc:me},Dk=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i=Math.floor(n/4)*4,o=n%4,l="sumValue += dot(values, ones);";if(t!=null){let p=1/t;l= ` sumValue += dot ( values * $ { w . isInt ( p ) ? p . toPrecision ( 2 ) : p } , ones ) ; ` }let u="";r%n>0&&(u= `
2022-03-07 19:17:31 +01:00
if ( inIdx < 0 || inIdx >= $ { r } ) {
return 0.0 ;
2021-05-18 14:11:17 +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 ) {
$ { u }
return getX ( batch , inIdx ) ;
}
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * $ { n } ;
float sumValue = 0.0 ;
for ( int i = 0 ; i < $ { i } ; i += 4 ) {
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
$ { l }
2021-10-22 15:06:43 +02:00
}
2022-03-07 19:17:31 +01:00
int inIdx = inOffset + $ { i } ;
if ( $ { o === 1 } ) {
vec4 values = vec4 ( getValue ( batch , inIdx ) , 0.0 , 0.0 , 0.0 ) ;
$ { l }
} else if ( $ { o === 2 } ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) , 0.0 , 0.0 ) ;
$ { l }
} else if ( $ { o === 3 } ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) , 0.0 ) ;
$ { l }
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( sumValue ) ;
}
2022-05-24 13:16:42 +02:00
` }},X9=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i="0.0",o="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",o="min"):t==="max"&&(i="-1.0 / 1e-20",o="max");let l= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let u=Math.floor(n/4)*4,p=n%4,d= `
2022-03-07 19:17:31 +01:00
if ( $ { t === "sum" } ) {
sumValue += dot ( values , ones ) ;
} else if ( $ { t === "prod" } ) {
vec2 tmp = vec2 ( values [ 0 ] , values [ 1 ] ) * vec2 ( values [ 2 ] , values [ 3 ] ) ;
prodValue *= tmp [ 0 ] * tmp [ 1 ] ;
} else {
minMaxValue = $ { o } ( values , minMaxValue ) ;
if ( $ { t === "min" } || $ { t === "max" } ) {
minMaxValue = $ { o } ( values , minMaxValue ) ;
bvec4 isNaN = isnan ( values ) ;
if ( isNaN . r || isNaN . g || isNaN . b || isNaN . a ) {
minMaxValue = vec4 ( NAN ) ;
2021-05-18 14:11:17 +02:00
}
}
2022-03-07 19:17:31 +01:00
}
` ,c="vec4";t==="all"?(i="1.0",d= `
bool reducedAllValue = all ( values ) ;
float floatedReducedAllValue = float ( reducedAllValue ) ;
allValue = float ( allValue >= 1.0 && floatedReducedAllValue >= 1.0 ) ;
` ,c="bvec4"):t==="any"&&(i="0.0",d= `
bool reducedAnyValue = any ( values ) ;
float floatedReducedAnyValue = float ( reducedAnyValue ) ;
anyValue = float ( anyValue >= 1.0 || floatedReducedAnyValue >= 1.0 ) ;
` ,c="bvec4");let h="";r%n>0&&(h= `
if ( inIdx < 0 || inIdx >= $ { r } ) {
return initializationValue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
` ),this.userCode= `
const float initializationValue = $ { i } ;
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float getValue ( int batch , int inIdx ) {
$ { h }
return getX ( batch , inIdx ) ;
}
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * $ { n } ;
vec4 minMaxValue = vec4 ( $ { i } ) ;
float prodValue = 1.0 ;
float sumValue = 0.0 ;
float allValue = 1.0 ;
float anyValue = 0.0 ;
for ( int i = 0 ; i < $ { u } ; i += 4 ) {
int inIdx = inOffset + i ;
$ { c } values = $ { c } (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
$ { d }
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
int inIdx = inOffset + $ { u } ;
if ( $ { p === 1 } ) {
$ { c } values = $ { c } (
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
$ { d }
} else if ( $ { p === 2 } ) {
$ { c } values = $ { c } (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
$ { d }
} else if ( $ { p === 3 } ) {
$ { c } values = $ { c } (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
$ { d }
2021-03-26 15:26:02 +01:00
}
2022-03-07 19:17:31 +01:00
setOutput ( $ { l } ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Y9(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],a=C.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:a,outSize:Math.ceil(n/a)})}return t}function No(e,t,n,a){let r=Y9(e.shape),s=e;for(let i=0;i<r.length;i++){let{inSize:o,windowSize:l,outSize:u}=r[i],p,d;n==="mean"?p=i===0?new Dk({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new Dk({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):p=new X9({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},n),d=s,s=a.runWebGLProgram(p,[s],t),d.dataId!==e.dataId&&a.disposeIntermediateTensorInfo(d)}return s}var Q9=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];this.outputShape=n,this.rank=n.length;let a=mt(this.rank),r=J9(t);this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { a } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { r } ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function J9(e){let t=e.length;if(t>6)throw Error( ` Transpose for rank $ { t } is not yet supported ` );let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],a=new Array(t);for(let r=0;r<e.length;r++)a[e[r]]=n[r];return a.join()}var Z9=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let u=0;u<n.length;u++)n[u]=e[t[u]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error( ` Packed transpose for rank $ { this . rank } is not yet supported . ` );let a=mt(this.rank),r=iC("rc",this.rank),s=new Array(this.rank);for(let u=0;u<t.length;u++)s[t[u]]=r[u];let i= ` vec2 ( $ { s . slice ( - 2 ) . join ( ) } ) ` ,o= ` ++ $ { r [ this . rank - 1 ] } < $ { n [ this . rank - 1 ] } ` ,l= ` getChannel ( getA ( $ { s . join ( ) } ) , $ { i } ) ` ;this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { a } rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
result [ 0 ] = $ { l } ;
if ( $ { o } ) {
result [ 1 ] = $ { l } ;
}
-- $ { r [ this . rank - 1 ] } ;
if ( ++ $ { r [ this . rank - 2 ] } < $ { n [ this . rank - 2 ] } ) {
result [ 2 ] = $ { l } ;
if ( $ { o } ) {
result [ 3 ] = $ { l } ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
}
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }};function qf(e,t,n){let a=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Z9(e.shape,t):new Q9(e.shape,t);return n.runWebGLProgram(a,[e],e.dtype)}function eQ(e,t,n,a){let r=t,s=e.shape.length,i=w.parseAxisParam(r,e.shape),o=i,l=C.getAxesPermutation(o,s),u=l!=null,p=e;u&&(p=qf(e,l,a),o=C.getInnerMostAxes(o.length,s)),C.assertAxesAreInnerMostDims("sum",o,s);let[d,c]=C.computeOutAndReduceShapes(p.shape,o),h=d;n&&(h=C.expandShapeToKeepDim(d,i));let m=w.sizeFromShape(c),f=w.sizeFromShape(e.shape)/m,g=me({inputs:{x:p},attrs:{shape:[f,m]},backend:a}),y=Bm(e.dtype),b=No(g,y,"sum",a),x=me({inputs:{x:b},attrs:{shape:h},backend:a});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(b),u&&a.disposeIntermediateTensorInfo(p),x}function Kf(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;return eQ(r,s,i,n)}var tQ={kernelName:po,backendName:"webgl",kernelFunc:Kf};function Wt(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{perm:s}=a,i=n,o=r.shape.length,l=new Array(o);for(let p=0;p<l.length;p++)l[p]=r.shape[s[p]];let u;if(i.shouldExecuteOnCPU([r])){let p=i.texData.get(r.dataId).values,d=D0(p,r.shape,r.dtype,s,l);u=i.makeTensorInfo(l,r.dtype);let c=i.texData.get(u.dataId);c.values=d}else u=qf(r,s,i);return u}var nQ={kernelName:Nr,backendName:"webgl",kernelFunc:Wt},fC=1e3;function tm({a:e,b:t,transposeA:n,transposeB:a,backend:r,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let u=e.shape.length,p=t.shape.length,d=n?e.shape[u-2]:e.shape[u-1],c=a?t.shape[p-1]:t.shape[p-2],h=n?e.shape[u-1]:e.shape[u-2],m=a?t.shape[p-2]:t.shape[p-1],f=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=w.sizeFromShape(f),b=w.sizeFromShape(g),x=Cu.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,m]);w.assert(d===c,()=> ` Error in matMul : inner shapes ( $ { d } ) and ( $ { c } ) of Tensors with shapes $ { e . shape } and $ { t . shape } and transposeA = $ { n } and transposeB = $ { a } must match . ` );let v=n?[y,d,h]:[y,h,d],k=a?[b,m,c]:[b,c,m],T=me({inputs:{x:e},backend:r,attrs:{shape:v}}),_=me({inputs:{x:t},backend:r,attrs:{shape:k}}),E=[T,_],A=Math.max(y,b),M=n?T.shape[1]:T.shape[2], $ =s!=null,S=i!=null,P=l==="leakyrelu",V=l!=null?jf(l,!0):null,j= $ ||S||P||V!=null,q;if((h===1||m===1)&&M>fC&&j===!1){let Z=T,ee=_;n&&(Z=Wt({inputs:{x:T},backend:r,attrs:{perm:[0,2,1]}}),E.push(Z)),a&&(ee=Wt({inputs:{x:_},backend:r,attrs:{perm:[0,2,1]}}),E.push(ee));let re=m!==1,Y=m===1,ie=Z;re&&(ie=me({inputs:{x:Z},backend:r,attrs:{shape:[A,M,1]}}),E.push(ie));let ae=m===1?2:1,le=ee;Y&&(le=me({inputs:{x:ee},backend:r,attrs:{shape:[A,1,M]}}),E.push(le));let ue=R0({inputs:{a:ie,b:le},backend:r});q=Kf({inputs:{x:ue},backend:r,attrs:{axis:ae,keepDims:!0}}),E.push(ue)}else{let Z=ma(e.dtype,t.dtype),ee=new mC(v,k,[A,h,m],n,a, $ ,V,S,P),re=[T,_];if(s!=null&&re.push(s),S&&re.push(i),P){let Y=r.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));re.push(Y),E.push(Y)}q=r.runWebGLProgram(ee,re,Z)}let K=me({inputs:{x:q},backend:r,attrs:{shape:x}});E.push(q);for(let Z of E)r.disposeIntermediateTensorInfo(Z);return K}function aQ(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:d}=a;return tm({a:r,b:s,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:d,activation:p})}var rQ={kernelName:ni,backendName:"webgl",kernelFunc:aQ},Rk="return abs(x);";function sQ(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])&&a.dtype!=="complex64"){let s=n.texData.get(a.dataId),i=rC(s.values);return n.makeTensorInfo(a.shape,a.dtype,i)}let r;return X().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Qs(a.shape,Rk):r=new Sr(a.shape,Rk),n.runWebGLProgram(r,[a],a.dtype)}var iQ={kernelName:Tl,backendName:"webgl",kernelFunc:sQ},oQ=Ea+ `
2022-03-07 19:17:31 +01:00
if ( abs ( x ) > 1. ) {
return NAN ;
}
return acos ( x ) ;
2022-05-24 13:16:42 +02:00
` ,lQ=Qe({opSnippet:oQ}),uQ={kernelName:_l,backendName:"webgl",kernelFunc:lQ},pQ=Ea+ `
2022-03-07 19:17:31 +01:00
if ( x < 1.0 ) return NAN ;
2022-05-24 13:16:42 +02:00
return log ( x + sqrt ( x * x - 1.0 ) ) ; ` ,cQ=Qe({opSnippet:pQ}),dQ={kernelName:Cl,backendName:"webgl",kernelFunc:cQ},Mk="return a + b;",hQ=pn({opSnippet:Mk,packedOpSnippet:Mk,supportsComplex:!0,cpuKernelImpl:NY}),mQ={kernelName:hs,backendName:"webgl",kernelFunc:hQ},fQ=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((r,s)=> ` T$ { s } ` );let n=[];this.variableNames.forEach(r=>{n.push( ` float v$ { r } = get$ { r } AtOutCoords ( ) ; ` )});let a=this.variableNames.map(r=> ` v$ { r } ` ).join(" + ");this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { n . join ( `
` )}
float result = $ { a } ;
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }},gQ=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((r,s)=> ` T$ { s } ` );let n=[];this.variableNames.forEach(r=>{n.push( ` vec4 v$ { r } = get$ { r } AtOutCoords ( ) ; ` )});let a=this.variableNames.map(r=> ` v$ { r } ` ).join(" + ");this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { n . join ( `
` )}
vec4 result = $ { a } ;
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Nh(e){let{inputs:t,backend:n}=e,a=t;if(a.length===1)return na({inputs:{x:a[0]},backend:n});if(a.length>X().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(a.length/2),l=Nh({inputs:a.slice(0,o),backend:n}),u=Nh({inputs:a.slice(o),backend:n});return Nh({inputs:[l,u],backend:n})}let r=a.map(o=>o.dtype).reduce((o,l)=>ma(o,l)),s=a.map(o=>o.shape),i=X().getBool("WEBGL_PACK")?new gQ(a[0].shape,s):new fQ(a[0].shape,s);return n.runWebGLProgram(i,a,r)}var yQ={kernelName:vi,backendName:"webgl",kernelFunc:Nh};function bQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=C.getAxesPermutation(u,o),d=r;p!=null&&(d=Wt({inputs:{x:r},backend:n,attrs:{perm:p}}),u=C.getInnerMostAxes(u.length,o)),C.assertAxesAreInnerMostDims("all",u,o);let[c,h]=C.computeOutAndReduceShapes(d.shape,u),m=w.sizeFromShape(h),f=me({inputs:{x:d},backend:n,attrs:{shape:[-1,m]}}),g=No(f,f.dtype,"all",n),y;if(i){let b=C.expandShapeToKeepDim(c,l);y=me({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=me({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),p!=null&&n.disposeIntermediateTensorInfo(d),y}var xQ={kernelName:El,backendName:"webgl",kernelFunc:bQ};function vQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=C.getAxesPermutation(u,o),d=r;p!=null&&(d=Wt({inputs:{x:r},backend:n,attrs:{perm:p}}),u=C.getInnerMostAxes(u.length,o)),C.assertAxesAreInnerMostDims("any",u,o);let[c,h]=C.computeOutAndReduceShapes(d.shape,u),m=w.sizeFromShape(h),f=me({inputs:{x:d},backend:n,attrs:{shape:[-1,m]}}),g=No(f,f.dtype,"any",n),y;if(i){let b=C.expandShapeToKeepDim(c,l);y=me({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=me({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),p!=null&&n.disposeIntermediateTensorInfo(d),y}var wQ={kernelName:Fl,backendName:"webgl",kernelFunc:vQ},kQ=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:a,batchSize:r,outSize:s}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,s];let i=t==="max"?">":"<",o=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * $ { a } ;
int bestIndex = inOffset ;
float bestValue = getA ( batch , bestIndex ) ;
for ( int i = 0 ; i < $ { a } ; i ++ ) {
int inIdx = $ { o } ;
float candidate = getA ( batch , inIdx ) ;
if ( candidate $ { i } bestValue ) {
bestValue = candidate ;
bestIndex = inIdx ;
2021-03-26 15:26:02 +01:00
}
}
2022-03-07 19:17:31 +01:00
setOutput ( float ( bestIndex ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},IQ=class{constructor(e,t,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=> ` Packed arg$ { n . charAt ( 0 ) . toUpperCase ( ) + n . slice ( 1 ) } supports only inputs with rank above 2. ` );let r=e[e.length-1],s=Math.ceil(r/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),a||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=mt(o),u=Sn("coords",o),p,d;if(s===1){d=o+1;let _=mt(d);p= `
$ { _ } sourceLocR = $ { _ } ( $ { u . join ( ) } , 0 ) ;
2022-03-07 19:17:31 +01:00
++ $ { u [ o - 1 ] } ;
2022-05-24 13:16:42 +02:00
$ { _ } sourceLocG = $ { _ } ( $ { u . join ( ) } , 0 ) ;
2022-03-07 19:17:31 +01:00
++ $ { u [ o - 2 ] } ;
2022-05-24 13:16:42 +02:00
$ { _ } sourceLocA = $ { _ } ( $ { u . join ( ) } , 0 ) ;
2022-03-07 19:17:31 +01:00
-- $ { u [ o - 1 ] } ;
2022-05-24 13:16:42 +02:00
$ { _ } sourceLocB = $ { _ } ( $ { u . join ( ) } , 0 ) ;
2022-03-07 19:17:31 +01:00
-- $ { u [ o - 2 ] } ; ` }else d=o,p= `
$ { l } sourceLocR = coords ;
++ $ { u [ o - 1 ] } ;
$ { l } sourceLocG = coords ;
++ $ { u [ o - 2 ] } ;
$ { l } sourceLocA = coords ;
-- $ { u [ o - 1 ] } ;
$ { l } sourceLocB = coords ;
2022-05-24 13:16:42 +02:00
-- $ { u [ o - 2 ] } ; ` ;let c=["x","y","z","w","u","v"].slice(0,d),h="."+c[d-1],m=c.map(_=>"int "+_),f=Sn("sourceLocR",d-1).concat("inIdx.r"),g=Sn("sourceLocG",d-1).concat("inIdx.g"),y=Sn("sourceLocB",d-1).concat("inIdx.b"),b=Sn("sourceLocA",d-1).concat("inIdx.a"),x=n==="max"?"greaterThan":"lessThan",v=a?"": `
2022-03-07 19:17:31 +01:00
inIdx = round ( vec4 ( getBestIndicesAChannel ( $ { f . join ( ) } ) ,
getBestIndicesAChannel ( $ { g . join ( ) } ) ,
getBestIndicesAChannel ( $ { y . join ( ) } ) ,
2022-05-18 14:36:05 +02:00
getBestIndicesAChannel ( $ { b . join ( ) } ) ) ) ; ` ,k= ` vec4 (
2022-03-07 19:17:31 +01:00
getAChannel ( $ { f . join ( ) } ) ,
hasNextCol ? getAChannel ( $ { g . join ( ) } ) : 0. ,
hasNextRow ? getAChannel ( $ { y . join ( ) } ) : 0. ,
hasNextRow && hasNextCol ? getAChannel ( $ { b . join ( ) } ) : 0. ) ` ,T=a?"": `
float getBestIndicesAChannel ( $ { m . join ( ) } ) {
return getChannel ( getBestIndicesA ( $ { c . join ( ) } ) ,
vec2 ( $ { c . slice ( - 2 ) . join ( ) } ) ) ;
} ` ;this.userCode= `
float getAChannel ( $ { m . join ( ) } ) {
return getChannel ( getA ( $ { c . join ( ) } ) ,
vec2 ( $ { c . slice ( - 2 ) . join ( ) } ) ) ;
}
$ { T }
void main ( ) {
$ { l } coords = getOutputCoords ( ) ;
bool hasNextCol = $ { u [ o - 1 ] } < $ { i [ o - 1 ] - 1 } ;
bool hasNextRow = $ { u [ o - 2 ] } < $ { i [ o - 2 ] - 1 } ;
$ { p }
ivec4 srcIdx = ivec4 ( sourceLocR$ { h } , sourceLocG$ { h } ,
sourceLocB$ { h } , sourceLocA$ { h } ) * $ { t } ;
ivec4 inIdx = srcIdx ;
vec4 bestIndex = vec4 ( inIdx ) ;
2022-05-18 14:36:05 +02:00
vec4 bestValue = $ { k } ;
2022-03-07 19:17:31 +01:00
for ( int i = 0 ; i < $ { t } ; i ++ ) {
inIdx = srcIdx ;
$ { v }
2022-05-18 14:36:05 +02:00
vec4 candidate = $ { k } ;
2022-03-07 19:17:31 +01:00
bvec4 nan = isnan ( candidate ) ;
bvec4 replace = bvec4 (
vec4 ( $ { x } ( candidate , bestValue ) ) * ( vec4 ( 1.0 ) - vec4 ( nan ) ) ) ;
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 ++ ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( bestIndex ) ;
}
2022-05-24 13:16:42 +02:00
` }};function gC(e,t,n,a=null){let r=t.shape[0],s=t.shape[1];a!=null&&(r=a.shape[0],s=a.shape[1]);let i=C.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new kQ(o,n,a==null),u=[t];a!=null&&u.push(a);let p=e.runWebGLProgram(l,u,"int32");if(p.shape[1]===1)return p;let d=gC(e,t,n,p);return e.disposeIntermediateTensorInfo(p),d}function yC(e,t,n,a=null){let r=a!=null?a.shape:t.shape,s=r[r.length-1],i=C.computeOptimalWindowSize(s),o=new IQ(r,i,n,a==null),l=a==null?[t]:[t,a],u=e.runWebGLProgram(o,l,"int32");if(u.shape.length===t.shape.length){let p=yC(e,t,n,u);return e.disposeIntermediateTensorInfo(u),p}return u}function bC(e,t,n,a){let r=[n];if(C.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),r,t.shape.length),!X().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],i=e.texData.get(t.dataId),o=i!==null&&i.isPacked,l=t;o&&(l=e.unpackTensor(t),s.push(l));let[u,p]=C.computeOutAndReduceShapes(l.shape,r),d=w.sizeFromShape(p),c=me({inputs:{x:l},backend:e,attrs:{shape:[-1,d]}});s.push(c);let h=gC(e,c,a);s.push(h);let m=me({inputs:{x:h},backend:e,attrs:{shape:u}});return s.forEach(f=>e.disposeIntermediateTensorInfo(f)),m}return yC(e,t,a)}function SQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=w.parseAxisParam(s,r.shape),o=C.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Wt({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let p=bC(n,l,i[0],"max");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),p}var NQ={kernelName:wi,backendName:"webgl",kernelFunc:SQ};function TQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=w.parseAxisParam(s,r.shape),o=C.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Wt({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let p=bC(n,l,i[0],"min");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),p}var _Q={kernelName:cc,backendName:"webgl",kernelFunc:TQ},CQ=Ea+ `
2022-03-07 19:17:31 +01:00
if ( abs ( x ) > 1. ) {
return NAN ;
}
return asin ( x ) ;
2022-05-24 13:16:42 +02:00
` ,EQ=Qe({opSnippet:CQ}),FQ={kernelName:Al,backendName:"webgl",kernelFunc:EQ},AQ=Ea+"return log(x + sqrt(x * x + 1.0));", $ Q=Qe({opSnippet:AQ}),DQ={kernelName: $ l,backendName:"webgl",kernelFunc: $ Q},RQ=Ea+ `
2022-03-07 19:17:31 +01:00
return atan ( x ) ;
2022-05-24 13:16:42 +02:00
` ,MQ=Qe({opSnippet:RQ}),PQ={kernelName:Dl,backendName:"webgl",kernelFunc:MQ},OQ=G9+ `
2022-03-07 19:17:31 +01:00
return atan ( a , b ) ;
2022-05-24 13:16:42 +02:00
` ,LQ= `
2022-03-07 19:17:31 +01:00
vec4 result = atan ( a , b ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2022-05-24 13:16:42 +02:00
` +H9+ `
2022-03-07 19:17:31 +01:00
return result ;
2022-05-24 13:16:42 +02:00
` ,zQ=pn({opSnippet:OQ,packedOpSnippet:LQ}),BQ={kernelName:Ml,backendName:"webgl",kernelFunc:zQ},WQ=Ea+ `
2022-03-07 19:17:31 +01:00
if ( ( x < - 1.0 ) || ( x > 1.0 ) ) return NAN ;
2022-05-24 13:16:42 +02:00
return ( log ( 1.0 + x ) - log ( 1.0 - x ) ) / 2.0 ; ` ,VQ=Qe({opSnippet:WQ}),UQ={kernelName:Rl,backendName:"webgl",kernelFunc:VQ},oc=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,c=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let m=t==="avg",f= ` ( ( batch * $ { e . inHeight } + xR ) * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,g= ` ( xR * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,y="0.0";if(m||(y="-1.0 / 1e-20"),n){let _=">=";this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec2 strides = ivec2 ( $ { i } , $ { o } ) ;
const ivec2 pads = ivec2 ( $ { c } , $ { h } ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
float avgValue = 0.0 ;
for ( int wR = 0 ; wR < $ { p } ;
wR += $ { l } ) {
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int wC = 0 ; wC < $ { d } ;
wC += $ { u } ) {
int xC = xCCorner + wC ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float value = getX ( batch , xR , xC , d ) ;
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
2022-05-24 13:16:42 +02:00
if ( value $ { _ } currMinMaxValue ) {
2022-03-07 19:17:31 +01:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
minMaxPosition = $ { a ? r ? f : g : ` wR * ${ d } + wC ` } ;
}
2021-05-18 14:11:17 +02:00
}
}
2022-03-07 19:17:31 +01:00
setOutput ( float ( minMaxPosition ) ) ;
2021-05-18 14:11:17 +02:00
}
2022-05-18 14:36:05 +02:00
` ;return}let b="max",x= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&(x="avgValue / count");let v=Math.floor(s/4)*4,k=s%4,T= `
2022-03-07 19:17:31 +01:00
if ( $ { m } ) {
avgValue += dot ( values , ones ) ;
} else {
minMaxValue = $ { b } ( values , minMaxValue ) ;
}
` ;this.userCode= `
const ivec2 strides = ivec2 ( $ { i } , $ { o } ) ;
const ivec2 pads = ivec2 ( $ { c } , $ { h } ) ;
const float initializationValue = $ { y } ;
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float count = 0.0 ;
float getValue ( int batch , int xR , int xC , int d ) {
if ( xC < 0 || xC >= $ { e . inWidth } ) {
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 ) ;
}
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4 ( $ { y } ) ;
float avgValue = 0.0 ;
count = 0.0 ;
for ( int wR = 0 ; wR < $ { p } ;
wR += $ { l } ) {
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int wC = 0 ; wC < $ { v } ; wC += 4 ) {
int xC = xCCorner + wC * $ { u } ;
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
getValue ( batch , xR , xC + $ { u } , d ) ,
getValue ( batch , xR , xC + 2 * $ { u } , d ) ,
getValue ( batch , xR , xC + 3 * $ { u } , d )
) ;
$ { T }
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
int xC = xCCorner + $ { v } ;
2022-05-18 14:36:05 +02:00
if ( $ { k === 1 } ) {
2022-03-07 19:17:31 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
$ { T }
2022-05-18 14:36:05 +02:00
} else if ( $ { k === 2 } ) {
2022-03-07 19:17:31 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
getValue ( batch , xR , xC + $ { u } , d ) ,
initializationValue ,
initializationValue
) ;
$ { T }
2022-05-18 14:36:05 +02:00
} else if ( $ { k === 3 } ) {
2022-03-07 19:17:31 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
getValue ( batch , xR , xC + $ { u } , d ) ,
getValue ( batch , xR , xC + 2 * $ { u } , d ) ,
initializationValue
) ;
$ { T }
2021-04-01 19:39:54 +02:00
}
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( $ { x } ) ;
}
2022-05-24 13:16:42 +02:00
` }},M0=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,p=e.dilationHeight,d=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let b=t==="avg",x="0.0";if(b||(x="-1.0 / 1e-20"),n){let A=">=";this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec3 strides =
ivec3 ( $ { i } , $ { o } , $ { l } ) ;
const ivec3 pads = ivec3 ( $ { f } , $ { g } , $ { y } ) ;
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
for ( int wD = 0 ; wD < $ { c } ;
wD += $ { u } ) {
int xD = xDCorner + wD ;
if ( xD < 0 || xD >= $ { e . inDepth } ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int wR = 0 ; wR < $ { h } ;
wR += $ { p } ) {
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
for ( int wC = 0 ; wC < $ { m } ;
wC += $ { d } ) {
int xC = xCCorner + wC ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float value = getX ( batch , xD , xR , xC , ch ) ;
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
2022-05-18 14:36:05 +02:00
if ( value $ { A } currMinMaxValue ) {
2022-03-07 19:17:31 +01:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
minMaxPosition = $ { a ? r ? ` (((batch * ${ e . inDepth } + xD) * ${ e . inHeight } + xR) * ${ e . inWidth } + xC) * ${ e . inChannels } + ch ` : ` ((xD * ${ e . inHeight } + xR) * ${ e . inWidth } + xC) * ${ e . inChannels } + ch ` : ` wD * ${ h } * ${ m } +
wR * $ { m } + wC ` };
2021-05-18 14:11:17 +02:00
}
}
}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( float ( minMaxPosition ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-05-24 13:16:42 +02:00
` ;return}let v="max",k= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&(k="avgValue / count");let T=Math.floor(s/4)*4,_=s%4,E= `
2022-03-07 19:17:31 +01:00
if ( $ { b } ) {
avgValue += dot ( values , ones ) ;
} else {
minMaxValue = $ { v } ( values , minMaxValue ) ;
}
` ;this.userCode= `
const ivec3 strides =
ivec3 ( $ { i } , $ { o } , $ { l } ) ;
const ivec3 pads = ivec3 ( $ { f } , $ { g } , $ { y } ) ;
const float initializationValue = $ { x } ;
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float count = 0.0 ;
float getValue ( int batch , int xD , int xR , int xC , int ch ) {
if ( xC < 0 || xC >= $ { e . inWidth } ) {
return initializationValue ;
2021-03-26 15:26:02 +01:00
}
2022-03-07 19:17:31 +01:00
count += 1.0 ;
return getX ( batch , xD , xR , xC , ch ) ;
}
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4 ( $ { x } ) ;
float avgValue = 0.0 ;
count = 0.0 ;
for ( int wD = 0 ; wD < $ { c } ;
wD += $ { u } ) {
int xD = xDCorner + wD ;
if ( xD < 0 || xD >= $ { e . inDepth } ) {
continue ;
}
for ( int wR = 0 ; wR < $ { h } ;
wR += $ { p } ) {
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2021-05-18 14:11:17 +02:00
continue ;
}
2022-03-07 19:17:31 +01:00
for ( int wC = 0 ; wC < $ { T } ; wC += 4 ) {
int xC = xCCorner + wC * $ { d } ;
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
getValue ( batch , xD , xR , xC + $ { d } , ch ) ,
getValue ( batch , xD , xR , xC + 2 * $ { d } , ch ) ,
getValue ( batch , xD , xR , xC + 3 * $ { d } , ch )
) ;
2022-04-01 15:16:17 +02:00
$ { E }
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
int xC = xCCorner + $ { T } ;
2022-05-24 13:16:42 +02:00
if ( $ { _ === 1 } ) {
2022-03-07 19:17:31 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2022-04-01 15:16:17 +02:00
$ { E }
2022-05-24 13:16:42 +02:00
} else if ( $ { _ === 2 } ) {
2022-03-07 19:17:31 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
getValue ( batch , xD , xR , xC + $ { d } , ch ) ,
initializationValue ,
initializationValue
) ;
2022-04-01 15:16:17 +02:00
$ { E }
2022-05-24 13:16:42 +02:00
} else if ( $ { _ === 3 } ) {
2022-03-07 19:17:31 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
getValue ( batch , xD , xR , xC + $ { d } , ch ) ,
getValue ( batch , xD , xR , xC + 2 * $ { d } , ch ) ,
initializationValue
) ;
2022-04-01 15:16:17 +02:00
$ { E }
2021-05-18 14:11:17 +02:00
}
}
2022-05-18 14:36:05 +02:00
setOutput ( $ { k } ) ;
2021-03-26 15:26:02 +01:00
}
2022-03-07 19:17:31 +01:00
}
2022-05-24 13:16:42 +02:00
` }};function GQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;Wu(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(C.eitherStridesOrDilationsAreOne(i,u),()=> ` Error in avgPool : Either strides or dilations must be 1. Got strides $ { i } and dilations '${u}' ` );let p=C.computePool2DInfo(r.shape,s,i,u,o,l);if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))return na({inputs:{x:r},backend:n});let d=new oc(p,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var HQ={kernelName:ki,backendName:"webgl",kernelFunc:GQ};function jQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a,p=[1,1,1],d=C.computePool3DInfo(r.shape,s,i,p,o,l,u),c=new M0(d,"avg",!1);return n.runWebGLProgram(c,[r],"float32")}var qQ={kernelName:dc,backendName:"webgl",kernelFunc:jQ},KQ=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,p=l-1-e.padInfo.left,d=1/(t*n);this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec2 pads = ivec2 ( $ { u } , $ { p } ) ;
const float avgMultiplier = float ( $ { d } ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < $ { o } ;
wR += $ { s } ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
int idyR = int ( dyR ) ;
for ( int wC = 0 ; wC < $ { l } ;
wC += $ { i } ) {
float dyC = float ( dyCCorner + wC ) / $ { r } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
int idyC = int ( dyC ) ;
float dyValue = getDy ( b , idyR , idyC , d ) ;
dotProd += dyValue * avgMultiplier ;
2021-05-18 14:11:17 +02:00
}
}
2022-03-07 19:17:31 +01:00
setOutput ( dotProd ) ;
}
2022-05-24 13:16:42 +02:00
` }},XQ=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,p=e.effectiveFilterDepth,d=e.effectiveFilterHeight,c=e.effectiveFilterWidth,h=p-1-e.padInfo.front,m=d-1-e.padInfo.top,f=c-1-e.padInfo.left,g=1/(t*n*a);this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec3 pads = ivec3 ( $ { h } , $ { m } , $ { f } ) ;
const float avgMultiplier = float ( $ { g } ) ;
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wD = 0 ; wD < $ { p } ;
wD += $ { o } ) {
float dyD = float ( dyDCorner + wD ) / $ { r } . 0 ;
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
int idyD = int ( dyD ) ;
for ( int wR = 0 ; wR < $ { d } ;
wR += $ { l } ) {
float dyR = float ( dyRCorner + wR ) / $ { s } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
fract ( dyR ) > 0.0 ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
int idyR = int ( dyR ) ;
for ( int wC = 0 ; wC < $ { c } ;
wC += $ { u } ) {
float dyC = float ( dyCCorner + wC ) / $ { i } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
2021-05-18 14:11:17 +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-05-18 14:11:17 +02:00
}
}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( dotProd ) ;
}
2022-05-24 13:16:42 +02:00
` }};function YQ(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:p}=a,d=[1,1,1],c=C.computePool3DInfo(i.shape,o,l,d,u,p),h=new XQ(c);return n.runWebGLProgram(h,[r],i.dtype)}var QQ={kernelName:lm,backendName:"webgl",kernelFunc:YQ};function JQ(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;Wu([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=a,p=C.computePool2DInfo(i.shape,o,l,1,u),d=new KQ(p);return n.runWebGLProgram(d,[r],i.dtype)}var ZQ={kernelName:om,backendName:"webgl",kernelFunc:JQ};function eJ(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;return tm({a:r,b:s,transposeA:i,transposeB:o,backend:n})}var tJ={kernelName:Ii,backendName:"webgl",kernelFunc:eJ},nJ=class{constructor(e,t,n,a,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,n);let i="0.0";a!=null&&(C.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(C.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
float x = getXAtOutCoords ( ) ;
float mean = getMeanAtOutCoords ( ) ;
float variance = getVarianceAtOutCoords ( ) ;
float offset = $ { i } ;
float scale = $ { o } ;
float inv = scale * inversesqrt ( variance + float ( $ { s } ) ) ;
setOutput ( dot ( vec3 ( x , - mean , offset ) , vec3 ( inv , inv , 1 ) ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},aJ=class{constructor(e,t,n,a,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";a!=null&&(C.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(C.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
vec4 offset = $ { i } ;
vec4 scale = $ { o } ;
vec4 x = getXAtOutCoords ( ) ;
vec4 mean = getMeanAtOutCoords ( ) ;
vec4 variance = getVarianceAtOutCoords ( ) ;
vec4 inv = scale * inversesqrt ( variance + vec4 ( $ { s } ) ) ;
setOutput ( ( x - mean ) * inv + offset ) ;
}
2022-05-24 13:16:42 +02:00
` }},rJ=({inputs:e,backend:t,attrs:n})=>{let{x:a,mean:r,variance:s,offset:i,scale:o}=e;w.assert(r.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;l==null&&(l=.001);let u=[a,r,s],p=null;i!=null&&(p=i.shape,u.push(i));let d=null;o!=null&&(d=o.shape,u.push(o));let c=X().getBool("WEBGL_PACK_NORMALIZATION")?new aJ(a.shape,r.shape,s.shape,p,d,l):new nJ(a.shape,r.shape,s.shape,p,d,l);return t.runWebGLProgram(c,u,u[0].dtype)},sJ={kernelName:Oi,backendName:"webgl",kernelFunc:rJ},iJ=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=mt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=oJ(this.rank),a,r=e.map((s,i)=> ` sourceLoc . $ { hx [ i ] } = start [ $ { i } ] + coords . $ { hx [ i ] } ; ` );a= `
2022-03-07 19:17:31 +01:00
$ { t } sourceLoc ;
$ { t } coords = getOutputCoords ( ) ;
$ { r . join ( `
` )}
` ,this.userCode= `
void main ( ) {
$ { a }
setOutput ( getSource ( $ { n } ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},hx=["x","y","z","w","u","v"];function oJ(e){if(e===1)return"sourceLoc";if(e<=6)return hx.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error( ` Slicing for rank $ { e } is not yet supported ` )}var lJ=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=mt(this.rank),n=Sn("coords",this.rank),a=Sn("sourceLoc",this.rank),r=this.rank===1?"sourceLoc": ` vec2 ( $ { a . slice ( - 2 ) . join ( ) } ) ` ,s= ` getChannel ( getSource ( $ { a . join ( ) } ) , $ { r } ) ` ,i= `
2022-03-07 19:17:31 +01:00
result . x = $ { s } ;
if ( ++ $ { n [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
++ $ { a [ this . rank - 1 ] } ;
result . y = $ { s } ;
-- $ { a [ this . rank - 1 ] } ;
}
` ,o=this.rank===1?"": `
-- $ { n [ this . rank - 1 ] } ;
if ( ++ $ { n [ this . rank - 2 ] } < $ { e [ this . rank - 2 ] } ) {
++ $ { a [ this . rank - 2 ] } ;
result . z = $ { s } ;
if ( ++ $ { n [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
++ $ { a [ this . rank - 1 ] } ;
result . w = $ { s } ;
}
}
` ,l=this.rank<=4? ` sourceLoc = coords +
$ { t } ( $ { e . map ( ( u , p ) => ` start[ ${ p } ] ` ) . join ( ) } ) ; ` :e.map((u,p)=> ` $ { a [ p ] } = $ { n [ p ] } + start [ $ { p } ] ; ` ).join( `
` );this.userCode= `
void main ( ) {
$ { t } coords = getOutputCoords ( ) ;
$ { t } sourceLoc ;
$ { l }
vec4 result = vec4 ( 0. ) ;
$ { i }
$ { o }
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }};function uJ(e,t,n,a){let r=a.texData.get(e.dataId),s=a.makeTensorInfo(n,e.dtype),i=a.texData.get(s.dataId);Object.assign(i,r),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=Kt.computeFlatOffset(t,w.computeStrides(e.shape));r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};let l=a.dataRefCount.get(i.slice.origDataId)||1;return a.dataRefCount.set(i.slice.origDataId,l+1),s}function qu(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a,[o,l]=Kt.parseSliceParams(r,s,i);if(Kt.assertParamsValid(r,o,l),w.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||r.dtype==="string"){let d=n.texData.get(r.dataId),c=JY(d.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,c)}let{isPacked:u}=n.texData.get(r.dataId),p=Kt.isSliceContinous(r.shape,o,l);if(u||!p){let d=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new lJ(l):new iJ(l),c=[o];return n.runWebGLProgram(d,[r],r.dtype,c)}return n.uploadToGPU(r.dataId),uJ(r,o,l,n)}var pJ={kernelName:fu,backendName:"webgl",kernelFunc:qu},cJ=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;w.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((b,x)=>b*x),l=C.getReshaped(r.shape,s,o),u=C.getPermuted(l.length,s.length),p=C.getReshapedPermuted(r.shape,s,o),d=C.getSliceBeginCoords(i,s.length),c=C.getSliceSize(p,i,s.length),h=[],m=me({inputs:{x:r},backend:n,attrs:{shape:l}}),f=Wt({inputs:{x:m},backend:n,attrs:{perm:u}}),g=me({inputs:{x:f},backend:n,attrs:{shape:p}}),y=qu({inputs:{x:g},backend:n,attrs:{begin:d,size:c}});return h.push(m),h.push(f),h.push(g),h.forEach(b=>n.disposeIntermediateTensorInfo(b)),y},dJ={kernelName:Pl,backendName:"webgl",kernelFunc:cJ};function hJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i}=a,o=n.readSync(r.dataId),l=n.readSync(s.dataId),u=aC(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}var mJ={kernelName:um,backendName:"webgl",kernelFunc:hJ};function fJ(e){let{inputs:t,backend:n}=e,{s0:a,s1:r}=t,s=n.readSync(a.dataId),i=n.readSync(r.dataId),o=C.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var gJ={kernelName:pm,backendName:"webgl",kernelFunc:fJ},yJ="return float(a != b);",xC=pn({opSnippet:yJ,cpuKernelImpl:jY,dtype:"bool"}),bJ={kernelName:ru,backendName:"webgl",kernelFunc:xC};function od(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return na({inputs:{x:r.complexTensorInfos.real},backend:n})}var xJ={kernelName:Fm,backendName:"webgl",kernelFunc:od},vJ="return float(int(x));";function wJ(e,t){let n=new Sr(e.shape,vJ),a=t.runWebGLProgram(n,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function mx(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return na({inputs:{x:r},backend:n});let i=St(r.shape),o=mx({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=Is({inputs:{real:o,imag:i},backend:n});return i.dispose(),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=od({inputs:{input:r},backend:n}),o=mx({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!w.hasEncodingLoss(r.dtype,s)){let i=na({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return wJ(r,n);if(s==="bool"){let i=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),o=xC({inputs:{a:r,b:i},backend:n});return n.disposeIntermediateTensorInfo(i),o}throw new Error( ` Error in Cast : failed to cast $ { r . dtype } to $ { s } ` )}var kJ={kernelName:Si,backendName:"webgl",kernelFunc:mx},Pk="return ceil(x);",IJ=Qe({opSnippet:Pk,packedOpSnippet:Pk,cpuKernelImpl:_Y}),SJ={kernelName:Ni,backendName:"webgl",kernelFunc:IJ},NJ=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
float value = getAAtOutCoords ( ) ;
if ( isnan ( value ) ) {
setOutput ( value ) ;
return ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( clamp ( value , minVal , maxVal ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},TJ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
vec4 value = getAAtOutCoords ( ) ;
if ( any ( isnan ( value ) ) ) {
setOutput ( value ) ;
return ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( clamp ( value , vec4 ( minVal ) , vec4 ( maxVal ) ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function _J(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o;X().getBool("WEBGL_PACK_CLIP")?o=new TJ(r.shape):o=new NJ(r.shape);let l=[[s],[i]];return n.runWebGLProgram(o,[r],r.dtype,l)}var CJ={kernelName:ms,backendName:"webgl",kernelFunc:_J},EJ=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
float re = abs ( getRealAtOutCoords ( ) ) ;
float im = abs ( getImagAtOutCoords ( ) ) ;
float mx = max ( re , im ) ;
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput (
mx == 0.0 ? 0.0 : mx * length ( vec2 ( 1 , min ( re , im ) / mx ) )
) ;
}
2022-05-24 13:16:42 +02:00
` }};function Ok(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function FJ(e){let{inputs:t,backend:n}=e,{x:a}=t,r=n.texData.get(a.dataId),s=new EJ(a.shape),i=[Ok(a,r.complexTensorInfos.real),Ok(a,r.complexTensorInfos.imag)];return n.runWebGLProgram(s,i,i[0].dtype)}var AJ={kernelName:hc,backendName:"webgl",kernelFunc:FJ}, $ J=class{constructor(e){this.outputShape=[],this.outputShape=C.computeOutShape(e,1),this.variableNames=e.map((s,i)=> ` T$ { i } ` );let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];let n=[ ` if ( yC < $ { t [ 0 ] } ) setOutput ( getT0 ( yR , yC ) ) ; ` ];for(let s=1;s<t.length;s++){let i=t[s-1];n.push( ` else if ( yC < $ { t [ s ] } ) setOutput ( getT$ { s } ( yR , yC - $ { i } ) ) ; ` )}let a=t.length,r=t[t.length-1];n.push( ` else setOutput ( getT$ { a } ( yR , yC - $ { r } ) ) ; ` ),this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int yR = coords . x ;
int yC = coords . y ;
$ { n . join ( `
` )}
}
2022-05-24 13:16:42 +02:00
` }},DJ=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=C.computeOutShape(e,t);let n=this.outputShape,a=n.length,r=mt(a),s=Sn("coords",a),i=["x","y","z","w","u","v"].slice(0,a);this.variableNames=e.map((m,f)=> ` T$ { f } ` );let o=new Array(e.length-1);o[0]=e[0][t];for(let m=1;m<o.length;m++)o[m]=o[m-1]+e[m][t];let l=i[t],u=i.slice(-2),p=i.join(),d= ` if ( $ { l } < $ { o [ 0 ] } ) {
2022-03-07 19:17:31 +01:00
return getChannel (
getT0 ( $ { p } ) , vec2 ( $ { u . join ( ) } ) ) ;
} ` ;for(let m=1;m<o.length;m++){let f=o[m-1];d+= `
if ( $ { l } < $ { o [ m ] } && $ { l } >= $ { o [ m - 1 ] } ) {
return getChannel (
2022-05-24 13:16:42 +02:00
getT$ { m } ( $ { mh ( i , l , f ) } ) ,
vec2 ( $ { mh ( u , l , f ) } ) ) ;
2022-03-07 19:17:31 +01:00
} ` }let c=o.length,h=o[o.length-1];d+= `
return getChannel (
2022-05-24 13:16:42 +02:00
getT$ { c } ( $ { mh ( i , l , h ) } ) ,
vec2 ( $ { mh ( u , l , h ) } ) ) ; ` ,this.userCode= `
2022-03-07 19:17:31 +01:00
float getValue ( $ { i . map ( m => "int " + m ) } ) {
$ { d }
}
void main ( ) {
$ { r } coords = getOutputCoords ( ) ;
vec4 result = vec4 ( getValue ( $ { s } ) , 0. , 0. , 0. ) ;
$ { s [ a - 1 ] } = $ { s [ a - 1 ] } + 1 ;
if ( $ { s [ a - 1 ] } < $ { n [ a - 1 ] } ) {
result . g = getValue ( $ { s } ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
$ { s [ a - 2 ] } = $ { s [ a - 2 ] } + 1 ;
if ( $ { s [ a - 2 ] } < $ { n [ a - 2 ] } ) {
result . a = getValue ( $ { s } ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
$ { s [ a - 1 ] } = $ { s [ a - 1 ] } - 1 ;
if ( $ { s [ a - 2 ] } < $ { n [ a - 2 ] } &&
$ { s [ a - 1 ] } < $ { n [ a - 1 ] } ) {
result . b = getValue ( $ { s } ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }};function mh(e,t,n){let a=e.indexOf(t);return e.map((r,s)=>s===a? ` $ { r } - $ { n } ` :r).join()}function Xf(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return na({inputs:{x:r.complexTensorInfos.imag},backend:n})}var RJ={kernelName:Im,backendName:"webgl",kernelFunc:Xf};function nl(e,t,n){let a=e[0].dtype;if(a==="complex64"){let p=e.map(f=>od({inputs:{input:f},backend:n})),d=e.map(f=>Xf({inputs:{input:f},backend:n})),c=nl(p,t,n),h=nl(d,t,n),m=Is({inputs:{real:c,imag:h},backend:n});return p.forEach(f=>n.disposeIntermediateTensorInfo(f)),d.forEach(f=>n.disposeIntermediateTensorInfo(f)),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),m}let r=n.shouldExecuteOnCPU(e);if(a==="string"&&(r=!0),r){let p=e.map(y=>{let b=w.sizeFromShape(y.shape.slice(t));return me({inputs:{x:y},backend:n,attrs:{shape:[-1,b]}})}),d=p.map(y=>({vals:n.readSync(y.dataId),shape:y.shape})),c=C.computeOutShape(p.map(y=>y.shape),1),h=p[0].shape[0]===1,m=CY(d,c,a,h),f=C.computeOutShape(e.map(y=>y.shape),t),g=n.makeTensorInfo(f,a,m);return p.forEach(y=>n.disposeIntermediateTensorInfo(y)),g}if(e.length>X().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let p=Math.floor(e.length/2),d=nl(e.slice(0,p),t,n),c=nl(e.slice(p),t,n),h=nl([d,c],t,n);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),h}if(X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let p=new DJ(e.map(d=>d.shape),t);return n.runWebGLProgram(p,e,a)}let{tensors2D:s,outShape:i}=MJ(e,t,n),o=new $ J(s.map(p=>p.shape)),l=n.runWebGLProgram(o,s,a);s.forEach(p=>n.disposeIntermediateTensorInfo(p));let u=me({inputs:{x:l},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(l),u}function MJ(e,t,n){let a=C.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>me({inputs:{x:r},attrs:{shape:[-1,w.sizeFromShape(r.shape.slice(t))]},backend:n})),outShape:a}}function vC(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=w.parseAxisParam(r,t[0].shape)[0],i=C.computeOutShape(t.map(u=>u.shape),s);if(w.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(u=>w.sizeFromShape(u.shape)>0);if(o.length===1)return na({inputs:{x:o[0]},backend:n});let l=o.map(u=>u.shape);return C.assertParamsConsistent(l,s),nl(o,s,n)}var PJ={kernelName:Ol,backendName:"webgl",kernelFunc:vC},wC=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,p=e.dilationWidth,d=e.filterHeight,c=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4,f=e.dataFormat==="channelsLast",g=f?1:2,y=f?2:3,b=f?3:1,x="",v="";n&&(a?x= ` float activation ( float a ) {
2022-03-07 19:17:31 +01:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
} ` :r?x= ` float activation ( float a ) {
float b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
} ` :x= `
float activation ( float x ) {
$ { n }
2021-05-18 14:11:17 +02:00
}
2022-05-18 14:36:05 +02:00
` ,v="result = activation(result);");let k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
2022-03-07 19:17:31 +01:00
$ { x }
const ivec2 strides = ivec2 ( $ { o } , $ { l } ) ;
const ivec2 pads = ivec2 ( $ { s } , $ { i } ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d2 = coords [ $ { b } ] ;
ivec2 xRCCorner =
ivec2 ( coords [ $ { g } ] , coords [ $ { y } ] ) * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < $ { d } ; wR ++ ) {
int xR = xRCorner + wR * $ { u } ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int wC = 0 ; wC < $ { c } ; wC ++ ) {
int xC = xCCorner + wC * $ { p } ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
2020-10-12 20:28:19 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int d1 = 0 ; d1 < $ { h } ; 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 )
) ;
if ( $ { f } ) {
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-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
if ( $ { m === 1 } ) {
if ( $ { f } ) {
dotProd +=
getX ( batch , xR , xC , $ { h } ) *
getW ( wR , wC , $ { h } , d2 ) ;
} else {
dotProd +=
getX ( batch , $ { h } , xR , xC ) *
getW ( wR , wC , $ { h } , d2 ) ;
}
} else if ( $ { m === 2 } ) {
vec2 wValues = vec2 (
getW ( wR , wC , $ { h } , d2 ) ,
getW ( wR , wC , $ { h } + 1 , d2 )
) ;
if ( $ { f } ) {
vec2 xValues = vec2 (
getX ( batch , xR , xC , $ { h } ) ,
getX ( batch , xR , xC , $ { h } + 1 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec2 xValues = vec2 (
getX ( batch , $ { h } , xR , xC ) ,
getX ( batch , $ { h } + 1 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
}
} else if ( $ { m === 3 } ) {
vec3 wValues = vec3 (
getW ( wR , wC , $ { h } , d2 ) ,
getW ( wR , wC , $ { h } + 1 , d2 ) ,
getW ( wR , wC , $ { h } + 2 , d2 )
) ;
if ( $ { f } ) {
vec3 xValues = vec3 (
getX ( batch , xR , xC , $ { h } ) ,
getX ( batch , xR , xC , $ { h } + 1 ) ,
getX ( batch , xR , xC , $ { h } + 2 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec3 xValues = vec3 (
getX ( batch , $ { h } , xR , xC ) ,
getX ( batch , $ { h } + 1 , xR , xC ) ,
getX ( batch , $ { h } + 2 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
2021-05-18 14:11:17 +02:00
}
}
}
2022-03-07 19:17:31 +01:00
float result = dotProd ;
2022-05-18 14:36:05 +02:00
$ { k }
2022-03-07 19:17:31 +01:00
$ { v }
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }},OJ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,a=e.padInfo.left,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,p=e.filterDepth,d=e.filterHeight,c=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec3 strides = ivec3 ( $ { r } , $ { s } , $ { i } ) ;
const ivec3 pads = ivec3 ( $ { t } , $ { n } , $ { a } ) ;
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d2 = coords . u ;
ivec3 xFRCCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xFCorner = xFRCCorner . x ;
int xRCorner = xFRCCorner . y ;
int xCCorner = xFRCCorner . z ;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0 ;
for ( int wF = 0 ; wF < $ { p } ; wF ++ ) {
int xF = xFCorner + wF * $ { o } ;
if ( xF < 0 || xF >= $ { e . inDepth } ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int wR = 0 ; wR < $ { d } ; wR ++ ) {
int xR = xRCorner + wR * $ { l } ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int wC = 0 ; wC < $ { c } ; wC ++ ) {
int xC = xCCorner + wC * $ { u } ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
for ( int d1 = 0 ; d1 < $ { h } ; 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 )
) ;
dotProd += dot ( xValues , wValues ) ;
}
if ( $ { m === 1 } ) {
dotProd +=
getX ( batch , xF , xR , xC , $ { h } ) *
getW ( wF , wR , wC , $ { h } , d2 ) ;
} else if ( $ { m === 2 } ) {
vec2 xValues = vec2 (
getX ( batch , xF , xR , xC , $ { h } ) ,
getX ( batch , xF , xR , xC , $ { h } + 1 )
) ;
vec2 wValues = vec2 (
getW ( wF , wR , wC , $ { h } , d2 ) ,
getW ( wF , wR , wC , $ { h } + 1 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else if ( $ { m === 3 } ) {
vec3 xValues = vec3 (
getX ( batch , xF , xR , xC , $ { h } ) ,
getX ( batch , xF , xR , xC , $ { h } + 1 ) ,
getX ( batch , xF , xR , xC , $ { h } + 2 )
) ;
vec3 wValues = vec3 (
getW ( wF , wR , wC , $ { h } , d2 ) ,
getW ( wF , wR , wC , $ { h } + 1 , d2 ) ,
getW ( wF , wR , wC , $ { h } + 2 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
}
2021-05-18 14:11:17 +02:00
}
}
}
2022-03-07 19:17:31 +01:00
setOutput ( dotProd ) ;
}
2022-05-24 13:16:42 +02:00
` }},LJ=class{constructor(e,t){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=e,this.enableShapeUniforms=Hn(this.outputShape.length);let{dataFormat:n}=t,a=Cn(),r=n==="channelsLast",s=r?0:1,i=r?1:2,o=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {": ` if ( blockIndex < $ { e [ 1 ] } && pos < $ { e [ 0 ] } ) { ` ,l="";for(let u=0;u<=1;u++)for(let p=0;p<=1;p++)l+= `
2022-03-07 19:17:31 +01:00
blockIndex = rc . y + $ { p } ;
pos = rc . x + $ { u } ;
$ { o }
offsetY = int ( blockIndex / outWidth ) * stride [ 0 ] - pad [ 0 ] ;
d0 = offsetY + dilation [ 0 ] * ( pos / itemsPerBlockRow ) ;
if ( d0 < inputShape [ $ { s } ] && d0 >= 0 ) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod ( blockIndex , outWidth ) * stride [ 1 ] - pad [ 1 ] ;
d1 = offsetX + dilation [ 1 ] * ( imod ( pos , itemsPerBlockRow ) /
inChannels ) ;
if ( d1 < inputShape [ $ { i } ] && d1 >= 0 ) {
ch = imod ( pos , inChannels ) ;
if ( $ { r } ) {
innerDims = vec2 ( d1 , ch ) ;
result [ $ { u * 2 + p } ] = getChannel (
getA ( d0 , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
} else {
innerDims = vec2 ( d0 , d1 ) ;
result [ $ { u * 2 + p } ] = getChannel (
getA ( ch , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
}
}
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
}
` ;this.userCode= `
void main ( ) {
ivec2 rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0 ) ;
int blockIndex , pos , offsetY , d0 , offsetX , d1 , ch ;
vec2 innerDims ;
$ { l }
$ { a . output } = result ;
}
2022-05-24 13:16:42 +02:00
` }};function kC({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,u=a.texData.get(e.dataId),p=n.inChannels,d=l[0]*l[1]*l[2],c=n.outChannels,h=n.dataFormat==="channelsLast",m=!1,f=!1,g,y=[];if(s!=null&&!h&&s.shape.length===3){let b=Wt({inputs:{x:s},backend:a,attrs:{perm:[1,2,0]}});y.push(b),s=b}if(!((d===1||c===1)&&p>fC)&&u.isPacked&&h&&u.texture!=null&&l[2]%2!==0&&w.arraysEqual(u.shape.slice(-3),l.slice(-3))){let b=l[0]*l[1]*(l[2]+1),x={dataId:e.dataId,shape:[1,b,n.inChannels],dtype:e.dtype},v=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,w.assert(ic(u.shape,x.shape),()=> ` packed reshape $ { u . shape } to $ { x . shape } isn ' t free ` );let k=me({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(k);let T=tm({a:x,b:k,backend:a,transposeA:m,transposeB:f,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),_=a.texData.get(T.dataId);w.assert(_.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=v,_.shape=n.outShape,g=na({inputs:{x:T},backend:a}),g.shape=n.outShape,y.push(T)}else{let b=h?e:Wt({inputs:{x:e},backend:a,attrs:{perm:[0,2,3,1]}}),x=b.shape,v=x[0]*x[1]*x[2],k=me({inputs:{x:b},backend:a,attrs:{shape:[1,v,n.inChannels]}}),T=me({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}}),_=tm({a:k,b:T,transposeA:m,transposeB:f,backend:a,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),E=[n.batchSize,n.outHeight,n.outWidth,n.outChannels],A=me({inputs:{x:_},backend:a,attrs:{shape:E}});g=h?A:Wt({inputs:{x:A},backend:a,attrs:{perm:[0,3,1,2]}}),h||(y.push(b),y.push(A)),y.push(k),y.push(T),y.push(_)}for(let b of y)a.disposeIntermediateTensorInfo(b);return g}function IC({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:u,inChannels:p,outWidth:d,outHeight:c,dataFormat:h}=n,m=h==="channelsLast",f=l*u*p,g=c*d,y=[f,g],b=!0,x=!1,v=[];if(s!=null&&!m&&s.shape.length===3){let Y=Wt({inputs:{x:s},backend:a,attrs:{perm:[1,2,0]}});v.push(Y),s=Y}let k=me({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),T=me({inputs:{x:t},backend:a,attrs:{shape:[1,f,w.sizeFromShape(t.shape)/f]}});v.push(k),v.push(T);let _=new LJ(y,n),E=[k.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],A=a.runWebGLProgram(_,[k],"float32",E),M=me({inputs:{x:A},backend:a,attrs:{shape:[1,y[0],y[1]]}});v.push(A),v.push(M);let $ =r!=null,S=s!=null,P=o==="leakyrelu",V=o?jf(o,!0):null,j=new mC(M.shape,T.shape,[1,g,n.outChannels],b,x, $ ,V,S,P),q=[M,T];if(r&&q.push(r),S&&q.push(s),P){let Y=a.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));q.push(Y),v.push(Y)}let K=a.runWebGLProgram(j,q,"float32"),Z=[1,c,d,n.outChannels],ee=me({inputs:{x:K},backend:a,attrs:{shape:Z}}),re=m?ee:Wt({inputs:{x:ee},backend:a,attrs:{perm:[0,3,1,2]}});m||v.push(ee),v.push(K);for(let Y of v)a.disposeIntermediateTensorInfo(Y);return re}function zJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:p}=a,d=C.convertConv2DDataFormat(l),c=C.computeConv2DInfo(r.shape,s.shape,i,u,o,p,!1,d),h;if(c.filterHeight===1&&c.filterWidth===1&&c.dilationHeight===1&&c.dilationWidth===1&&c.strideHeight===1&&c.strideWidth===1&&(c.padInfo.type==="SAME"||c.padInfo.type==="VALID"))h=kC({x:r,filter:s,convInfo:c,backend:n});else if(X().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)h=IC({x:r,filter:s,convInfo:c,backend:n});else{let f=new wC(c);h=n.runWebGLProgram(f,[r,s],"float32")}let m=me({inputs:{x:h},backend:n,attrs:{shape:c.outShape}});return n.disposeIntermediateTensorInfo(h),m}var BJ={kernelName:Ti,backendName:"webgl",kernelFunc:zJ},WJ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.dataFormat==="channelsLast";this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int d2 = coords . w ;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { t } - $ { a } ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { n } - $ { r } ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
if ( $ { s } ) {
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 ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
2021-05-18 14:11:17 +02:00
}
}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( dotProd ) ;
}
2022-05-24 13:16:42 +02:00
` }},VJ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,l=s?1:2,u=s?2:3,p=s?3:1;this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec2 pads = ivec2 ( $ { i } , $ { o } ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d1 = coords [ $ { p } ] ;
ivec2 dyCorner = ivec2 ( coords [ $ { l } ] , coords [ $ { u } ] ) - pads ;
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
int idyR = int ( dyR ) ;
int wRPerm = $ { t } - 1 - wR ;
for ( int wC = 0 ; wC < $ { n } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { r } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
int wCPerm = $ { n } - 1 - wC ;
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
if ( $ { s } ) {
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-05-18 14:11:17 +02:00
}
}
}
2022-03-07 19:17:31 +01:00
setOutput ( dotProd ) ;
}
2022-05-24 13:16:42 +02:00
` }},UJ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.padInfo.front,s=e.padInfo.top,i=e.padInfo.left;this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int wF = coords . x ;
int wR = coords . y ;
int wC = coords . z ;
int d1 = coords . w ;
int d2 = coords . u ;
float dotProd = 0.0 ;
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yF = 0 ; yF < $ { e . outDepth } ; yF ++ ) {
int xF = wF + yF * $ { t } - $ { r } ;
if ( xF < 0 || xF >= $ { e . inDepth } ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { n } - $ { s } ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { a } - $ { i } ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
2021-05-18 14:11:17 +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 ) ;
2021-03-31 13:01:22 +02:00
}
2021-05-18 14:11:17 +02:00
}
}
}
2022-03-07 19:17:31 +01:00
setOutput ( dotProd ) ;
}
2022-05-24 13:16:42 +02:00
` }},GJ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=a-1-e.padInfo.left;this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec3 pads = ivec3 ( $ { o } , $ { l } , $ { u } ) ;
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d1 = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyFCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
float dotProd = 0.0 ;
for ( int wF = 0 ; wF < $ { t } ; wF ++ ) {
float dyF = float ( dyFCorner + wF ) / $ { r } . 0 ;
if ( dyF < 0.0 || dyF >= $ { e . outDepth } . 0 || fract ( dyF ) > 0.0 ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
int idyF = int ( dyF ) ;
int wFPerm = $ { t } - 1 - wF ;
for ( int wR = 0 ; wR < $ { n } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { s } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
int wRPerm = $ { n } - 1 - wR ;
for ( int wC = 0 ; wC < $ { a } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { i } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
2021-05-18 14:11:17 +02:00
continue ;
}
2022-03-07 19:17:31 +01:00
int idyC = int ( dyC ) ;
int wCPerm = $ { a } - 1 - wC ;
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
float xValue = getDy ( batch , idyF , idyR , idyC , d2 ) ;
float wValue = getW ( wFPerm , wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
2021-05-18 14:11:17 +02:00
}
}
}
}
2022-03-07 19:17:31 +01:00
setOutput ( dotProd ) ;
}
2022-05-24 13:16:42 +02:00
` }};function HJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:p}=a,d=C.convertConv2DDataFormat(l),c=C.computeConv2DInfo(r.shape,p,i,1,o,u,!1,d),h=new WJ(c);return n.runWebGLProgram(h,[r,s],"float32")}var jJ={kernelName:dm,backendName:"webgl",kernelFunc:HJ};function qJ(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:p}=a,d=C.convertConv2DDataFormat(u),c=C.computeConv2DInfo(i,s.shape,o,1,l,p,!1,d),h=new VJ(c);return n.runWebGLProgram(h,[r,s],"float32")}var KJ={kernelName:_i,backendName:"webgl",kernelFunc:qJ};function XJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,u=C.computeConv3DInfo(r.shape,s.shape,i,l,o),p=new OJ(u);return n.runWebGLProgram(p,[r,s],"float32")}var YJ={kernelName:mc,backendName:"webgl",kernelFunc:XJ};function QJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a,u=C.computeConv3DInfo(r.shape,l,i,1,o),p=new UJ(u);return n.runWebGLProgram(p,[r,s],"float32")}var JJ={kernelName:hm,backendName:"webgl",kernelFunc:QJ};function ZJ(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a,u=C.computeConv3DInfo(l,s.shape,o,1,i),p=new GJ(u);return n.runWebGLProgram(p,[r,s],"float32")}var eZ={kernelName:mm,backendName:"webgl",kernelFunc:ZJ},tZ=ju+ `
2022-03-07 19:17:31 +01:00
return cos ( x ) ;
2022-05-24 13:16:42 +02:00
` ,nZ=Qe({opSnippet:tZ}),aZ={kernelName:Ci,backendName:"webgl",kernelFunc:nZ},rZ= `
2022-03-07 19:17:31 +01:00
float e2x = exp ( - x ) ;
return ( e2x + 1.0 / e2x ) / 2.0 ;
2022-05-24 13:16:42 +02:00
` ,sZ=Qe({opSnippet:rZ}),iZ={kernelName:Ei,backendName:"webgl",kernelFunc:sZ},oZ=class{constructor(e,t,n,a,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[u]=t,[p,d]=n;this.outputShape=[u,p,d,l];let c=a==="bilinear"?1:0,[h,m]=[ ` $ { i - 1 } . 0 ` , ` $ { o - 1 } . 0 ` ],[f,g,y]=p>1?[ ` $ { ( i - 1 ) / ( p - 1 ) } ` ,"(y2-y1) * height_ratio", ` y1 * $ { h } + float ( y ) * ( height _scale ) ` ]:["0.0","0.0", ` 0.5 * ( y1 + y2 ) * $ { h } ` ],[b,x,v]=d>1?[ ` $ { ( o - 1 ) / ( d - 1 ) } ` ,"(x2-x1) * width_ratio", ` x1 * $ { m } + float ( x ) * ( width _scale ) ` ]:["0.0","0.0", ` 0.5 * ( x1 + x2 ) * $ { m } ` ];this.userCode= `
2022-03-07 19:17:31 +01:00
const float height _ratio = float ( $ { f } ) ;
const float width _ratio = float ( $ { b } ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int y = coords [ 1 ] ;
int x = coords [ 2 ] ;
int d = coords [ 3 ] ;
// get box vals
float y1 = getBoxes ( b , 0 ) ;
float x1 = getBoxes ( b , 1 ) ;
float y2 = getBoxes ( b , 2 ) ;
float x2 = getBoxes ( b , 3 ) ;
// get image in batch index
int bInd = round ( getBoxInd ( b ) ) ;
if ( bInd < 0 || bInd >= $ { s } ) {
return ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
float height _scale = $ { g } ;
float width _scale = $ { x } ;
float in _y = $ { y } ;
if ( in _y < 0.0 || in _y > $ { h } ) {
setOutput ( float ( $ { r } ) ) ;
return ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
float in _x = $ { v } ;
if ( in _x < 0.0 || in _x > $ { m } ) {
setOutput ( float ( $ { r } ) ) ;
return ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
vec2 sourceFracIndexCR = vec2 ( in _x , in _y ) ;
if ( $ { c } == 1 ) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2 ( sourceFracIndexCR ) ;
ivec2 sourceCeilCR = ivec2 ( ceil ( sourceFracIndexCR ) ) ;
float topLeft = getImage ( b , sourceFloorCR . y , sourceFloorCR . x , d ) ;
float bottomLeft = getImage ( b , sourceCeilCR . y , sourceFloorCR . x , d ) ;
float topRight = getImage ( b , sourceFloorCR . y , sourceCeilCR . x , d ) ;
float bottomRight = getImage ( b , sourceCeilCR . y , sourceCeilCR . x , d ) ;
vec2 fracCR = sourceFracIndexCR - vec2 ( sourceFloorCR ) ;
float top = topLeft + ( topRight - topLeft ) * fracCR . x ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracCR . x ;
float newValue = top + ( bottom - top ) * fracCR . y ;
setOutput ( newValue ) ;
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2 ( floor (
sourceFracIndexCR + vec2 ( 0.5 , 0.5 ) ) ) ;
float newValue = getImage ( b , sourceNearestCR . y , sourceNearestCR . x , d ) ;
setOutput ( newValue ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
}
2022-05-24 13:16:42 +02:00
` }},lZ=e=>{let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=a,p=new oZ(r.shape,s.shape,o,l,u);return n.runWebGLProgram(p,[r,s,i],"float32")},uZ={kernelName:zl,backendName:"webgl",kernelFunc:lZ},lc;(function(e){e.Prod="*",e.Sum="+"})(lc||(lc={}));var Lk=class{constructor(e,t,n,a){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let r=this.outputShape.length,s=this.op===lc.Prod?"1.0":"0.0",i=n?s: ` getX ( $ { zk ( r , "coords" , this . op ) } ) ` ,o=this.outputShape[this.outputShape.length-1],l="",u="";n?(l=a? ` end != $ { o - 1 } ` :"end != 0",u=a?"end + 1":"end - 1"):(l=a? ` end + pow2 < $ { o } ` :"end >= pow2",u=a?"end + pow2":"end - pow2"),this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
2022-05-18 14:36:05 +02:00
$ { mt ( r ) } coords = getOutputCoords ( ) ;
2022-05-24 13:16:42 +02:00
int end = $ { Bk ( r , "coords" , this . op ) } ;
2022-05-18 14:36:05 +02:00
float val = $ { i } ;
2022-03-07 19:17:31 +01:00
int pow2 = int ( pow ( 2.0 , index ) ) ;
2022-05-18 14:36:05 +02:00
if ( $ { l } ) {
int idx = $ { u } ;
2022-05-24 13:16:42 +02:00
$ { Bk ( r , "coords" , this . op ) } = idx ;
val $ { this . op } = getX ( $ { zk ( r , "coords" , this . op ) } ) ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
setOutput ( val ) ;
}
2022-05-24 13:16:42 +02:00
` }};function zk(e,t,n){if(e===1)return ` $ { t } ` ;if(e===2)return ` $ { t } . x , $ { t } . y ` ;if(e===3)return ` $ { t } . x , $ { t } . y , $ { t } . z ` ;if(e===4)return ` $ { t } . x , $ { t } . y , $ { t } . z , $ { t } . w ` ;throw new Error( ` Cumulative $ { n } for rank $ { e } is not yet supported ` )}function Bk(e,t,n){if(e===1)return ` $ { t } ` ;if(e===2)return ` $ { t } . y ` ;if(e===3)return ` $ { t } . z ` ;if(e===4)return ` $ { t } . w ` ;throw new Error( ` Cumulative $ { n } for rank $ { e } is not yet supported ` )}function SC(e,t,n,a,r,s){let i=t.shape.length,o=C.getAxesPermutation([a],i),l=t;o!=null&&(l=Wt({inputs:{x:t},backend:n,attrs:{perm:o}}));let u=C.getInnerMostAxes(1,i)[0];if(u!==i-1)throw new Error( ` WebGL cumprod shader expects an inner - most axis = $ { t . shape . length - 1 } but got axis = $ { a } ` );let p=l.shape[u],d=na({inputs:{x:l},backend:n});for(let c=0;c<=Math.ceil(Math.log2(p))-1;c++){let h=new Lk(e,l.shape,!1,s),m=[[c]],f=d;d=n.runWebGLProgram(h,[d],d.dtype,m),n.disposeIntermediateTensorInfo(f)}if(r){let c=new Lk(e,l.shape,r,s),h=d;d=n.runWebGLProgram(c,[d],d.dtype),n.disposeIntermediateTensorInfo(h)}if(o!=null){let c=C.getUndoAxesPermutation(o),h=Wt({inputs:{x:d},backend:n,attrs:{perm:c}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(l),h}return d}function pZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;return SC(lc.Prod,r,n,s,i,o)}var cZ={kernelName:Ll,backendName:"webgl",kernelFunc:pZ};function dZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a;return SC(lc.Sum,r,n,s,i,o)}var hZ={kernelName:Fi,backendName:"webgl",kernelFunc:dZ};function mZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=a;if(r.shape.length===1){let l=n.readSync(r.dataId),u=n.readSync(s.dataId),p=aC(l,u,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,p)}else if(r.shape.length===2){let l=n.bufferSync(r),u=n.bufferSync(s),p=TY(l,u,i,o);return n.makeTensorInfo(p.shape,s.dtype,p.values)}throw new Error( ` Error in denseBincount : input must be at most rank 2 , but got rank$ { r . shape . length } . ` )}var fZ={kernelName:fm,backendName:"webgl",kernelFunc:mZ},gZ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int h = $ { this . getHeightCoordString ( ) } ;
int w = $ { this . getWidthCoordString ( ) } ;
int d = $ { this . getDepthCoordString ( ) } ;
int in _h = h / $ { t } ;
int offset _h = imod ( h , $ { t } ) ;
int in _w = w / $ { t } ;
int offset _w = imod ( w , $ { t } ) ;
int offset _d = ( offset _h * $ { t } + offset _w ) *
$ { this . getOutputDepthSize ( ) } ;
int in _d = d + offset _d ;
float result = $ { this . getInputSamplingString ( ) } ;
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }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 yZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a,o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],p=i==="NHWC"?r.shape[3]:r.shape[1],d=l*s,c=u*s,h=p/(s*s),m=i==="NHWC"?[o,d,c,h]:[o,h,d,c],f=new gZ(m,s,i);return n.runWebGLProgram(f,[r],r.dtype)}var bZ={kernelName:Bl,backendName:"webgl",kernelFunc:yZ},NC=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Hn(this.outputShape.length);let s=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels,l="",u="";n&&(a?l= ` float activation ( float a ) {
2022-03-07 19:17:31 +01:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
} ` :r?l= ` float activation ( float a ) {
float b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
} ` :l= `
float activation ( float x ) {
$ { n }
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
` ,u="result = activation(result);");let p=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { l }
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
int d1 = d2 / $ { o } ;
int q = d2 - d1 * $ { o } ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for ( int wR = 0 ; wR < $ { s } ; wR ++ ) {
int xR = xRCorner + wR * dilations [ 0 ] ;
if ( xR < 0 || xR >= inDims [ 0 ] ) {
continue ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
for ( int wC = 0 ; wC < $ { i } ; wC ++ ) {
int xC = xCCorner + wC * dilations [ 1 ] ;
if ( xC < 0 || xC >= inDims [ 1 ] ) {
continue ;
2021-05-18 14:11:17 +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 }
$ { u }
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }},TC=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Hn(this.outputShape.length);let s=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,p=e.filterWidth,d=p,c= `
2022-03-07 19:17:31 +01:00
int xR ; int xC ; int xCOffset ;
vec4 wTexel ; vec4 previous ; vec4 final ; ` ;for(let g=0;g<p;g++)c+= `
vec4 xTexelC$ { g * 2 } ;
int xTexelC$ { g * 2 } Ready ;
vec4 xTexelC$ { g * 2 + 1 } ;
int xTexelC$ { g * 2 + 1 } Ready ;
vec4 xC$ { g } ; ` ;c+= `
for ( int r = 0 ; r < $ { u } ; r ++ ) {
` ;for(let g=0;g<p;g++)c+= `
xTexelC$ { g * 2 } = vec4 ( 0.0 ) ;
xTexelC$ { g * 2 } Ready = 0 ;
xTexelC$ { g * 2 + 1 } = vec4 ( 0.0 ) ;
xTexelC$ { g * 2 + 1 } Ready = 0 ;
xC$ { g } = vec4 ( 0.0 ) ; ` ;c+= `
xR = xRCorner + r * dilations [ 0 ] ;
if ( xR >= 0 && xR < inDims [ 0 ] ) {
` ;for(let g=0;g<(d+1)/2;g++){let y=g*2;if(c+= `
xC = xCCorner + $ { y * l } ;
` ,o===1){if(y<p&&(i%2===1?(c+= `
xCOffset = xC + 1 ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { y } Ready == 0 ) {
xTexelC$ { y } = 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$ { y } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { y } Ready = 1 ;
2021-05-18 14:11:17 +02:00
}
2022-03-07 19:17:31 +01:00
` ,l===1&&y>0?c+= `
xC$ { y } = vec4 ( xTexelC$ { y - 2 } . zw , xTexelC$ { y } . xy ) ;
` :c+= `
xCOffset = xC + 1 - 2 ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
previous = getX ( batch , xR , xCOffset , d1 ) ;
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
previous . zw = vec2 ( 0.0 ) ;
}
xC$ { y } = vec4 ( previous . zw , xTexelC$ { y } . xy ) ;
} else {
xC$ { y } = vec4 ( 0.0 , 0.0 , xTexelC$ { y } . xy ) ;
}
` ):c+= `
if ( xC >= 0 && xC < inDims [ 1 ] && xTexelC$ { y } Ready == 0 ) {
xTexelC$ { y } = getX ( batch , xR , xC , d1 ) ;
if ( xC + 1 >= inDims [ 1 ] ) {
xTexelC$ { y } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { y } Ready = 1 ;
}
xC$ { y } = xTexelC$ { y } ;
2022-05-18 14:36:05 +02:00
` ,y+1<p)){let b=i%2===0?w.nearestLargerEven(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(c+= `
2022-03-07 19:17:31 +01:00
xCOffset = xC + imod ( pads [ 1 ] , 2 ) + $ { b } ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { y + 1 } Ready == 0 ) {
xTexelC$ { y + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
xTexelC$ { y + 1 } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { y + 1 } Ready = 1 ;
}
` ,l>1&&(c+= `
xCOffset -= 2 ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { y } Ready == 0 ) {
xTexelC$ { y } = getX ( batch , xR , xCOffset , d1 ) ;
xTexelC$ { y } Ready = 1 ;
}
` ),c+= `
xC$ { y + 1 } = vec4 ( xTexelC$ { y } . zw , xTexelC$ { y + 1 } . xy ) ;
` ):b===1?c+= `
xC$ { y + 1 } = xTexelC$ { y } ;
` :c+= `
xCOffset = xC + $ { b } ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { y + 1 } Ready == 0 ) {
xTexelC$ { y + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
if ( xCOffset + 1 >= inDims [ 1 ] ) {
xTexelC$ { y + 1 } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { y + 1 } Ready = 1 ;
}
xC$ { y + 1 } = xTexelC$ { y + 1 } ;
` }}else y<p&&(i%2===1?(c+= `
xCOffset = xC + 1 - strides [ 1 ] ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { y } Ready == 0 ) {
xTexelC$ { y } = 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$ { y } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { y } Ready = 1 ;
}
if ( xC + 1 >= 0 && xC + 1 < inDims [ 1 ] && xTexelC$ { y + 1 } Ready == 0 ) {
xTexelC$ { y + 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$ { y + 1 } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { y + 1 } Ready = 1 ;
}
xC$ { y } = vec4 ( xTexelC$ { y } . zw , xTexelC$ { y + 1 } . zw ) ;
` ,y+1<p&&(c+= `
final = vec4 ( 0.0 ) ;
xCOffset = xC + 1 + strides [ 1 ] ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
final = getX ( batch , xR , xCOffset , d1 ) ;
}
xC$ { y + 1 } = vec4 ( xTexelC$ { y + 1 } . xy , final . xy ) ;
` )):(c+= `
if ( xC >= 0 && xC < inDims [ 1 ] && xTexelC$ { y } Ready == 0 ) {
xTexelC$ { y } = getX ( batch , xR , xC , d1 ) ;
if ( xC + 1 >= inDims [ 1 ] ) {
xTexelC$ { y } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { y } Ready = 1 ;
}
xCOffset = xC + strides [ 1 ] ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { y + 1 } Ready == 0 ) {
xTexelC$ { y + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
if ( xCOffset + 1 >= inDims [ 1 ] ) {
xTexelC$ { y + 1 } . zw = vec2 ( 0. ) ;
}
xTexelC$ { y + 1 } Ready = 1 ;
}
xC$ { y } = vec4 (
xTexelC$ { y } . xy , xTexelC$ { y + 1 } . xy ) ;
` ,y+1<p&&(c+= `
xC$ { y + 1 } = vec4 ( xTexelC$ { y } . zw , xTexelC$ { y + 1 } . zw ) ;
` )));y<p&&(c+= `
wTexel = getW ( r , $ { y } , d1 , q ) ;
dotProd += xC$ { y } * vec4 ( wTexel . xz , wTexel . xz ) ;
` ,y+1<p&&(c+= `
wTexel = getW ( r , $ { y + 1 } , d1 , q ) ;
dotProd += xC$ { y + 1 } * vec4 ( wTexel . xz , wTexel . xz ) ;
` ))}c+= `
}
` ,c+= `
}
` ;let h="",m="";n&&(a?h= ` vec4 activation ( vec4 a ) {
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
} ` :r?h= ` vec4 activation ( vec4 a ) {
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
} ` :h= ` vec4 activation ( vec4 x ) {
$ { n }
} ` ,m="result = activation(result);");let f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { h }
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
int d1 = d2 / $ { s } ;
int q = d2 - d1 * $ { s } ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4 ( 0.000000000000001 ) ;
$ { c }
vec4 result = dotProd - vec4 ( 0.000000000000001 ) ;
$ { f }
$ { m }
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }};function xZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=a,p=l;p==null&&(p=[1,1]),w.assert(C.eitherStridesOrDilationsAreOne(i,p),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { i } and dilations '${p}' ` );let d=C.computeConv2DInfo(r.shape,s.shape,i,p,o,u,!0),c;X().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels===1?c=new TC(d):c=new NC(d);let h=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return n.runWebGLProgram(c,[r,s],"float32",h)}var vZ={kernelName:Ai,backendName:"webgl",kernelFunc:xZ},wZ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int dm = coords . w ;
int d2 = d1 * $ { s } + dm ;
float dotProd = 0.0 ;
// TO DO: Vec4 over the batch size
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { t } - $ { a } ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2021-05-18 14:11:17 +02:00
continue ;
}
2022-03-07 19:17:31 +01:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { n } - $ { r } ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
2021-05-18 14:11:17 +02: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 ) ;
2020-10-12 20:28:19 +02:00
}
2022-05-24 13:16:42 +02:00
` }},kZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec2 pads = ivec2 ( $ { s } , $ { i } ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d1 = coords [ 3 ] ;
ivec2 dyCorner = coords . yz - pads ;
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
int wRPerm = $ { t } - 1 - wR ;
for ( int wC = 0 ; wC < $ { n } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { r } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
int wCPerm = $ { n } - 1 - wC ;
// TO DO: Vec4 over the channelMul
for ( int dm = 0 ; dm < $ { o } ; dm ++ ) {
int d2 = d1 * $ { o } + dm ;
float xValue = getDy ( batch , idyR , idyC , d2 ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , dm ) ;
dotProd += xValue * wValue ;
}
}
}
setOutput ( dotProd ) ;
2020-12-15 14:15:43 +01:00
}
2022-05-24 13:16:42 +02:00
` }};function IZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:p}=a,d=C.computeConv2DInfo(r.shape,p,i,o,l,u,!0),c=new wZ(d);return n.runWebGLProgram(c,[r,s],"float32")}var SZ={kernelName:gm,backendName:"webgl",kernelFunc:IZ};function NZ(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:p}=a,d=C.computeConv2DInfo(p,s.shape,i,o,l,u,!0),c=new kZ(d);return n.runWebGLProgram(c,[r,s],"float32")}var TZ={kernelName:ym,backendName:"webgl",kernelFunc:NZ},_Z=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
float val = coords [ 0 ] == coords [ 1 ] ? getX ( coords [ 0 ] ) : 0.0 ;
setOutput ( val ) ;
2020-12-15 14:15:43 +01:00
}
2022-05-24 13:16:42 +02:00
` }};function CZ(e){let{inputs:t,backend:n}=e,{x:a}=t,r=[...a.shape,...a.shape],s=w.sizeFromShape(a.shape),i=me({inputs:{x:a},backend:n,attrs:{shape:[s]}}),o=new _Z(s),l=n.runWebGLProgram(o,[i],i.dtype),u=me({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}var EZ={kernelName:bm,backendName:"webgl",kernelFunc:CZ},FZ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:a,strideHeight:r,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:p,left:d}=a;this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec2 strides = ivec2 ( $ { r } , $ { s } ) ;
const ivec2 pads = ivec2 ( $ { p } , $ { d } ) ;
const float neg _infinity = - 3.4 e38 ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d1 = coords . w ;
ivec2 outTopLeftCorner =
coords . yz * strides - pads ;
int hBeg = outTopLeftCorner . x ;
int wBeg = outTopLeftCorner . y ;
float curVal = neg _infinity ;
for ( int h = 0 ; h < $ { i } ; h ++ ) {
int hIn = hBeg + h * $ { l } ;
if ( hIn >= 0 && hIn < $ { t } ) {
for ( int w = 0 ; w < $ { o } ; w ++ ) {
int wIn = wBeg + w * $ { u } ;
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 ;
}
}
}
}
}
float result = curVal ;
setOutput ( result ) ;
2021-03-26 15:26:02 +01:00
}
2022-05-24 13:16:42 +02:00
` }};function AZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,u=C.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),p,d=new FZ(u);p=n.runWebGLProgram(d,[r,s],"float32");let c=me({inputs:{x:p},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(p),c}var $ Z={kernelName:fc,backendName:"webgl",kernelFunc:AZ};function DZ(e){let{inputs:t,backend:n,attrs:a}=e,{equation:r}=a,s=t,{allDims:i,summedDims:o,idDims:l}=C.decodeEinsumEquation(r,s.length);C.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=C.getEinsumComputePath(o,l),d=p.length,c=null,h=i.length,m=[];for(let f=0;f<d;++f){for(let g of p[f]){let{permutationIndices:y,expandDims:b}=C.getEinsumPermutation(h,l[g]),x;C.isIdentityPermutation(y)?x=s[g]:(x=Wt({inputs:{x:s[g]},backend:n,attrs:{perm:y}}),m.push(x));let v=x.shape.slice();for(let k=0;k<b.length;++k)v.splice(b[k],0,1);w.arraysEqual(x.shape,v)||(x=me({inputs:{x},backend:n,attrs:{shape:v}}),m.push(x)),c===null?c=x:(c=R0({inputs:{a:x,b:c},backend:n}),m.push(c))}f<d-1&&(u[f]>=0&&(c=Kf({inputs:{x:c},backend:n,attrs:{axis:u[f]-(i.length-h),keepDims:!1}}),m.push(c)),h--)}for(let f of m)f!==c&&n.disposeIntermediateTensorInfo(f);return c}var RZ={kernelName:xm,backendName:"webgl",kernelFunc:DZ},MZ="return (x >= 0.0) ? x : (exp(x) - 1.0);",PZ= `
2022-03-07 19:17:31 +01:00
vec4 result ;
result . r = ( x . r >= 0.0 ) ? x . r : ( exp ( x . r ) - 1.0 ) ;
result . g = ( x . g >= 0.0 ) ? x . g : ( exp ( x . g ) - 1.0 ) ;
result . b = ( x . b >= 0.0 ) ? x . b : ( exp ( x . b ) - 1.0 ) ;
result . a = ( x . a >= 0.0 ) ? x . a : ( exp ( x . a ) - 1.0 ) ;
return result ;
2022-05-24 13:16:42 +02:00
` ,OZ=Qe({opSnippet:MZ,packedOpSnippet:PZ}),LZ={kernelName:Di,backendName:"webgl",kernelFunc:OZ},zZ="return (b >= 1.0) ? a : a * (b + 1.0);",BZ= `
2022-03-07 19:17:31 +01:00
vec4 bGTEZero = vec4 ( greaterThanEqual ( b , vec4 ( 0. ) ) ) ;
return ( bGTEZero * a ) + ( ( vec4 ( 1.0 ) - bGTEZero ) * ( a * ( b + vec4 ( 1.0 ) ) ) ) ;
2022-05-24 13:16:42 +02:00
` ,WZ=e=>{let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new id(BZ,a.shape,r.shape):new Sl(zZ,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)},VZ={kernelName:vm,backendName:"webgl",kernelFunc:WZ},UZ= `
2022-03-07 19:17:31 +01:00
return vec4 ( equal ( a , b ) ) ;
2022-05-24 13:16:42 +02:00
` ,GZ="return float(a == b);",HZ=pn({opSnippet:GZ,packedOpSnippet:UZ,dtype:"bool",cpuKernelImpl:EY}),jZ={kernelName:Vl,backendName:"webgl",kernelFunc:HZ},qZ= `
2022-03-07 19:17:31 +01:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2022-05-24 13:16:42 +02:00
float p = $ { C . ERF _P } ;
float a1 = $ { C . ERF _A1 } ;
float a2 = $ { C . ERF _A2 } ;
float a3 = $ { C . ERF _A3 } ;
float a4 = $ { C . ERF _A4 } ;
float a5 = $ { C . ERF _A5 } ;
2022-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 ) ) ;
2022-05-24 13:16:42 +02:00
` ,KZ=Qe({opSnippet:qZ}),XZ={kernelName:Wl,backendName:"webgl",kernelFunc:KZ},YZ=ju+ `
2022-03-07 19:17:31 +01:00
return exp ( x ) ;
2022-05-24 13:16:42 +02:00
` ,QZ= `
2022-03-07 19:17:31 +01:00
vec4 result = exp ( x ) ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2022-05-24 13:16:42 +02:00
` ,_C=Qe({opSnippet:YZ,packedOpSnippet:QZ,cpuKernelImpl:FY,dtype:"float32"}),JZ={kernelName:Ri,backendName:"webgl",kernelFunc:_C};function fx(e){let{inputs:t,attrs:n,backend:a}=e,{dim:r}=n,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=r;return r<0&&(w.assert(-(i+1)<=r,()=> ` Axis must be in the interval [ $ { - ( i + 1 ) } , $ { i } ] ` ),l=i+r+1),o.splice(l,0,1),me({inputs:{x:s},backend:a,attrs:{shape:o}})}var ZZ={kernelName:Ul,backendName:"webgl",kernelFunc:fx},Wk="return exp(x) - 1.0;",eee=Qe({opSnippet:Wk,packedOpSnippet:Wk,cpuKernelImpl:AY}),tee={kernelName:Gl,backendName:"webgl",kernelFunc:eee},Vk=class{constructor(e,t,n){this.variableNames=["real","imag"];let a=t[1];this.outputShape=t;let r=n? ` 2.0 * $ { Math . PI } ` : ` - 2.0 * $ { Math . PI } ` ,s=n? ` $ { a } . 0 ` :"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error( ` FFT component must be either "real" or "imag" , got $ { e } . ` );this.userCode= `
2022-03-07 19:17:31 +01:00
const float exponentMultiplier = $ { r } ;
float unaryOpComplex ( float real , float expR , float imag , float expI ) {
$ { i }
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
float mulMatDFT ( int batch , int index ) {
float indexRatio = float ( index ) / float ( $ { a } ) ;
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
float result = 0.0 ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
for ( int i = 0 ; i < $ { a } ; 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 ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
result +=
unaryOpComplex ( real , expR , imag , expI ) / $ { s } ;
}
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
return result ;
}
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
setOutput ( mulMatDFT ( coords [ 0 ] , coords [ 1 ] ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function CC(e,t,n){let a=n.texData.get(e.dataId),r=w.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=r/s,o=me({inputs:{x:e},backend:n,attrs:{shape:[i,s]}}),l=o.shape,u=new Vk("real",l,t),p=new Vk("imag",l,t),d=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:l},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:l}],c=n.runWebGLProgram(u,d,"float32"),h=n.runWebGLProgram(p,d,"float32"),m=Is({inputs:{real:c,imag:h},backend:n});n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h);let f=me({inputs:{x:m},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(m),f}function nee(e){let{inputs:t,backend:n}=e,{input:a}=t;return CC(a,!1,n)}var aee={kernelName:wm,backendName:"webgl",kernelFunc:nee},ree=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
// Input can be obtained from uniform value.
setOutput ( value ) ;
}
2022-05-24 13:16:42 +02:00
` }};function ld(e){let{backend:t,attrs:n}=e,{shape:a,value:r}=n,{dtype:s}=n;if(s=s||w.inferDtype(r),s==="string"){let i=w.getArrayFromDType(s,w.sizeFromShape(a));return i.fill(r),t.makeTensorInfo(a,s,i)}else{let i=new ree(a,r),o=[[r]];return t.runWebGLProgram(i,[],s,o)}}var see={kernelName:gc,backendName:"webgl",kernelFunc:ld},iee=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
2020-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
int coordX = $ { t } - x - 1 ;
float outputValue ;
if ( coordX >= 0 && coordX < $ { t } ) {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coordX , coords [ 3 ] ) ;
} else {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coords [ 2 ] , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
}
2022-05-24 13:16:42 +02:00
` }},oee={kernelName:Hl,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,a=t,r=new iee(n.shape);return a.runWebGLProgram(r,[n],n.dtype)}},Uk="return floor(x);",lee=Qe({opSnippet:Uk,packedOpSnippet:Uk,cpuKernelImpl: $ Y}),uee={kernelName:Mi,backendName:"webgl",kernelFunc:lee},pee= `
2022-03-07 19:17:31 +01:00
float s = sign ( a ) * sign ( b ) ;
int ia = round ( a ) ;
int ib = round ( b ) ;
if ( ib != 0 ) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float ( idiv ( ia , ib , s ) ) ;
} else {
return NAN ;
2021-04-01 19:39:54 +02:00
}
2022-05-24 13:16:42 +02:00
` ,cee= `
2022-03-07 19:17:31 +01:00
ivec4 ia = round ( a ) ;
ivec4 ib = round ( b ) ;
bvec4 cond = notEqual ( ib , ivec4 ( 0 ) ) ;
ivec4 result = ivec4 ( 0 ) ;
vec4 s = sign ( a ) * sign ( b ) ;
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if ( cond [ 0 ] ) {
result [ 0 ] = idiv ( ia [ 0 ] , ib [ 0 ] , s [ 0 ] ) ;
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 ] ) ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
if ( cond [ 3 ] ) {
result [ 3 ] = idiv ( ia [ 3 ] , ib [ 3 ] , s [ 3 ] ) ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
return vec4 ( result ) ;
2022-05-24 13:16:42 +02:00
` ,dee=pn({opSnippet:pee,packedOpSnippet:cee,dtype:"int32"}),hee={kernelName:Pi,backendName:"webgl",kernelFunc:dee},mee=class{constructor(e){this.variableNames=["A"];let t=Cn(),[n,a]=e;this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { a } . 0 , $ { n } . 0 ) ;
2020-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
vec4 values = $ { t . 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-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
setOutput ( floor ( value * 255.0 + 0.5 ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},fee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Cn(),[n,a]=e;this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
2020-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
vec4 result = vec4 ( 0. ) ;
2020-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
for ( int row = 0 ; row <= 1 ; row ++ ) {
for ( int col = 0 ; col <= 1 ; col ++ ) {
texC = coords [ 1 ] + row ;
depth = coords [ 2 ] + col ;
2020-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { a } . 0 , $ { n } . 0 ) ;
vec4 values = $ { t . 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-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
result [ row * 2 + col ] = floor ( value * 255.0 + 0.5 ) ;
}
}
2020-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
$ { t . output } = result ;
}
2022-05-24 13:16:42 +02:00
` }},gee={kernelName:Ah,backendName:"webgl",kernelFunc:yee},Zo;function yee(e){let{inputs:t,backend:n,attrs:a}=e,{pixels:r}=t,{numChannels:s}=a,i=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,[l,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],p=[u,l],d=[u,l,s];(o||i)&&(Zo==null&&(Zo=document.createElement("canvas").getContext("2d")),Zo.canvas.width=l,Zo.canvas.height=u,Zo.drawImage(r,0,0,l,u),r=Zo.canvas);let c=n.makeTensorInfo(p,"int32");n.texData.get(c.dataId).usage=ca.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(c.dataId),r);let h=X().getBool("WEBGL_PACK")?new fee(d):new mee(d),m=n.runWebGLProgram(h,[c],"int32");return n.disposeData(c.dataId),m}function bee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:d,dimRoundingMode:c,activation:h,leakyreluAlpha:m}=a,f=C.convertConv2DDataFormat(p),g=C.computeConv2DInfo(r.shape,s.shape,l,d,u,c,!1,f),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=kC({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else if(X().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)y=IC({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else{let v=i!=null,k=o!=null,T=h==="leakyrelu",_=h?jf(h,!1):null,E=new wC(g,v,_,k,T),A=[r,s],M=( $ ,S)=>{if(S==="NCHW"&& $ .shape.length===1&& $ .shape[0]!==1){let P=me({inputs:{x: $ },backend:n,attrs:{shape:[ $ .shape[0],1,1]}});return b.push(P),P}return $ };if(v&&A.push(M(i,p)),k&&A.push(M(o,p)),T){let $ =n.makeTensorInfo([],"float32",w.createScalarValue(m,"float32"));A.push( $ ),b.push( $ )}y=n.runWebGLProgram(E,A,"float32")}let x=me({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var xee={kernelName:ai,backendName:"webgl",kernelFunc:bee};function vee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dimRoundingMode:d,activation:c,leakyreluAlpha:h}=a,m=[],f=p;f==null&&(f=[1,1]),w.assert(C.eitherStridesOrDilationsAreOne(l,f),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { l } and dilations '${f}' ` );let g=C.computeConv2DInfo(r.shape,s.shape,l,f,u,d,!0),y=X().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,b=c?jf(c,y):null,x=[r,s],v=i!=null,k=o!=null,T=c==="leakyrelu";if(v&&x.push(i),k&&x.push(o),T){let M=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));x.push(M),m.push(M)}let _;y?_=new TC(g,v,b,k,T):_=new NC(g,v,b,k,T);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],A=n.runWebGLProgram(_,x,"float32",E);return m.forEach(M=>n.disposeIntermediateTensorInfo(M)),A}var wee={kernelName:ri,backendName:"webgl",kernelFunc:vee},kee=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let a=mt(t.length),r=mt(n.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode= `
2022-03-07 19:17:31 +01:00
$ { a } strides = $ { a } ( $ { this . strides } ) ;
void main ( ) {
$ { r } coords = getOutputCoords ( ) ;
int flattenIndex = 0 ;
for ( int j = 0 ; j < $ { this . sliceDim } ; j ++ ) {
int index = round ( getIndices ( coords [ 0 ] , j ) ) ;
flattenIndex += index * $ { s } ;
}
setOutput ( getX ( flattenIndex , coords [ 1 ] ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Iee(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=r.shape,i=s[s.length-1],o=w.sizeFromShape(a.shape),[l,u,p,d]=C.prepareAndValidate(a,r),c=me({inputs:{x:r},backend:n,attrs:{shape:[u,i]}}),h=me({inputs:{x:a},backend:n,attrs:{shape:[w.sizeFromShape(a.shape)/p,p]}});if(n.shouldExecuteOnCPU([a,r])||a.dtype==="string"){let y=n.readSync(r.dataId),b=n.bufferSync(a),x=DY(y,b,a.dtype,u,i,p,d,a.shape,o);return n.makeTensorInfo(l,a.dtype,x.values)}let m=new kee(i,d,[u,p]),f=n.runWebGLProgram(m,[h,c],h.dtype),g=me({inputs:{x:f},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),g}var See={kernelName:ql,backendName:"webgl",kernelFunc:Iee},Nee=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=mt(this.rank),a=Tee(e,2);this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { n } resRC = getOutputCoords ( ) ;
int index = int ( getIndices ( resRC . x , resRC . z ) ) ;
float inBounds = ( index >= 0 ) && ( index < $ { e [ 2 ] } ) ? 1.0 : 0.0 ;
setOutput ( inBounds * getA ( $ { a } ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Tee(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let r=0;r<e.length;r++)r===2?a.push("index"):a.push( ` $ { n [ r ] } ` );return a.join()}function EC(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,r.shape)[0];if(X().get("DEBUG")){let b=n.readSync(s.dataId),x=r.shape[l];for(let v=0;v<b.length;++v){let k=b[v];w.assert(k<=x-1&&k>=0,()=> ` GatherV2 : the index value $ { k } is not in [ 0 , $ { x - 1 } ] ` )}}let u=C.segment_util.collectGatherOpShapeInfo(r,s,l,o),p=w.sizeFromShape(s.shape),d=[],c=me({inputs:{x:r},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=me({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,p/u.batchSize]}});d.push(c),d.push(h);let m=[u.batchSize,u.outerSize,p/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.bufferSync(h),x=n.bufferSync(c),v=RY(x,b,m);return d.forEach(k=>n.disposeIntermediateTensorInfo(k)),n.makeTensorInfo(u.outputShape,v.dtype,v.values)}let f=new Nee(c.shape,m),g=n.runWebGLProgram(f,[c,h],c.dtype);d.push(g);let y=me({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return d.forEach(b=>n.disposeIntermediateTensorInfo(b)),y}var _ee={kernelName:jl,backendName:"webgl",kernelFunc:EC},Cee="return float(a > b);",Eee= `
2022-03-07 19:17:31 +01:00
return vec4 ( greaterThan ( a , b ) ) ;
2022-05-24 13:16:42 +02:00
` ,Fee=pn({opSnippet:Cee,packedOpSnippet:Eee,cpuKernelImpl:MY,dtype:"bool"}),Aee={kernelName:Kl,backendName:"webgl",kernelFunc:Fee}, $ ee="return float(a >= b);",Dee= `
2022-03-07 19:17:31 +01:00
return vec4 ( greaterThanEqual ( a , b ) ) ;
2022-05-24 13:16:42 +02:00
` ,Ree=pn({opSnippet: $ ee,packedOpSnippet:Dee,dtype:"bool",cpuKernelImpl:PY}),Mee={kernelName:Li,backendName:"webgl",kernelFunc:Ree};function Pee(e){let{inputs:t,backend:n}=e,{input:a}=t;return CC(a,!0,n)}var Oee={kernelName:km,backendName:"webgl",kernelFunc:Pee},Lee="return float(!isnan(x) && !isinf(x));",zee=Qe({opSnippet:Lee,dtype:"bool"}),Bee={kernelName:Xl,backendName:"webgl",kernelFunc:zee},Wee="return float(isinf(x));",Vee=Qe({opSnippet:Wee,dtype:"bool"}),Uee={kernelName:Yl,backendName:"webgl",kernelFunc:Vee},Gee="return float(isnan(x));",Hee=Qe({opSnippet:Gee,dtype:"bool"}),jee={kernelName:Ql,backendName:"webgl",kernelFunc:Hee},qee="return float(a < b);",Kee= `
2022-03-07 19:17:31 +01:00
return vec4 ( lessThan ( a , b ) ) ;
2022-05-24 13:16:42 +02:00
` ,Xee=pn({opSnippet:qee,packedOpSnippet:Kee,cpuKernelImpl:OY,dtype:"bool"}),Yee={kernelName:Jl,backendName:"webgl",kernelFunc:Xee},Qee="return float(a <= b);",Jee= `
2022-03-07 19:17:31 +01:00
return vec4 ( lessThanEqual ( a , b ) ) ;
2022-05-24 13:16:42 +02:00
` ,Zee=pn({opSnippet:Qee,packedOpSnippet:Jee,cpuKernelImpl:LY,dtype:"bool"}),ete={kernelName:Zl,backendName:"webgl",kernelFunc:Zee};function tte(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=zY(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var nte={kernelName:Sm,backendName:"webgl",kernelFunc:tte},ate=ju+ `
2022-03-07 19:17:31 +01:00
return x < 0.0 ? 0. / 0. : log ( x ) ;
2022-05-24 13:16:42 +02:00
` ,rte= `
2022-03-07 19:17:31 +01:00
vec4 result = log ( x ) ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : ( x . r < 0.0 ? 0. / 0. : result . r ) ;
result . g = isNaN . g ? x . g : ( x . g < 0.0 ? 0. / 0. : result . g ) ;
result . b = isNaN . b ? x . b : ( x . b < 0.0 ? 0. / 0. : result . b ) ;
result . a = isNaN . a ? x . a : ( x . a < 0.0 ? 0. / 0. : result . a ) ;
return result ;
2022-05-24 13:16:42 +02:00
` ,ste=Qe({opSnippet:ate,packedOpSnippet:rte,cpuKernelImpl:BY}),ite={kernelName:Wi,backendName:"webgl",kernelFunc:ste},ote=ju+ `
2022-03-07 19:17:31 +01:00
return log ( 1.0 + x ) ;
2022-05-24 13:16:42 +02:00
` ,lte=Qe({opSnippet:ote}),ute={kernelName:eu,backendName:"webgl",kernelFunc:lte},pte="return float(a >= 1.0 && b >= 1.0);",cte= `
2022-03-07 19:17:31 +01:00
return vec4 (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) *
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ) ;
2022-05-24 13:16:42 +02:00
` ,dte=pn({opSnippet:pte,packedOpSnippet:cte,dtype:"bool"}),hte={kernelName:tu,backendName:"webgl",kernelFunc:dte},mte="return float(!(x >= 1.0));",fte=Qe({opSnippet:mte}),gte={kernelName:yc,backendName:"webgl",kernelFunc:fte},yte="return float(a >= 1.0 || b >= 1.0);",bte= `
2022-03-07 19:17:31 +01:00
return min (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) +
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ,
vec4 ( 1.0 ) ) ;
2022-05-24 13:16:42 +02:00
` ,xte=pn({opSnippet:yte,packedOpSnippet:bte,dtype:"bool"}),vte={kernelName:bc,backendName:"webgl",kernelFunc:xte},wte=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l= ` float ( $ { n } ) + float ( $ { a } ) * sum ` ;r===.5?o= ` inversesqrt ( $ { l } ) ` :r===1?o= ` 1.0 / ( $ { l } ) ` :o= ` exp ( log ( $ { l } ) * float ( - $ { r } ) ) ; ` ,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
int d = coords [ 3 ] ;
float x = getX ( b , r , c , d ) ;
float sum = 0.0 ;
for ( int j = - $ { s } ; j <= $ { s } ; j ++ ) {
int idx = d + j ;
if ( idx >= 0 && idx <= $ { i } ) {
float z = getX ( b , r , c , idx ) ;
sum += z * z ;
}
}
float val = x * $ { o } ;
setOutput ( val ) ;
}
2022-05-24 13:16:42 +02:00
` }},kte=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let s=t,i=e[3]-1;this.outputShape=e;let o,l= ` float ( $ { n } ) + float ( $ { a } ) * sum ` ;r===.5?o= ` inversesqrt ( $ { l } ) ` :r===1?o= ` 1.0 / ( $ { l } ) ` :o= ` exp ( log ( $ { l } ) * float ( - $ { r } ) ) ; ` ,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords . x ;
int r = coords . y ;
int c = coords . z ;
int d = coords . w ;
2020-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
bool hasNextCol = d < $ { this . outputShape [ 3 ] } ;
bool hasNextRow = c < $ { this . outputShape [ 2 ] } ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
vec4 sum = vec4 ( 0. ) ;
vec4 xFragAtOutputCoords = getX ( b , r , c , d ) ;
2020-08-29 20:56:29 +02: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
) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
int firstChannel = d - $ { s } ;
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 ) ) ;
}
}
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
ivec2 depth = ivec2 ( d , d + 1 ) ;
for ( int j = - $ { s } ; j <= $ { s } ; j ++ ) {
ivec2 idx = depth + j ;
bvec2 aboveLowerBound = greaterThanEqual ( idx , ivec2 ( 0 ) ) ;
bvec2 belowUpperBound = lessThanEqual ( idx , ivec2 ( $ { i } ) ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
bool depthInRange = aboveLowerBound . x && belowUpperBound . x ;
bool depthPlusOneInRange = aboveLowerBound . y && belowUpperBound . y ;
2020-10-12 20:28:19 +02: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 * $ { o } ;
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }},Ite=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a,u=X().getBool("WEBGL_PACK_NORMALIZATION")?new kte(r.shape,s,i,o,l):new wte(r.shape,s,i,o,l);return n.runWebGLProgram(u,[r],r.dtype)},Ste={kernelName:xc,backendName:"webgl",kernelFunc:Ite},Nte=class{constructor(e,t,n,a,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=a,this.beta=r,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-10-12 20:28:19 +02: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 - $ { t } ) ) ) ;
int depthEnd = int ( min ( float ( $ { this . depth } ) ,
float ( d + $ { t } + 1 ) ) ) ;
const int MIN _DEPTH _BEGIN = 0 ;
const int MAX _DEPTH _END = $ { this . depth } ;
float norm = 0.0 ;
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
norm += getInputImage ( b , r , c , k ) * getInputImage ( b , r , c , k ) ;
}
else {
break ;
}
}
norm = float ( $ { a } ) * norm + float ( $ { n } ) ;
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 ( $ { a } )
* float ( $ { r } )
* getInputImage ( b , r , c , k ) * getOutputImage ( b , r , c , d )
/ n o r m ;
if ( k == d ) {
dyi += pow ( norm , - 1.0 * $ { r } ) ;
}
if ( k == coords [ 3 ] ) {
dyi *= getDy ( b , r , c , d ) ;
result += dyi ;
}
}
else {
break ;
}
}
}
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }},Tte=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:p}=a,d=new Nte(r.shape,o,l,u,p);return n.runWebGLProgram(d,[r,s,i],r.dtype)},_te={kernelName:Nm,backendName:"webgl",kernelFunc:Tte};function Cte(e,t,n,a){let r=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/r,i=me({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=No(i,e.dtype,"max",a),l=me({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}function FC(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=C.getAxesPermutation(u,o),d=p!=null,c=n.shouldExecuteOnCPU([r]),h=r;if(d){if(c){let b=n.texData.get(h.dataId).values,x=new Array(o);for(let T=0;T<x.length;T++)x[T]=r.shape[p[T]];let v=D0(b,r.shape,r.dtype,p,x);h=n.makeTensorInfo(x,r.dtype);let k=n.texData.get(h.dataId);k.values=v}else h=qf(r,p,n);u=C.getInnerMostAxes(u.length,o)}C.assertAxesAreInnerMostDims("max",u,o);let[m,f]=C.computeOutAndReduceShapes(h.shape,u),g=m;i&&(g=C.expandShapeToKeepDim(m,l));let y;if(c){let b=n.texData.get(h.dataId).values,x=WY(b,w.sizeFromShape(f),g,r.dtype);y=n.makeTensorInfo(g,r.dtype);let v=n.texData.get(y.dataId);v.values=x}else y=Cte(h,f,g,n);return d&&n.disposeIntermediateTensorInfo(h),y}var Ete={kernelName:Vi,backendName:"webgl",kernelFunc:FC},Fte=uC+ `
2022-03-07 19:17:31 +01:00
return max ( a , b ) ;
2022-05-24 13:16:42 +02:00
` ,Ate= `
2022-03-07 19:17:31 +01:00
vec4 result = vec4 ( max ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2022-05-24 13:16:42 +02:00
` +Hf+ `
2022-03-07 19:17:31 +01:00
return result ;
2022-05-24 13:16:42 +02:00
` , $ te=pn({opSnippet:Fte,packedOpSnippet:Ate,cpuKernelImpl:VY}),Dte={kernelName:Ui,backendName:"webgl",kernelFunc: $ te};function Rte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;Wu(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;w.assert(C.eitherStridesOrDilationsAreOne(i,u),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { i } and dilations '${u}' ` );let p=C.computePool2DInfo(r.shape,s,i,u,o,l);if(p.filterWidth===1&&p.filterHeight===1&&w.arraysEqual(p.inShape,p.outShape))return na({inputs:{x:r},backend:n});let d=new oc(p,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var Mte={kernelName:Gi,backendName:"webgl",kernelFunc:Rte};function Pte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=a,p=[1,1,1],d=C.computePool3DInfo(r.shape,s,i,p,o,u,l),c=new M0(d,"max",!1);return n.runWebGLProgram(c,[r],r.dtype)}var Ote={kernelName:vc,backendName:"webgl",kernelFunc:Pte},Lte=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,a=e.dilationHeight,r=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=r-1-e.padInfo.top,o=s-1-e.padInfo.left,l=r*s-1;this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec2 pads = ivec2 ( $ { i } , $ { o } ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
2020-08-29 20:56:29 +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 < $ { r } ;
wR += $ { a } ) {
float dyR = float ( dyRCorner + wR ) / $ { t } . 0 ;
2020-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2021-12-03 17:28:27 +01:00
2022-03-07 19:17:31 +01:00
for ( int wC = 0 ; wC < $ { s } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { n } . 0 ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2020-08-29 20:56:29 +02: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 ) ) ;
2020-10-12 20:28:19 +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 = wR * $ { s } + wC ;
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
dotProd += dyValue * mask ;
}
}
setOutput ( dotProd ) ;
}
2022-05-24 13:16:42 +02:00
` }},zte=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,p=o-1-e.padInfo.front,d=l-1-e.padInfo.top,c=u-1-e.padInfo.left,h=o*l*u-1;this.userCode= `
2022-03-07 19:17:31 +01:00
const ivec3 pads = ivec3 ( $ { p } , $ { d } , $ { c } ) ;
2020-08-29 20:56:29 +02:00
2022-03-07 19:17:31 +01:00
void main ( ) {
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 ;
2020-10-12 20:28:19 +02: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 ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
for ( int wD = 0 ; wD < $ { o } ;
wD += $ { r } ) {
float dyD = float ( dyDCorner + wD ) / $ { t } . 0 ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
continue ;
}
int idyD = int ( dyD ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
for ( int wR = 0 ; wR < $ { l } ;
wR += $ { s } ) {
float dyR = float ( dyRCorner + wR ) / $ { n } . 0 ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
for ( int wC = 0 ; wC < $ { u } ;
wC += $ { i } ) {
float dyC = float ( dyCCorner + wC ) / $ { a } . 0 ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
int maxPosValue = $ { h } -
int ( getMaxPos ( batch , idyD , idyR , idyC , ch ) ) ;
2020-12-15 14:15:43 +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 =
wD * $ { l } * $ { u } +
wR * $ { u } + wC ;
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
2021-03-31 13:01:22 +02:00
2022-03-07 19:17:31 +01:00
dotProd += dyValue * mask ;
}
}
}
setOutput ( dotProd ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Bte(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:p}=a,d=[1,1,1],c=C.computePool3DInfo(i.shape,o,l,d,u,p),h=new M0(c,"max",!0),m=n.runWebGLProgram(h,[i],i.dtype),f=new zte(c),g=n.runWebGLProgram(f,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),g}var Wte={kernelName:_m,backendName:"webgl",kernelFunc:Bte};function Vte(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;Wu([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:p,dimRoundingMode:d}=a,c=C.computePool2DInfo(o.shape,l,u,1,p,d),h=!0,m=new oc(c,"max",h),f=n.runWebGLProgram(m,[o],o.dtype),g=new Lte(c),y=n.runWebGLProgram(g,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),y}var Ute={kernelName:Tm,backendName:"webgl",kernelFunc:Vte};function Gte(e,t,n,a){let r=new oc(n,"max",!1),s=a.runWebGLProgram(r,[e],"float32");r=new oc(n,"max",!0,!0,t);let i=a.runWebGLProgram(r,[e],"float32");return[s,i]}var Hte={kernelName:Cm,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;w.assert(a.shape.length===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { a . shape . length } . ` );let u=[1,1];w.assert(C.eitherStridesOrDilationsAreOne(s,u),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { s } and dilations '${u}' ` );let p=C.computePool2DInfo(a.shape,r,s,u,i),[d,c]=Gte(a,o,p,l);return[d,c]}};function jte(e,t,n,a){let r=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/r,i=me({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=No(i,"float32","mean",a),l=me({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}var qte={kernelName:Hi,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{keepDims:r,axis:s}=t,i=n,o=a.shape.length,l=w.parseAxisParam(s,a.shape),u=l,p=C.getAxesPermutation(u,o),d=p!=null,c=i.shouldExecuteOnCPU([a]),h=[],m=a;if(d){if(c){let x=i.texData.get(m.dataId).values,v=new Array(o);for(let _=0;_<v.length;_++)v[_]=a.shape[p[_]];let k=D0(x,a.shape,a.dtype,p,v);m=i.makeTensorInfo(v,a.dtype);let T=i.texData.get(m.dataId);T.values=k}else m=qf(a,p,i);h.push(m),u=C.getInnerMostAxes(u.length,o)}C.assertAxesAreInnerMostDims("sum",u,o);let[f,g]=C.computeOutAndReduceShapes(m.shape,u),y=f;r&&(y=C.expandShapeToKeepDim(f,l));let b=jte(m,g,y,i);for(let x of h)i.disposeIntermediateTensorInfo(x);return b}};function Kte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=w.parseAxisParam(s,r.shape),u=l,p=C.getAxesPermutation(u,o),d=r;p!=null&&(d=Wt({inputs:{x:r},backend:n,attrs:{perm:p}}),u=C.getInnerMostAxes(u.length,r.shape.length)),C.assertAxesAreInnerMostDims("min",u,o);let[c,h]=C.computeOutAndReduceShapes(d.shape,u),m=w.sizeFromShape(h),f=me({inputs:{x:d},backend:n,attrs:{shape:[-1,m]}}),g=No(f,f.dtype,"min",n),y;if(i){let b=C.expandShapeToKeepDim(c,l);y=me({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=me({inputs:{x:g},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),p!=null&&n.disposeIntermediateTensorInfo(d),y}var Xte={kernelName:ji,backendName:"webgl",kernelFunc:Kte},Yte=uC+ `
2022-03-07 19:17:31 +01:00
return min ( a , b ) ;
2022-05-24 13:16:42 +02:00
` ,Qte= `
2022-03-07 19:17:31 +01:00
vec4 result = vec4 ( min ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2022-05-24 13:16:42 +02:00
` +Hf+ `
2022-03-07 19:17:31 +01:00
return result ;
2022-05-24 13:16:42 +02:00
` ,Jte=pn({opSnippet:Yte,packedOpSnippet:Qte,cpuKernelImpl:UY}),Zte={kernelName:qi,backendName:"webgl",kernelFunc:Jte},ene=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,p)=>u[0]+e[p]+u[1]);let a=e.length,r=mt(a),s=t.map(u=>u[0]).join(","),i=t.map((u,p)=>u[0]+e[p]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a),l=n==="reflect"?0:1;if(a===1){this.userCode= `
2022-03-07 19:17:31 +01:00
int start = $ { s } ;
int end = $ { i } ;
2020-10-12 20:28:19 +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= `
$ { r } start = $ { r } ( $ { s } ) ;
$ { r } end = $ { r } ( $ { i } ) ;
void main ( ) {
$ { r } outC = getOutputCoords ( ) ;
for ( int i = 0 ; i < $ { a } ; 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 } ;
}
}
$ { r } coords = outC - start ;
setOutput ( getX ( $ { o } ) ) ;
2021-03-31 13:01:22 +02:00
}
2022-05-24 13:16:42 +02:00
` }},tne=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,m)=>h[0]+e[m]+h[1]);let a=e.length,r=mt(a),s=t.map(h=>h[0]).join(","),i=t.map((h,m)=>h[0]+e[m]).join(","),o=Sn("rc",a),l=Sn("source",a),u= ` $ { o [ a - 1 ] } < $ { this . outputShape [ a - 1 ] } ` ,p=a===1?"source": ` vec2 ( $ { l . slice ( - 2 ) . join ( ) } ) ` ,d=n==="reflect"?0:1,c="";if(a===1){let h= `
2022-03-07 19:17:31 +01:00
$ { r } source = rc ;
if ( source < start ) {
source = start * 2 - source - $ { d } ;
} else if ( source >= end ) {
source = ( end - 1 ) * 2 - source + $ { d } ;
}
source -= start ;
` ;c= `
$ { r } rc = outputLoc ;
$ { h }
result [ 0 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { p } ) ;
$ { o [ a - 1 ] } += 1 ;
if ( $ { u } ) {
$ { h }
result [ 1 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { p } ) ;
}
` }else{let h= `
$ { r } source = rc ;
$ { r } lt = $ { r } ( lessThan ( source , start ) ) ;
$ { r } gte = $ { r } ( greaterThanEqual ( source , end ) ) ;
$ { r } orig = 1 - ( lt + gte ) ;
source = orig * source +
lt * ( start * 2 - source - $ { d } ) +
gte * ( ( end - 1 ) * 2 - source + $ { d } ) ;
source -= start ;
` ;c= `
$ { r } rc = outputLoc ;
$ { h }
result [ 0 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { p } ) ;
$ { o [ a - 1 ] } += 1 ;
if ( $ { u } ) {
$ { h }
result [ 1 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { p } ) ;
}
rc = outputLoc ;
$ { o [ a - 2 ] } += 1 ;
if ( $ { o [ a - 2 ] } < $ { this . outputShape [ a - 2 ] } ) {
$ { h }
result [ 2 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { p } ) ;
$ { o [ a - 1 ] } += 1 ;
if ( $ { u } ) {
$ { h }
result [ 3 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { p } ) ;
}
2021-03-31 13:01:22 +02:00
}
2022-03-07 19:17:31 +01:00
` }this.userCode= `
const $ { r } start = $ { r } ( $ { s } ) ;
const $ { r } end = $ { r } ( $ { i } ) ;
void main ( ) {
$ { r } outputLoc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
$ { c }
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2022-05-24 13:16:42 +02:00
` }},nne=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{paddings:r,mode:s}=n,i=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new tne(a.shape,r,s):new ene(a.shape,r,s);return t.runWebGLProgram(i,[a],a.dtype)},ane={kernelName:Ki,backendName:"webgl",kernelFunc:nne},rne= ` if ( b == 0.0 ) return NAN ;
return mod ( a , b ) ; ` ,sne= `
2022-03-07 19:17:31 +01:00
vec4 result = mod ( a , b ) ;
vec4 isNaN = vec4 ( equal ( b , vec4 ( 0.0 ) ) ) ;
2022-05-24 13:16:42 +02:00
` +Hf+ `
2022-03-07 19:17:31 +01:00
return result ;
2022-05-24 13:16:42 +02:00
` ,ine=pn({opSnippet:rne,packedOpSnippet:sne}),one={kernelName:nu,backendName:"webgl",kernelFunc:ine},lne=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
float r = random ( seed ) ;
float cdf = 0.0 ;
for ( int i = 0 ; i < $ { t - 1 } ; i ++ ) {
cdf += getProbs ( batch , i ) ;
if ( r < cdf ) {
setOutput ( float ( i ) ) ;
return ;
}
}
// If no other event happened, last event happened.
setOutput ( float ( $ { t - 1 } ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},une= `
2022-03-07 19:17:31 +01:00
if ( a == b ) {
return 1.0 ;
} ;
2022-05-24 13:16:42 +02:00
return a / b ; ` ,pne= `
2022-03-07 19:17:31 +01:00
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b ;
if ( a . x == b . x ) {
result . x = 1. ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
if ( a . y == b . y ) {
result . y = 1. ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
if ( a . z == b . z ) {
result . z = 1. ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
if ( a . w == b . w ) {
result . w = 1. ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
return result ;
2022-05-24 13:16:42 +02:00
` ,AC=pn({opSnippet:une,packedOpSnippet:pne,checkOutOfBounds:!0}),cne={kernelName: $ i,backendName:"webgl",kernelFunc:AC},Gk="return a - b;", $ C=pn({opSnippet:Gk,packedOpSnippet:Gk,supportsComplex:!0,cpuKernelImpl:i9}),dne={kernelName:mo,backendName:"webgl",kernelFunc: $ C};function DC(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=w.parseAxisParam([s],r.shape),o=FC({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=C.expandShapeToKeepDim(o.shape,i),u=me({inputs:{x:o},backend:n,attrs:{shape:l}}),p= $ C({inputs:{a:r,b:u},backend:n}),d=_C({inputs:{x:p},backend:n}),c=Kf({inputs:{x:d},backend:n,attrs:{axis:i,keepDims:!1}}),h=me({inputs:{x:c},backend:n,attrs:{shape:l}}),m=AC({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),m}var hne={kernelName:co,backendName:"webgl",kernelFunc:DC};function mne(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a,l=o?r:DC({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),u=l.shape[0],p=l.shape[1],d=new lne(u,p,s),c=[[i]],h=n.runWebGLProgram(d,[l],"int32",c);return o||n.disposeIntermediateTensorInfo(l),h}var fne={kernelName:Em,backendName:"webgl",kernelFunc:mne},gne=Ea+ `
2022-03-07 19:17:31 +01:00
return - x ;
2022-05-24 13:16:42 +02:00
` ,yne= `
2022-03-07 19:17:31 +01:00
vec4 result = - x ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2022-05-24 13:16:42 +02:00
` ;function bne(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])){let s=n.texData.get(a.dataId),[i,o]=HY(s.values,a.shape,a.dtype);return n.makeTensorInfo(o,a.dtype,i)}let r;return X().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Qs(a.shape,yne):r=new Sr(a.shape,gne),n.runWebGLProgram(r,[a],a.dtype)}var xne={kernelName:au,backendName:"webgl",kernelFunc:bne},vne=mr.nonMaxSuppressionV3Impl;function wne(e){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a,u=n.readSync(r.dataId),p=n.readSync(s.dataId),{selectedIndices:d}=vne(u,p,i,o,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var kne={kernelName:su,backendName:"webgl",kernelFunc:wne},Ine=mr.nonMaxSuppressionV4Impl;function Sne(e){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=a,p=n.readSync(r.dataId),d=n.readSync(s.dataId),{selectedIndices:c,validOutputs:h}=Ine(p,d,i,o,l,u);return[n.makeTensorInfo([c.length],"int32",new Int32Array(c)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Nne={kernelName:iu,backendName:"webgl",kernelFunc:Sne},Tne=mr.nonMaxSuppressionV5Impl;function _ne(e){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=a,p=n.readSync(r.dataId),d=n.readSync(s.dataId),c=i,h=o,m=l,f=u,{selectedIndices:g,selectedScores:y}=Tne(p,d,c,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var Cne={kernelName:ou,backendName:"webgl",kernelFunc:_ne},Ene=class{constructor(e,t,n,a){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int index = round ( getIndices ( coords . x ) ) ;
setOutput ( mix ( float ( $ { a } ) , float ( $ { n } ) ,
float ( index == coords . y ) ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},Fne=e=>{let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{depth:s,onValue:i,offValue:o}=a,l=w.sizeFromShape(r.shape),u=new Ene(l,s,i,o),p=me({inputs:{x:r},backend:n,attrs:{shape:[l]}}),d=n.runWebGLProgram(u,[p],r.dtype);n.disposeIntermediateTensorInfo(p);let c=[...r.shape,s],h=me({inputs:{x:d},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(d),h},Ane={kernelName:Yi,backendName:"webgl",kernelFunc:Fne};function nm(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="complex64"){let r=od({inputs:{input:a},backend:n}),s=nm({inputs:{x:r},backend:n}),i=Xf({inputs:{input:a},backend:n}),o=nm({inputs:{x:i},backend:n}),l=Is({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return ld({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:n})}var $ ne={kernelName:Tu,backendName:"webgl",kernelFunc:nm};function RC(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(a.dtype==="complex64"){let r=od({inputs:{input:a},backend:n}),s=RC({inputs:{x:r},backend:n}),i=Xf({inputs:{input:a},backend:n}),o=nm({inputs:{x:i},backend:n}),l=Is({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return ld({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:n})}var Dne={kernelName:lu,backendName:"webgl",kernelFunc:RC};function Rne(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return fx({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{w.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let d=fx({inputs:{input:p},backend:n,attrs:{dim:r}});return o.push(d),d}),u=vC({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var Mne={kernelName:uu,backendName:"webgl",kernelFunc:Rne},Pne=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let a=e.length,r=mt(a),s=t.map(l=>l[0]).join(","),i=t.map((l,u)=>l[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a);if(a===1){this.userCode= `
2022-03-07 19:17:31 +01:00
int start = $ { s } ;
int end = $ { i } ;
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start || outC >= end ) {
setOutput ( value ) ;
} else {
setOutput ( getX ( outC - start ) ) ;
2021-03-31 13:01:22 +02:00
}
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
` ;return}this.userCode= `
$ { r } start = $ { r } ( $ { s } ) ;
$ { r } end = $ { r } ( $ { i } ) ;
void main ( ) {
$ { r } outC = getOutputCoords ( ) ;
if ( any ( lessThan ( outC , start ) ) || any ( greaterThanEqual ( outC , end ) ) ) {
setOutput ( value ) ;
} else {
$ { r } coords = outC - start ;
setOutput ( getX ( $ { o } ) ) ;
}
}
2022-05-24 13:16:42 +02:00
` }},One=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);let a=e.length,r=mt(a),s=t.map(m=>m[0]).join(","),i=t.map((m,f)=>m[0]+e[f]).join(","),o=Sn("rc",a),l=Sn("source",a),u= ` $ { o [ a - 1 ] } < $ { this . outputShape [ a - 1 ] } ` ,p=a===1?"source": ` vec2 ( $ { l . slice ( - 2 ) . join ( ) } ) ` ,d=[ ` $ { r } rc = outputLoc ; ` , ` $ { o [ a - 1 ] } += 1 ;
2022-03-07 19:17:31 +01:00
if ( $ { u } ) {
` ,a===1?"": ` }
rc = outputLoc ;
$ { o [ a - 2 ] } += 1 ;
if ( $ { o [ a - 2 ] } < $ { this . outputShape [ a - 2 ] } ) { ` ,a===1?"": ` $ { o [ a - 1 ] } += 1 ;
if ( $ { u } ) { ` ],c=a===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let m=0,f=a===1?2:4;m<f;m++)h+= `
$ { d [ m ] }
if ( $ { c } ) {
result [ $ { m } ] = float ( value ) ;
} else {
$ { r } source = rc - start ;
result [ $ { m } ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { p } ) ;
2021-03-31 13:01:22 +02:00
}
2022-03-07 19:17:31 +01:00
` ;h+=a===1?"} ":"}}",this.userCode= `
const $ { r } start = $ { r } ( $ { s } ) ;
const $ { r } end = $ { r } ( $ { i } ) ;
void main ( ) {
$ { r } outputLoc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
$ { h }
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` }},MC=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a;if(w.sizeFromShape(r.shape)===0){let u=s.map((p,d)=>p[0]+r.shape[d]+p[1]);return ld({backend:n,attrs:{shape:u,value:i,dtype:r.dtype}})}let o=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new One(r.shape,s,i):new Pne(r.shape,s,i),l=[[i]];return n.runWebGLProgram(o,[r],r.dtype,l)},Lne={kernelName:Qi,backendName:"webgl",kernelFunc:MC},zne= `
2022-03-07 19:17:31 +01:00
if ( a < 0.0 && floor ( b ) < b ) {
return NAN ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
if ( b == 0.0 ) {
return 1.0 ;
}
return ( round ( mod ( b , 2.0 ) ) != 1 ) ?
pow ( abs ( a ) , b ) : sign ( a ) * pow ( abs ( a ) , b ) ;
2022-05-24 13:16:42 +02:00
` ,Bne= `
2022-03-07 19:17:31 +01:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4 ( equal ( round ( mod ( b , 2.0 ) ) , ivec4 ( 1 ) ) ) ;
vec4 multiplier = sign ( a ) * isModRound1 + ( vec4 ( 1.0 ) - isModRound1 ) ;
vec4 result = multiplier * pow ( abs ( a ) , b ) ;
2020-10-12 20:28:19 +02: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 ;
2021-03-26 15:26:02 +01:00
2022-03-07 19:17:31 +01:00
vec4 isNaN = vec4 ( lessThan ( a , vec4 ( 0.0 ) ) ) * vec4 ( lessThan ( floor ( b ) , b ) ) ;
2022-05-24 13:16:42 +02:00
` +Hf+ `
2022-03-07 19:17:31 +01:00
return result ;
2022-05-24 13:16:42 +02:00
` ,Wne=pn({opSnippet:zne,packedOpSnippet:Bne}),Vne={kernelName:Ji,backendName:"webgl",kernelFunc:Wne};function Une(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=[],u=w.parseAxisParam(s,r.shape),p=u,d=C.getAxesPermutation(p,o),c=r;d!=null&&(c=Wt({inputs:{x:r},backend:n,attrs:{perm:d}}),p=C.getInnerMostAxes(p.length,o),l.push(c)),C.assertAxesAreInnerMostDims("prod",p,o);let h;if(n.shouldExecuteOnCPU([c])){let m=n.texData.get(c.dataId).values,{outVals:f,outShape:g,outDtype:y}=qY(c.shape,c.dtype,m,p);h=n.makeTensorInfo(g,y,f)}else{let[m,f]=C.computeOutAndReduceShapes(c.shape,p),g=w.sizeFromShape(f),y=me({inputs:{x:c},backend:n,attrs:{shape:[-1,g]}}),b=Bm(r.dtype),x=No(y,b,"prod",n);h=me({inputs:{x},backend:n,attrs:{shape:m}}),l.push(y),l.push(x)}if(i){l.push(h);let m=C.expandShapeToKeepDim(h.shape,u);h=me({inputs:{x:h},backend:n,attrs:{shape:m}})}return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var Gne={kernelName:eo,backendName:"webgl",kernelFunc:Une},PC=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=KY(a,r,s,i);return t.makeTensorInfo([o.length],i,o)},Hne={kernelName:wc,backendName:"webgl",kernelFunc:PC},jne="return 1.0 / x;",qne=Qe({opSnippet:jne}),Kne={kernelName:pu,backendName:"webgl",kernelFunc:qne},Xne=Ea+ `
2022-03-07 19:17:31 +01:00
return ( x < 0.0 ) ? 0.0 : x ;
2022-05-24 13:16:42 +02:00
` ,Yne= `
2022-03-07 19:17:31 +01:00
vec4 result = x * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2021-03-26 15:26:02 +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-03-26 15:26:02 +01:00
2022-03-07 19:17:31 +01:00
return result ;
2022-05-24 13:16:42 +02:00
` ,Qne=Qe({opSnippet:Xne,packedOpSnippet:Yne}),Jne={kernelName:to,backendName:"webgl",kernelFunc:Qne},Zne=Ea+ `
2022-03-07 19:17:31 +01:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2022-05-24 13:16:42 +02:00
` ,eae= `
2022-03-07 19:17:31 +01:00
vec4 result = min ( x , vec4 ( 6. ) ) * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2021-03-26 15:26:02 +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-03-26 15:26:02 +01:00
2022-03-07 19:17:31 +01:00
return result ;
2022-05-24 13:16:42 +02:00
` ,tae=Qe({opSnippet:Zne,packedOpSnippet:eae}),nae={kernelName:ao,backendName:"webgl",kernelFunc:tae},aae=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d;r?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2022-03-07 19:17:31 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
$ { u [ 0 ] / p [ 0 ] } ,
$ { u [ 1 ] / p [ 1 ] } ) ;
const vec2 inputShapeRC = vec2 ( $ { i } . 0 , $ { o } . 0 ) ;
2021-04-01 19:39:54 +02: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-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
// Fractional source index.
vec2 sourceFracIndexRC = $ { d } ;
2021-05-27 22:04:17 +02: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-05-27 22:04:17 +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 ) ;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
vec2 fracRC = sourceFracIndexRC - vec2 ( sourceFloorRC ) ;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
float top = topLeft + ( topRight - topLeft ) * fracRC . y ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracRC . y ;
float newValue = top + ( bottom - top ) * fracRC . x ;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
setOutput ( newValue ) ;
2020-12-15 14:15:43 +01:00
}
2022-05-24 13:16:42 +02:00
` }},rae=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d;r?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2022-03-07 19:17:31 +01:00
const vec3 effectiveInputOverOutputRatioRC = vec3 (
$ { u [ 0 ] / p [ 0 ] } ,
$ { u [ 1 ] / p [ 1 ] } ,
$ { u [ 1 ] / p [ 1 ] } ) ;
const vec3 inputShapeRC = vec3 ( $ { i } . 0 , $ { o } . 0 ,
$ { o } . 0 ) ;
float getAValue ( int b , int r , int c , int d ) {
return getChannel ( getA ( b , r , c , d ) , vec2 ( c , d ) ) ;
2021-03-31 13:01:22 +02:00
}
2020-10-12 20:28:19 +02: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 ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
// Fractional source index.
vec3 sourceFracIndexRC = $ { d } ;
2021-03-26 15:26:02 +01:00
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 ) ) ) ;
2021-04-01 19:39:54 +02: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-04-01 19:39:54 +02:00
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 ) ;
2021-04-01 19:39:54 +02: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 ) ;
2021-04-01 19:39:54 +02: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 ) ;
2020-10-12 20:28:19 +02: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 ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
vec3 fracRC = sourceFracIndexRC - vec3 ( sourceFloorRC ) ;
2020-10-12 20:28:19 +02: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 ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
setOutput ( newValue ) ;
}
2022-05-24 13:16:42 +02:00
` }};function sae(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,p=X().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new rae(r.shape,l,u,s,i):new aae(r.shape,l,u,s,i);return n.runWebGLProgram(p,[r],"float32")}var iae={kernelName:no,backendName:"webgl",kernelFunc:sae},oae=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],u=o[0]/l[0],p=o[1]/l[1],d=1/u,c=1/p,h=Math.ceil(d)*2+2,m=Math.ceil(c)*2+2;this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
float accumulator = 0.0 ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
const float heightScale = float ( $ { u } ) ;
const float widthScale = float ( $ { p } ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
const float invHeightScale = float ( $ { d } ) ;
const float invWidthScale = float ( $ { c } ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
const int winHeight = int ( $ { h } ) ;
const int winWidth = int ( $ { m } ) ;
2020-12-15 14:15:43 +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 ) ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( startCLerp - float ( winWidth / 2 ) ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
// Guard against the window exceeding the bounds of dy
if ( dyR < 0 || dyR >= $ { s } ) {
continue ;
}
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
// Guard against the window exceeding the bounds of dy
if ( dyC < 0 || dyC >= $ { i } ) {
continue ;
}
2020-12-15 14:15:43 +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 ) , $ { a - 1 } . 0 ) ) ;
float dxRLerp = dxR - float ( topDxRIndex ) ;
float inverseDxRLerp = 1.0 - dxRLerp ;
2020-12-15 14:15:43 +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 ) , $ { r - 1 } . 0 ) ) ;
float dxCLerp = dxC - float ( leftDxCIndex ) ;
float inverseDxCLerp = 1.0 - dxCLerp ;
if ( r == topDxRIndex && c == leftDxCIndex ) {
// topLeft
accumulator +=
getDy ( b , dyR , dyC , d ) * inverseDxRLerp * inverseDxCLerp ;
}
if ( r == topDxRIndex && c == rightDxCIndex ) {
// topRight
accumulator += getDy ( b , dyR , dyC , d ) * inverseDxRLerp * dxCLerp ;
}
if ( r == bottomDxRIndex && c == leftDxCIndex ) {
// bottomLeft
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * inverseDxCLerp ;
}
2020-12-15 14:15:43 +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
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
setOutput ( accumulator ) ;
}
2022-05-24 13:16:42 +02:00
` }};function lae(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new oae(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var uae={kernelName: $ m,backendName:"webgl",kernelFunc:lae},pae=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d=a?"0.5":"0.0",c;r?c="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":c="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2022-03-07 19:17:31 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
$ { u [ 0 ] / p [ 0 ] } ,
$ { u [ 1 ] / p [ 1 ] } ) ;
const vec2 inputShapeRC = vec2 ( $ { i } . 0 , $ { o } . 0 ) ;
2020-12-15 14:15:43 +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 ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
// Fractional source index.
vec2 sourceFracIndexRC = $ { c } ;
2020-12-15 14:15:43 +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 + $ { d } ) ) ) ;
float newValue = getA ( b , sourceNearestRC . x , sourceNearestRC . y , d ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
setOutput ( newValue ) ;
}
2022-05-24 13:16:42 +02:00
` }},cae=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],p=[a&&t>1?t-1:t,a&&n>1?n-1:n],d=a?"0.5":"0.0",c;r?c="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":c="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2022-03-07 19:17:31 +01:00
const vec3 effectiveInputOverOutputRatioRC = vec3 (
$ { u [ 0 ] / p [ 0 ] } ,
$ { u [ 1 ] / p [ 1 ] } ,
$ { u [ 1 ] / p [ 1 ] } ) ;
const vec3 inputShapeRC = vec3 ( $ { i } . 0 , $ { o } . 0 ,
$ { o } . 0 ) ;
2020-12-15 14:15:43 +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 ) ) ;
}
2020-12-15 14:15:43 +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 ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
// Fractional source index.
vec3 sourceFracIndexRC = $ { c } ;
2021-04-01 19:39:54 +02: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 + $ { d } ) ) ) ;
2020-12-15 14:15:43 +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 } ;
2020-12-15 14:15:43 +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 ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
setOutput ( newValue ) ;
}
2022-05-24 13:16:42 +02:00
` }};function dae(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,p=X().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new cae(r.shape,l,u,s,i):new pae(r.shape,l,u,s,i);return n.runWebGLProgram(p,[r],r.dtype)}var hae={kernelName:kc,backendName:"webgl",kernelFunc:dae},mae=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],u=o[0]/l[0],p=o[1]/l[1],d=1/u,c=1/p,h=Math.ceil(d)*2+2,m=Math.ceil(c)*2+2;this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
float accumulator = 0.0 ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
const float heightScale = float ( $ { u } ) ;
const float widthScale = float ( $ { p } ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
const float invHeightScale = float ( $ { d } ) ;
const float invWidthScale = float ( $ { c } ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
const int winHeight = int ( $ { h } ) ;
const int winWidth = int ( $ { m } ) ;
2020-12-15 14:15:43 +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 ) ) ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( floor ( startCLerp - float ( winWidth / 2 ) ) ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
// Guard against the window exceeding the bounds of dy
if ( dyR < 0 || dyR >= $ { s } ) {
continue ;
}
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
// Guard against the window exceeding the bounds of dy
if ( dyC < 0 || dyC >= $ { i } ) {
continue ;
}
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
float sourceFracRow =
float ( $ { o [ 0 ] } ) *
( float ( dyR ) / float ( $ { l [ 0 ] } ) ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
float sourceFracCol =
float ( $ { o [ 1 ] } ) *
( float ( dyC ) / float ( $ { l [ 1 ] } ) ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
int sourceNearestRow = int ( min (
float ( int ( $ { a } ) - 1 ) ,
$ { n } ? float ( round ( sourceFracRow ) ) :
float ( floor ( sourceFracRow ) ) ) ) ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
int sourceNearestCol = int ( min (
float ( int ( $ { r } ) - 1 ) ,
$ { n } ? float ( round ( sourceFracCol ) ) :
float ( floor ( sourceFracCol ) ) ) ) ;
2020-10-11 18:41:17 +02:00
2022-03-07 19:17:31 +01:00
if ( r == sourceNearestRow && c == sourceNearestCol ) {
accumulator += getDy ( b , dyR , dyC , d ) ;
}
}
}
// End loop over dy
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
setOutput ( accumulator ) ;
}
2022-05-24 13:16:42 +02:00
` }};function fae(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new mae(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var gae={kernelName:Am,backendName:"webgl",kernelFunc:fae},yae=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error( ` WebGL backend : Reverse of rank - $ { n } tensor is not yet supported ` );if(this.outputShape=e,n===1){this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
int coord = getOutputCoords ( ) ;
setOutput ( getX ( $ { e [ 0 ] } - coord - 1 ) ) ;
}
2022-05-18 14:36:05 +02:00
` ;return}let a=i=>t.indexOf(i)!==-1&&e[i]!==1? ` $ { e [ i ] } - coords [ $ { i } ] - 1 ` : ` coords [ $ { i } ] ` ,r=e.map((i,o)=>a(o)).join(","),s=mt(n);this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { s } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { r } ) ) ;
}
2022-05-24 13:16:42 +02:00
` }},bae=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error( ` WebGL backend : Reverse of rank - $ { n } tensor is not yet supported ` );this.outputShape=e;let a=Sn("rc",n),r= ` $ { a [ n - 1 ] } + 1 < $ { this . outputShape [ n - 1 ] } ` ,s= ` $ { a [ n - 2 ] } + 1 < $ { this . outputShape [ n - 2 ] } ` ,i=mt(n);n===1?this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
int rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
result . r = getChannel ( getX ( $ { e [ 0 ] } - rc - 1 ) ,
$ { e [ 0 ] } - rc - 1 ) ;
if ( $ { r } ) {
result . g = getChannel ( getX ( $ { e [ 0 ] } - ( rc + 1 ) - 1 ) ,
$ { e [ 0 ] } - ( rc + 1 ) - 1 ) ;
}
setOutput ( result ) ;
}
` :this.userCode= `
void main ( ) {
$ { i } rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
result . r = $ { o ( a . slice ( ) ) } ;
if ( $ { r } ) {
result . g = $ { l ( a . slice ( ) ) } ;
}
if ( $ { s } ) {
result . b = $ { u ( a . slice ( ) ) } ;
if ( $ { r } ) {
result . a = $ { p ( a . slice ( ) ) } ;
}
}
setOutput ( result ) ;
}
2022-05-24 13:16:42 +02:00
` ;function o(h){return d(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function u(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function p(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let m=e.map((y,b)=>c(b,h)),f=m.join(","),g=m.slice(-2).join(",");return ` getChannel ( getX ( $ { f } ) , vec2 ( $ { g } ) ) ` }function c(h,m){return t.indexOf(h)!==-1&&e[h]!==1? ` $ { e [ h ] } - $ { m [ h ] } - 1 ` : ` $ { m [ h ] } ` }}};function xae(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=r.shape.length,o=w.parseAxisParam(s,r.shape);if(i===0)return na({inputs:{x:r},backend:n});let l=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new bae(r.shape,o):new yae(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}var vae={kernelName:ro,backendName:"webgl",kernelFunc:xae},wae=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],a=e[2];this.outputShape=e;let r="";typeof t=="number"?r= ` float outputValue = $ { t . toFixed ( 2 ) } ; ` :r= `
2022-03-07 19:17:31 +01:00
vec3 fill = vec3 ( $ { t . 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 ] ) ) ;
$ { r }
if ( coordX >= 0 && coordX < $ { a } && coordY >= 0 && coordY < $ { n } ) {
outputValue = getImage ( coords [ 0 ] , coordY , coordX , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
}
2022-05-24 13:16:42 +02:00
` }},kae={kernelName:_u,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=new wae(a.shape,s),[u,p]=C.getImageCenter(i,a.shape[1],a.shape[2]),d=[[u,p,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[a],a.dtype,d)}},Iae= `
2022-03-07 19:17:31 +01:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor ( x ) ;
if ( ( x - base ) < 0.5 ) {
return floor ( x ) ;
} else if ( ( x - base ) > 0.5 ) {
return ceil ( x ) ;
} else {
if ( mod ( base , 2.0 ) == 0.0 ) {
return base ;
} else {
return base + 1.0 ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
}
2022-05-24 13:16:42 +02:00
` ,Sae=Qe({opSnippet:Iae}),Nae={kernelName:so,backendName:"webgl",kernelFunc:Sae},Tae="return inversesqrt(x);",_ae=Qe({opSnippet:Tae,cpuKernelImpl:XY}),Cae={kernelName:io,backendName:"webgl",kernelFunc:_ae},OC=class{constructor(e,t,n,a,r,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=mt(r.length),l=mt(s.length),u="";n===1?u="i":n===2&&(u="i, j");let p= ` getIndices ( $ { u } ) ` ,d="";a===1?d="i":a===2&&(d="i, coords[1]");let c= ` getUpdates ( $ { d } ) ` ,h=t>1?"strides[j]":"strides";this.userCode= `
2022-03-07 19:17:31 +01:00
$ { o } strides = $ { o } ( $ { r } ) ;
2020-10-29 05:16: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 < $ { e } ; i ++ ) {
int flattenedIndex = 0 ;
for ( int j = 0 ; j < $ { t } ; j ++ ) {
int index = round ( $ { p } ) ;
flattenedIndex += index * $ { h } ;
}
if ( flattenedIndex == coords [ 0 ] ) {
sum += $ { c } ;
found = true ;
}
}
setOutput ( mix ( getDefaultValue ( ) , sum , float ( found ) ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Eae(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:d}=C.calculateShapes(s,r,i),c=[d/u,u];if(d===0)return n.makeTensorInfo(i,r.dtype);let h=me({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),m=me({inputs:{x:s},backend:n,attrs:{shape:[l,u]}}),f=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new OC(l,o,h.shape.length,m.shape.length,p,c),y=n.runWebGLProgram(g,[m,h,f],m.dtype),b=me({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(f),b}var Fae={kernelName:du,backendName:"webgl",kernelFunc:Eae},Aae=class{constructor(e,t,n,a){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];let r="while (left < right) {",s= ` for ( int i = 0 ; i < $ { Math . ceil ( Math . log2 ( t + 1 ) ) } ; ++ i ) { if ( left >= right ) break ; ` ,i=X().getNumber("WEBGL_VERSION")===2?r:s,o=a==="left"?"<":"<=";this.userCode= `
2022-05-18 14:36:05 +02:00
int findBound ( int batch , float value ) {
int left = 0 ;
int right = numInputs ;
int mid ;
$ { i }
mid = ( left + right ) / 2 ;
if ( getSortedSequence ( batch , mid ) $ { o } value ) {
left = mid + 1 ;
} else {
right = mid ;
}
}
return right ;
}
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int valueIndex = coords [ 1 ] ;
float value = getValues ( batch , valueIndex ) ;
setOutput ( float ( findBound ( batch , value ) ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function $ ae(e){let{inputs:t,backend:n,attrs:a}=e,{sortedSequence:r,values:s}=t,{side:i}=a,o=new Aae(r.shape[0],r.shape[1],s.shape[1],i),l=[[r.shape[1]]];return n.runWebGLProgram(o,[r,s],"int32",l)}var Dae={kernelName:Dm,backendName:"webgl",kernelFunc: $ ae},Rae=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let a,r;if(n>4)throw Error( ` Where for rank $ { n } is not yet supported ` );if(n===1)r="resRC",a="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let u=0;u<t.length;u++)l.push( ` $ { i [ u ] } ` ),u<e&&o.push( ` $ { i [ u ] } ` );a=o.join(),r=l.join()}let s=mt(n);this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { s } resRC = getOutputCoords ( ) ;
float cVal = getC ( $ { a } ) ;
if ( cVal >= 1.0 ) {
setOutput ( getA ( $ { r } ) ) ;
} else {
setOutput ( getB ( $ { r } ) ) ;
}
}
2022-05-24 13:16:42 +02:00
` }};function Mae(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=new Rae(a.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[a,r,s],ma(r.dtype,s.dtype))}var Pae={kernelName:hu,backendName:"webgl",kernelFunc:Mae},Oae= `
2022-03-07 19:17:31 +01:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2022-05-24 13:16:42 +02:00
float scaleAlpha = $ { C . SELU _SCALEALPHA } ;
float scale = $ { C . SELU _SCALE } ;
2022-03-07 19:17:31 +01:00
return ( x >= 0.0 ) ? scale * x : scaleAlpha * ( exp ( x ) - 1.0 ) ;
2022-05-24 13:16:42 +02:00
` ,Lae=Qe({opSnippet:Oae}),zae={kernelName:mu,backendName:"webgl",kernelFunc:Lae},Bae=ju+ `
2022-03-07 19:17:31 +01:00
return 1.0 / ( 1.0 + exp ( - 1.0 * x ) ) ;
2022-05-24 13:16:42 +02:00
` ,Wae= `
2022-03-07 19:17:31 +01:00
vec4 result = 1.0 / ( 1.0 + exp ( - 1.0 * x ) ) ;
bvec4 isNaN = isnan ( x ) ;
2020-10-29 05:16: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 ;
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
return result ;
2022-05-24 13:16:42 +02:00
` ,Vae=Qe({opSnippet:Bae,packedOpSnippet:Wae,cpuKernelImpl:QY}),Uae={kernelName:lo,backendName:"webgl",kernelFunc:Vae},Gae= `
2022-03-07 19:17:31 +01:00
if ( isnan ( x ) ) { return 0.0 ; }
return sign ( x ) ;
2022-05-24 13:16:42 +02:00
` ,Hae=Qe({opSnippet:Gae}),jae={kernelName:yu,backendName:"webgl",kernelFunc:Hae},qae=ju+ `
2022-03-07 19:17:31 +01:00
return sin ( x ) ;
2022-05-24 13:16:42 +02:00
` ,Kae=Qe({opSnippet:qae}),Xae={kernelName:oo,backendName:"webgl",kernelFunc:Kae},Yae= `
2022-03-07 19:17:31 +01:00
float e2x = exp ( x ) ;
return ( e2x - 1.0 / e2x ) / 2.0 ;
2022-05-24 13:16:42 +02:00
` ,Qae=Qe({opSnippet:Yae}),Jae={kernelName:gu,backendName:"webgl",kernelFunc:Qae},Zae= `
2022-03-07 19:17:31 +01:00
float epsilon = 1.1920928955078125 e - 7 ;
float threshold = log ( epsilon ) + 2.0 ;
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
bool too _large = x > - threshold ;
bool too _small = x < threshold ;
2020-10-12 20:28:19 +02:00
2022-03-07 19:17:31 +01:00
float result ;
float exp _x = exp ( x ) ;
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
if ( too _large ) {
result = x ;
2021-04-01 19:39:54 +02:00
}
2022-03-07 19:17:31 +01:00
else if ( too _small ) {
result = exp _x ;
2021-04-01 19:39:54 +02: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 ;
2022-05-24 13:16:42 +02:00
` ,ere=Qe({opSnippet:Zae}),tre={kernelName:bu,backendName:"webgl",kernelFunc:ere},nre=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;w.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((y,b)=>y*b),l=[[0,0]];l.push(...i);for(let y=1+s.length;y<r.shape.length;++y)l.push([0,0]);let u=[],p=MC({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),d=C.getReshaped(p.shape,s,o,!1),c=C.getPermuted(d.length,s.length,!1),h=C.getReshapedPermuted(p.shape,s,o,!1),m=me({inputs:{x:p},backend:n,attrs:{shape:d}}),f=Wt({inputs:{x:m},backend:n,attrs:{perm:c}}),g=me({inputs:{x:f},backend:n,attrs:{shape:h}});return u.push(p),u.push(m),u.push(f),u.forEach(y=>n.disposeIntermediateTensorInfo(y)),g},are={kernelName:xu,backendName:"webgl",kernelFunc:nre};function rre(e){let{inputs:t,backend:n}=e,{indices:a,values:r,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error( ` Dense shape must be a vector , saw :
2022-03-07 19:17:31 +01:00
$ { s . shape } ` );if(a.shape.length!==2)throw new Error( ` Indices must be a matrix , saw :
$ { a . shape } ` );if(r.shape.length!==1)throw new Error( ` Values must be a vector , saw :
$ { r . shape } ` );if(i.shape.length!==0)throw new Error( ` Default value must be a scalar , saw :
2022-05-24 13:16:42 +02:00
$ { i . shape } ` );let o=n.readSync(a.dataId),l=n.readSync(r.dataId),u=n.readSync(s.dataId),p=n.readSync(i.dataId)[0],[d,c,h,m,f]=ZY(o,a.shape,a.dtype,l,r.dtype,u,p);return[n.makeTensorInfo(c,a.dtype,d),n.makeTensorInfo([c[0]],r.dtype,h),n.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),n.makeTensorInfo([f.length],a.dtype,new Int32Array(f))]}var sre={kernelName:Ic,backendName:"webgl",kernelFunc:rre};function ire(e){let{inputs:t,backend:n}=e,{inputIndices:a,inputShape:r,newShape:s}=t;if(a.shape.length!==2)throw new Error( ` Input indices should be a matrix but received shape $ { a . shape } ` );if(r.shape.length!==1)throw new Error( ` Input shape should be a vector but received shape $ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Target shape should be a vector but received shape $ { s . shape } ` );let i=Array.from(n.readSync(r.dataId)),o=n.readSync(a.dataId),l=Array.from(n.readSync(s.dataId)),[u,p,d]=e9(o,a.shape,a.dtype,i,l);return[n.makeTensorInfo(p,a.dtype,u),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}var ore={kernelName:wu,backendName:"webgl",kernelFunc:ire};function lre(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
2022-03-07 19:17:31 +01:00
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
2022-05-24 13:16:42 +02:00
$ { s . shape } ` );let i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,p]=sC(i,a.shape,a.dtype,o,l,!0);return n.makeTensorInfo(p,a.dtype,u)}var ure={kernelName:Sc,backendName:"webgl",kernelFunc:lre};function pre(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
2022-03-07 19:17:31 +01:00
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
2022-05-24 13:16:42 +02:00
$ { s . shape } ` );let i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,p]=sC(i,a.shape,a.dtype,o,l);return n.makeTensorInfo(p,a.dtype,u)}var cre={kernelName:Nc,backendName:"webgl",kernelFunc:pre};function dre(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:u,sliceSize:p,strides:d,outputSize:c}=C.calculateShapes(s,r,o),h=!1;if(s.dtype==="string"){let y=n.bufferSync(r),b=n.bufferSync(s),x=w.decodeString(n.readSync(i.dataId)[0]),v=YY(y,b,o,c,p,u,l,d,x,h);return n.makeTensorInfo(o,v.dtype,v.values)}let m=new OC(u,l,r.shape.length,s.shape.length,d,[c,1],h),f=n.runWebGLProgram(m,[s,r,i],s.dtype),g=me({inputs:{x:f},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(f),g}var hre={kernelName:Rm,backendName:"webgl",kernelFunc:dre};function mre(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,r.shape)[0],l=C.prepareSplitSize(r,s,o),u=r.shape.length,p=new Array(u).fill(0),d=r.shape.slice();return l.map(c=>{let h=[...d];h[o]=c;let m=qu({inputs:{x:r},backend:n,attrs:{begin:p,size:h}});return p[o]+=c,m})}var fre={kernelName:vu,backendName:"webgl",kernelFunc:mre},Hk="return sqrt(x);",gre=Qe({opSnippet:Hk,packedOpSnippet:Hk,cpuKernelImpl:t9}),yre={kernelName:uo,backendName:"webgl",kernelFunc:gre},bre="return x * x;",xre=Qe({opSnippet:bre}),vre={kernelName:Tc,backendName:"webgl",kernelFunc:xre},jk="return (a - b) * (a - b);",wre=pn({opSnippet:jk,packedOpSnippet:jk}),kre={kernelName:ho,backendName:"webgl",kernelFunc:wre};function Ire({inputs:e,attrs:t,backend:n}){let{x:a}=e,r=Ea+ `
2022-03-07 19:17:31 +01:00
return x > 0.0 ? 1.0 : float ( $ { t . alpha } ) ;
2022-05-24 13:16:42 +02:00
` ,s=new Sr(a.shape,r);return n.runWebGLProgram(s,[a],a.dtype)}var Sre={kernelName:gs,backendName:"webgl",kernelFunc:Ire},Nre=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let a=n.length,r=mt(n.length),s=mt(n.length),i="";if(a===1)i="coords * strides + begin";else{let o=0;i=n.map((l,u)=>(o++,n.length===1? ` coords * strides [ $ { u } ] + begin [ $ { u } ] ` : ` coords [ $ { o - 1 } ] * strides [ $ { u } ] + begin [ $ { u } ] ` )).join(",")}this.userCode= `
2022-03-07 19:17:31 +01:00
$ { r } begin = $ { r } ( $ { e } ) ;
$ { r } strides = $ { r } ( $ { t } ) ;
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { s } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { i } ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Tre(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:d,shrinkAxisMask:c}=a,{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:v}=Kt.sliceInfo(r.shape,s,i,o,l,u,p,d,c),k;if(f)k=me({inputs:{x:r},backend:n,attrs:{shape:m}});else if(g||y){w.assert(r.shape.length>=1,()=> ` Input must have rank at least 1 , got : $ { r . shape . length } ` );let _=Kt.computeOutShape(b,x,v),E=qu({inputs:{x:r},backend:n,attrs:{begin:b,size:_}});k=me({inputs:{x:E},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(E)}else if(n.shouldExecuteOnCPU([r])){let _=n.readSync(r.dataId),E=Ve(r.shape,r.dtype,_),A=n9(h,E,v,b);k=n.makeTensorInfo(m,r.dtype,A.values)}else{let _=new Nre(b,v,h);k=n.runWebGLProgram(_,[r],r.dtype)}let T=me({inputs:{x:k},backend:n,attrs:{shape:m}});return n.disposeIntermediateTensorInfo(k),T}var _re={kernelName:ku,backendName:"webgl",kernelFunc:Tre};function Cre(e){let{inputs:t,backend:n,attrs:a}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=a,{data:p,dataSplits:d}=t,c=n.readSync(p.dataId),h=n.readSync(d.dataId),[m,f]=a9(c,h,r,s,i,o,l,u);return[n.makeTensorInfo([m.length],"string",m),n.makeTensorInfo(d.shape,"int32",f)]}var Ere={kernelName:Mm,backendName:"webgl",kernelFunc:Cre};function Fre(e){let{inputs:t,backend:n,attrs:a}=e,{skipEmpty:r}=a,{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 o=n.readSync(s.dataId),l=n.readSync(i.dataId)[0],[u,p,d]=r9(o,l,r),c=p.length;return[n.makeTensorInfo([c,2],"int32",u),n.makeTensorInfo([c],"string",p),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var Are={kernelName:Pm,backendName:"webgl",kernelFunc:Fre};function $ re(e){let{inputs:t,backend:n,attrs:a}=e,{numBuckets:r}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let i=n.readSync(s.dataId),o=s9(i,r);return n.makeTensorInfo(s.shape,"int32",o)}var Dre={kernelName:Om,backendName:"webgl",kernelFunc: $ re},Rre="return tan(x);",Mre=Qe({opSnippet:Rre}),Pre={kernelName:fo,backendName:"webgl",kernelFunc:Mre},Ore= `
2022-03-07 19:17:31 +01:00
float e2x = exp ( - 2.0 * abs ( x ) ) ;
return sign ( x ) * ( 1.0 - e2x ) / ( 1.0 + e2x ) ;
2022-05-24 13:16:42 +02:00
` ,Lre=Qe({opSnippet:Ore}),zre={kernelName:go,backendName:"webgl",kernelFunc:Lre},Bre=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[s]*t[s];this.outputShape=n,this.rank=n.length;let a=mt(this.rank),r=Wre(e);this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
$ { a } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { r } ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Wre(e){let t=e.length;if(t>5)throw Error( ` Tile for rank $ { t } is not yet supported ` );if(t===1)return ` imod ( resRC , $ { e [ 0 ] } ) ` ;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],a=[];for(let r=0;r<e.length;r++)a.push( ` imod ( $ { n [ r ] } , $ { e [ r ] } ) ` );return a.join()}function LC(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;if(r.dtype==="string"||r.shape.length>5){let o=n.readSync(r.dataId),l=r.dtype==="string"?o.map(d=>w.decodeString(d)):o,u=Ve(r.shape,r.dtype,l),p=o9(u,s);return n.makeTensorInfo(p.shape,p.dtype,p.values)}let i=new Bre(r.shape,s);return n.runWebGLProgram(i,[r],r.dtype)}var Vre={kernelName:fs,backendName:"webgl",kernelFunc:LC},Ure=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int elemIdx = coords [ 1 ] ;
2020-10-29 05:16: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.
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
bool isFirstInPair = imod ( elemIdx , 2 * inc ) < inc ;
int i = isFirstInPair ? elemIdx : elemIdx - inc ;
2020-12-15 14:15:43 +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 ;
2020-10-29 05:16: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 ) ) ;
}
}
2022-05-24 13:16:42 +02:00
` }},Gre=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode= `
2022-03-07 19:17:31 +01:00
void main ( ) {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int elemIdx = coords [ 1 ] ;
2021-03-26 15:26:02 +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-03-26 15:26:02 +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-03-31 13:01:22 +02:00
2022-03-07 19:17:31 +01:00
float x0 = getX ( batch , i0 ) ;
float x1 = i1 < n ? getX ( batch , i1 ) : x0 ;
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
setOutput ( x0 >= x1 ? float ( i0 ) : float ( i1 ) ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Vs(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function qk(e){let t=1;for(;t<e;)t*=2;return t}function Hre(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a,o=X().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=X().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=r.shape,p=u[u.length-1];if(n.shouldExecuteOnCPU([r])||p<o||s>l){let A=n.readSync(r.dataId),[M, $ ]=l9(A,u,r.dtype,s,i);return[n.makeTensorInfo(M.shape,M.dtype,M.values),n.makeTensorInfo( $ .shape, $ .dtype, $ .values)]}if(s===0)return u[u.length-1]=0,[n.makeTensorInfo(u,r.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(p===1)return[r,ld({attrs:{shape:u,dtype:"int32",value:0},backend:n})];let d=n.texData.get(r.dataId),c=d!==null&&d.isPacked,h=c?n.unpackTensor(r):r,m=w.sizeFromShape(u)/p,f=me({inputs:{x:h},attrs:{shape:[m,p]},backend:n});c&&Vs(n,h);let g=qk(s),y=qk(p),b=null,x=()=>b===null?[f,f]:[f,b],v=(A,M, $ )=>{let S=x(),P=new Ure( $ ),V=[[p],[b===null?1:0],[Number.NEGATIVE_INFINITY],[A],[M]],j=b;b=n.runWebGLProgram(P,S,"int32",V),Vs(n,j)};for(let A=1;A<g;A*=2){let M=A*2;for(let $ =A; $ >=1; $ /=2)v(M, $ ,[m,y])}for(let A=y;A>g;A/=2){let M=x(), $ =new Gre([m,A/2]),S=[[p],[b===null?1:0],[g]],P=b;b=n.runWebGLProgram( $ ,M,"int32",S),Vs(n,P);let V=g/2,j=V*2;for(let q=V;q>=1;q/=2)v(j,q,b.shape)}let k=b;b=qu({inputs:{x:b},backend:n,attrs:{begin:0,size:[m,s]}}),Vs(n,k);let T=EC({inputs:{x:f,indices:b},backend:n,attrs:{axis:1,batchDims:1}});Vs(n,f);let _=u.slice(0,-1);_.push(s),k=b,b=me({inputs:{x:b},attrs:{shape:_},backend:n}),Vs(n,k);let E=T;return T=me({inputs:{x:T},attrs:{shape:_},backend:n}),Vs(n,E),[T,b]}var jre={kernelName:Iu,backendName:"webgl",kernelFunc:Hre},qre=class{constructor(e,t,n,a,r,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let i=n==="nearest"?1:2,o;switch(a){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1;break}this.userCode= `
2022-03-07 19:17:31 +01:00
float mapCoord ( float outCoord , float len ) {
float inCoord = outCoord ;
if ( $ { o } == 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 ( $ { o } == 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 ( $ { o } == 4 ) {
return clamp ( outCoord , 0.0 , len - 1.0 ) ;
} else {
return outCoord ;
}
}
float readWithFillValue ( int batch , int coordY , int coordX ,
int channel ) {
float outputValue ;
if ( 0 <= coordY && coordY < $ { e } && 0 <= coordX && coordX < $ { t } ) {
outputValue = getImage ( batch , coordY , coordX , channel ) ;
} else {
outputValue = float ( $ { r } ) ;
}
return outputValue ;
}
2021-04-01 19:39:54 +02: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 ( $ { r } ) ;
} else {
float inX = ( a1 * xf + a2 * yf + a3 ) / projection ;
float inY = ( b1 * xf + b2 * yf + b3 ) / projection ;
float mapX = mapCoord ( inX , float ( $ { t } ) ) ;
float mapY = mapCoord ( inY , float ( $ { e } ) ) ;
2021-03-09 23:32:33 +01:00
2022-03-07 19:17:31 +01:00
if ( $ { i } == 1 ) {
int coordY = int ( round ( mapY ) ) ;
int coordX = int ( round ( mapX ) ) ;
outputValue = readWithFillValue ( batch , coordY , coordX ,
channel ) ;
} else {
float yFloor = floor ( mapY ) ;
float xFloor = floor ( mapX ) ;
float yCeil = yFloor + 1.0 ;
float xCeil = xFloor + 1.0 ;
float valueYFloor = ( xCeil - mapX ) *
readWithFillValue ( batch , int ( yFloor ) , int ( xFloor ) , channel ) +
( mapX - xFloor ) *
readWithFillValue ( batch , int ( yFloor ) , int ( xCeil ) , channel ) ;
float valueYCeil = ( xCeil - mapX ) *
readWithFillValue ( batch , int ( yCeil ) , int ( xFloor ) , channel ) +
( mapX - xFloor ) *
readWithFillValue ( batch , int ( yCeil ) , int ( xCeil ) , channel ) ;
outputValue = ( yCeil - mapY ) * valueYFloor +
( mapY - yFloor ) * valueYCeil ;
}
}
setOutput ( outputValue ) ;
}
2022-05-24 13:16:42 +02:00
` }};function Kre(e){let{inputs:t,backend:n,attrs:a}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=a,[p,d,c,h]=r.shape,[m,f]=u!=null?u:[d,c],g=[p,m,f,h],y=new qre(d,c,i,o,l,g);return n.runWebGLProgram(y,[r,s],"float32")}var Xre={kernelName:Su,backendName:"webgl",kernelFunc:Kre};function Yre(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;Wu(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=a.readSync(s.dataId),{outputValues:o,outputShape:l,indices:u}=u9(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([u.length],"int32",u)]}var Qre={kernelName:Lm,backendName:"webgl",kernelFunc:Yre};function Jre(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r,o=i.shape.length,l=r.shape[s],u=new Array(o-1),p=0;for(let f=0;f<o;f++)f!==s&&(u[p++]=i.shape[f]);let d=[],c=new Array(o).fill(0),h=i.shape.slice();h[s]=1;let m=new Array(l);for(let f=0;f<m.length;f++){c[s]=f;let g=qu({inputs:{x:i},backend:n,attrs:{begin:c,size:h}}),y=me({inputs:{x:g},backend:n,attrs:{shape:u}});m[f]=y,d.push(g)}return d.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var Zre={kernelName:Nu,backendName:"webgl",kernelFunc:Jre},ese=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,a=e.batchSize,r=e.inSize,s=e.numSegments,i=s*Math.ceil(r/n);this.outputShape=[a,i];let o="0.0",l="sumValue",u=Math.floor(n/4)*4,p=n%4,d= `
2022-03-07 19:17:31 +01:00
sumValue += dot ( values , segFilter ) ;
` ,c="";r%n>0&&(c= `
if ( inIdx < 0 || inIdx >= $ { r } ) {
return initializationValue ;
}
` );let h="";r%n>0&&(h= `
if ( inIdx < 0 || inIdx >= $ { r } ) {
return - 1.0 ;
}
` ),this.userCode= `
const float initializationValue = $ { o } ;
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
float getValue ( int batch , int inIdx ) {
$ { c }
return getX ( batch , inIdx ) ;
}
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
float getSegmentIdAtIndex ( int inIdx ) {
$ { h }
return getSegmentIds ( inIdx ) ;
}
2020-12-15 14:15:43 +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 (
$ { s } ) ) * float ( $ { n } ) ) ;
int currentSeg = int ( mod ( float ( outIdx ) , float ( $ { s } ) ) ) ;
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
float sumValue = 0.0 ;
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
for ( int i = 0 ; i < $ { u } ; 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-03-31 13:01:22 +02: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-03-31 13:01:22 +02:00
2022-03-07 19:17:31 +01:00
$ { d }
}
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
int inIdx = inOffset + $ { u } ;
if ( $ { p === 1 } ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
int inIdxSeg = int ( getSegmentIdAtIndex ( inIdx ) ) ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
0 ,
0 ,
0
) ;
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
$ { d }
} else if ( $ { p === 2 } ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
2020-10-29 05:16: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
) ;
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
$ { d }
} else if ( $ { p === 3 } ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
2020-10-29 05:16: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-03-31 13:01:22 +02:00
2022-03-07 19:17:31 +01:00
$ { d }
}
setOutput ( $ { l } ) ;
}
2022-05-24 13:16:42 +02:00
` }};function tse(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a,o=r.shape.length,l=[],u=0,p=C.getAxesPermutation([u],o),d=r;p!=null&&(d=Wt({inputs:{x:r},backend:n,attrs:{perm:p}}),l.push(d),u=C.getInnerMostAxes(1,o)[0]);let c=C.segment_util.computeOutShape(d.shape,u,i),h=w.sizeFromShape([d.shape[u]]),m=me({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});l.push(m);let f=Bm(r.dtype),g=(v,k,T,_,E)=>{let A=v.shape[0],M=v.shape[1], $ =C.segment_util.segOpComputeOptimalWindowSize(M,E),S={windowSize: $ ,inSize:M,batchSize:A,numSegments:E},P=new ese(S,k),V=n.compileAndRun(P,[v,T],_);if(l.push(V),V.shape[1]===E)return V;let j=PC({backend:n,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),q=LC({inputs:{x:j},backend:n,attrs:{reps:[M/ $ ]}});return l.push(j),l.push(q),g(V,k,q,_,E)},y=g(m,"unsortedSegmentSum",s,f,i),b=me({inputs:{x:y},backend:n,attrs:{shape:c}}),x=b;if(p!=null){l.push(b);let v=C.getUndoAxesPermutation(p);x=Wt({inputs:{x},backend:n,attrs:{perm:v}})}return l.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var nse={kernelName:_c,backendName:"webgl",kernelFunc:tse},ase=[rQ,iQ,uQ,dQ,mQ,yQ,xQ,wQ,NQ,_Q,FQ,DQ,PQ,BQ,UQ,HQ,qQ,QQ,ZQ,tJ,sJ,dJ,mJ,gJ,kJ,SJ,CJ,z9,AJ,PJ,BJ,jJ,KJ,YJ,JJ,eZ,aZ,iZ,uZ,cZ,hZ,fZ,bZ,vZ,SZ,TZ,EZ, $ Z,RZ,LZ,VZ,jZ,XZ,JZ,ZZ,tee,aee,see,oee,uee,hee,gee,xee,wee,See,_ee,Aee,Mee,L9,Oee,RJ,Bee,Uee,jee,W9,Yee,ete,nte,ite,ute,hte,gte,vte,Ste,_te,Ete,Dte,Mte,Ote,Wte,Ute,Hte,qte,Xte,Zte,ane,one,fne,j9,xne,kne,Nne,Cne,bJ,Ane,Dne,Mne,Lne,Vne,U9,Gne,Hne,xJ,cne,Kne,Jne,nae,K9,iae,uae,hae,gae,vae,kae,Nae,Cae,Fae,Dae,Pae,zae,Uae,jae,Xae,Jae,pJ,hne,tre,are,sre,ore,ure,cre,hre,fre,yre,vre,kre,Sre,_re,Ere,Are,Dre,dne,tQ,Pre,zre,Vre,jre,Xre,nQ,Qre,Zre,nse, $ ne];for(let e of ase)Cc(e);var $ t;(function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"})( $ t||( $ t={}));var uc;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(uc||(uc={}));var zC;function rse(e){zC=e.wasm.cwrap(ni,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function sse(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:d}=a,c=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(s.dataId).id,m=0;if(i!=null){let E=n.dataIdMap.get(i.dataId);if(E.shape.length!==1)throw new Error( ` _FusedMatMul only supports rank - 1 bias but got rank $ { E . shape . length } . ` );m=E.id}let f=o==null?0:n.dataIdMap.get(o.dataId).id,g=uc[p];if(g==null)throw new Error( ` $ { p } activation not yet supported for FusedConv2D in the wasm backend . ` );let y=l?r.shape[2]:r.shape[1],b=u?s.shape[1]:s.shape[2],x=Cu.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)),v=n.makeOutput([...x,y,b],r.dtype),k=n.dataIdMap.get(v.dataId).id,T=new Uint8Array(new Int32Array(r.shape).buffer),_=new Uint8Array(new Int32Array(s.shape).buffer);return zC(c,T,r.shape.length,h,_,s.shape.length,l,u,g,m,f,d||0,k),v}var ise={kernelName:ni,backendName:"wasm",setupFunc:rse,kernelFunc:sse};function cn(e,t){let n;function a(s){n=s.wasm.cwrap(e,null,["number","number","number"])}function r(s){let{backend:i,inputs:{x:o}}=s,l=i.dataIdMap.get(o.dataId).id,u=i.makeOutput(o.shape,t||o.dtype),p=i.dataIdMap.get(u.dataId).id;return w.sizeFromShape(u.shape)===0||n(l, $ t[o.dtype],p),u}return{kernelName:e,backendName:"wasm",setupFunc:a,kernelFunc:r}}var ose=cn(Tl);function En(e,t,n){let a;function r(i){a=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:u,b:p}=l,d=o.dataIdMap.get(u.dataId).id,c=o.dataIdMap.get(p.dataId).id,h=n!=null?n:u.dtype,m=C.assertAndGetBroadcastShape(u.shape,p.shape),f=o.makeOutput(m,h);if(w.sizeFromShape(m)===0)return f;let g=new Uint8Array(new In
2022-03-07 19:17:31 +01:00
$ { a . shape } ` );if(r.shape.length!==1)throw new Error( ` Input shape should be a vector but received shape
2022-05-24 13:16:42 +02:00
$ { r . 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(a.dataId).id,o=t.dataIdMap.get(r.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=a.shape[0],p=w.sizeFromShape(s.shape),d=t.makeOutput([u,p],a.dtype),c=t.dataIdMap.get(d.dataId).id,h=t.makeOutput([p],s.dtype),m=t.dataIdMap.get(h.dataId).id,f=t.makeOutput([3],"int32"),g=t.dataIdMap.get(f.dataId).id;AE(i,o,l,u,c,m,g);let y=t.readSync(f.dataId),b;switch(y[0]){case 0:{b=C.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(y[1],y[2]);break}case 1:{b=C.getSparseReshapeNegativeOutputDimErrorMessage(y[1],y[2]);break}case 2:b=C.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let x=Array.from(t.readSync(r.dataId)),v=Array.from(t.readSync(h.dataId));b=C.getSparseReshapeInputOutputMultipleErrorMessage(x,v);break}case 4:{let x=Array.from(t.readSync(r.dataId)),v=Array.from(t.readSync(h.dataId));b=C.getSparseReshapeInputOutputMismatchErrorMessage(x,v);break}default:b=""}if(t.disposeData(f.dataId),b)throw t.disposeData(d.dataId),t.disposeData(h.dataId),new Error(b);return[d,h]}var Mle={kernelName:wu,backendName:"wasm",setupFunc:Dle,kernelFunc:Rle}, $ E;function DE(e){ $ E=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function RE(e,t){let{backend:n,inputs:a}=e,{data:r,indices:s,segmentIds:i}=a,o=s.shape[0],l=n.readSync(i.dataId,o-1,o)[0],u=o>0?l+1:0;if(u<0)throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=r.shape.slice();p[0]=u;let d=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(i.dataId).id,m=n.makeOutput(p,r.dtype),f=n.dataIdMap.get(m.dataId).id,g=n.makeOutput([4],"int32"),y=n.dataIdMap.get(g.dataId).id; $ E(d, $ t[r.dtype],r.shape[0],c,h,f,y,t,0);let b=n.readSync(g.dataId),x;switch(b[0]){case 0:{x=C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{x=C.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:x=C.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(b[1],b[2]);break;case 3:x=C.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(b[1],b[2],b[3]);break;default:x=""}if(n.disposeData(g.dataId),x)throw n.disposeData(m.dataId),new Error(x);return m}function Ple(e){return RE(e,!0)}var Ole={kernelName:Sc,backendName:"wasm",setupFunc:DE,kernelFunc:Ple};function Lle(e){return RE(e,!1)}var zle={kernelName:Nc,backendName:"wasm",setupFunc:DE,kernelFunc:Lle};function Ble(e){let{inputs:t,attrs:n,backend:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=n,o=w.parseAxisParam(i,r.shape)[0],l=C.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),p=r.shape.slice();return l.map(d=>{let c=[...p];c[o]=d;let h=yi({inputs:{x:r},attrs:{begin:u,size:c},backend:a});return u[o]+=d,h})}var Wle={kernelName:vu,backendName:"wasm",kernelFunc:Ble},Vle=cn(uo),Ule=cn(Tc),Gle=!0,Hle=En(ho,Gle),ME;function jle(e){ME=e.wasm.cwrap(gs,null,["number","number","number","number"])}function qle(e){let{backend:t,inputs:n,attrs:a}=e,{alpha:r}=a,{x:s}=n,i=t.dataIdMap.get(s.dataId).id,o=t.makeOutput(s.shape,s.dtype),l=t.dataIdMap.get(o.dataId).id;return ME(i,r, $ t[s.dtype],l),o}var Kle={kernelName:gs,backendName:"wasm",setupFunc:jle,kernelFunc:qle},PE;function Xle(e){PE=e.wasm.cwrap(ku,null,["number","array","number","array","array","array","array","array","number","number"])}function Yle(e){let{backend:t,inputs:n,attrs:a}=e,{x:r}=n,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:d,shrinkAxisMask:c}=a,{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:v}=Kt.sliceInfo(r.shape,s,i,o,l,u,p,d,c),k;if(f)k=Bn({inputs:{x:r},backend:t,attrs:{shape:m}});else if(g||y){w.assert(r.shape.length>=1,()=> ` Input must have rank at least 1 , got : $ { r . shape . length } ` );let T=Kt.computeOutShape(b,x,v),_=yi({inputs:{x:r},backend:t,attrs:{begin:b,size:T}});k=Bn({inputs:{x:_},backend:t,attrs:{shape:m}}),t.disposeData(_.dataId)}else{let T=t.makeOutput(h,"float32"),_=t.dataIdMap.get(
2022-05-24 13:18:59 +02:00
");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}});`,vue=bi(c$()),WE=class extends pc{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(VE),vx=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new rm(this,ar())}write(e,t,n){let a={id:this.dataIdNextNumber++};return this.move(a,e,t,n,1),a}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}move(e,t,n,a,r){let s=this.dataIdNextNumber++;if(a===" string "){let u=t;this.dataIdMap.set(e,{id:s,stringBytes:u,shape:n,dtype:a,memoryOffset:null,refCount:r});return}let i=w.sizeFromShape(n),o=i*w.bytesPerElement(a),l=this.wasm._malloc(o);this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:n,dtype:a,refCount:r}),this.wasm.tfjs.registerTensor(s,i,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),l)}async read(e){return this.readSync(e)}readSync(e,t,n){let{memoryOffset:a,dtype:r,shape:s,stringBytes:i}=this.dataIdMap.get(e);if(r===" string ")return(t==null||t===0)&&(n==null||n>=i.length)?i:i.slice(t,n);t=t||0,n=n||w.sizeFromShape(s);let o=w.bytesPerElement(r),l=this.wasm.HEAPU8.slice(a+t*o,a+n*o);return Iue(l.buffer,r)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose()," PThread " in this . wasm && this . wasm . PThread . terminateAllThreads ( ) , this . wasm = null } memory ( ) { return { unreliable : ! 1 } } makeOutput ( e , t , n ) { let a ; if ( n == null ) a = this . write ( null , e , t ) ; else { let r = this . dataIdNextNumber ++ ; a = { id : r } , this . dataIdMap . set ( a , { id : r , memoryOffset : n , shape : e , dtype : t , refCou
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 ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
2022-01-14 16:04:13 +01:00
* See the License for the specific language governing permissions and
* limitations under the License .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
2022-05-09 14:12:24 +02:00
/ * *
* @ license
* Copyright 2022 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 2022 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.
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
2022-01-14 16:04:13 +01:00
/ * *
* @ 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 ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
2022-04-01 15:16:17 +02:00
* 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 ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
2021-04-30 18:01:04 +02:00
* 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. */
2020-09-16 18:43:53 +02:00
//# sourceMappingURL=face-api.esm.js.map