2020-12-02 22:46:41 +01:00
/ *
Face - API
homepage : < https : //github.com/vladmandic/face-api>
author : < https : //github.com/vladmandic>'
* /
2021-01-12 16:01:34 +01:00
var YB = Object . create , Lh = Object . defineProperty , ZB = Object . getPrototypeOf , JB = Object . prototype . hasOwnProperty , QB = Object . getOwnPropertyNames , e3 = Object . getOwnPropertyDescriptor ; var AI = r => Lh ( r , "__esModule" , { value : ! 0 } ) ; var Ur = ( r , e ) => ( ) => ( e || ( e = { exports : { } } , r ( e . exports , e ) ) , e . exports ) , et = ( r , e ) => { AI ( r ) ; for ( var t in e ) Lh ( r , t , { get : e [ t ] , enumerable : ! 0 } ) } , t3 = ( r , e , t ) => { if ( AI ( r ) , e && typeof e == "object" || typeof e == "function" ) for ( let o of QB ( e ) ) ! JB . call ( r , o ) && o !== "default" && Lh ( r , o , { get : ( ) => e [ o ] , enumerable : ! ( t = e3 ( e , o ) ) || t . enumerable } ) ; return r } , Ec = r => r && r . _ _esModule ? r : t3 ( Lh ( r != null ? YB ( ZB ( r ) ) : { } , "default" , { value : r , enumerable : ! 0 } ) , r ) ; var hN = Ur ( ( ) => { } ) ; var KN = Ur ( ( HN , I _ ) => { ( function ( r , e , t ) { function o ( i ) { var l = this , u = a ( ) ; l . next = function ( ) { var c = 2091639 * l . s0 + l . c * 23283064365386963e-26 ; return l . s0 = l . s1 , l . s1 = l . s2 , l . s2 = c - ( l . c = c | 0 ) } , l . c = 1 , l . s0 = u ( " " ) , l . s1 = u ( " " ) , l . s2 = u ( " " ) , l . s0 -= u ( i ) , l . s0 < 0 && ( l . s0 += 1 ) , l . s1 -= u ( i ) , l . s1 < 0 && ( l . s1 += 1 ) , l . s2 -= u ( i ) , l . s2 < 0 && ( l . s2 += 1 ) , u = null } function n ( i , l ) { return l . c = i . c , l . s0 = i . s0 , l . s1 = i . s1 , l . s2 = i . s2 , l } function s ( i , l ) { var u = new o ( i ) , c = l && l . state , p = u . next ; return p . int32 = function ( ) { return u . next ( ) * 4294967296 | 0 } , p . double = function ( ) { return p ( ) + ( p ( ) * 2097152 | 0 ) * 11102230246251565e-32 } , p . quick = p , c && ( typeof c == "object" && n ( c , u ) , p . state = function ( ) { return n ( u , { } ) } ) , p } function a ( ) { var i = 4022871197 , l = function ( u ) { u = u . toString ( ) ; for ( var c = 0 ; c < u . length ; c ++ ) { i += u . charCodeAt ( c ) ; var p = . 02519603282416938 * i ; i = p >>> 0 , p -= i , p *= i , i = p >>> 0 , p -= i , i += p * 4294967296 } return ( i >>> 0 ) * 23283064365386963e-26 } ; return l } e && e . exports ? e . exports = s : t && t . amd ? t ( function ( ) { return s } ) : this . alea = s } ) ( HN , typeof I _ == "object" && I _ , typeof define == "function" && define ) } ) ; var YN = Ur ( ( XN , N _ ) => { ( function ( r , e , t ) { function o ( a ) { var i = this , l = "" ; i . x = 0 , i . y = 0 , i . z = 0 , i . w = 0 , i . next = function ( ) { var c = i . x ^ i . x << 11 ; return i . x = i . y , i . y = i . z , i . z = i . w , i . w ^= i . w >>> 19 ^ c ^ c >>> 8 } , a === ( a | 0 ) ? i . x = a : l += a ; for ( var u = 0 ; u < l . length + 64 ; u ++ ) i . x ^= l . charCodeAt ( u ) | 0 , i . next ( ) } function n ( a , i ) { return i . x = a . x , i . y = a . y , i . z = a . z , i . w = a . w , i } function s ( a , i ) { var l = new o ( a ) , u = i && i . state , c = function ( ) { return ( l . next ( ) >>> 0 ) / 4294967296 } ; return c . double = function ( ) { do var p = l . next ( ) >>> 11 , m = ( l . next ( ) >>> 0 ) / 4294967296 , f = ( p + m ) / ( 1 << 21 ) ; while ( f === 0 ) ; return f } , c . int32 = l . next , c . quick = c , u && ( typeof u == "object" && n ( u , l ) , c . state = function ( ) { return n ( l , { } ) } ) , c } e && e . exports ? e . exports = s : t && t . amd ? t ( function ( ) { return s } ) : this . xor128 = s } ) ( XN , typeof N _ == "object" && N _ , typeof define == "function" && define ) } ) ; var JN = Ur ( ( ZN , S _ ) => { ( function ( r , e , t ) { function o ( a ) { var i = this , l = "" ; i . next = function ( ) { var c = i . x ^ i . x >>> 2 ; return i . x = i . y , i . y = i . z , i . z = i . w , i . w = i . v , ( i . d = i . d + 362437 | 0 ) + ( i . v = i . v ^ i . v << 4 ^ ( c ^ c << 1 ) ) | 0 } , i . x = 0 , i . y = 0 , i . z = 0 , i . w = 0 , i . v = 0 , a === ( a | 0 ) ? i . x = a : l += a ; for ( var u = 0 ; u < l . length + 64 ; u ++ ) i . x ^= l . charCodeAt ( u ) | 0 , u == l . length && ( i . d = i . x << 10 ^ i . x >>> 4 ) , i . next ( ) } function n ( a , i ) { return i . x = a . x , i . y = a . y , i . z = a . z , i . w = a . w , i . v = a . v , i . d = a . d , i } function s ( a , i ) { var l = new o ( a ) , u = i && i . state , c = function ( ) { return ( l . next ( ) >>> 0 ) / 4294967296 } ; return c . double = function ( ) { do var p = l . next ( ) >>> 11 , m = ( l . next ( ) >>> 0 ) / 4294967296 , f = ( p + m ) / ( 1 << 21 ) ; while ( f === 0 ) ; return f } , c . int32 = l . next , c . quick = c , u && ( typeof u == "object" && n ( u , l ) , c . state = function ( ) { return n ( l , { } ) } ) , c } e && e . exports ? e . exports = s : t && t . amd ? t ( function ( ) { return s } ) : this . xorwow = s } ) ( ZN , typeof S _ == "object" && S _ , typeof define == "function" && define ) } ) ; var eS = Ur ( ( QN , T _ ) => { ( function ( r , e , t ) { function o ( a ) { var i = this ; i . next = function ( ) { var u = i . x , c = i . i , p , m , f ; return p = u [ c ] , p ^= p >>> 7 , m = p ^ p << 24 , p = u [ c + 1 & 7 ] , m ^= p ^ p >>> 10 , p = u [ c + 3 & 7 ] , m ^= p ^ p >>> 3 , p = u [ c + 4 & 7 ] , m ^= p ^ p << 7 , p = u [ c + 7 & 7 ] , p = p ^ p << 13 , m ^= p ^ p << 9 , u [ c ] = m , i . i = c + 1 & 7 , m } ; function l ( u , c ) { var p , m , f = [ ] ; if ( c === ( c | 0 ) ) m = f [ 0 ] = c ; else for ( c = "" + c , p = 0 ; p < c . length ; ++ p ) f [ p & 7 ] = f [ p & 7 ] << 15 ^ c . charCodeAt ( p ) + f [ p + 1 & 7 ] << 13 ; for ( ; f . length < 8 ; ) f . push ( 0 ) ; for ( p = 0 ; p < 8 && f [ p ] === 0 ; ++ p ) ; for ( p == 8 ? m = f [ 7 ] = - 1 : m = f [ p ] , u . x = f , u . i = 0 , p = 256 ; p > 0 ; -- p ) u . next ( ) } l ( i , a ) } function n ( a , i ) { return i . x = a . x . slice ( ) , i . i = a . i , i } function s ( a , i ) { a == null && ( a = + new Date ) ; var l = new o ( a ) , u = i && i . state , c = function ( ) { return ( l . next ( ) >>> 0 ) / 4294967296 } ; return c . double = function ( ) { do var p = l . next ( ) >>> 11 , m = ( l . next ( ) >>> 0 ) / 4294967296 , f = ( p + m ) / ( 1 << 21 ) ; while ( f === 0 ) ; return f } , c . int32 = l . next , c . quick = c , u && ( u . x && n ( u , l ) , c . state = function ( ) { return n (
` )),l.join( `
` )}function E3(r,e,t,o){let n=dt(e),s=o[o.length-1],a=new Array(s).fill(0),i=e.length,l=t==="complex64"?ym(r):r;if(i>1)for(let u=0;u<n/s;u++){let c=u*s;for(let p=0;p<s;p++)a[p]=Math.max(a[p],xm(l[c+p],0,t).length)}return a}function xm(r,e,t){let o;return Array.isArray(r)?o= ` $ { parseFloat ( r [ 0 ] . toFixed ( kb ) ) } + $ { parseFloat ( r [ 1 ] . toFixed ( kb ) ) } j ` :ss(r)?o= ` '${r}' ` :t==="bool"?o=WI(r):o=parseFloat(r.toFixed(kb)).toString(),Wl(o,e)}function WI(r){return r===0?"false":"true"}function Wh(r,e,t,o,n,s=!0){let a=t==="complex64"?2:1,i=e[0],l=e.length;if(l===0){if(t==="complex64"){let h=ym(r);return[xm(h[0],0,t)]}return t==="bool"?[WI(r[0])]:[r[0].toString()]}if(l===1){if(i>BI){let g=gm*a,y=Array.from(r.slice(0,g)),b=Array.from(r.slice((i-gm)*a,i*a));return t==="complex64"&&(y=ym(y),b=ym(b)),["["+y.map((_,w)=>xm(_,n[w],t)).join(", ")+", ..., "+b.map((_,w)=>xm(_,n[i-gm+w],t)).join(", ")+"]"]}let h=t==="complex64"?ym(r):Array.from(r);return["["+h.map((g,y)=>xm(g,n[y],t)).join(", ")+"]"]}let u=e.slice(1),c=o.slice(1),p=o[0]*a,m=[];if(i>BI){for(let h=0;h<gm;h++){let g=h*p,y=g+p;m.push(...Wh(r.slice(g,y),u,t,c,n,!1))}m.push("...");for(let h=i-gm;h<i;h++){let g=h*p,y=g+p;m.push(...Wh(r.slice(g,y),u,t,c,n,h===i-1))}}else for(let h=0;h<i;h++){let g=h*p,y=g+p;m.push(...Wh(r.slice(g,y),u,t,c,n,h===i-1))}let f=l===2?",":"";m[0]="["+m[0]+f;for(let h=1;h<m.length-1;h++)m[h]=" "+m[h]+f;let d= ` ,
` ;for(let h=2;h<l;h++)d+= `
` ;return m[m.length-1]=" "+m[m.length-1]+"]"+(s?"":d),m}function ym(r){let e=[];for(let t=0;t<r.length;t+=2)e.push([r[t],r[t+1]]);return e}var ct=class{constructor(e,t,o){if(this.dtype=t,this.shape=e.slice(),this.size=dt(e),o!=null){let n=o.length;E(n===this.size,()=> ` Length of values '${n}' does not match the size inferred by the shape '${this.size}' . ` )}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=o||lb(t,this.size),this.strides=Us(e)}set(e,...t){t.length===0&&(t=[0]),E(t.length===this.rank,()=> ` The number of provided coordinates ( $ { t . length } ) must match the rank ( $ { this . rank } ) ` );let o=this.locToIndex(t);this.values[o]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let n of e){if(n<0||n>=this.shape[t]){let s= ` Requested out of range element at $ { e } . Buffer shape = $ { this . shape } ` ;throw new Error(s)}t++}let o=e[e.length-1];for(let n=0;n<e.length-1;++n)o+=this.strides[n]*e[n];return this.values[o]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let o=0;o<e.length-1;++o)t+=this.strides[o]*e[o];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let o=0;o<t.length-1;++o)t[o]=Math.floor(e/this.strides[o]),e-=t[o]*this.strides[o];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Ri().makeTensor(this.values,this.shape,this.dtype)}},Ri=null,Bc=null,A3=null;function GI(r){Ri=r}function UI(r){Bc=r}function jI(r){A3=r}var R=class{constructor(e,t,o,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=dt(e),this.strides=Us(e),this.dataId=o,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Bc.buffer(this.shape,this.dtype,e)}bufferSync(){return Bc.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Gl(this.shape,e)}arraySync(){return Gl(this.shape,this.dataSync())}async data(){this.throwIfDisposed();let e=Ri().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(o=>zc(o))}catch(o){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();let e=Ri().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>zc(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 Ri().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Ri().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Bc.print(this,e)}clone(){return this.throwIfDisposed(),Bc.clone(this)}toString(e=!1){let t=this.dataSync();return VI(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Bc.cast(this,e)}variable(e=!0,t,o){return this.throwIfDisposed(),Ri().makeVariable(this,e,t,o)}};Object.defineProperty(R,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});var ol=class extends R{constructor(e,t,o,n){super(e.shape,e.dtype,e.dataId,n);this.trainable=t,this.name=o}assign(e){if(e.dtype!==this.dtype)throw new Error( ` dtype of the new value ( $ { e . dtype } ) and previous value ( $ { this . dtype } ) must match ` );if(!jr(e.shape,this.shape))throw new Error( ` shape of the new value ( $ { e . shape } ) and previous value ( $ { this . shape } ) must match ` );Ri().disposeTensor(this),this.dataId=e.dataId,Ri().incRef(this,null)}dispose(){Ri().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(ol,Symbol.hasInstance,{value:r=>r instanceof R&&r.assign!=null&&r.assign instanceof Function});var Mn={};et(Mn,{assertTypesMatch:()=>Eb,getTensorsInCont
Manifest JSON has weights with names : $ { i . join ( ", " ) } . ` )}let l=n.reduce((f,d,h)=>(d&&f.push(h),f),[]),u=[];l.forEach(f=>{e[f].paths.forEach(d=>{let h=t+(t.endsWith("/")?"":"/")+d;u.push(h)})});let c=await r(u),p={},m=0;return l.forEach(f=>{let d=e[f].paths.length,h=0;for(let w=0;w<d;w++)h+=c[m+w].byteLength;let g=new ArrayBuffer(h),y=new Uint8Array(g),b=0;for(let w=0;w<d;w++){let k=new Uint8Array(c[m+w]);y.set(k,b),b+=k.byteLength}s[f].forEach(w=>{let k=g.slice(w.groupOffset,w.groupOffset+w.sizeBytes), $ =Uh(k,[w.manifestEntry]);for(let T in $ )p[T]= $ [T]}),m+=d}),p}}var lV="application/octet-stream",uV="application/json",qh=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?(E(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=W().platform.fetch,E(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&E(e.length===2,()=> ` URL paths for http must have a length of 2 , ( actual length is $ { e . length } ) . ` ),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let o=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:o};e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(n)],{type:uV}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:lV}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Oi(e),responses:[s]};throw new Error( ` BrowserHTTPRequest . save ( ) failed due to HTTP response status $ { s . 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(d){let h= ` Failed to parse model JSON of response from $ { this . path } . ` ;throw this.path.endsWith(".pb")?h+=" 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.":h+=" Please make sure the server is serving valid JSON for this request.",new Error(h)}let o=t.modelTopology,n=t.weightsManifest,s=t.generatedBy,a=t.convertedBy,i=t.format,l=t.signature,u=t.userDefinedMetadata;if(o==null&&n==null)throw new Error( ` The JSON from HTTP path $ { this . path } contains neither model topology or manifest for weights . ` );let c,p;n!=null&&([c,p]=await this.loadWeights(n));let m={modelTopology:o,weightSpecs:c,weightData:p,generatedBy:s,convertedBy:a,format:i};l!=null&&(m.signature=l),u!=null&&(m.userDefinedMetadata=u);let f=t.modelInitializer;return f&&(m.modelInitializer=f),m}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[o,n]=cV(t),s=this.weightPathPrefix||o,a=[];for(let c of e)a.push(...c.weights);let i=[],l=[];for(let c of e)for(let p of c.paths)this.weightUrlConverter!=null?l.push(this.weightUrlConverter(p)):i.push(s+p+n);this.weightUrlConverter&&i.push(...await Promise.all(l));let u=await Gb(i,{requestInit:this
Actual : $ { n } .
Expected : $ { s } . ` );for(let a=0;a<s.length;++a){let i=n[a],l=s[a];if(!t(i,l))throw new Error( ` Arrays differ : actual [ $ { a } ] = $ { i } , expected [ $ { a } ] = $ { l } .
Actual : $ { n } .
Expected : $ { s } . ` )}}function IV(r,e){r().then(()=>e.fail(),()=>e())}function NV(r,e){let t=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return ss(r)||ss(r[0])||ss(e)||ss(e[0])?Xb(r,t,(o,n)=>o==n):Xb(r,e,(o,n)=>Yb(o,n,0))}function SV(r,e,t){if(t==null&&(t=Kb()),!Yb(r,e,t))throw new Error( ` Numbers differ : actual === $ { r } , expected === $ { e } ` )}function Yb(r,e,t){return!isFinite(r)&&!isFinite(e)?!0:!(isNaN(r)||isNaN(e)||Math.abs(r-e)>t)}function TV(r,e,t){for(let o=0;o<r.length;o++)if(r[o]<e||r[o]>t)throw new Error( ` Value out of range : $ { r [ o ] } low : $ { e } , high : $ { t } ` )}function EV(r,e){expect(new Float32Array(r)).toEqual(new Float32Array(e))}function VN(r){for(let e=0;e<r.length;e++){let t=r[e];Array.isArray(t)?VN(t):r[e]=rl(t)}return r}var Zb="2.8.3";function AV(){W().set("PROD",!0)}function DV(){W().set("DEBUG",!0)}function $ V(){W().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Ot(r){W().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}jI(Ot);function RV(){A.disposeVariables()}function Cs(){return A}function qc(){return A.memory()}function FV(r){return A.profile(r)}function V(r,e){return A.tidy(r,e)}function Ae(r){bm(r).forEach(t=>t.dispose())}function Dt(r){return A.keep(r)}function OV(r){return A.time(r)}function WN(r){return A.setBackend(r)}function PV(){return A.ready()}function MV(){return A.backendName}function LV(r){A.removeBackend(r)}function zV(r){return A.findBackend(r)}function BV(r){return A.findBackendFactory(r)}function wu(r,e,t=1){return A.registerBackend(r,e,t)}function Jb(){return A.backend}function VV(r,e){W().setPlatform(r,e)}function WV(r,e){let t=v(r,"a","add"),o=v(e,"b","add");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(bo,n)}var ee=N({add_:WV});function GV(r,e){let t=v(r,"a","floorDiv"),o=v(e,"b","floorDiv");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(sn,n)}var vu=N({floorDiv_:GV});function UV(r,e){let t=v(r,"a","div"),o=v(e,"b","div");if([t,o]=Ue(t,o),t.dtype==="int32"&&o.dtype==="int32")return vu(t,o);let n={a:t,b:o},s={};return A.runKernel(rn,n,s)}var fe=N({div_:UV});function jV(r,e){let t=v(r,"a","mul"),o=v(e,"b","mul");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(xn,n)}var O=N({mul_:jV});function qV(r){let e=v(r,"x","abs");if(e.dtype==="complex64"){let t={x:e};return A.runKernel(ia,t)}else{let t={x:e};return A.runKernel(is,t)}}var Et=N({abs_:qV});function HV(r){let t={x:v(r,"x","acos")};return A.runKernel(js,t)}var wm=N({acos_:HV});function KV(r){let t={x:v(r,"x","acosh")};return A.runKernel(qs,t)}var vm=N({acosh_:KV});function XV(r){E(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),E(r.length>=1,()=> ` Must pass at least one tensor to tf . addN ( ) , but got $ { r . length } ` );let e=r.map((n,s)=>v(n, ` tensors$ { s } ` ,"addN")),t=e[0];e.forEach(n=>{if(n.dtype!==t.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(n=>{if(!jr(n.shape,t.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let o=e;return A.runKernel(Ho,o)}var Qb=N({addN_:XV});function YV(r,e=null,t=!1){let n={x:v(r,"x","all","bool")},s={axis:e,keepDims:t};return A.runKernel(Ul,n,s)}var ku=N({all_:YV});function ZV(r,e=null,t=!1){let n={x:v(r,"x","any","bool")},s={axis:e,keepDims:t};return A.runKernel(jl,n,s)}var il=N({any_:ZV});function JV(r,e=0){let o={x:v(r,"x","argMax")},n={axis:e};return A.runKernel(Ko,o,n)}var al=N({argMax_:JV});function QV(r,e=0){let o={x:v(r,"x","argMin")},n={axis:e};return A.runKernel(oa,o,n)}var km=N({argMin_:QV});function eW(r){let t={x:v(r,"x","asin")};return A.runKernel(Hs,t)}var Cm=N({asin_:eW});function tW(r){let t={x:v(r,"x","asinh")};return A.runKernel(Ks,t)}var Im=N({asinh_:tW});function rW(r){let t={x:v(r,"x","atan")};return A.runKernel(Xs,t)}var Nm=N({atan_:rW});function oW(r,e){let t=v(r,"a","atan2"),o=v(e,"b","atan2");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(Zs,n)}var Sm=N({atan2_:oW});function nW(r){let t={x:v
with dtype $ { s . dtype } . ` )}),t.length===1)return Po(t[0]);let o=t,n={axis:e};return A.runKernel(as,o,n)}var Je=N({concat_:dW});function hW(r){let t={x:v(r,"x","sigmoid")};return A.runKernel(En,t)}var Kr=N({sigmoid_:hW});function gW(r,e,t){let o=v(r,"x","slice","string_or_numeric");if(o.rank===0)throw new Error("Slicing scalar is not possible");let n={x:o},s={begin:e,size:t};return A.runKernel(gs,n,s)}var Fe=N({slice_:gW});function xW(r){let t={x:v(r,"x","tanh")};return A.runKernel(On,t)}var Pi=N({tanh_:xW});function yW(r,e,t,o,n,s){let a=v(r,"forgetBias","basicLSTMCell"),i=v(e,"lstmKernel","basicLSTMCell"),l=v(t,"lstmBias","basicLSTMCell"),u=v(o,"data","basicLSTMCell"),c=v(n,"c","basicLSTMCell"),p=v(s,"h","basicLSTMCell"),m=Je([u,p],1),f=je(m,i),d=ee(f,l),h=d.shape[0],g=d.shape[1]/4,y=[h,g],b=Fe(d,[0,0],y),_=Fe(d,[0,g],y),w=Fe(d,[0,g*2],y),k=Fe(d,[0,g*3],y), $ =ee(O(Kr(b),Pi(_)),O(c,Kr(ee(a,w)))),T=O(Pi( $ ),Kr(k));return[ $ ,T]}var bW=N({basicLSTMCell_:yW});function _W(r,e,t){let o=v(r,"x","batchToSpaceND"),n=e.reduce((i,l)=>i*l);E(o.rank>=1+e.length,()=> ` input rank is $ { o . rank } but should be > than blockShape . length $ { e . length } ` ),E(t.length===e.length,()=> ` crops . length is $ { t . length } but should be equal to blockShape . length $ { e . length } ` ),E(o.shape[0]%n==0,()=> ` input tensor batch is $ { o . shape [ 0 ] } but is not divisible by the product of the elements of blockShape $ { e . join ( " * " ) } === $ { n } ` );let s={x:o},a={blockShape:e,crops:t};return A.runKernel(sa,s,a)}var Ca=N({batchToSpaceND_:_W});function jN(r){let e;return r.rank===0||r.rank===1?e=z(r,[1,1,1,r.size]):r.rank===2?e=z(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?e=z(r,[1,r.shape[0],r.shape[1],r.shape[2]]):e=r,e}function wW(r,e,t,o,n,s){s==null&&(s=.001);let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;o!=null&&(c=v(o,"offset","batchNorm")),E(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),E(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),E(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:jN(a),scale:u,offset:c,mean:i,variance:l},f={varianceEpsilon:s},d=A.runKernel(an,m,f);return z(d,a.shape)}var Ln=N({batchNorm_:wW});function vW(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;return o!=null&&(c=v(o,"offset","batchNorm")),E(a.rank===2,()=> ` Error in batchNorm2D : x must be rank 2 but got rank $ { a . rank } . ` ),E(i.rank===2||i.rank===1,()=> ` Error in batchNorm2D : mean must be rank 2 or rank 1 but got rank $ { i . rank } . ` ),E(l.rank===2||l.rank===1,()=> ` Error in batchNorm2D : variance must be rank 2 or rank 1 but got rank $ { l . rank } . ` ),u!=null&&E(u.rank===2||u.rank===1,()=> ` Error in batchNorm2D : scale must be rank 2 or rank 1 but got rank $ { u . rank } . ` ),c!=null&&E(c.rank===2||c.rank===1,()=> ` Error in batchNorm2D : offset must be rank 2 or rank 1 but got rank $ { c . rank } . ` ),Ln(a,i,l,c,u,s)}var o_=N({batchNorm2d_:vW});function kW(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;return o!=null&&(c=v(o,"offset","batchNorm")),E(a.rank===3,()=> ` Error in batchNorm3D : x must be rank 3 but got rank $ { a . rank } . ` ),E(i.rank===3||i.rank===1,()=> ` Error in batchNorm3D : mean must be rank 3 or rank 1 but got rank $ { i . rank } . ` ),E(l.rank===3||l.rank===1,()=> ` Error in batchNorm3D : variance must be rank 3 or rank 1 but got rank $ { l . rank } . ` ),u!=null&&E(u.rank===3||u.rank===1,()=> ` Error in batchNorm3D : scale must be rank 3 or rank 1 but got rank $ { u . rank } . ` ),c!=null&&E(c.rank===3||c.rank===1,()=> ` Error in batchNorm3D : offset must be rank 3 or rank 1 but got rank $ { c . rank } . ` ),Ln(a,i,l,c,u,s)}var n_=N({batchNorm3d_:kW});function CW(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;return o!=
$ { n } and $ { e } for depthToSpace with input shape
$ { o . shape } ` ),E(s*e>=0,()=> ` Negative dimension size caused by overflow when multiplying
$ { s } and $ { e } for depthToSpace with input shape
$ { o . shape } ` ),E(a%(e*e)==0,()=> ` Dimension size must be evenly divisible by $ { e * e } but is $ { a } for depthToSpace with input shape $ { o . shape } ` );let i={x:o},l={blockSize:e,dataFormat:t};return A.runKernel(ti,i,l)}var $ m=N({depthToSpace_:jW});function qW(r,e,t,o,n="NHWC",s=[1,1],a){let i=v(r,"x","depthwiseConv2d"),l=v(e,"filter","depthwiseConv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=z(i,[1,i.shape[0],i.shape[1],i.shape[2]])),E(u.rank===4,()=> ` Error in depthwiseConv2d : input must be rank 4 , but got rank $ { u . rank } . ` ),E(l.rank===4,()=> ` Error in depthwiseConv2d : filter must be rank 4 , but got rank $ { l . rank } . ` ),E(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 ] } . ` ),a!=null&&E(it(o),()=> ` Error in depthwiseConv2d : pad must be an integer when using , dimRoundingMode $ { a } but got pad $ { o } . ` );let p={x:u,filter:l},m={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a},f=A.runKernel(tn,p,m);return c?z(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Lo=N({depthwiseConv2d_:qW});function HW(r){let t={x:v(r,"x","diag")};return A.runKernel(ru,t)}var KW=N({diag_:HW});function XW(r,e,t,o,n=[1,1],s="NHWC"){let a=v(r,"x","dilation2d"),i=v(e,"filter","dilation2d");E(a.rank===3||a.rank===4,()=> ` Error in dilation2d : input must be rank 3 or 4 , but got rank $ { a . rank } . ` ),E(i.rank===3,()=> ` Error in dilation2d : filter must be rank 3 , but got rank $ { i . rank } . ` ),E(s==="NHWC",()=> ` Error in dilation2d : Only NHWC is currently supported , but got dataFormat of $ { s } ` );let l=a,u=!1;a.rank===3&&(l=z(a,[1,a.shape[0],a.shape[1],a.shape[2]]),u=!0);let c={x:l,filter:i},p={strides:t,pad:o,dilations:n},m=A.runKernel(la,c,p);return u?z(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Rm=N({dilation2d_:XW});function YW(r,e){let t=r.length,o=[];for(let n=0;n<t;n++){let s=t-1-n,a=r[s]||1;(e[e.length-1-n]||1)>1&&a===1&&o.unshift(s)}return o}function Nt(r,e){let t=[];for(let o=0;o<e.length;o++){let n=r[r.length-o-1],s=e.length-o-1,a=e[s];(n==null||n===1&&a>1)&&t.unshift(s)}return t}function Ve(r,e){let t=[],o=Math.max(r.length,e.length);for(let n=0;n<o;n++){let s=r[r.length-n-1];s==null&&(s=1);let a=e[e.length-n-1];if(a==null&&(a=1),s===1)t.unshift(a);else if(a===1)t.unshift(s);else if(s!==a){let i= ` Operands could not be broadcast together with shapes $ { r } and $ { e } . ` ;throw Error(i)}else t.unshift(s)}return t}function ZW(r,e){let t=v(r,"a","equal"),o=v(e,"b","equal");[t,o]=Ue(t,o),Ve(t.shape,o.shape);let n={a:t,b:o};return A.runKernel(ni,n)}var Yr=N({equal_:ZW});function JW(r,e,t){let o=v(e,"a","where"),n=v(t,"b","where"),s=v(r,"condition","where","bool"),a=Ve(o.shape,n.shape),i=ll(o,a),l=ll(n,a);s.rank===1&&E(s.shape[0]===o.shape[0],()=>"The first dimension of ` a ` must match the size of ` condition ` ."),s.rank!==1&&Ge(s.shape,l.shape,"Error in where: ");let u={condition:s,t:i,e:l};return A.runKernel(hs,u)}var $ t=N({where_:JW});function QW(r){let t={x:v(r,"x","zerosLike")};return A.runKernel(bs,t)}var Ne=N({zerosLike_:QW});function eG(r,e){let t=v(r,"a","div"),o=v(e,"b","div");[t,o]=Ue(t,o);let n=fe(t,o),s=Ne(n),a=Yr(o,s);return $ t(a,s,n)}var Fm=N({divNoNan_:eG});function tG(r,e){let t=v(r,"t1","dot"),o=v(e,"t2","dot");E((t.rank===1||t.rank===2)&&(o.rank===1||o.rank===2),()=> ` Error in dot : inputs must all be rank 1 or 2 , but got ranks $ { t . rank } and $ { o . rank } . ` );let n=t.rank===1?t.size:t.shape[1],s=o.rank===1?o.size:o.shape[0];if(E(n===s,()=> ` Error in dot : inner dimensions of inputs must match , but got $ { n } and $ { s } . ` ),t.rank===1&&o.rank===1){let a=z(t,[1,-1]),i=z(o,[-1,1]),l=je(a,i);return z(l,[])}else if(t.rank===1&&o.rank===2){let a=z(t,[1,-1]),i=z(o,[o.shape[0],o.shape[1]]),l=je(a,i);return z(l,[l.size])}else if(t.rank===2&&o.rank===1){let a=z(o,[-1,1]),i=je(t,a);return z(i,[i.size])}else{let a=z(o,[o.shape[0],o.shape[1]]);return je(t,a)}}var m_=N({dot_:tG});function rG(r){let t={x:v(r,"x","elu")};return A.runKernel(ri,t)}var Is=N({elu_:rG});function oG(r){let e=v(r,"x","erf");E(e.dtype==="int32"||e.dtype==="float32",()=>"Input dtype must be ` int32 ` or ` float32 ` ."),e.dtype=
rank $ { s . rank } . ` ),E(it(e),()=> ` Error in localResponseNormalization : depthRadius must be an integer but got depthRadius $ { e } . ` );let a=s,i=!1;s.rank===3&&(i=!0,a=z(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:a},u={depthRadius:e,bias:t,alpha:o,beta:n},c=A.runKernel(ca,l,u);return i?z(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Mm=N({localResponseNormalization_:_G});function wG(r){let t={x:v(r,"x","log")};return A.runKernel(cn,t)}var ar=N({log_:wG});function vG(r){let t={x:v(r,"x","log1p")};return A.runKernel(di,t)}var Du=N({log1p_:vG});function kG(r){return E(Gs(r),()=>"The f passed in grad(f) must be a function"),(e,t)=>{let o=v(e,"x","tf.grad","string_or_numeric"),n=t!=null?v(t,"dy","tf.grad"):null;return A.tidy(()=>{let{value:s,grads:a}=A.gradients(()=>r(o),[o],n);return n!=null&&Ge(s.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),ng(a),a[0]})}}function CG(r){return E(Gs(r),()=>"The f passed in grads(f) must be a function"),(e,t)=>{E(Array.isArray(e),()=>"The args passed in grads(f)(args) must be an array of ` Tensor ` s or ` TensorLike ` s");let o=ya(e,"args","tf.grads","string_or_numeric"),n=t!=null?v(t,"dy","tf.grads"):null;return A.tidy(()=>{let{value:s,grads:a}=A.gradients(()=>r(...o),o,n);return n!=null&&Ge(s.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ng(a),a})}}function IG(r){return E(Gs(r),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{E(e instanceof R,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),E(t==null||t instanceof R,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:o,value:n}=A.gradients(()=>r(e),[e],t);return ng(o),{grad:o[0],value:n}}}function NG(r){return E(Gs(r),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{E(Array.isArray(e)&&e.every(n=>n instanceof R),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),E(t==null||t instanceof R,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let o=A.gradients(()=>r(...e),e,t);return t!=null&&Ge(o.value.shape,t.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ng(o.grads),o}}function sg(r,e){E(Gs(r),()=>"The f passed in variableGrads(f) must be a function"),E(e==null||Array.isArray(e)&&e.every(u=>u instanceof ol),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let t=e!=null;if(!t){e=[];for(let u in A.registeredVariables)e.push(A.registeredVariables[u])}let o=t?e.filter(u=>!u.trainable):null,n=e.length;e=e.filter(u=>u.trainable),E(e.length>0,()=> ` variableGrads ( ) expects at least one of the input variables to be trainable , but none of the $ { n } variables is trainable . ` );let s=!0,{value:a,grads:i}=A.gradients(r,e,null,s);E(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),E(a.rank===0,()=> ` The f passed in variableGrads ( f ) must return a scalar , but it returned a rank - $ { a . rank } tensor ` );let l={};return e.forEach((u,c)=>{i[c]!=null&&(l[u.name]=i[c])}),o!=null&&o.forEach(u=>l[u.name]=null),{value:a,grads:l}}function Zr(r){return A.customGrad(r)}function ng(r){if(r.filter(t=>t==null).length>0)throw new Error( ` Cannot compute gradient of y = f ( x ) with respect to x . Make sure that
the f you passed encloses all operations that lead from x to y . ` )}function SG(r){let t={x:v(r,"x","neg")};return A.runKernel(ps,t)}var He=N({neg_:SG});function TG(r){let t={x:v(r,"x","softplus")};return A.runKernel(Si,t)}var Ss=N({softplus_:TG});function EG(r){let e=v(r,"x","logSigmoid");return Zr(o=>({value:He(Ss(He(o))),gradFunc:a=>O(a,Kr(He(o)))}))(e)}var x_=N({logSigmoid_:EG});function AG(r,e=null,t=!1){let n={x:v(r,"x","max")},s={reductionIndices:e,keepDims:t};return A.runKernel(pn,n,s)}var lr=N({max_:AG});function DG(r,e){let t=v(r,"a","sub"),o=v(e,"b","sub");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(Fn,n)}var pe=N({sub_:DG});function $ G(r,e=null,t=!1){let o=v(r,"x","sum");o.dtype==="bool"&&(o=ne(o,"int32"));let n={x:o},s={axis:e,keepDims:t};return A.runKernel(Dn,n,s)}var be=N({sum_: $ G});function RG(r,e=-1){let t=v(r,"logits","logSoftmax");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error( ` Log Softmax along a non - last dimension is not yet supported . Logits was rank $ { t . rank } and axis was $ { e } ` );return Zr((n,s)=>{let a=!0,i=lr(n,e,!0),l=pe(n,i),u=pe(ne(l,"float32"),ar(be(Qt(l),e,a)));return s([u]),{value:u,gradFunc:(p,m)=>{let[f]=m,d=!0,h=Qt(f);return pe(p,O(be(p,e,d),h))}}})(t)}var $ u=N({logSoftmax_:RG});function y_(r,e){for(let t=0;t<r.length;++t)if(r[r.length-t-1]!==e-1-t)return!1;return!0}function qN(r,e,t){let o=r.length+e.length,n=[],s=0,a=0;for(let i=0;i<o;i++)t.indexOf(i)===-1?n.push(r[s++]):n.push(e[a++]);return n}function b_(r,e){let t=[],o=r.length;for(let s=0;s<o;s++)e.indexOf(s)===-1&&t.push(r[s]);let n=e.map(s=>r[s]);return[t,n]}function Bn(r,e){let t=e.map(o=>1);return qN(r,t,e)}function FG(r,e,t){E(y_(e,t),()=> ` $ { r } supports only inner - most axes for now . Got axes $ { e } and rank - $ { t } input . ` )}function __(r,e){if(y_(r,e))return null;let t=[];for(let o=0;o<e;++o)r.indexOf(o)===-1&&t.push(o);return r.forEach(o=>t.push(o)),t}function Lm(r){return r.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function OG(r,e){let t=[];for(let o=e-r;o<e;++o)t.push(o);return t}function PG(r,e=null,t=!1){let o=v(r,"x","logSumExp"),n=tr(e,o.shape),s=lr(o,n,!0),a=pe(o,s),i=Qt(a),l=be(i,n),u=ar(l),c=ee(z(s,u.shape),u);if(t){let p=Bn(c.shape,n);return z(c,p)}return c}var zm=N({logSumExp_:PG});function MG(r,e){let t=v(r,"a","logicalAnd","bool"),o=v(e,"b","logicalAnd","bool");Ve(t.shape,o.shape);let n={a:t,b:o};return A.runKernel(hi,n)}var dr=N({logicalAnd_:MG});function LG(r){let t={x:v(r,"x","logicalNot","bool")};return A.runKernel(Qa,t)}var Ea=N({logicalNot_:LG});function zG(r,e){let t=v(r,"a","logicalOr","bool"),o=v(e,"b","logicalOr","bool");Ve(t.shape,o.shape);let n={a:t,b:o};return A.runKernel(el,n)}var Ru=N({logicalOr_:zG});function BG(r,e){let t=v(r,"a","logicalXor","bool"),o=v(e,"b","logicalXor","bool");return Ve(t.shape,o.shape),dr(Ru(r,e),Ea(dr(r,e)))}var w_=N({logicalXor_:BG});function VG(r,e,t,o,n){let s=v(r,"x","maxPool"),a=1,i=s,l=!1;s.rank===3&&(l=!0,i=z(s,[1,s.shape[0],s.shape[1],s.shape[2]])),E(i.rank===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { i . rank } . ` ),E(Pt(t,a),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { t } and dilations '${a}' ` ),n!=null&&E(it(o),()=> ` Error in maxPool : pad must be an integer when using , dimRoundingMode $ { n } but got pad $ { o } . ` );let u={x:i},c={filterSize:e,strides:t,pad:o,dimRoundingMode:n},p=A.runKernel(fn,u,c);return l?z(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Aa=N({maxPool_:VG});function WG(r,e=[1,1,1],t,o,n,s="NDHWC",a){a==null?a=[1,1,1]:Ot("dilations is deprecated, this field will be gone in v3.0.0.");let i=v(r,"x","maxPool3d"),l=i,u=!1;i.rank===4&&(u=!0,l=z(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),E(l.rank===5,()=> ` Error in maxPool3d : x must be rank 5 but got rank $ { l . rank } . ` ),E(s==="NDHWC",()=> ` Error in maxPool3d : Only NDHWC is currently supported , but got dataFormat of $ { s } ` ),E(Pt(t,a),()=> ` Error in maxPool3d : Either strides or dilations must be 1. Got strides $ { t } and dilations '${a}' ` ),n!=null&&E(it(o),()=> ` Error in maxPool3d : pad must be an integer when using , dimRoundingMode $ { n } but got pad $ { o } . ` )
$ { s } ) . ` );if(t<o)throw new Error( ` batchDims ( $ { o } ) must be less than or equal to axis ( $ { t } ) . ` );for(let p=0;p<o;++p)if(r.shape[p]!==e.shape[p])throw new Error( ` x . shape [ $ { p } ] : $ { r . shape [ p ] } should be equal to indices . shape [ $ { p } ] : $ { e . shape [ p ] } . ` );let a=r.shape[t],i=[],l=1,u=1,c=1;for(let p=0;p<o;++p)i.push(r.shape[p]),l*=r.shape[p];for(let p=o;p<t;p++)i.push(r.shape[p]),u*=r.shape[p];for(let p=o;p<n;p++)i.push(e.shape[p]);for(let p=t+1;p<s;p++)i.push(r.shape[p]),c*=r.shape[p];return{batchSize:l,sliceSize:c,outerSize:u,dimSize:a,outputShape:i}}function _q(r,e,t){if(e==="complex64"){if(r.dtype==="complex64")return r.clone();let o=pt(r.shape),n=ne(r,"float32"),s=t.complex(n,o);return o.dispose(),n.dispose(),s}if(!pb(r.dtype,e))return A.makeTensorFromDataId(r.dataId,r.shape,e);if(r.dtype==="complex64"){let o=t.real(r),n=ne(o,e);return o.dispose(),n}if(e==="int32")return t.int(r);if(e==="bool"){let o=ce(0,r.dtype),n=t.notEqual(r,o);return o.dispose(),n}else throw new Error( ` Error in Cast : failed to cast $ { r . dtype } to $ { e } ` )}function wq(r,e){return A.makeTensorFromDataId(r.dataId,e,r.dtype)}function vq(r){try{return r.map(e=>zc(e))}catch(e){throw new Error( ` Failed to decode encoded string bytes into utf - 8 , error : $ { e } ` )}}function kq(r){return r.map(e=>rl(e))}var Er={};et(Er,{nonMaxSuppressionV3Impl:()=>rw,nonMaxSuppressionV4Impl:()=>ow,nonMaxSuppressionV5Impl:()=>nw,whereImpl:()=>O_});var xg={kernelName:is,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,Es(ne(t,"float32"),-1))}}};var MS={kernelName:js,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=Me(ne(t,"float32")),n=_t(pe(ce(1),o));return He(fe(r,n))}}}};var LS={kernelName:qs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=_t(pe(Me(ne(t,"float32")),1));return fe(r,o)}}}};var zS={kernelName:bo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Ve(t.shape,o.shape);return{a:()=>{let i=r,l=Nt(t.shape,n);return l.length>0&&(i=be(i,l)),z(i,t.shape)},b:()=>{let i=r,l=Nt(o.shape,n);return l.length>0&&(i=be(i,l)),z(i,o.shape)}}}};var BS={kernelName:Ho,saveAllInputs:!0,gradFunc:(r,e)=>{let t={};return e.forEach((o,n)=>{t[n]=()=>r.clone()}),t}};var VS={kernelName:Ko,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ne(t)}}};var WS={kernelName:oa,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ne(t)}}};var GS={kernelName:Hs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,_t(pe(ce(1),Me(ne(t,"float32")))))}}};var US={kernelName:Ks,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=_t(ee(ce(1),Me(ne(t,"float32"))));return fe(r,o)}}}};var jS={kernelName:Zs,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Ve(t.shape,o.shape);return{a:()=>{let i=ee(Me(t),Me(o)),l=O(r,fe(o,i)),u=Nt(t.shape,n);return u.length>0&&(l=be(l,u)),z(l,t.shape)},b:()=>{let i=ee(Me(t),Me(o)),l=He(O(r,fe(t,i))),u=Nt(o.shape,n);return u.length>0&&(l=be(l,u)),z(l,o.shape)}}}};var qS={kernelName:Xs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,ee(Me(ne(t,"float32")),1))}}};var HS={kernelName:Ys,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,pe(ce(1),Me(ne(t,"float32"))))}}};function Cq(r,e,t,o,n=[1,1,1],s,a){let i=v(r,"dy","avgPool3dGrad"),l=v(e,"input","avgPool3dGrad"),u=i,c=l,p=!1;l.rank===4&&(p=!0,u=z(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),c=z(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),E(u.rank===5,()=> ` Error in avgPool3dGrad : dy must be rank 5 but got rank $ { u . rank } . ` ),E(c.rank===5,()=> ` Error in avgPool3dGrad : input must be rank 5 but got rank $ { c . rank } . ` ),E(Pt(o,n),()=> ` Error in avgPool3dGrad : Either strides or dilations must be 1. Got strides $ { o } and dilations '${n}' ` ),a!=null&&E(it(s),()=> ` Error in avgPool3dGrad : pad must be an integer when using , dimRoundingMode $ { a } but got pad $ { s } . ` );let m={dy:u,input:c},f={filterSize:t,strides:o,dilations:n,pad:s,dimRoundingMode:a},d=A.runKernel(Hl,m,f);return p?z(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var KS=N({avgPool3dGrad_:Cq});var XS={kernelName:na,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{filterS
1. The $ { o } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2. The custom $ { o } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );return a}else{let s=r;if(s.className==null||s.config==null)throw new B( ` $ { o } : Improper config format : $ { JSON . stringify ( s ) } .
'className' and 'config' must set . ` );let a=s.className,i,l;if(a in t?[i,l]=t[a]:a in jn?[i,l]=jn.className:a in e&&([i,l]=e[a]),i==null)throw new B( ` Unknown $ { o } : $ { a } . This may be due to one of the following reasons :
1. The $ { o } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2. The custom $ { o } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );if(l!=null){let u={};for(let f of Object.keys(jn))u[f]=jn[f];for(let f of Object.keys(t))u[f]=t[f];let c=s.config;c.customObjects=u;let p=Object.assign({},jn);for(let f of Object.keys(t))jn[f]=t[f];hw(s.config);let m=l(i,s.config,t,n);return jn=Object.assign({},p),m}else{let u=Object.assign({},jn);for(let p of Object.keys(t))jn[p]=t[p];let c=new i(s.config);return jn=Object.assign({},u),c}}}function $ q(r,e){return r<e?-1:r>e?1:0}function nf(r,e){return-1* $ q(r,e)}function qn(r){if(r==null)return r;let e=[];for(let t of r)e.indexOf(t)===-1&&e.push(t);return e}function $ T(r){if(r==null)throw new B( ` Invalid value in obj : $ { JSON . stringify ( r ) } ` );for(let e in r)if(r.hasOwnProperty(e))return!1;return!0}function Vi(r,e,t){if(t!=null&&r.indexOf(t)<0)throw new B( ` $ { t } is not a valid $ { e } . Valid values are $ { r } or null / undefined . ` )}function bg(r,e,t=0,o=Infinity){return Vo(t>=0),Vo(o>=t),Array.isArray(r)&&r.length>=t&&r.length<=o&&r.every(n=>typeof n===e)}function jt(r,e){Array.isArray(r)?(x.assert(r.length>0,()=> ` $ { e } is unexpectedly an empty array . ` ),r.forEach((t,o)=>jt(t, ` element $ { o + 1 } of $ { e } ` ))):x.assert(Number.isInteger(r)&&r>0,()=> ` Expected $ { e } to be a positive integer , but got $ { RT ( r ) } . ` )}function RT(r){return r===null?"null":Array.isArray(r)?"["+r.map(e=>RT(e)).join(",")+"]":typeof r=="string"? ` "${r}" ` : ` $ { r } ` }function FT(r,e){let t=x.now(),o;return(...s)=>{let a=x.now();return a-t<e||(t=a,o=r(...s)),o}}function _g(r){return r==="relu"?"relu":r==="linear"?"linear":r==="elu"?"elu":null}function gw(r,e){return V(()=>_t(be(O(r,r),e,!0)))}var up=class extends te.Serializable{getConfig(){return{}}},sf=class extends up{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return V(()=>{let t=gw(e,this.axis),o=ir(t,0,this.maxValue);return O(e,fe(o,ee(er(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};sf.className="MaxNorm";te.registerClass(sf);var af=class extends up{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return V(()=>fe(e,ee(er(),gw(e,this.axis))))}getConfig(){return{axis:this.axis}}};af.className="UnitNorm";te.registerClass(af);var lf=class extends up{apply(e){return Sr(e)}};lf.className="NonNeg";te.registerClass(lf);var uf=class extends up{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return V(()=>{let t=gw(e,this.axis),o=ee(O(this.rate,ir(t,this.minValue,this.maxValue)),O(1-this.rate,t));return O(e,fe(o,ee(er(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};uf.className="MinMaxNorm";te.registerClass(uf);var OT={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Mt(r){return lp(r)}function PT(r,e={}){return Bi(r,te.SerializationMap.getMap().classNameMap,e,"constraint")}function Lt(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in OT?OT[r]:r,config:{}};return PT(t)}else return r instanceof up?r:PT(r)}function Rq(r){return new sf(r)}function Fq(r){return new af(r)}function Oq(){return new lf}function Pq(r){return new uf(r)}var vw={};et(vw,{constant:()=>Uq,glorotNormal:()=>Zq,glorotUniform:()=>Yq,heNormal:()=>Jq,heUniform:()=>Qq,identity:()=>Kq,leCunNormal:()=>eH,leCunUniform:()=>tH,ones:()=>Gq,orthogonal:()=>rH,randomNormal:()=>qq,randomUniform:()=>jq,truncatedNormal:()=>Hq,varianceScaling:()=>Xq,zeros:()=>Wq});var MT=["channelsFirst","channelsLast"],LT=["nearest","bilinear"],zT=["valid","same","causal"],BT=["max","avg"],VT=["sum","mul","concat","ave"];var cp=new Map;function Rt(r){Vi(MT,"DataFormat",r)}func
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),No(this.elementShape,t.shape, ` TensorArray $ { this . name } : Could not write to TensorArray index $ { e } . ` ),o.read)throw new Error( ` TensorArray $ { this . name } : Could not write to TensorArray index $ { e } , because it has already been read . ` );if(o.written)throw new Error( ` TensorArray $ { this . name } : Could not write to TensorArray index $ { e } , because it has already been written . ` );o.tensor=t,Dt(t),o.written=!0,this.tensors[e]=o}writeMany(e,t){if(e.length!==t.length)throw new Error( ` TensorArray $ { this . name } : could not write multiple tensors , because the index size : $ { e . length } is not the same as tensors size : $ { t . length } . ` );e.forEach((o,n)=>this.write(o,t[n]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but gather requested dtype $ { t } ` );if(e)e=e.slice(0,this.size());else{e=[];for(let n=0;n<this.size();n++)e.push(n)}if(e.length===0)return Fr([],[0].concat(this.elementShape));let o=this.readMany(e);return No(this.elementShape,o[0].shape,"TensorArray shape mismatch: "),Wt(o,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but concat requested dtype $ { e } ` );if(this.size()===0)return Fr([],[0].concat(this.elementShape));let t=[];for(let n=0;n<this.size();n++)t.push(n);let o=this.readMany(t);return No(this.elementShape,o[0].shape, ` TensorArray shape mismatch : tensor array shape ( $ { this . elementShape } ) vs first tensor shape ( $ { o [ 0 ] . shape } ) ` ),Je(o,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but tensor has dtype $ { t . dtype } ` );if(e.length!==t.shape[0])throw new Error( ` Expected len ( indices ) == tensor . shape [ 0 ] , but saw : $ { e . length } vs . $ { t . shape [ 0 ] } ` );let o=Math.max(...e);if(!this.dynamicSize&&o>=this.maxSize)throw new Error( ` Max index must be < array size ( $ { o } vs . $ { this . maxSize } ) ` );this.writeMany(e,cr(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but tensor has dtype $ { t . dtype } ` );let o=0,n=e.map(l=>(o+=l,o));if(o!==t.shape[0])throw new Error( ` Expected sum of lengths to be equal to
2020-12-02 22:46:41 +01:00
tensor . shape [ 0 ] , but sum of lengths is
2021-01-12 16:01:34 +01:00
$ { o } , and tensor 's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray' s size is not equal to the size of lengths ( $ { this . maxSize } vs . $ { e . length } ) , and the TensorArray is not marked as dynamically resizeable ` );let s=o===0?0:t.size/o,a=[];V(()=>{t=z(t,[1,o,s]);for(let l=0;l<e.length;++l){let u=l===0?0:n[l-1],c=[0,u,0],p=[1,e[l],s];a[l]=z(Fe(t,c,p),this.elementShape)}return a});let i=[];for(let l=0;l<e.length;l++)i[l]=l;this.writeMany(i,a)}};var sc=class{constructor(e,t,o,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=o,e!=null&&e.forEach(s=>{if(o!==s.dtype)throw new Error( ` Invalid data types ; op elements $ { o } , but list elements $ { s . dtype } ` );No(t,s.shape,"TensorList shape mismatch: "),Dt(s)}),this.idTensor=ce(0),this.maxNumElements=n,Dt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new sc([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,o=-1){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , but list elements $ { this . elementDtype } ` );if(o!==-1&&this.tensors.length!==o)throw new Error( ` Operation expected a list with $ { o } elements but got a list with $ { this . tensors . length } elements . ` );return No(e,this.elementShape,"TensorList shape mismatch: "),V(()=>{let n=this.tensors.map(s=>z(s,e));return Wt(n,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , but list elements $ { this . elementDtype } ` );if(this.size()===0)throw new Error("Trying to pop from an empty list.");let o=this.tensors.pop();return No(o.shape,e,"TensorList shape mismatch: "),z(o,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { e . dtype } , but list elements $ { this . elementDtype } ` );if(No(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Dt(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 } . ` );this.tensors.length=e}getItem(e,t,o){if(o!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { o } , but list elements $ { this . elementDtype } ` );if(e<0||e>this.tensors.length)throw new Error( ` Trying to access element $ { e } in a list with $ { this . tensors . length } elements . ` );if(this.tensors[e]==null)throw new Error( ` element at index $ { e } is null . ` );return No(this.tensors[e].shape,t,"TensorList shape mismatch: "),this.tensors[e]}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 . ` );No(this.elementShape,t.shape,"TensorList shape mismatch: "),Dt(t),this.tensors[e]=t}gather(e,t,o){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , but list elements $ { this . elementDtype } ` );return No(this.elementShape,o,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?Fr([],[0].concat(this.elementShape)):V(()=>{let n=e.map(s=>z(this.tensors[s],o));return Wt(n,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error( ` TensorList dtype is $ { this . elementDtype } but concat requested dtype $ { e } ` );return No(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?Fr([],[0].concat(this.elementShape)):V(()=>{let o=this.tensors.map(n=>z(n,t));return Je(o,0)})}};function J1(r,e,t){let o=r.dtype;if(r.shape.length<1)throw new Error( ` Tensor must be at least a vector , but saw shape : $ { r . shape } ` );if(r.dtype!==t)throw new Error( ` Invalid data types ; op elements $ { r . dtype } , but list elements $ { t } ` );let n=r.shape.slice(1);No
2020-12-02 22:46:41 +01:00
tensor . shape [ 0 ] , but sum of lengths is
2021-01-12 16:01:34 +01:00
$ { o } , and tensor ' s shape is : $ { r . shape } ` );let s=o===0?0:r.size/o,a=V(()=>{let l=[];r=z(r,[1,o,s]);for(let u=0;u<e.length;++u){let c=u===0?0:n[u-1],p=[0,c,0],m=[1,e[u],s];l[u]=z(Fe(r,p,m),t)}return r.dispose(),l}),i=new sc([],t,r.dtype,e.length);for(let l=0;l<a.length;l++)i.setItem(l,a[l]);return i}var rE=async(r,e,t)=>{switch(r.op){case"If":case"StatelessIf":{let o=C("thenBranch",r,e,t),n=C("elseBranch",r,e,t),s=C("cond",r,e,t),a=C("args",r,e,t);return(await s.data())[0]?t.functionMap[o].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap):t.functionMap[n].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap)}case"While":case"StatelessWhile":{let o=C("body",r,e,t),n=C("cond",r,e,t),s=C("args",r,e,t),a=await t.functionMap[n].executeFunctionAsync(s,t.tensorArrayMap,t.tensorListMap),i=s.map(c=>c.id),l=await a[0].data();a.forEach(c=>{!c.kept&&i.indexOf(c.id)===-1&&c.dispose()});let u=s;for(;l[0];){let c=u;u=await t.functionMap[o].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);let p=u.map(f=>f.id);c.forEach(f=>{!f.kept&&i.indexOf(f.id)===-1&&p.indexOf(f.id)===-1&&f.dispose()});let m=await t.functionMap[n].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);l=await m[0].data(),m.forEach(f=>{!f.kept&&i.indexOf(f.id)===-1&&p.indexOf(f.id)===-1&&f.dispose()})}return u}case"LoopCond":{let o=C("pred",r,e,t);return[Ms(o)]}case"Switch":{let o=C("pred",r,e,t),n=C("data",r,e,t);return n.kept||(n=Ms(n)),(await o.data())[0]?[void 0,n]:[n,void 0]}case"Merge":{let o=r.inputNames.find(n=>gr(n,e,t)!==void 0);if(o){let n=gr(o,e,t);return[Ms(n)]}return}case"Enter":{let o=C("frameName",r,e,t),n=C("tensor",r,e,t);return t.enterFrame(o),[Ms(n)]}case"Exit":{let o=C("tensor",r,e,t);return t.exitFrame(),[Ms(o)]}case"NextIteration":{let o=C("tensor",r,e,t);return t.nextIteration(),[Ms(o)]}case"TensorArrayV3":{let o=C("size",r,e,t),n=C("dtype",r,e,t),s=C("elementShape",r,e,t),a=C("dynamicSize",r,e,t),i=C("clearAfterRead",r,e,t),l=C("identicalElementShapes",r,e,t),u=C("name",r,e,t),c=new Dv(u,n,o,s,l,a,i);return t.addTensorArray(c),[c.idTensor,ce(1)]}case"TensorArrayWriteV3":{let o=C("tensorArrayId",r,e,t),n=C("index",r,e,t),s=C("tensor",r,e,t),a=t.getTensorArray(o.id);return a.write(n,s),[a.idTensor]}case"TensorArrayReadV3":{let o=C("tensorArrayId",r,e,t),n=C("index",r,e,t);return[t.getTensorArray(o.id).read(n)]}case"TensorArrayGatherV3":{let o=C("tensorArrayId",r,e,t),n=C("indices",r,e,t),s=C("dtype",r,e,t);return[t.getTensorArray(o.id).gather(n,s)]}case"TensorArrayScatterV3":{let o=C("tensorArrayId",r,e,t),n=C("indices",r,e,t),s=C("tensor",r,e,t),a=t.getTensorArray(o.id);return a.scatter(n,s),[a.idTensor]}case"TensorArrayConcatV3":{let o=C("tensorArrayId",r,e,t),n=t.getTensorArray(o.id),s=C("dtype",r,e,t);return[n.concat(s)]}case"TensorArraySplitV3":{let o=C("tensorArrayId",r,e,t),n=C("tensor",r,e,t),s=C("lengths",r,e,t),a=t.getTensorArray(o.id);return a.split(s,n),[a.idTensor]}case"TensorArraySizeV3":{let o=C("tensorArrayId",r,e,t),n=t.getTensorArray(o.id);return[ce(n.size(),"int32")]}case"TensorArrayCloseV3":{let o=C("tensorArrayId",r,e,t),n=t.getTensorArray(o.id);return n.clearAndClose(),[n.idTensor]}case"TensorListSetItem":{let o=C("tensorListId",r,e,t),n=C("index",r,e,t),s=C("tensor",r,e,t),a=t.getTensorList(o.id);return a.setItem(n,s),[a.idTensor]}case"TensorListGetItem":{let o=C("tensorListId",r,e,t),n=C("index",r,e,t),s=C("elementShape",r,e,t),a=C("elementDType",r,e,t);return[t.getTensorList(o.id).getItem(n,s,a)]}case"TensorListScatterV2":case"TensorListScatter":{let o=C("indices",r,e,t),n=C("tensor",r,e,t),s=C("elementShape",r,e,t),a=C("numElements",r,e,t),i=eE(n,o,s,a);return t.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let o=C("elementShape",r,e,t),n=C("elementDType",r,e,t),s;r.op==="TensorListReserve"?s="numElements":s="maxNumElements";let a=C(s,r,e,t),i=Q1(o,n,a);return t.addTensorList(i),[i.idTensor]}case"TensorListGather":{let o=C("tensorListId",r,e,t),n=C("indices",r,e,t),s=C("elementShape",r,e,t),a=C("elementDType",r,e,t);return[t.getTensorList(o.id).gather(n,a,s)]}cas
$ { e } ` );let n;return this.size===Infinity||this.size==null?n=this.size:t?n=Math.ceil(this.size/e):n=Math.floor(this.size/e),po(async()=>(await o.iterator()).columnMajorBatch(e,t,a5),n)}concatenate(e){let t=this,o;return this.size===Infinity||e.size===Infinity?o=Infinity:this.size!=null&&e.size!=null?o=this.size+e.size:o=null,po(async()=>(await t.iterator()).concatenate(await e.iterator()),o)}filter(e){let t=this,o;return this.size===Infinity?o=Infinity:o=null,po(async()=>(await t.iterator()).filter(n=>V(()=>e(n))),o)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return po(async()=>(await t.iterator()).map(o=>V(()=>e(o))),this.size)}mapAsync(e){let t=this;return po(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 po(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,o;return this.size!=null&&e>0?o=this.size*e:e===0?o=0:this.size!=null&&(e===void 0||e<0)?o=Infinity:o=null,po(async()=>{let n=Ad(async()=>({value:await t.iterator(),done:!1}));return TE(n.take(e))},o)}skip(e){let t=this,o;return this.size!=null&&e>=0&&this.size>=e?o=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?o=0:o=null,po(async()=>(await t.iterator()).skip(e),o)}shuffle(e,t,o=!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 n = this , s = BE . alea ( t || x . now ( ) . toString ( ) ) ; return po ( async ( ) => { let a = s . int32 ( ) ; return o && ( a += s . int32 ( ) ) , ( await n . iterator ( ) ) . shuffle ( e , a . toString ( ) ) } , this . size ) } take ( e ) { let t = this , o ; return this . size != null && this . size > e ? o = e : this . size != null && this . size <= e ? o = this . size : o = null , po ( async ( ) => ( await t . iterator ( ) ) . take ( e ) , o ) } async toArray ( ) { if ( this . size === Infinity ) throw new Error ( "Can not convert infinite data stream to array." ) ; return ( await this . iterator ( ) ) . toArray ( ) } async toArrayForTest ( ) { if ( this . size === Infinity ) throw new Error ( "Can not convert infinite data stream to array." ) ; return ( await this . iterator ( ) ) . toArrayForTest ( ) } } ; qi . MAX _BUFFER _SIZE = 1e4 ; function po ( r , e = null ) { return new class extends qi { constructor ( ) { super ( ... arguments ) ; this . size = e } async iterator ( ) { return r ( ) } } } function VE ( r ) { return po ( async ( ) => zv ( r ) , r . length ) } function WE ( r ) { if ( ! Cl ( r ) ) throw new Error ( "The argument to zip() must be an object or array." ) ; let e ; if ( Array . isArray ( r ) ) for ( let t = 0 ; t < r . length ; t ++ ) e = e == null ? r [ t ] . size : Math . min ( e , r [ t ] . size ) ; else if ( r instanceof Object ) for ( let t in r ) e = e == null ? r [ t ] . size : Math . min ( e , r [ t ] . size ) ; return po ( async ( ) => { let t = await hx ( r , o => { if ( o instanceof qi ) return { value : o . iterator ( ) , recurse : ! 1 } ; if ( Cl ( o ) ) return { value : null , recurse : ! 0 } ; throw new Error ( "Leaves of the structure passed to zip() must be Datasets, not primitives." ) } ) ; return AE ( t , Ga . SHORTEST ) } , e ) } function a5 ( r ) { if ( r === null ) return null ; let e = r [ 0 ] ; return kE ( e ) ? { value : l5 ( r ) , recurse : ! 1 } : { value : null , recurse : ! 0 } } function l5 ( r ) { if ( r . length === 0 ) throw new Error ( "Can't make a batch of zero elements." ) ; return r [ 0 ] instanceof R ? Wt ( r ) : Fr ( r ) } var Dd = class extends qi { constructor ( e ) { super ( ) ; this . input = e } async iterator ( ) { return ( await this . input . iterator ( ) ) . decodeUTF8 ( ) . split ( `
` ).map(n=>(n.endsWith(" \r ")&&(n=n.slice(0,-1)),n))}};var gx='"', $ d=Symbol("out"),GE=Symbol("field"),xx=Symbol("quote"),Gv=Symbol("quoteafterquote"),UE=Symbol("quoteinquote"),Rd=class extends qi{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 Dd(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(x.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&&x.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((n,s)=>(n[s]=n[s]+1||1,n),{}),o=Object.keys(t).filter(n=>t[n]>1);if(x.assert(o.length===0,()=>"Duplicate column names found: "+o.toString()),this.columnConfigs){for(let n of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(n)===-1)throw new Error('The key "'+n+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let o=t.value;return this.parseRow(o,!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),o={},n={};for(let s=0;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],i=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!i)){let l=t[s],u=null;if(l==="")if(i&&i.default!==void 0)u=i.default;else{if(i&&(i.required||i.isLabel))throw new Error( ` Required column $ { a } is empty in this line : $ { e } ` );u=void 0}else{let c=Number(l);if(isNaN(c))i&&i.dtype==="bool"?u=this.getBoolean(l):u=l;else if(!i||!i.dtype)u=c;else switch(i.dtype){case"float32":u=c;break;case"int32":u=Math.floor(c);break;case"bool":u=this.getBoolean(l);break;default:u=c}}i&&i.isLabel?n[a]=u:o[a]=u}}return Object.keys(n).length===0?o:{xs:o,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let o=[],n=0,s=e.length,a= $ d;for(let i=0;i<s;i++)switch(a){case $ d:switch(e.charAt(i)){case gx:n=i+1,a=xx;break;case this.delimiter:if(n=i+1,this.delimiter===" "&&this.delimWhitespace)break;o.push(""),a= $ d;break;default:a=GE,n=i;break}break;case GE:switch(e.charAt(i)){case this.delimiter:o.push(e.substring(n,i)),a= $ d,n=i+1;break;default:}break;case xx:switch(e.charAt(i)){case gx:a=Gv;break;default:}break;case Gv:switch(e.charAt(i)){case this.delimiter:o.push(e.substring(n,i-1)),a= $ d,n=i+1;break;case gx:a=xx;break;default:a=UE;break}break;case UE:switch(e.charAt(i)){case gx:a=xx;break;default:}break;default:}if(a===Gv?o.push(e.substring(n,s-1)):o.push(e.substring(n)),t&&o.length!==this.fullColumnNames.length)throw new Error( ` Invalid row in csv file . Should have $ { this . fullColumnNames . length } elements in a row , but got $ { o } ` );return o}};var Fd=class extends Zt{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( ` Inval
2020-12-02 22:46:41 +01:00
=== === === === === === === === === =
Hi there \ u { 1 F44B } . Looks like you are running TensorFlow . js in Node . js . To speed things up dramatically , install our node backend , which binds to TensorFlow C ++ , by running npm i @ tensorflow / tfjs - node , or npm i @ tensorflow / tfjs - node - gpu if you have CUDA . Then call require ( '@tensorflow/tfjs-node' ) ; ( - gpu suffix for CUDA ) at the start of your program . Visit https : //github.com/tensorflow/tfjs-node for more details.
2021-01-12 16:01:34 +01:00
=== === === === === === === === === = ` ));let n={};return this.data.set(n,{values:e,dtype:o,refCount:1}),n}makeTensorInfo(e,t,o){let n;if(t==="string"&&o!=null&&o.length>0&&x.isString(o[0])){let s=o.map(a=>x.encodeString(a));n=this.write(s,e,t)}else n=this.write(o,e,t);return{dataId:n,shape:e,dtype:t}}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,o,n){this.data.set(e,{values:t,dtype:n,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:o}=this.data.get(e);if(t==="complex64"){let n=this.readSync(o.real.dataId),s=this.readSync(o.imag.dataId);return S.mergeRealAndImagArrays(n,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),o=t;if(e.dtype==="string")try{o=t.map(n=>x.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ie(e.shape,e.dtype,o)}makeOutput(e,t,o){let n=this.write(e,t,o);return Cs().makeTensorFromDataId(n,t,o,this)}disposeData(e){if(this.data.has(e)){let{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){let t=e.dataId;if(this.data.has(t)){let o=this.data.get(t);o.refCount--,o.refCount<1&&this.disposeData(t)}}async time(e){let t=x.now();return e(),{kernelMs:x.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){re([e],"where");let t=this.readSync(e.dataId);return c5(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};var rk={};et(rk,{addImpl:()=>lA,bincountImpl:()=>Bd,bincountReduceImpl:()=>Hv,ceilImpl:()=>cA,concatImpl:()=>Vd,expImpl:()=>mA,expm1Impl:()=>dA,floorImpl:()=>gA,gatherV2Impl:()=>Xv,greaterImpl:()=>yA,lessImpl:()=>_A,linSpaceImpl:()=>Yv,logImpl:()=>vA,maxImpl:()=>Zv,maximumImpl:()=>CA,minimumImpl:()=>NA,multiplyImpl:()=>wx,negImpl:()=>EA,notEqualImpl:()=>DA,prodImpl:()=>FA,rangeImpl:()=>Ud,rsqrtImpl:()=>PA,simpleAbsImpl:()=>rA,sliceImpl:()=>jd,squaredDifferenceImpl:()=>zA,stridedSliceImpl:()=>Jv,subImpl:()=>VA,tileImpl:()=>Qv,topKImpl:()=>ek,transposeImpl:()=>Gd,uniqueImpl:()=>tk});function rA(r){let e=new Float32Array(r.length);for(let t=0;t<r.length;++t)e[t]=Math.abs(r[t]);return e}var p5=r=>{let{x:e}=r.inputs,t=r.backend;re(e,"abs");let o=new Float32Array(x.sizeFromShape(e.shape)),n=t.data.get(e.dataId).values;return o=rA(n),t.makeOutput(o,e.shape,"float32")},oA={kernelName:is,backendName:"cpu",kernelFunc:p5};function Ye(r){return(e,t,o,n,s)=>{let a=S.assertAndGetBroadcastShape(e,t),i=a.length,l=x.computeStrides(a),u=x.sizeFromShape(a),c=x.getTypedArrayFromDType(s,u),p=e.length,m=t.length,f=x.computeStrides(e),d=x.computeStrides(t),h=S.getBroadcastDims(e,a),g=S.getBroadcastDims(t,a);if(h.length+g.length===0)for(let y=0;y<c.length;++y)c[y]=r(o[y%o.length],n[y%n.length]);else for(let y=0;y<c.length;++y){let b=x.indexToLoc(y,i,l),_=b.slice(-p);h.forEach(T=>_[T]=0);let w=x.locToIndex(_,p,f),k=b.slice(-m);g.forEach(T=>k[T]=0);let $ =x.locToIndex(k,m,d);c[y]=r(o[w],n[ $ ])}return[c,a]}}function pr(r){let{inputs:e,backend:t}=r,{real:o,imag:n}=e,s=t.data.get(o.dataId).values,a=t.data.get(n.dataId).values,i=t.makeTensorInfo(o.shape,"complex64"),l=t.data.get(i.dataId);return l.complexTensorInfos={real:t.makeTensorInfo(o.shape,"float32",s),imag:t.makeTensorInfo(n.shape,"float32",a)},i}var nA={kernelName:Xl,backendName:"cpu",kernelFunc:pr};function Op(r,e,t="float32"){if(t==="complex64"){let n=Op(r,e,"float32"),s=Op(r,e,"float32");return pr({inputs:{real:n,imag:s},backend:r})}let o=x.makeZerosTypedArray(x.sizeFromShape(e),t);return r.makeTensorInfo(e,t,o)}function Ar(r){let{inputs:e,backend:t}=r,{x:o}=e;return t.incRef(o.dataId),{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}var sA={kernelName:cs,backendName:"cpu",kernelFunc:Ar};function Yn(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.data.get(o.dataId).complexTensorInfos.
` ),s=n.length.toString().length+2,a=n.map((p,m)=>x.rightPad((m+1).toString(),s)+p),i=0;for(let p=0;p<a.length;p++)i=Math.max(a[p].length,i);let l=a.slice(0,o-1),u=a.slice(o-1,o),c=a.slice(o);console.log(l.join( `
` )),console.log(e.split( `
` )[0]),console.log( ` % c $ { x . rightPad ( u [ 0 ] , i ) } ` ,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join( `
` ))}function _ $ (r){return ja(r,()=>r.createProgram(),"Unable to create WebGLProgram.")}function w $ (r,e){if(De(r,()=>r.linkProgram(e)),r.getProgramParameter(e,r.LINK_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function Sx(r,e){if(De(r,()=>r.validateProgram(e)),r.getProgramParameter(e,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function v $ (r,e){let t=ja(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return De(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),De(r,()=>r.bufferData(r.ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function k $ (r,e){let t=ja(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return De(r,()=>r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t)),De(r,()=>r.bufferData(r.ELEMENT_ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function C $ (r){return ja(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function I $ (r,e){let t=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(r<=0||e<=0){let o= ` [ $ { r } x$ { e } ] ` ;throw new Error("Requested texture size "+o+" is invalid.")}if(r>t||e>t){let o= ` [ $ { r } x$ { e } ] ` ,n= ` [ $ { t } x$ { t } ] ` ;throw new Error("Requested texture size "+o+" greater than WebGL maximum on this browser / GPU "+n+".")}}function N $ (r){return ja(r,()=>r.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function xk(r,e,t,o,n,s,a){let i=r.getAttribLocation(e,t);return i===-1?!1:(De(r,()=>r.bindBuffer(r.ARRAY_BUFFER,o)),De(r,()=>r.vertexAttribPointer(i,n,r.FLOAT,!1,s,a)),De(r,()=>r.enableVertexAttribArray(i)),!0)}function nY(r,e,t){oY(r,t),De(r,()=>r.activeTexture(r.TEXTURE0+t)),De(r,()=>r.bindTexture(r.TEXTURE_2D,e))}function S $ (r,e,t){return ja(r,()=>r.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function T $ (r,e,t){return r.getUniformLocation(e,t)}function E $ (r,e,t,o){De(r,()=>nY(r,e,o)),De(r,()=>r.uniform1i(t,o))}function Tx(r,e,t){De(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,t)),De(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0))}function yk(r,e){De(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,e)),De(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0))}function Qd(r){let e=r.checkFramebufferStatus(r.FRAMEBUFFER);if(e!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+sY(r,e))}function sY(r,e){switch(e){case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return ` unknown error $ { e } ` }}function ja(r,e,t){let o=De(r,()=>e());if(o==null)throw new Error(t);return o}function oY(r,e){let t=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,o=e+r.TEXTURE0;if(o<r.TEXTURE0||o>t){let n= ` [ gl . TEXTURE0 , gl . TEXTURE$ { t } ] ` ;throw new Error( ` textureUnit must be in $ { n } . ` )}}function Tl(r,e=2){return x.sizeFromShape(r.slice(0,r.length-e))}function El(r){if(r.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[r.length>1?r[r.length-2]:1,r[r.length-1]]}function Ex(r){let e=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(e=[Tl(r),...El(r)]),e}function A $ (r,e=!1){let t=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");e&&(t=t*2,r=r.map((n,s)=>s>=r.length-2?x.nearestLargerEven(r[s]):r[s]),r.length===1&&(r=[2,r[0]])),r.length!==2&&(r=x.squeezeShape(r).newShape);let o=x.sizeFromShape(r);if(r.length<=1&&o<=t)return[1,o];if(r.length===2&&r[0]<=t&&r[1]<=t)return r;if(r.length===3&&r[0]*r[1]<=t&&r[2]<=t)return[r[0]*r[1],r[2]];if(r.length===3&&r[0]<=t&&r[1]*r[2]<=t)return[r[0],r[1]*r[2]];if(r.length===4&&r[0]*r[1]*r[2]<=t&&r[3]<=t)return[r[0]*r[1]*r[2],r[3]];if(r.length===4&&r[0]<=t&&r[1]*r[2]*r[3]<=t)return[r[0],r[1]*r[2]*r[3]];if(e){let n=Tl(r),s=2,a=2;return r.length&&([s,a]=El(r)),o=n*(s/2)*(a/2),x.sizeToSquarishShape(o).map(i=>i*2)}return x.sizeToSquarishShape(o)}function Ax(r){return r%2==0}function uc(r,e){if(r=r.slice(-2),e=e.slice(-2),x.array
2020-12-02 22:46:41 +01:00
bool isnan _custom ( float val ) {
return ( val > 0.0 || val < 0.0 ) ? false : val != 0.0 ;
}
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan _custom ( val . x ) ,
isnan _custom ( val . y ) , isnan _custom ( val . z ) , isnan _custom ( val . w ) ) ;
}
# define isnan ( value ) isnan _custom ( value )
2021-01-12 16:01:34 +01:00
` ,l="",u= `
2020-12-02 22:46:41 +01:00
# define round ( value ) newRound ( value )
int newRound ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
}
ivec4 newRound ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
}
2021-01-12 16:01:34 +01:00
` ):(r="",e="attribute",t="varying",o="varying",n="texture2D",s="gl_FragColor",a="",i= `
2020-12-02 22:46:41 +01:00
# define isnan ( value ) isnan _custom ( value )
bool isnan _custom ( float val ) {
return ( val > 0. || val < 1. || val == 0. ) ? false : true ;
}
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan ( val . x ) , isnan ( val . y ) , isnan ( val . z ) , isnan ( val . w ) ) ;
}
2021-01-12 16:01:34 +01:00
` ,l= `
2020-12-02 22:46:41 +01:00
uniform float INFINITY ;
bool isinf ( float val ) {
return abs ( val ) == INFINITY ;
}
bvec4 isinf ( vec4 val ) {
return equal ( abs ( val ) , vec4 ( INFINITY ) ) ;
}
2021-01-12 16:01:34 +01:00
` ,u= `
2020-12-02 22:46:41 +01:00
int round ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
}
ivec4 round ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
}
2021-01-12 16:01:34 +01:00
` ),{version:r,attribute:e,varyingVs:t,varyingFs:o,texture2D:n,output:s,defineOutput:a,defineSpecialNaN:i,defineSpecialInf:l,defineRound:u}}function Ls(r,e,t="index"){let o=x.computeStrides(e);return o.map((n,s)=>{let a= ` int $ { r [ s ] } = $ { t } / $ { n } ` ,i=s===o.length-1? ` int $ { r [ s + 1 ] } = $ { t } - $ { r [ s ] } * $ { n } ` : ` index -= $ { r [ s ] } * $ { n } ` ;return ` $ { a } ; $ { i } ; ` }).join("")}function Bp(r){let e=x.computeStrides(r).map(t=>t.toString());return `
2020-12-02 22:46:41 +01:00
int getFlatIndex ( ivec3 coords ) {
2021-01-12 16:01:34 +01:00
return coords . x * $ { e [ 0 ] } + coords . y * $ { e [ 1 ] } + coords . z ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }var Dx= `
2020-12-02 22:46:41 +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 ;
}
2021-01-12 16:01:34 +01:00
` ;var kk=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Nl.DENSE;let t=Sl(e),o=zt();this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2021-01-12 16:01:34 +01:00
$ { Ls ( [ "r" , "c" , "d" ] , e ) }
2020-12-15 14:15:43 +01:00
return ivec3 ( r , c , d ) ;
}
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = 4 * ( resTexRC . x * $ { t [ 1 ] } + resTexRC . y ) ;
2020-12-15 14:15:43 +01:00
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-01-12 16:01:34 +01:00
$ { o . output } = result ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var Ck=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Nl.DENSE;let t=Sl(e),o=zt();this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2021-01-12 16:01:34 +01:00
$ { Ls ( [ "r" , "c" , "d" ] , e ) }
2020-12-15 14:15:43 +01:00
return ivec3 ( r , c , d ) ;
}
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = 4 * ( resTexRC . x * $ { t [ 1 ] } + resTexRC . y ) ;
2020-12-15 14:15:43 +01:00
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-01-12 16:01:34 +01:00
$ { o . output } = result ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var Ik=class{constructor(e){this.variableNames=["A"],this.outTexUsage=Dr.DOWNLOAD;let t=zt();this.outputShape=e,this.userCode= `
$ { Dx }
2020-12-15 14:15:43 +01:00
void main ( ) {
float x = getAAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { t . output } = encode _float ( x ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var Nk=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Dr.DOWNLOAD;let t=zt();this.outputShape=e,this.userCode= `
$ { Dx }
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
float x = getChannel ( getAAtOutCoords ( ) , vec2 ( coords . y , coords . z ) ) ;
2021-01-12 16:01:34 +01:00
$ { t . output } = encode _float ( x ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var Sk=class{constructor(e,t,o=!1){this.variableNames=["A"];let n=zt(),[s,a]=t;this.outputShape=e;let i="result";o&&(i="floor(result * 255. + 0.5)"),this.userCode= `
$ { Bp ( e ) }
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int flatIndex = getFlatIndex ( coords ) ;
int offset = imod ( flatIndex , 4 ) ;
flatIndex = idiv ( flatIndex , 4 , 1. ) ;
2021-01-12 16:01:34 +01:00
int r = flatIndex / $ { a } ;
int c = imod ( flatIndex , $ { a } ) ;
vec2 uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( $ { a } . 0 , $ { s } . 0 ) ;
vec4 values = $ { n . texture2D } ( A , uv ) ;
2020-12-15 14:15:43 +01:00
float result ;
if ( offset == 0 ) {
result = values [ 0 ] ;
} else if ( offset == 1 ) {
result = values [ 1 ] ;
} else if ( offset == 2 ) {
result = values [ 2 ] ;
} else {
result = values [ 3 ] ;
}
2021-01-12 16:01:34 +01:00
$ { n . output } = vec4 ( $ { i } , 0. , 0. , 0. ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var Tk=class{constructor(e,t,o=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let n=zt(),[s,a]=t;this.outputShape=e;let i="",l="result";o&&(l="floor(result * 255. + 0.5)");for(let u=0;u<=1;u++)for(let c=0;c<=1;c++){let p=u*2+c;i+= `
2020-12-15 14:15:43 +01:00
localCoords = coords ;
2021-01-12 16:01:34 +01:00
if ( localCoords [ 2 ] + $ { c } < $ { e [ 2 ] } ) {
localCoords [ 2 ] += $ { c } ;
if ( localCoords [ 1 ] + $ { u } < $ { e [ 1 ] } ) {
localCoords [ 1 ] += $ { u } ;
2020-12-15 14:15:43 +01:00
flatIndex = getFlatIndex ( localCoords ) ;
offset = imod ( flatIndex , 4 ) ;
flatIndex = idiv ( flatIndex , 4 , 1. ) ;
2021-01-12 16:01:34 +01:00
r = flatIndex / $ { a } ;
c = imod ( flatIndex , $ { a } ) ;
uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( $ { a } . 0 , $ { s } . 0 ) ;
values = $ { n . texture2D } ( A , uv ) ;
2020-12-15 14:15:43 +01:00
if ( offset == 0 ) {
2021-01-12 16:01:34 +01:00
result [ $ { p } ] = values [ 0 ] ;
2020-12-15 14:15:43 +01:00
} else if ( offset == 1 ) {
2021-01-12 16:01:34 +01:00
result [ $ { p } ] = values [ 1 ] ;
2020-12-15 14:15:43 +01:00
} else if ( offset == 2 ) {
2021-01-12 16:01:34 +01:00
result [ $ { p } ] = values [ 2 ] ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
result [ $ { p } ] = values [ 3 ] ;
2020-12-15 14:15:43 +01:00
}
}
}
` }this.userCode= `
2021-01-12 16:01:34 +01:00
$ { Bp ( e ) }
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
int flatIndex , r , c , offset ;
ivec3 localCoords ;
vec2 uv ;
vec4 values ;
2021-01-12 16:01:34 +01:00
$ { i }
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
$ { n . output } = $ { l } ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function M $ (r){let e=zt(),t= ` $ { e . version }
2020-12-15 14:15:43 +01:00
precision highp float ;
2021-01-12 16:01:34 +01:00
$ { e . attribute } vec3 clipSpacePos ;
$ { e . attribute } vec2 uv ;
$ { e . varyingVs } vec2 resultUV ;
2020-12-15 14:15:43 +01:00
void main ( ) {
gl _Position = vec4 ( clipSpacePos , 1 ) ;
resultUV = uv ;
2021-01-12 16:01:34 +01:00
} ` ;return y $ (r,t)}function L $ (r){let e=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return v $ (r,e)}function z $ (r){let e=new Uint16Array([0,1,2,2,1,3]);return k $ (r,e)}function eh(r,e,t,o,n,s){I $ (e,t);let a=C $ (r),i=r.TEXTURE_2D;return De(r,()=>r.bindTexture(i,a)),De(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)),De(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)),De(r,()=>r.texParameteri(i,r.TEXTURE_MIN_FILTER,r.NEAREST)),De(r,()=>r.texParameteri(i,r.TEXTURE_MAG_FILTER,r.NEAREST)),De(r,()=>r.texImage2D(i,0,o,e,t,0,n,s,null)),De(r,()=>r.bindTexture(r.TEXTURE_2D,null)),a}function Ek(r){return r.internalFormatFloat}function B $ (r,e,t,o){let[n,s]=lc(e,t);return eh(r,n,s,Ek(o),o.textureFormatFloat,r.FLOAT)}function Ak(r){return r.internalFormatHalfFloat}function V $ (r,e,t,o){let[n,s]=lc(e,t);return eh(r,n,s,Ak(o),o.textureFormatFloat,o.textureTypeHalfFloat)}function Dk(r){return r.downloadTextureFormat}function W $ (r,e,t,o){let[n,s]=lc(e,t);return eh(r,n,s,Dk(o),r.RGBA,r.UNSIGNED_BYTE)}function $ k(r){return r.internalFormatPackedFloat}function G $ (r,e,t,o){let[n,s]=Ki(e,t);return eh(r,n,s, $ k(o),r.RGBA,r.FLOAT)}function Rk(r){return r.internalFormatPackedHalfFloat}function U $ (r,e,t,o){let[n,s]=Ki(e,t);return eh(r,n,s,Rk(o),r.RGBA,o.textureTypeHalfFloat)}function j $ (r,e,t){let o=0,n=3*4,s=3*4+2*4;return De(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),xk(r,e,"clipSpacePos",t,3,s,o)&&xk(r,e,"uv",t,2,s,n)}function q $ (r,e,t,o,n,s){De(r,()=>r.bindTexture(r.TEXTURE_2D,e));let a,i,l;n instanceof Uint8Array?(a=new Uint8Array(t*o*4),i=r.UNSIGNED_BYTE,l=r.RGBA):(a=new Float32Array(t*o*4),i=r.FLOAT,l=s.internalFormatPackedFloat),a.set(n),De(r,()=>r.texImage2D(r.TEXTURE_2D,0,l,t,o,0,r.RGBA,i,a)),De(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function H $ (r,e,t){De(r,()=>r.bindTexture(r.TEXTURE_2D,e)),t.data instanceof Uint8Array?De(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,t.width,t.height,0,r.RGBA,r.UNSIGNED_BYTE,t.data)):De(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t)),De(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function K $ (r,e,t,o){let n=r.createBuffer();De(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,n));let i=4*4*e*t;return De(r,()=>r.bufferData(r.PIXEL_PACK_BUFFER,i,r.STREAM_READ)),De(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,0)),De(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,null)),n}function X $ (r,e,t){let o=r,n=new Float32Array(t);return o.bindBuffer(o.PIXEL_PACK_BUFFER,e),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,n),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),n}function Y $ (r,e,t,o){let[n,s]=lc(e,t),a=4,i=new Uint8Array(h $ (e*t,a));return De(r,()=>r.readPixels(0,0,n,s,o.downloadTextureFormat,r.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function Z $ (r,e,t,o,n,s,a,i){let l=r,u=new Float32Array(g $ (s,a));return l.bindBuffer(l.PIXEL_PACK_BUFFER,e),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function J $ (r,e,t){let o=new Float32Array(e*t*4);return De(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,o)),o}var Fk=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=W().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,d $ (t,e)):this.gl=Go(t);let o="WEBGL_color_buffer_float",n="EXT_color_buffer_half_float";if(W().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=Jd(this.gl,s),Uo(this.gl,a))this.textureHalfFloatExtension=Jd(this.gl,a);else if(W().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(o),Uo(this.gl,n))this.colorBufferHalfFloatExtension=Jd(this.gl,n);else if(W().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(o="EXT_color_buffer_float",Uo(this.gl,o))this.colorBufferFloatExtension=this.gl.getExtension(o);else if(Uo(this.gl,n))this.
` ),a=r.map(d=>lY(d,e,o)).join( `
` ),i=e.texShape,l=zt(),u=pY(l),c,p,m=dY(l);return e.isPacked?(c=uY(e.logicalShape,i),p=fY(l)):(c=cY(e.logicalShape,i),p=mY(l)),o&&(m+=hY),[m,u,p,s,c,a,t].join( `
` )}function Vp(r){let e=r.shapeInfo.logicalShape;switch(e.length){case 0:return gY(r);case 1:return xY(r);case 2:return yY(r);case 3:return bY(r);case 4:return _Y(r);case 5:return wY(r);case 6:return vY(r);default:throw new Error( ` $ { e . length } - D input sampling is not yet supported ` )}}function tR(r){switch(r.shapeInfo.logicalShape.length){case 0:return kY(r);case 1:return CY(r);case 2:return IY(r);case 3:return NY(r);default:return SY(r)}}function lY(r,e,t=!1){let o="";t?o+=tR(r):o+=Vp(r);let n=r.shapeInfo.logicalShape,s=e.logicalShape;return n.length<=s.length&&(t?o+=TY(r,e):o+=EY(r,e)),o}function uY(r,e){switch(r.length){case 0:return rR();case 1:return AY(r,e);case 2:return RY(r,e);case 3:return DY(r,e);default:return $ Y(r,e)}}function cY(r,e){switch(r.length){case 0:return rR();case 1:return FY(r,e);case 2:return zY(r,e);case 3:return OY(r,e);case 4:return PY(r,e);case 5:return MY(r,e);case 6:return LY(r,e);default:throw new Error( ` $ { r . length } - D output sampling is not yet supported ` )}}function pY(r){return `
2020-12-02 22:46:41 +01:00
float sampleTexture ( sampler2D textureSampler , vec2 uv ) {
2021-01-12 16:01:34 +01:00
return $ { r . texture2D } ( textureSampler , uv ) . r ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function mY(r){return `
2020-12-02 22:46:41 +01:00
void setOutput ( float val ) {
2021-01-12 16:01:34 +01:00
$ { r . output } = vec4 ( val , 0 , 0 , 0 ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function fY(r){return `
2020-12-02 22:46:41 +01:00
void setOutput ( vec4 val ) {
2021-01-12 16:01:34 +01:00
$ { r . output } = val ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function dY(r){return ` $ { r . version }
2020-12-02 22:46:41 +01:00
precision highp float ;
precision highp int ;
precision highp sampler2D ;
2021-01-12 16:01:34 +01:00
$ { r . varyingFs } vec2 resultUV ;
$ { r . defineOutput }
2020-12-02 22:46:41 +01:00
const vec2 halfCR = vec2 ( 0.5 , 0.5 ) ;
struct ivec5
{
int x ;
int y ;
int z ;
int w ;
int u ;
} ;
struct ivec6
{
int x ;
int y ;
int z ;
int w ;
int u ;
int v ;
} ;
uniform float NAN ;
2021-01-12 16:01:34 +01:00
$ { r . defineSpecialNaN }
$ { r . defineSpecialInf }
$ { r . defineRound }
2020-12-02 22:46:41 +01:00
int imod ( int x , int y ) {
return x - y * ( x / y ) ;
}
int idiv ( int a , int b , float sign ) {
int res = a / b ;
int mod = imod ( a , b ) ;
if ( sign < 0. && mod != 0 ) {
res -= 1 ;
}
return res ;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
# define HASHSCALE1 443.8975
float random ( float seed ) {
vec2 p = resultUV * seed ;
vec3 p3 = fract ( vec3 ( p . xyx ) * HASHSCALE1 ) ;
p3 += dot ( p3 , p3 . yzx + 19.19 ) ;
return fract ( ( p3 . x + p3 . y ) * p3 . z ) ;
}
2021-01-12 16:01:34 +01:00
$ { BY }
$ { VY }
$ { WY }
` }var BY= `
2020-12-02 22:46:41 +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 ) ;
}
2021-01-12 16:01:34 +01:00
` ,VY= `
2020-12-02 22:46:41 +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 ) ;
}
2021-01-12 16:01:34 +01:00
` ,WY= `
2020-12-02 22:46:41 +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 ) ;
}
2021-01-12 16:01:34 +01:00
` ,hY= `
2020-12-02 22:46:41 +01:00
float getChannel ( vec4 frag , vec2 innerDims ) {
vec2 modCoord = mod ( innerDims , 2. ) ;
return modCoord . x == 0. ?
( modCoord . y == 0. ? frag . r : frag . g ) :
( modCoord . y == 0. ? frag . b : frag . a ) ;
}
float getChannel ( vec4 frag , int dim ) {
float modCoord = mod ( float ( dim ) , 2. ) ;
return modCoord == 0. ? frag . r : frag . g ;
}
2021-01-12 16:01:34 +01:00
` ;function rR(){return `
2020-12-02 22:46:41 +01:00
int getOutputCoords ( ) {
return 0 ;
}
2021-01-12 16:01:34 +01:00
` }function AY(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return t[0]===1? `
2020-12-02 22:46:41 +01:00
int getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return 2 * int ( resultUV . x * $ { t [ 1 ] } . 0 ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` :t[1]===1? `
2020-12-02 22:46:41 +01:00
int getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return 2 * int ( resultUV . y * $ { t [ 0 ] } . 0 ) ;
2020-12-02 22:46:41 +01:00
}
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
return 2 * ( resTexRC . x * $ { t [ 1 ] } + resTexRC . y ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function FY(r,e){return e[0]===1? `
2020-12-02 22:46:41 +01:00
int getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return int ( resultUV . x * $ { e [ 1 ] } . 0 ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` :e[1]===1? `
2020-12-02 22:46:41 +01:00
int getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return int ( resultUV . y * $ { e [ 0 ] } . 0 ) ;
2020-12-02 22:46:41 +01:00
}
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { e [ 0 ] } , $ { e [ 1 ] } ) ) ;
return resTexRC . x * $ { e [ 1 ] } + resTexRC . y ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function DY(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],o=Math.ceil(r[2]/2),n=o*Math.ceil(r[1]/2);return `
2020-12-02 22:46:41 +01:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int b = index / $ { n } ;
index -= b * $ { n } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int r = 2 * ( index / $ { o } ) ;
int c = imod ( index , $ { o } ) * 2 ;
2020-12-02 22:46:41 +01:00
return ivec3 ( b , r , c ) ;
}
2021-01-12 16:01:34 +01:00
` }function OY(r,e){let t=Ls(["r","c","d"],r);return `
2020-12-02 22:46:41 +01:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { e [ 0 ] } , $ { e [ 1 ] } ) ) ;
int index = resTexRC . x * $ { e [ 1 ] } + resTexRC . y ;
$ { t }
2020-12-02 22:46:41 +01:00
return ivec3 ( r , c , d ) ;
}
2021-01-12 16:01:34 +01:00
` }function $ Y(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],o=Math.ceil(r[r.length-1]/2),n=o*Math.ceil(r[r.length-2]/2),s=n,a="",i="b, r, c";for(let l=2;l<r.length-1;l++)s*=r[r.length-l-1],a= `
int b$ { l } = index / $ { s } ;
index -= b$ { l } * $ { s } ;
` +a,i= ` b$ { l } , ` +i;return `
ivec$ { r . length } getOutputCoords ( ) {
2020-12-02 22:46:41 +01:00
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { a }
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int b = index / $ { n } ;
index -= b * $ { n } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int r = 2 * ( index / $ { o } ) ;
int c = imod ( index , $ { o } ) * 2 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
return ivec$ { r . length } ( $ { i } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function PY(r,e){let t=Ls(["r","c","d","d2"],r);return `
2020-12-02 22:46:41 +01:00
ivec4 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { e [ 0 ] } , $ { e [ 1 ] } ) ) ;
int index = resTexRC . x * $ { e [ 1 ] } + resTexRC . y ;
$ { t }
2020-12-02 22:46:41 +01:00
return ivec4 ( r , c , d , d2 ) ;
}
2021-01-12 16:01:34 +01:00
` }function MY(r,e){let t=Ls(["r","c","d","d2","d3"],r);return `
2020-12-02 22:46:41 +01:00
ivec5 getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( $ { e [ 0 ] } ,
$ { e [ 1 ] } ) ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int index = resTexRC . x * $ { e [ 1 ] } + resTexRC . y ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { t }
2020-12-02 22:46:41 +01:00
ivec5 outShape = ivec5 ( r , c , d , d2 , d3 ) ;
return outShape ;
}
2021-01-12 16:01:34 +01:00
` }function LY(r,e){let t=Ls(["r","c","d","d2","d3","d4"],r);return `
2020-12-02 22:46:41 +01:00
ivec6 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { e [ 0 ] } , $ { e [ 1 ] } ) ) ;
int index = resTexRC . x * $ { e [ 1 ] } + resTexRC . y ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { t }
2020-12-02 22:46:41 +01:00
ivec6 result = ivec6 ( r , c , d , d2 , d3 , d4 ) ;
return result ;
}
2021-01-12 16:01:34 +01:00
` }function RY(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(x.arraysEqual(r,e))return `
2020-12-02 22:46:41 +01:00
ivec2 getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return 2 * ivec2 ( resultUV . yx * vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let o=Math.ceil(r[1]/2);return `
2020-12-02 22:46:41 +01:00
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
int r = 2 * ( index / $ { o } ) ;
int c = imod ( index , $ { o } ) * 2 ;
2020-12-02 22:46:41 +01:00
return ivec2 ( r , c ) ;
}
2021-01-12 16:01:34 +01:00
` }function zY(r,e){return x.arraysEqual(r,e)? `
2020-12-02 22:46:41 +01:00
ivec2 getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return ivec2 ( resultUV . yx * vec2 ( $ { e [ 0 ] } , $ { e [ 1 ] } ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` :r[1]===1? `
2020-12-02 22:46:41 +01:00
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { e [ 0 ] } , $ { e [ 1 ] } ) ) ;
int index = resTexRC . x * $ { e [ 1 ] } + resTexRC . y ;
2020-12-02 22:46:41 +01:00
return ivec2 ( index , 0 ) ;
}
2021-01-12 16:01:34 +01:00
` :r[0]===1? `
2020-12-02 22:46:41 +01:00
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { e [ 0 ] } , $ { e [ 1 ] } ) ) ;
int index = resTexRC . x * $ { e [ 1 ] } + resTexRC . y ;
2020-12-02 22:46:41 +01:00
return ivec2 ( 0 , index ) ;
}
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { e [ 0 ] } , $ { e [ 1 ] } ) ) ;
int index = resTexRC . x * $ { e [ 1 ] } + resTexRC . y ;
int r = index / $ { r [ 1 ] } ;
int c = index - r * $ { r [ 1 ] } ;
2020-12-02 22:46:41 +01:00
return ivec2 ( r , c ) ;
}
2021-01-12 16:01:34 +01:00
` }function cc(r){return ` offset$ { r } ` }function kY(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),o=zt();return `
vec4 $ { t } ( ) {
return $ { o . texture2D } ( $ { e } , halfCR ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function gY(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return ` float $ { t } ( ) { return $ { e } ; } ` ;let[o,n]=r.shapeInfo.texShape;if(o===1&&n===1)return `
float $ { t } ( ) {
return sampleTexture ( $ { e } , halfCR ) ;
}
` ;let[s,a]=r.shapeInfo.texShape,i=cc(e);return `
float $ { t } ( ) {
vec2 uv = uvFromFlat ( $ { s } , $ { a } , $ { i } ) ;
return sampleTexture ( $ { e } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function CY(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),o=r.shapeInfo.texShape,n=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],s=zt();return `
vec4 $ { t } ( int index ) {
2020-12-02 22:46:41 +01:00
vec2 uv = packedUVfrom1D (
2021-01-12 16:01:34 +01:00
$ { n [ 0 ] } , $ { n [ 1 ] } , index ) ;
return $ { s . texture2D } ( $ { e } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function xY(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return `
float $ { t } ( int index ) {
$ { Wp ( r ) }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let o=r.shapeInfo.texShape,n=o[0],s=o[1];if(s===1&&n===1)return `
float $ { t } ( int index ) {
return sampleTexture ( $ { e } , halfCR ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let a=cc(e);return s===1? `
float $ { t } ( int index ) {
vec2 uv = vec2 ( 0.5 , ( float ( index + $ { a } ) + 0.5 ) / $ { n } . 0 ) ;
return sampleTexture ( $ { e } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` :n===1? `
float $ { t } ( int index ) {
vec2 uv = vec2 ( ( float ( index + $ { a } ) + 0.5 ) / $ { s } . 0 , 0.5 ) ;
return sampleTexture ( $ { e } , uv ) ;
2020-12-02 22:46:41 +01:00
}
` : `
2021-01-12 16:01:34 +01:00
float $ { t } ( int index ) {
vec2 uv = uvFromFlat ( $ { n } , $ { s } , index + $ { a } ) ;
return sampleTexture ( $ { e } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function IY(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape,s=n[0],a=n[1],i=zt();if(n!=null&&x.arraysEqual(e,n))return `
vec4 $ { o } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { a } . 0 , $ { s } . 0 ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
return $ { i . texture2D } ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let l=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],u=Math.ceil(e[1]/2);return `
vec4 $ { o } ( int row , int col ) {
vec2 uv = packedUVfrom2D ( $ { u } , $ { l [ 0 ] } , $ { l [ 1 ] } , row , col ) ;
return $ { i . texture2D } ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function yY(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape;if(n!=null&&x.arraysEqual(e,n)){let p=n[0],m=n[1];return `
float $ { o } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { m } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }let{newShape:s,keptDims:a}=x.squeezeShape(e),i=s;if(i.length<e.length){let p=Gp(r,i),m=["row","col"];return `
$ { Vp ( p ) }
float $ { o } ( int row , int col ) {
return $ { o } ( $ { Up ( m , a ) } ) ;
}
` }if(r.shapeInfo.isUniform)return `
float $ { o } ( int row , int col ) {
int index = round ( dot ( vec2 ( row , col ) , vec2 ( $ { e [ 1 ] } , 1 ) ) ) ;
$ { Wp ( r ) }
}
` ;let l=n[0],u=n[1],c=cc(t);return u===1? `
float $ { o } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { c } ) , vec3 ( $ { e [ 1 ] } , 1 , 1 ) ) ;
vec2 uv = vec2 ( 0.5 , ( index + 0.5 ) / $ { l } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` :l===1? `
float $ { o } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { c } ) , vec3 ( $ { e [ 1 ] } , 1 , 1 ) ) ;
vec2 uv = vec2 ( ( index + 0.5 ) / $ { u } . 0 , 0.5 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
` : `
2021-01-12 16:01:34 +01:00
float $ { o } ( int row , int col ) {
2020-12-02 22:46:41 +01:00
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { e [ 1 ] } + col + $ { c } ;
vec2 uv = uvFromFlat ( $ { l } , $ { u } , index ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function NY(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape,s=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)];if(e[0]===1){let p=e.slice(1),m=[1,2],f=Gp(r,p),d=["b","row","col"];return `
$ { tR ( f ) }
vec4 $ { o } ( int b , int row , int col ) {
return $ { o } ( $ { Up ( d , m ) } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }let a=s[0],i=s[1],l=Math.ceil(e[2]/2),u=l*Math.ceil(e[1]/2),c=zt();return `
vec4 $ { o } ( int b , int row , int col ) {
2020-12-02 22:46:41 +01:00
vec2 uv = packedUVfrom3D (
2021-01-12 16:01:34 +01:00
$ { a } , $ { i } , $ { u } , $ { l } , b , row , col ) ;
return $ { c . texture2D } ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function bY(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[1]*e[2],s=e[2],{newShape:a,keptDims:i}=x.squeezeShape(e),l=a;if(l.length<e.length){let d=Gp(r,l),h=["row","col","depth"];return `
$ { Vp ( d ) }
float $ { o } ( int row , int col , int depth ) {
return $ { o } ( $ { Up ( h , i ) } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }if(r.shapeInfo.isUniform)return `
float $ { o } ( int row , int col , int depth ) {
2020-12-02 22:46:41 +01:00
int index = round ( dot ( vec3 ( row , col , depth ) ,
2021-01-12 16:01:34 +01:00
vec3 ( $ { n } , $ { s } , 1 ) ) ) ;
$ { Wp ( r ) }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let u=r.shapeInfo.texShape,c=u[0],p=u[1],m=r.shapeInfo.flatOffset;if(p===n&&m==null)return `
float $ { o } ( int row , int col , int depth ) {
2020-12-02 22:46:41 +01:00
float texR = float ( row ) ;
2021-01-12 16:01:34 +01:00
float texC = dot ( vec2 ( col , depth ) , vec2 ( $ { s } , 1 ) ) ;
2020-12-02 22:46:41 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { p } . 0 , $ { c } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;if(p===s&&m==null)return `
float $ { o } ( int row , int col , int depth ) {
float texR = dot ( vec2 ( row , col ) , vec2 ( $ { e [ 1 ] } , 1 ) ) ;
2020-12-02 22:46:41 +01:00
float texC = float ( depth ) ;
2021-01-12 16:01:34 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { p } . 0 , $ { c } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let f=cc(t);return `
float $ { o } ( int row , int col , int depth ) {
2020-12-02 22:46:41 +01:00
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { n } + col * $ { s } + depth + $ { f } ;
vec2 uv = uvFromFlat ( $ { c } , $ { p } , index ) ;
return sampleTexture ( $ { t } , uv ) ;
}
` }function SY(r){let e=r.shapeInfo.logicalShape,t=e.length,o=r.name,n="get"+o.charAt(0).toUpperCase()+o.slice(1),s=r.shapeInfo.texShape,a=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],i=a[0],l=a[1],u=Math.ceil(e[t-1]/2),c=u*Math.ceil(e[t-2]/2),p="int b, int row, int col",m= ` b * $ { c } + ( row / 2 ) * $ { u } + ( col / 2 ) ` ;for(let d=2;d<t-1;d++)p= ` int b$ { d } , ` +p,c*=e[t-d-1],m= ` b$ { d } * $ { c } + ` +m;let f=zt();return `
vec4 $ { n } ( $ { p } ) {
int index = $ { m } ;
int texR = index / $ { l } ;
int texC = index - texR * $ { l } ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { l } , $ { i } ) ;
return $ { f . texture2D } ( $ { o } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function _Y(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[3],s=e[2]*n,a=e[1]*s,{newShape:i,keptDims:l}=x.squeezeShape(e);if(i.length<e.length){let d=Gp(r,i),h=["row","col","depth","depth2"];return `
$ { Vp ( d ) }
float $ { o } ( int row , int col , int depth , int depth2 ) {
return $ { o } ( $ { Up ( h , l ) } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }if(r.shapeInfo.isUniform)return `
float $ { o } ( int row , int col , int depth , int depth2 ) {
2020-12-02 22:46:41 +01:00
int index = round ( dot ( vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { a } , $ { s } , $ { n } , 1 ) ) ) ;
$ { Wp ( r ) }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let u=r.shapeInfo.flatOffset,c=r.shapeInfo.texShape,p=c[0],m=c[1];if(m===a&&u==null)return `
float $ { o } ( int row , int col , int depth , int depth2 ) {
2020-12-02 22:46:41 +01:00
float texR = float ( row ) ;
float texC =
dot ( vec3 ( col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec3 ( $ { s } , $ { n } , 1 ) ) ;
2020-12-02 22:46:41 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { m } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;if(m===n&&u==null)return `
float $ { o } ( int row , int col , int depth , int depth2 ) {
2020-12-02 22:46:41 +01:00
float texR = dot ( vec3 ( row , col , depth ) ,
2021-01-12 16:01:34 +01:00
vec3 ( $ { e [ 1 ] * e [ 2 ] } , $ { e [ 2 ] } , 1 ) ) ;
2020-12-02 22:46:41 +01:00
float texC = float ( depth2 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { m } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let f=cc(t);return `
float $ { o } ( int row , int col , int depth , int depth2 ) {
2020-12-02 22:46:41 +01:00
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { a } + col * $ { s } +
depth * $ { n } + depth2 ;
vec2 uv = uvFromFlat ( $ { p } , $ { m } , index + $ { f } ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function wY(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[4],s=e[3]*n,a=e[2]*s,i=e[1]*a,{newShape:l,keptDims:u}=x.squeezeShape(e);if(l.length<e.length){let h=Gp(r,l),g=["row","col","depth","depth2","depth3"];return `
$ { Vp ( h ) }
float $ { o } ( int row , int col , int depth , int depth2 , int depth3 ) {
return $ { o } ( $ { Up ( g , u ) } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }if(r.shapeInfo.isUniform)return `
float $ { o } ( int row , int col , int depth , int depth2 , int depth3 ) {
2020-12-02 22:46:41 +01:00
float index = dot (
vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { i } , $ { a } , $ { s } , $ { n } ) ) +
2020-12-02 22:46:41 +01:00
depth3 ;
2021-01-12 16:01:34 +01:00
$ { Wp ( r ) }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let c=r.shapeInfo.flatOffset,p=r.shapeInfo.texShape,m=p[0],f=p[1];if(f===i&&c==null)return `
float $ { o } ( int row , int col , int depth , int depth2 , int depth3 ) {
2020-12-02 22:46:41 +01:00
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { a } , $ { s } , $ { n } , 1 ) ) ;
2020-12-02 22:46:41 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { f } . 0 , $ { m } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;if(f===n&&c==null)return `
float $ { o } ( int row , int col , int depth , int depth2 , int depth3 ) {
2020-12-02 22:46:41 +01:00
float texR = dot (
vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { e [ 1 ] * e [ 2 ] * e [ 3 ] } ,
$ { e [ 2 ] * e [ 3 ] } , $ { e [ 3 ] } , 1 ) ) ;
2020-12-02 22:46:41 +01:00
int texC = depth3 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { f } . 0 , $ { m } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let d=cc(t);return `
float $ { o } ( int row , int col , int depth , int depth2 , int depth3 ) {
2020-12-02 22:46:41 +01:00
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { i } + col * $ { a } + depth * $ { s } +
depth2 * $ { n } + depth3 + $ { d } ;
vec2 uv = uvFromFlat ( $ { m } , $ { f } , index ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function vY(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),{newShape:n,keptDims:s}=x.squeezeShape(e);if(n.length<e.length){let g=Gp(r,n),y=["row","col","depth","depth2","depth3","depth4"];return `
$ { Vp ( g ) }
float $ { o } ( int row , int col , int depth ,
2020-12-02 22:46:41 +01:00
int depth2 , int depth3 , int depth4 ) {
2021-01-12 16:01:34 +01:00
return $ { o } ( $ { Up ( y , s ) } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }let a=e[5],i=e[4]*a,l=e[3]*i,u=e[2]*l,c=e[1]*u;if(r.shapeInfo.isUniform)return `
float $ { o } ( int row , int col , int depth ,
2020-12-02 22:46:41 +01:00
int depth2 , int depth3 , int depth4 ) {
int index = round ( dot (
vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { c } , $ { u } , $ { l } , $ { i } ) ) +
2020-12-02 22:46:41 +01:00
dot (
vec2 ( depth3 , depth4 ) ,
2021-01-12 16:01:34 +01:00
vec2 ( $ { a } , 1 ) ) ) ;
$ { Wp ( r ) }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let p=r.shapeInfo.flatOffset,m=r.shapeInfo.texShape,f=m[0],d=m[1];if(d===c&&p==null)return `
float $ { o } ( int row , int col , int depth ,
2020-12-02 22:46:41 +01:00
int depth2 , int depth3 , int depth4 ) {
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { u } , $ { l } , $ { i } , $ { a } ) ) +
2020-12-02 22:46:41 +01:00
float ( depth4 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { d } . 0 , $ { f } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;if(d===a&&p==null)return `
float $ { o } ( int row , int col , int depth ,
2020-12-02 22:46:41 +01:00
int depth2 , int depth3 , int depth4 ) {
float texR = dot ( vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { e [ 1 ] * e [ 2 ] * e [ 3 ] * e [ 4 ] } ,
$ { e [ 2 ] * e [ 3 ] * e [ 4 ] } ,
$ { e [ 3 ] * e [ 4 ] } ,
$ { e [ 4 ] } ) ) + float ( depth3 ) ;
2020-12-02 22:46:41 +01:00
int texC = depth4 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { d } . 0 , $ { f } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;let h=cc(t);return `
float $ { o } ( int row , int col , int depth ,
2020-12-02 22:46:41 +01:00
int depth2 , int depth3 , int depth4 ) {
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { c } + col * $ { u } + depth * $ { l } +
depth2 * $ { i } + depth3 * $ { a } + depth4 + $ { h } ;
vec2 uv = uvFromFlat ( $ { f } , $ { d } , index ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function Wp(r){let e=r.name,t=x.sizeFromShape(r.shapeInfo.logicalShape);return t<2? ` return $ { e } ; ` : `
for ( int i = 0 ; i < $ { t } ; i ++ ) {
2020-12-02 22:46:41 +01:00
if ( i == index ) {
2021-01-12 16:01:34 +01:00
return $ { e } [ i ] ;
2020-12-02 22:46:41 +01:00
}
}
2021-01-12 16:01:34 +01:00
` }function TY(r,e){let t=r.name,o=t.charAt(0).toUpperCase()+t.slice(1),n="get"+o+"AtOutCoords",s=r.shapeInfo.logicalShape.length,a=e.logicalShape.length,i=Q $ (r.shapeInfo.logicalShape,e.logicalShape),l=Be(a),u=a-s,c,p=["x","y","z","w","u","v"];s===0?c="":a<2&&i.length>=1?c="coords = 0;":c=i.map(b=> ` coords . $ { p [ b + u ] } = 0 ; ` ).join( `
` );let m="";a<2&&s>0?m="coords":m=r.shapeInfo.logicalShape.map((b,_)=> ` coords . $ { p [ _ + u ] } ` ).join(", ");let f="return outputValue;",h=x.sizeFromShape(r.shapeInfo.logicalShape)===1,y=x.sizeFromShape(e.logicalShape)===1;if(s===1&&!h&&!y)f= `
2020-12-02 22:46:41 +01:00
return vec4 ( outputValue . xy , outputValue . xy ) ;
2021-01-12 16:01:34 +01:00
` ;else if(h&&!y)a===1?f= `
2020-12-02 22:46:41 +01:00
return vec4 ( outputValue . x , outputValue . x , 0. , 0. ) ;
2021-01-12 16:01:34 +01:00
` :f= `
2020-12-02 22:46:41 +01:00
return vec4 ( outputValue . x ) ;
2021-01-12 16:01:34 +01:00
` ;else if(i.length){let b=s-2,_=s-1;i.indexOf(b)>-1&&i.indexOf(_)>-1?f="return vec4(outputValue.x);":i.indexOf(b)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(_)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return `
vec4 $ { n } ( ) {
$ { l } coords = getOutputCoords ( ) ;
$ { c }
vec4 outputValue = get$ { o } ( $ { m } ) ;
$ { f }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function EY(r,e){let t=r.name,o=t.charAt(0).toUpperCase()+t.slice(1),n="get"+o+"AtOutCoords",s=e.texShape,a=r.shapeInfo.texShape,i=r.shapeInfo.logicalShape.length,l=e.logicalShape.length;if(!r.shapeInfo.isUniform&&i===l&&r.shapeInfo.flatOffset==null&&x.arraysEqual(a,s))return `
float $ { n } ( ) {
return sampleTexture ( $ { t } , resultUV ) ;
}
` ;let u=Be(l),c=Q $ (r.shapeInfo.logicalShape,e.logicalShape),p=l-i,m,f=["x","y","z","w","u","v"];i===0?m="":l<2&&c.length>=1?m="coords = 0;":m=c.map(h=> ` coords . $ { f [ h + p ] } = 0 ; ` ).join( `
` );let d="";return l<2&&i>0?d="coords":d=r.shapeInfo.logicalShape.map((h,g)=> ` coords . $ { f [ g + p ] } ` ).join(", "), `
float $ { n } ( ) {
$ { u } coords = getOutputCoords ( ) ;
$ { m }
return get$ { o } ( $ { d } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }function Be(r){if(r<=1)return"int";if(r===2)return"ivec2";if(r===3)return"ivec3";if(r===4)return"ivec4";if(r===5)return"ivec5";if(r===6)return"ivec6";throw Error( ` GPU for rank $ { r } is not yet supported ` )}function Gp(r,e){let t=JSON.parse(JSON.stringify(r));return t.shapeInfo.logicalShape=e,t}function Up(r,e){return e.map(t=>r[t]).join(", ")}function oR(r,e,t,o){let n=e.userCode,s=t.map((f,d)=>{let h={logicalShape:f.shape,texShape:f.isUniform?null:f.texData.texShape,isUniform:f.isUniform,isPacked:f.isUniform?!1:f.texData.isPacked,flatOffset:null};return f.texData!=null&&f.texData.slice!=null&&f.texData.slice.flatOffset>0&&(h.flatOffset=f.texData.slice.flatOffset),{name:e.variableNames[d],shapeInfo:h}}),a=s.map(f=>f.shapeInfo),i={logicalShape:o.shape,texShape:o.texData.texShape,isUniform:!1,isPacked:o.texData.isPacked,flatOffset:null},l=eR(s,i,n,e.packedInputs),u=r.createProgram(l),c=null,p=r.getUniformLocation(u,"NAN",!1);W().getNumber("WEBGL_VERSION")===1&&(c=r.getUniformLocation(u,"INFINITY",!1));let m={};for(let f=0;f<e.variableNames.length;f++){let d=e.variableNames[f],h=!1;m[d]=r.getUniformLocation(u,d,h),m[ ` offset$ { d } ` ]=r.getUniformLocation(u, ` offset$ { d } ` ,h)}return{program:e,source:l,webGLProgram:u,uniformLocations:m,inShapeInfos:a,outShapeInfo:i,infLoc:c,nanLoc:p}}function nR(r,e){if(r.length!==e.length)throw Error( ` Binary was compiled with $ { r . length } inputs , but was executed with $ { e . length } inputs ` );r.forEach((t,o)=>{let n=t.logicalShape,s=e[o],a=s.shape;if(!x.arraysEqual(n,a))throw Error( ` Binary was compiled with different shapes than the current args . Shapes $ { n } and $ { a } must match ` );if(t.isUniform&&s.isUniform)return;let i=t.texShape,l=s.isUniform?null:s.texData.texShape;if(!x.arraysEqual(i,l))throw Error( ` Binary was compiled with different texture shapes than the current args . Shape $ { i } and $ { l } must match ` )})}function sR(r,e,t,o,n){nR(e.inShapeInfos,t),nR([e.outShapeInfo],[o]);let s=o.texData.texture,a=o.texData.texShape;o.texData.isPacked?r.setOutputPackedMatrixTexture(s,a[0],a[1]):r.setOutputMatrixTexture(s,a[0],a[1]),r.setProgram(e.webGLProgram),W().getNumber("WEBGL_VERSION")===1&&e.infLoc!==null&&r.gl.uniform1f(e.infLoc,Infinity),e.nanLoc!==null&&r.gl.uniform1f(e.nanLoc,NaN),t.forEach((i,l)=>{let u=e.program.variableNames[l],c=e.uniformLocations[u],p=e.uniformLocations[ ` offset$ { u } ` ];if(c!=null){if(i.isUniform){if(x.sizeFromShape(i.shape)<2)r.gl.uniform1f(c,i.uniformValues[0]);else{let m=i.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),r.gl.uniform1fv(c,m)}return}i.texData.slice!=null&&p!=null&&r.gl.uniform1i(p,i.texData.slice.flatOffset),r.setInputMatrixTexture(i.texData.texture,c,l)}}),n!=null&&n(r,e.webGLProgram),r.executeProgram()}function iR(r,e,t){let o="";e.concat(t).forEach(a=>{let i=a.texData!=null&&a.texData.slice!=null&&a.texData.slice.flatOffset>0,l=a.isUniform?"uniform":a.texData.texShape;o+= ` $ { a . shape } _$ { l } _$ { i } ` });let n=r.userCode,s=r.constructor.name;return s+="_"+o+"_"+n,s}var{addImpl:aR,bincountImpl: $ x,bincountReduceImpl:lR,ceilImpl:uR,concatImpl:cR,expImpl:pR,expm1Impl:mR,floorImpl:fR,gatherV2Impl:dR,greaterImpl:hR,lessImpl:gR,linSpaceImpl:xR,logImpl:yR,maxImpl:bR,maximumImpl:_R,minimumImpl:wR,multiplyImpl:vR,negImpl:kR,prodImpl:CR,rangeImpl:IR,rsqrtImpl:NR,simpleAbsImpl:Rx,sliceImpl:SR,stridedSliceImpl:TR,subImpl:ER,tileImpl:AR,topKImpl:DR,transposeImpl:jp,uniqueImpl: $ R}=rk;function Ok(r,e){return["x","y","z","w","u","v"].slice(0,e).map(t=> ` $ { r } . $ { t } ` )}function qt(r,e){return e===1?[r]:Ok(r,e)}function RR(r,e){if(r===1)return"rc";let t="";for(let o=0;o<r;o++)t+=e[o],o<r-1&&(t+=",");return t}var Pk=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;let t=e.length;if(t===0)this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
setOutput ( vec4 ( getA ( ) , 0. , 0. , 0. ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;else{let o=qt("rc",t),n=Be(t),s=GY(t,e,o),a=UY(t,e[e.length-1],e[e.length-2],o),i=jY(e,o);this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { n } rc = getOutputCoords ( ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( $ { s } ) {
2020-12-15 14:15:43 +01:00
setOutput ( vec4 ( 0 ) ) ;
} else {
2021-01-12 16:01:34 +01:00
$ { a }
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
setOutput ( vec4 ( $ { i } ) ) ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }}};function qY(r,e){let t=[];for(let o=0;o<=1;o++)for(let n=0;n<=1;n++){let s= ` $ { o === 0 ? "r" : "rp1" } , $ { n === 0 ? "c" : "cp1" } ` ;for(let a=2;a<r;a++)s= ` $ { e [ e . length - 1 - a ] } , ` +s;t.push(s)}return t}function GY(r,e,t){if(r===1)return ` rc > $ { e [ 0 ] } ` ;let o="";for(let n=r-2;n<r;n++)o+= ` $ { t [ n ] } >= $ { e [ n ] } ` ,n<r-1&&(o+="||");return o}function UY(r,e,t,o){if(r===1)return"";let n=o.slice(-2);return `
int r = $ { n [ 0 ] } ;
int c = $ { n [ 1 ] } ;
2020-12-15 14:15:43 +01:00
int rp1 = r + 1 ;
int cp1 = c + 1 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
bool cEdge = cp1 >= $ { e } ;
bool rEdge = rp1 >= $ { t } ;
` }function jY(r,e){let t=r.length,o=qY(t,e);return t===1? ` getA ( rc ) ,
rc + 1 >= $ { r [ 0 ] } ? 0. : getA ( rc + 1 ) ,
0 , 0 ` : ` getA ( $ { o [ 0 ] } ) ,
cEdge ? 0. : getA ( $ { o [ 1 ] } ) ,
rEdge ? 0. : getA ( $ { o [ 2 ] } ) ,
rEdge || cEdge ? 0. : getA ( $ { o [ 3 ] } ) ` }var th=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let o="";for(let n=0;n<4;n++){let s="thisRC = rc;";n%2==1&&(s+="thisRC.z += 1;"),n>1&&(s+="thisRC.y += 1;"),o+= `
$ { s }
$ { n > 0 ? "if(thisRC.y < rows && thisRC.z < cols){" : "" }
2020-12-15 14:15:43 +01:00
int flatIndex = getFlatIndex ( thisRC ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
ivec3 inputRC = inputCoordsFromReshapedOutCoords ( flatIndex ) ;
vec2 inputRCInnerDims = vec2 ( float ( inputRC . y ) , float ( inputRC . z ) ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
result [ $ { n } ] =
2020-12-15 14:15:43 +01:00
getChannel ( getA ( inputRC . x , inputRC . y , inputRC . z ) , inputRCInnerDims ) ;
2021-01-12 16:01:34 +01:00
$ { n > 0 ? "}" : "" }
2020-12-15 14:15:43 +01:00
` }this.userCode= `
2021-01-12 16:01:34 +01:00
$ { HY ( t ) }
$ { Bp ( e ) }
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
ivec3 thisRC ;
2021-01-12 16:01:34 +01:00
int rows = $ { e [ 1 ] } ;
int cols = $ { e [ 2 ] } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
$ { o }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function HY(r){return `
2020-12-15 14:15:43 +01:00
ivec3 inputCoordsFromReshapedOutCoords ( int index ) {
2021-01-12 16:01:34 +01:00
$ { Ls ( [ "r" , "c" , "d" ] , r ) }
2020-12-15 14:15:43 +01:00
return ivec3 ( r , c , d ) ;
}
2021-01-12 16:01:34 +01:00
` }var Mk=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,o){let n=OR(t,o),s=PR(e,n,o);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=FR(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,o);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let l=this.freeTextures[s].shift();return this.usedTextures[s].push(l),l}let i;return n===wr.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===wr.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===wr.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===wr.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===wr.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,o,n){if(this.freeTextures==null)return;let s=OR(o,n),a=PR(t,s,n);a in this.freeTextures||(this.freeTextures[a]=[]);let i=FR(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,n),l=W().get("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let u=this.usedTextures[a],c=u.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(c,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)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function KY(r,e){let t=r;if(e===t.R32F)return 4;if(e===t.R16F)return 2;if(e===t.RGBA32F)return 16;if(e===r.RGBA)return 16;if(e===t.RGBA16F)return 8;throw new Error( ` Unknown internal format $ { e } ` )}function FR(r,e,t,o,n){let s=XY(e,o),a;if(n){let[l,u]=Ki(r[0],r[1]);a=l*u}else{let[l,u]=lc(r[0],r[1]);a=l*u}let i=KY(t,s);return a*i}function XY(r,e){switch(r){case wr.PACKED_2X2_FLOAT32:return $ k(e);case wr.PACKED_2X2_FLOAT16:return Rk(e);case wr.UNPACKED_FLOAT32:return Ek(e);case wr.UNPACKED_FLOAT16:return Ak(e);case wr.PACKED_4X1_UNSIGNED_BYTE:return Dk(e);default:throw new Error( ` Unknown physical texture type $ { r } ` )}}function YY(r){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?wr.PACKED_2X2_FLOAT32:wr.UNPACKED_FLOAT32:r?wr.PACKED_2X2_FLOAT16:wr.UNPACKED_FLOAT16}function OR(r,e){if(r===Dr.UPLOAD)return wr.PACKED_2X2_FLOAT32;if(r===Dr.RENDER||r==null)return YY(e);if(r===Dr.DOWNLOAD||r===Dr.PIXELS)return wr.PACKED_4X1_UNSIGNED_BYTE;throw new Error( ` Unknown logical texture type $ { r } ` )}function PR(r,e,t){return ` $ { r [ 0 ] } _$ { r [ 1 ] } _$ { e } _$ { t } ` }var mo=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
float unaryOperation ( float x ) {
2021-01-12 16:01:34 +01:00
$ { t }
2020-12-02 22:46:41 +01:00
}
void main ( ) {
2020-12-15 14:15:43 +01:00
float x = getAAtOutCoords ( ) ;
float y = unaryOperation ( x ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
setOutput ( y ) ;
}
2021-01-12 16:01:34 +01:00
` }},xr="if (isnan(x)) return x;",MR="return x;",Lk="return abs(x);";var LR="return (x >= 0.0) ? x : (exp(x) - 1.0);",zR=xr+ `
2020-12-15 14:15:43 +01:00
return ( x < 0.0 ) ? 0.0 : x ;
2021-01-12 16:01:34 +01:00
` ,BR=xr+ `
2020-12-15 14:15:43 +01:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2021-01-12 16:01:34 +01:00
` ,rh="return x;";var VR="return x;",WR= `
2020-12-15 14:15:43 +01:00
vec4 result ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
result . r = ( x . r >= 0.0 ) ? x . r : ( exp ( x . r ) - 1.0 ) ;
result . g = ( x . g >= 0.0 ) ? x . g : ( exp ( x . g ) - 1.0 ) ;
result . b = ( x . b >= 0.0 ) ? x . b : ( exp ( x . b ) - 1.0 ) ;
result . a = ( x . a >= 0.0 ) ? x . a : ( exp ( x . a ) - 1.0 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,GR= `
2020-12-15 14:15:43 +01:00
vec4 result = x * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,UR= `
2020-12-15 14:15:43 +01:00
vec4 result = min ( x , vec4 ( 6. ) ) * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,zs=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
vec4 unaryOperation ( vec4 x ) {
2021-01-12 16:01:34 +01:00
$ { t }
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
vec4 x = getAAtOutCoords ( ) ;
vec4 y = unaryOperation ( x ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
setOutput ( y ) ;
}
2021-01-12 16:01:34 +01:00
` }};var zk=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,o=qt("rc",t),n=Be(t),s=RR(t,o),a=o.slice(-2),i=t<=1?"rc": ` vec2 ( $ { a . join ( "," ) } ) ` ;this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { n } rc = getOutputCoords ( ) ;
vec4 packedInput = getA ( $ { s } ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
setOutput ( getChannel ( packedInput , $ { i } ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var ZY=Er.whereImpl,JY=1e-7,QY=1e-4,Fx={};function e7(r){return r in Fx||(Fx[r]={}),Fx[r]}var t7=128,r7=600;function o7(){return W().global.screen==null?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*r7/1024/1024}var Bk=class extends Ws{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!W().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=Go(W().getNumber("WEBGL_VERSION"));this.binaryCache=e7(W().getNumber("WEBGL_VERSION")),this.gpgpu=new Fk(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new Mk(this.gpgpu),this.numMBBeforeWarning=o7(),this.texData=new Ja(this,Cs())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,o){if((W().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||W().getBool("DEBUG"))&&this.checkNumericalProblems(e),o==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let n={};return this.texData.set(n,{shape:t,dtype:o,values:e,usage:Dr.UPLOAD,refCount:1,complexParentRefCount:0}),n}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,o,n){if(W().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:o,dtype:n,values:t,usage:Dr.UPLOAD,refCount:1,complexParentRefCount:0})}disposeIntermediateTensorInfo(e){let t=e.dataId;if(this.texData.has(t)){let o=this.texData.get(t);o.refCount--,o.refCount<1&&this.disposeData(t)}}readSync(e){let t=this.texData.get(e),{values:o,dtype:n,complexTensorInfos:s,slice:a,shape:i,isPacked:l}=t;if(a!=null){let m;l?m=new zs(i,rh):m=new mo(i,rh);let f=this.runWebGLProgram(m,[{dataId:e,shape:i,dtype:n}],n),d=this.readSync(f.dataId);return this.disposeIntermediateTensorInfo(f),d}if(o!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return o;let u=this.activeTimers!=null,c;u&&(c=x.now());let p;if(n==="complex64"){let m=this.readSync(s.real.dataId),f=this.readSync(s.imag.dataId);p=S.mergeRealAndImagArrays(m,f)}else p=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=x.now()-c),this.convertAndCacheOnCPU(e,p)}async read(e){if(this.pendingRead.has(e)){let d=this.pendingRead.get(e);return new Promise(h=>d.push(h))}let t=this.texData.get(e),{values:o,shape:n,slice:s,dtype:a,complexTensorInfos:i,isPacked:l}=t;if(s!=null){let d;l?d=new zs(n,rh):d=new mo(n,rh);let h=this.runWebGLProgram(d,[{dataId:e,shape:n,dtype:a}],a),g=this.read(h.dataId);return this.disposeIntermediateTensorInfo(h),g}if(o!=null)return this.convertAndCacheOnCPU(e);if(!W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&W().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,c;if(a!=="complex64"&&W().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let d=this.texData.get(c.dataId);u=this.gpgpu.createBufferFromTexture(d.texture,...Sl(n))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(a==="complex64"){let d=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),h=d[0],g=d[1];p=S.mergeRealAndImagArrays(h,g)}else if(u==null)p=this.getValuesFromTexture(e);else{let d=x.sizeFromShape(n);p=this.gpgpu.downloadFloat32MatrixFromBuffer(u,d)}c!=null&&this.disposeIntermediateTensorInfo(c);let m=this.convertAndCacheOnCPU(e,p),f=this.pendingRead.get(e);return this.pendingRead.delete(e),f.forEach(d=>d(m)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),m}bufferSync(e){let t
2020-12-02 22:46:41 +01:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2021-01-12 16:01:34 +01:00
` ;var ts=class{constructor(e,t,o){this.variableNames=["A","B"],this.outputShape=S.assertAndGetBroadcastShape(t,o),this.userCode= `
2020-12-02 22:46:41 +01:00
float binaryOperation ( float a , float b ) {
2021-01-12 16:01:34 +01:00
$ { e }
2020-12-02 22:46:41 +01:00
}
void main ( ) {
float a = getAAtOutCoords ( ) ;
float b = getBAtOutCoords ( ) ;
setOutput ( binaryOperation ( a , b ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};var Al= `
2020-12-02 22:46:41 +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 ;
2021-01-12 16:01:34 +01:00
` ;var Bs=class{constructor(e,t,o,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=S.assertAndGetBroadcastShape(t,o);let s=this.outputShape.length,a="";if(n)if(s===0||x.sizeFromShape(this.outputShape)===1)a= `
2020-12-02 22:46:41 +01:00
result . y = 0. ;
result . z = 0. ;
result . w = 0. ;
2021-01-12 16:01:34 +01:00
` ;else if(a= `
$ { Be ( s ) } coords = getOutputCoords ( ) ;
` ,s===1)a+= `
2020-12-02 22:46:41 +01:00
result . y = ( coords + 1 ) >= $ { this . outputShape [ 0 ] } ? 0. : result . y ;
result . z = 0. ;
result . w = 0. ;
2021-01-12 16:01:34 +01:00
` ;else{let l=qt("coords",s);a+= `
2020-12-02 22:46:41 +01:00
bool nextRowOutOfBounds =
2021-01-12 16:01:34 +01:00
( $ { l [ s - 2 ] } + 1 ) >= $ { this . outputShape [ s - 2 ] } ;
2020-12-02 22:46:41 +01:00
bool nextColOutOfBounds =
2021-01-12 16:01:34 +01:00
( $ { l [ s - 1 ] } + 1 ) >= $ { this . outputShape [ s - 1 ] } ;
2020-12-02 22:46:41 +01:00
result . y = nextColOutOfBounds ? 0. : result . y ;
result . z = nextRowOutOfBounds ? 0. : result . z ;
result . w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result . w ;
2021-01-03 17:05:09 +01:00
` }this.userCode= `
2020-12-02 22:46:41 +01:00
vec4 binaryOperation ( vec4 a , vec4 b ) {
2021-01-12 16:01:34 +01:00
$ { e }
2020-12-02 22:46:41 +01:00
}
void main ( ) {
vec4 a = getAAtOutCoords ( ) ;
vec4 b = getBAtOutCoords ( ) ;
vec4 result = binaryOperation ( a , b ) ;
2021-01-12 16:01:34 +01:00
$ { a }
2020-12-02 22:46:41 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function Ht(r){let{inputs:e,backend:t}=r,{x:o}=e;return t.incRef(o.dataId),{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}var qR={kernelName:cs,backendName:"webgl",kernelFunc:Ht};function fo(r){let{inputs:e,backend:t}=r,{real:o,imag:n}=e,s=t.makeTensorInfo(o.shape,"complex64"),a=t.texData.get(s.dataId),i=Ht({inputs:{x:o},backend:t}),l=t.texData.get(i.dataId);l.complexParentRefCount++;let u=Ht({inputs:{x:n},backend:t}),c=t.texData.get(u.dataId);return c.complexParentRefCount++,a.complexTensorInfos={real:i,imag:u},s}var HR={kernelName:Xl,backendName:"webgl",kernelFunc:fo};var Vk="return (a < 0.) ? b * a : a;",Wk= `
2020-12-15 14:15:43 +01:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2021-01-12 16:01:34 +01:00
` ;function s7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o,a=t.makeTensorInfo([],"float32",x.createScalarValue(s,"float32")),i=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bs(Wk,n.shape,a.shape):new ts(Vk,n.shape,a.shape),l=t.runWebGLProgram(i,[n,a],n.dtype);return t.disposeIntermediateTensorInfo(a),l}var KR={kernelName:un,backendName:"webgl",kernelFunc:s7};var Gk="return (a < 0.) ? b * a : a;",Uk= `
2020-12-15 14:15:43 +01:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2021-01-12 16:01:34 +01:00
` ;function i7(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bs(Uk,o.shape,n.shape):new ts(Gk,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)}var XR={kernelName:wn,backendName:"webgl",kernelFunc:i7};var Px="if (isnan(x)) return x;",YR= `
2020-12-15 14:15:43 +01:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2021-01-12 16:01:34 +01:00
` ,ZR= `
2020-12-15 14:15:43 +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 ;
2021-01-12 16:01:34 +01:00
` ;function Ce({opSnippet:r,packedOpSnippet:e,cpuKernelImpl:t,dtype:o}){return({inputs:n,backend:s})=>{let{x:a}=n,i=s,l=o||a.dtype;if(i.shouldExecuteOnCPU([a])&&t!=null){let p=i.texData.get(a.dataId),m=t(p.values,l);return i.makeTensorInfo(a.shape,l,m)}let u=W().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&e!=null,c;return u?c=new zs(a.shape,e):c=new mo(a.shape,r),i.runWebGLProgram(c,[a],l)}}function at({opSnippet:r,packedOpSnippet:e,checkOutOfBounds:t=!1,supportsComplex:o=!1,cpuKernelImpl:n,dtype:s}){return({inputs:a,backend:i})=>{let{a:l,b:u}=a,c=i;if(o&&l.dtype==="complex64"){let d=c.texData.get(l.dataId),h=c.texData.get(u.dataId),[g,y]=[[d.complexTensorInfos.real,h.complexTensorInfos.real],[d.complexTensorInfos.imag,h.complexTensorInfos.imag]].map(_=>{let[w,k]=_, $ ={dataId:w.dataId,dtype:w.dtype,shape:l.shape},T={dataId:k.dataId,dtype:k.dtype,shape:u.shape},F=new ts(r,l.shape,u.shape);return c.runWebGLProgram(F,[ $ ,T],fr(w.dtype,k.dtype))}),b=fo({inputs:{real:g,imag:y},backend:c});return c.disposeIntermediateTensorInfo(g),c.disposeIntermediateTensorInfo(y),b}let p=s||fr(l.dtype,u.dtype);if(c.shouldExecuteOnCPU([l,u])&&n!=null){let d=c.texData.get(l.dataId),h=c.texData.get(u.dataId),[g,y]=n(l.shape,u.shape,d.values,h.values,p),b=c.makeTensorInfo(y,p),_=c.texData.get(b.dataId);return _.values=g,b}let m=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null,f;return m?f=new Bs(e,l.shape,u.shape,t):f=new ts(r,l.shape,u.shape),c.runWebGLProgram(f,[l,u],p)}}function Dl(r,e=!1){if(r==="linear")return e?VR:MR;if(r==="relu")return e?GR:zR;if(r==="elu")return e?WR:LR;if(r==="relu6")return e?UR:BR;if(r==="prelu")return e?Uk:Gk;if(r==="leakyrelu")return e?Wk:Vk;throw new Error( ` Activation $ { r } has not been implemented for the WebGL backend . ` )}var oh=class{constructor(e,t,o,n=!1,s=!1,a=!1,i=null,l=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=o;let c=n?e[1]:e[2],p=Math.ceil(c/2),m=n?"i * 2, rc.y":"rc.y, i * 2",f=s?"rc.z, i * 2":"i * 2, rc.z",d=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],g="",y="";i&&(l?g= ` vec4 activation ( vec4 a ) {
2020-12-15 14:15:43 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { i }
} ` :u?g= ` vec4 activation ( vec4 a ) {
2020-12-15 14:15:43 +01:00
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { i }
} ` :g= ` vec4 activation ( vec4 x ) {
$ { i }
} ` ,y="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let _="rc.x",w="rc.x";e[0]<t[0]?_= ` int ( min ( float ( rc . x ) , $ { e [ 0 ] - 1 } . ) ) ` :t[0]<e[0]&&(w= ` int ( min ( float ( rc . x ) , $ { t [ 0 ] - 1 } . ) ) ` ),this.userCode= `
$ { g }
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
const float sharedDimension = $ { p } . 0 ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
vec4 dot2x2ARowBCol ( ivec3 rc ) {
vec4 result = vec4 ( 0 ) ;
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { p } ; i ++ ) {
int batchA = $ { _ } ;
int batchB = $ { w } ;
vec4 a = getMatrixA ( batchA , $ { m } ) ;
vec4 b = getMatrixB ( batchB , $ { f } ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
2021-01-12 16:01:34 +01:00
result += ( $ { d [ 0 ] } * $ { h [ 0 ] } ) ;
result += ( $ { d [ 1 ] } * $ { h [ 1 ] } ) ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
return result ;
2020-12-02 22:46:41 +01:00
}
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec3 rc = getOutputCoords ( ) ;
vec4 result = dot2x2ARowBCol ( rc ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { b }
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { y }
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};var jk={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},Mx=class{constructor(e,t,o){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=S.assertAndGetBroadcastShape(t,o),this.userCode= `
2020-12-15 14:15:43 +01:00
float binaryOpComplex (
float areal , float aimag , float breal , float bimag ) {
2021-01-12 16:01:34 +01:00
$ { e }
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
float areal = getARealAtOutCoords ( ) ;
float aimag = getAImagAtOutCoords ( ) ;
float breal = getBRealAtOutCoords ( ) ;
float bimag = getBImagAtOutCoords ( ) ;
setOutput ( binaryOpComplex ( areal , aimag , breal , bimag ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};var JR="return a * b;";function qk(r){let{inputs:e,backend:t}=r,{a:o,b:n}=e,s=S.upcastType(o.dtype,n.dtype);if(o.dtype==="complex64"){let i=t.texData.get(o.dataId),l=t.texData.get(n.dataId),u=new Mx(jk.REAL,o.shape,n.shape),c=new Mx(jk.IMAG,o.shape,n.shape),p=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:o.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:n.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:n.shape}],m=t.runWebGLProgram(u,p,"float32"),f=t.runWebGLProgram(c,p,"float32"),d=fo({inputs:{real:m,imag:f},backend:t});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}if(t.shouldExecuteOnCPU([o,n])){let i=t.texData.get(o.dataId),l=t.texData.get(n.dataId),[u,c]=vR(o.shape,n.shape,i.values,l.values,s),p=t.makeTensorInfo(c,s),m=t.texData.get(p.dataId);return m.values=u,p}let a;return W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new Bs(JR,o.shape,n.shape):a=new ts(JR,o.shape,n.shape),t.runWebGLProgram(a,[o,n],s)}var QR={kernelName:xn,backendName:"webgl",kernelFunc:qk};function eF(r,e,t){let o=[Tl(r.shape),...El(r.shape)],n={dtype:r.dtype,shape:o,dataId:r.dataId},s=[Tl(e),...El(e)],a=new th(s,o),i=!0,l=t.runWebGLProgram(a,[n],r.dtype,null,i);return{dataId:l.dataId,shape:e,dtype:l.dtype}}function me(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{shape:s}=o,a=t,i=x.sizeFromShape(n.shape),l=x.inferFromImplicitShape(s,i),u=x.sizeFromShape(l);x.assert(i===u,()=> ` The new shape ( $ { l } ) has $ { u } elements and the old shape ( $ { n . shape } ) has $ { i } elements . The new shape and old shape must have the same number of elements . ` );let c=a.texData.get(n.dataId);return c.isPacked&&!uc(n.shape,l)&&!(c.texture!==null&&uc(c.shape,l))?eF(n,l,a):(a.incRef(n.dataId),{dataId:n.dataId,shape:l,dtype:n.dtype})}var tF={kernelName:ds,backendName:"webgl",kernelFunc:me};var Lx=class{constructor(e,t){this.variableNames=["x"];let{windowSize:o,batchSize:n,inSize:s,outSize:a}=e;this.outputShape=[n,a];let i=Math.floor(o/4)*4,l=o%4,u="sumValue += dot(values, ones);";if(t!=null){let p=1/t;u= ` sumValue += dot ( values * $ { x . isInt ( p ) ? p . toPrecision ( 2 ) : p } , ones ) ; ` }let c="";s%o>0&&(c= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
2020-12-15 14:15:43 +01:00
return 0.0 ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
` ),this.userCode= `
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float getValue ( int batch , int inIdx ) {
2021-01-12 16:01:34 +01:00
$ { c }
2020-12-15 14:15:43 +01:00
return getX ( batch , inIdx ) ;
2020-12-02 22:46:41 +01:00
}
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec2 coords = getOutputCoords ( ) ;
2020-12-02 22:46:41 +01:00
int batch = coords [ 0 ] ;
2020-12-15 14:15:43 +01:00
int outIdx = coords [ 1 ] ;
2021-01-12 16:01:34 +01:00
int inOffset = outIdx * $ { o } ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float sumValue = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { i } ; i += 4 ) {
2020-12-15 14:15:43 +01:00
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { u }
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int inIdx = inOffset + $ { i } ;
if ( $ { l === 1 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 ( getValue ( batch , inIdx ) , 0.0 , 0.0 , 0.0 ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { u }
} else if ( $ { l === 2 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) , 0.0 , 0.0 ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { u }
} else if ( $ { l === 3 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) , 0.0 ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { u }
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
setOutput ( sumValue ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var Hk=class{constructor(e,t){this.variableNames=["x"];let{windowSize:o,batchSize:n,inSize:s,outSize:a}=e;this.outputShape=[n,a];let i="0.0",l="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",l="min"):t==="max"&&(i="-1.0 / 1e-20",l="max");let u= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="sum"?u="sumValue":t==="prod"?u="prodValue":t==="all"?u="allValue":t==="any"&&(u="anyValue");let c=Math.floor(o/4)*4,p=o%4,m= `
if ( $ { t === "sum" } ) {
2020-12-15 14:15:43 +01:00
sumValue += dot ( values , ones ) ;
2021-01-12 16:01:34 +01:00
} else if ( $ { t === "prod" } ) {
2020-12-15 14:15:43 +01:00
vec2 tmp = vec2 ( values [ 0 ] , values [ 1 ] ) * vec2 ( values [ 2 ] , values [ 3 ] ) ;
prodValue *= tmp [ 0 ] * tmp [ 1 ] ;
} else {
2021-01-12 16:01:34 +01:00
minMaxValue = $ { l } ( values , minMaxValue ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ,f="vec4";t==="all"?(i="1.0",m= `
2020-12-15 14:15:43 +01:00
bool reducedAllValue = all ( values ) ;
float floatedReducedAllValue = float ( reducedAllValue ) ;
allValue = float ( allValue >= 1.0 && floatedReducedAllValue >= 1.0 ) ;
2021-01-12 16:01:34 +01:00
` ,f="bvec4"):t==="any"&&(i="0.0",m= `
2020-12-15 14:15:43 +01:00
bool reducedAnyValue = any ( values ) ;
float floatedReducedAnyValue = float ( reducedAnyValue ) ;
anyValue = float ( anyValue >= 1.0 || floatedReducedAnyValue >= 1.0 ) ;
2021-01-12 16:01:34 +01:00
` ,f="bvec4");let d="";s%o>0&&(d= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
2020-12-15 14:15:43 +01:00
return initializationValue ;
}
` ),this.userCode= `
2021-01-12 16:01:34 +01:00
const float initializationValue = $ { i } ;
2020-12-15 14:15:43 +01:00
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float getValue ( int batch , int inIdx ) {
2021-01-12 16:01:34 +01:00
$ { d }
2020-12-15 14:15:43 +01:00
return getX ( batch , inIdx ) ;
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
2021-01-12 16:01:34 +01:00
int inOffset = outIdx * $ { o } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
vec4 minMaxValue = vec4 ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
float prodValue = 1.0 ;
float sumValue = 0.0 ;
float allValue = 1.0 ;
float anyValue = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { c } ; i += 4 ) {
2020-12-15 14:15:43 +01:00
int inIdx = inOffset + i ;
2021-01-12 16:01:34 +01:00
$ { f } values = $ { f } (
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { m }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
int inIdx = inOffset + $ { c } ;
if ( $ { p === 1 } ) {
$ { f } values = $ { f } (
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { m }
} else if ( $ { p === 2 } ) {
$ { f } values = $ { f } (
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { m }
} else if ( $ { p === 3 } ) {
$ { f } values = $ { f } (
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { m }
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
setOutput ( $ { u } ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function a7(r){let e=[];for(;e.length===0||e[e.length-1].outSize!==1;){let t=e.length?e[e.length-1].outSize:r[1],o=S.computeOptimalWindowSize(t);e.push({inSize:t,windowSize:o,outSize:Math.ceil(t/o)})}return e}function So(r,e,t,o){let n=a7(r.shape),s=r;for(let a=0;a<n.length;a++){let{inSize:i,windowSize:l,outSize:u}=n[a],c,p;t==="mean"?c=a===0?new Lx({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u},i):new Lx({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u}):c=new Hk({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u},t),p=s,s=o.runWebGLProgram(c,[s],e),p.dataId!==r.dataId&&o.disposeIntermediateTensorInfo(p)}return s}var Kk=class{constructor(e,t){this.variableNames=["A"];let o=new Array(e.length);for(let a=0;a<o.length;a++)o[a]=e[t[a]];this.outputShape=o,this.rank=o.length;let n=Be(this.rank),s=l7(t);this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { n } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { s } ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function l7(r){let e=r.length;if(e>6)throw Error( ` Transpose for rank $ { e } is not yet supported ` );let t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],o=new Array(e);for(let n=0;n<r.length;n++)o[r[n]]=t[n];return o.join()}var Xk=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let o=new Array(e.length);for(let c=0;c<o.length;c++)o[c]=e[t[c]];if(this.outputShape=o,this.rank=o.length,this.rank>6)throw Error( ` Packed transpose for rank $ { this . rank } is not yet supported . ` );let n=Be(this.rank),s=Ok("rc",this.rank),a=new Array(this.rank);for(let c=0;c<t.length;c++)a[t[c]]=s[c];let i= ` vec2 ( $ { a . slice ( - 2 ) . join ( ) } ) ` ,l= ` ++ $ { s [ this . rank - 1 ] } < $ { o [ this . rank - 1 ] } ` ,u= ` getChannel ( getA ( $ { a . join ( ) } ) , $ { i } ) ` ;this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { n } rc = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
result [ 0 ] = $ { u } ;
if ( $ { l } ) {
result [ 1 ] = $ { u } ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
-- $ { s [ this . rank - 1 ] } ;
if ( ++ $ { s [ this . rank - 2 ] } < $ { o [ this . rank - 2 ] } ) {
result [ 2 ] = $ { u } ;
if ( $ { l } ) {
result [ 3 ] = $ { u } ;
2020-12-15 14:15:43 +01:00
}
}
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function $ l(r,e,t){let o=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Xk(r.shape,e):new Kk(r.shape,e);return t.runWebGLProgram(o,[r],r.dtype)}function rF(r,e,t,o){let n=e,s=r.shape.length,a=x.parseAxisParam(n,r.shape),i=a,l=S.getAxesPermutation(i,s),u=l!=null,c=r;u&&(c= $ l(r,l,o),i=S.getInnerMostAxes(i.length,s)),S.assertAxesAreInnerMostDims("sum",i,s);let[p,m]=S.computeOutAndReduceShapes(c.shape,i),f=p;t&&(f=S.expandShapeToKeepDim(p,a));let d=x.sizeFromShape(m),g=x.sizeFromShape(r.shape)/d,y=me({inputs:{x:c},attrs:{shape:[g,d]},backend:o}),b=yu(r.dtype),_=So(y,b,"sum",o),w=me({inputs:{x:_},attrs:{shape:f},backend:o});return o.disposeIntermediateTensorInfo(y),o.disposeIntermediateTensorInfo(_),u&&o.disposeIntermediateTensorInfo(c),w}function nh(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;return rF(n,s,a,t)}var oF={kernelName:Dn,backendName:"webgl",kernelFunc:nh};function Bt(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{perm:s}=o,a=t,i=n.shape.length,l=new Array(i);for(let c=0;c<l.length;c++)l[c]=n.shape[s[c]];let u;if(a.shouldExecuteOnCPU([n])){let p=a.texData.get(n.dataId).values,m=jp(p,n.shape,n.dtype,s,l);u=a.makeTensorInfo(l,n.dtype);let f=a.texData.get(u.dataId);f.values=m}else u= $ l(n,s,a);return u}var nF={kernelName:Pn,backendName:"webgl",kernelFunc:Bt};var Yk=1e3;function pc({a:r,b:e,transposeA:t,transposeB:o,backend:n,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:l=null}){let u=r.shape.length,c=e.shape.length,p=t?r.shape[u-2]:r.shape[u-1],m=o?e.shape[c-1]:e.shape[c-2],f=t?r.shape[u-1]:r.shape[u-2],d=o?e.shape[c-2]:e.shape[c-1],h=r.shape.slice(0,-2),g=e.shape.slice(0,-2),y=x.sizeFromShape(h),b=x.sizeFromShape(g),_=y===b||y===1||b===1;x.assert(u>=2&&c>=2&&_,()=> ` Error in matMul : the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of ( $ { h } ) and ( $ { g } ) . ` );let k=(y>b?r.shape.slice(0,-2):e.shape.slice(0,-2)).concat([f,d]);x.assert(p===m,()=> ` Error in matMul : inner shapes ( $ { p } ) and ( $ { m } ) of Tensors with shapes $ { r . shape } and $ { e . shape } and transposeA = $ { t } and transposeB = $ { o } must match . ` );let $ =t?[y,p,f]:[y,f,p],T=o?[b,d,m]:[b,m,d],F=me({inputs:{x:r},backend:n,attrs:{shape: $ }}),M=me({inputs:{x:e},backend:n,attrs:{shape:T}}),L=[F,M],G=Math.max(y,b),H=t?F.shape[1]:F.shape[2],U=s!=null,Z=a!=null,K=l==="leakyrelu",X=l!=null?Dl(l,!0):null,oe=U||Z||K||X!=null,J;if((f===1||d===1)&&H>Yk&&oe===!1){let ie=F,ae=M;t&&(ie=Bt({inputs:{x:F},backend:n,attrs:{perm:[0,2,1]}}),L.push(ie)),o&&(ae=Bt({inputs:{x:M},backend:n,attrs:{perm:[0,2,1]}}),L.push(ae));let ue=d!==1,le=d===1,ge=ie;ue&&(ge=me({inputs:{x:ie},backend:n,attrs:{shape:[G,H,1]}}),L.push(ge));let we=d===1?2:1,ye=ae;le&&(ye=me({inputs:{x:ae},backend:n,attrs:{shape:[G,1,H]}}),L.push(ye));let ke=qk({inputs:{a:ge,b:ye},backend:n});J=nh({inputs:{x:ke},backend:n,attrs:{axis:we,keepDims:!0}}),L.push(ke)}else{let ie=fr(r.dtype,e.dtype),ae=new oh( $ ,T,[G,f,d],t,o,U,X,Z,K),ue=[F,M];if(s!=null&&ue.push(s),Z&&ue.push(a),K){let le=n.makeTensorInfo([],"float32",x.createScalarValue(i,"float32"));ue.push(le),L.push(le)}J=n.runWebGLProgram(ae,ue,ie)}let Q=me({inputs:{x:J},backend:n,attrs:{shape:k}});L.push(J);for(let ie of L)n.disposeIntermediateTensorInfo(ie);return Q}function u7(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=o;return pc({a:n,b:s,transposeA:l,transposeB:u,backend:t,bias:a,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}var sF={kernelName:_s,backendName:"webgl",kernelFunc:u7};var iF="return abs(x);";function c7(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])&&o.dtype!=="complex64"){let s=t.texData.get(o.dataId),a=Rx(s.values);return t.makeTensorInfo(o.shape,o.dtype,a)}let n;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new zs(o.shape,iF):n=new mo(o.shape,iF),t.runWebGLProgram(n,[o],o.dtype)}var aF={kernelName:is,backendName:"webgl",kernelFunc:c7};var p7=xr+ `
2020-12-15 14:15:43 +01:00
if ( abs ( x ) > 1. ) {
return NAN ;
}
return acos ( x ) ;
2021-01-12 16:01:34 +01:00
` ,m7=Ce({opSnippet:p7}),lF={kernelName:js,backendName:"webgl",kernelFunc:m7};var f7=xr+ `
2020-12-15 14:15:43 +01:00
if ( x < 1.0 ) return NAN ;
2021-01-12 16:01:34 +01:00
return log ( x + sqrt ( x * x - 1.0 ) ) ; ` ,d7=Ce({opSnippet:f7}),uF={kernelName:qs,backendName:"webgl",kernelFunc:d7};var cF="return a + b;",h7=at({opSnippet:cF,packedOpSnippet:cF,supportsComplex:!0,cpuKernelImpl:aR}),pF={kernelName:bo,backendName:"webgl",kernelFunc:h7};var Zk=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=> ` T$ { a } ` );let o=[];this.variableNames.forEach(s=>{o.push( ` float v$ { s } = get$ { s } AtOutCoords ( ) ; ` )});let n=this.variableNames.map(s=> ` v$ { s } ` ).join(" + ");this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { o . join ( `
2020-12-15 14:15:43 +01:00
` )}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
float result = $ { n } ;
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};var Jk=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=> ` T$ { a } ` );let o=[];this.variableNames.forEach(s=>{o.push( ` vec4 v$ { s } = get$ { s } AtOutCoords ( ) ; ` )});let n=this.variableNames.map(s=> ` v$ { s } ` ).join(" + ");this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { o . join ( `
2020-12-15 14:15:43 +01:00
` )}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
vec4 result = $ { n } ;
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function zx(r){let{inputs:e,backend:t}=r,o=e;if(o.length===1)return Ht({inputs:{x:o[0]},backend:t});if(o.length>W().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(o.length/2),u=zx({inputs:o.slice(0,l),backend:t}),c=zx({inputs:o.slice(l),backend:t});return zx({inputs:[u,c],backend:t})}let n=o.map(l=>l.dtype).reduce((l,u)=>fr(l,u)),s=o.map(l=>l.shape),i=W().getBool("WEBGL_PACK")?new Jk(o[0].shape,s):new Zk(o[0].shape,s);return t.runWebGLProgram(i,o,n)}var mF={kernelName:Ho,backendName:"webgl",kernelFunc:zx};function g7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=x.parseAxisParam(s,n.shape),u=l,c=S.getAxesPermutation(u,i),p=n;c!=null&&(p=Bt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=S.getInnerMostAxes(u.length,i)),S.assertAxesAreInnerMostDims("all",u,i);let[m,f]=S.computeOutAndReduceShapes(p.shape,u),d=x.sizeFromShape(f),h=me({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=So(h,h.dtype,"all",t),y;if(a){let b=S.expandShapeToKeepDim(m,l);y=me({inputs:{x:g},backend:t,attrs:{shape:b}})}else y=me({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),y}var fF={kernelName:Ul,backendName:"webgl",kernelFunc:g7};function x7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=x.parseAxisParam(s,n.shape),u=l,c=S.getAxesPermutation(u,i),p=n;c!=null&&(p=Bt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=S.getInnerMostAxes(u.length,i)),S.assertAxesAreInnerMostDims("any",u,i);let[m,f]=S.computeOutAndReduceShapes(p.shape,u),d=x.sizeFromShape(f),h=me({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=So(h,h.dtype,"any",t),y;if(a){let b=S.expandShapeToKeepDim(m,l);y=me({inputs:{x:g},backend:t,attrs:{shape:b}})}else y=me({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),y}var dF={kernelName:jl,backendName:"webgl",kernelFunc:x7};var Qk=class{constructor(e,t,o){this.variableNames=["A"];let{windowSize:n,batchSize:s,outSize:a}=e;o||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let i=t==="max"?">":"<",l=o?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
2021-01-12 16:01:34 +01:00
int inOffset = outIdx * $ { n } ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
int bestIndex = inOffset ;
float bestValue = getA ( batch , bestIndex ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { n } ; i ++ ) {
int inIdx = $ { l } ;
2020-12-15 14:15:43 +01:00
float candidate = getA ( batch , inIdx ) ;
2021-01-12 16:01:34 +01:00
if ( candidate $ { i } bestValue ) {
2020-12-15 14:15:43 +01:00
bestValue = candidate ;
bestIndex = inIdx ;
2020-12-02 22:46:41 +01:00
}
}
2020-12-15 14:15:43 +01:00
setOutput ( float ( bestIndex ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};var eC=class{constructor(e,t,o,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,x.assert(e.length>2,()=> ` Packed arg$ { o . charAt ( 0 ) . toUpperCase ( ) + o . slice ( 1 ) } supports only inputs with rank above 2. ` );let s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),n||this.variableNames.push("bestIndicesA");let i=this.outputShape,l=i.length,u=Be(l),c=qt("coords",l),p,m;if(a===1){m=l+1;let F=Be(m);p= `
$ { F } sourceLocR = $ { F } ( $ { c . join ( ) } , 0 ) ;
++ $ { c [ l - 1 ] } ;
$ { F } sourceLocG = $ { F } ( $ { c . join ( ) } , 0 ) ;
++ $ { c [ l - 2 ] } ;
$ { F } sourceLocA = $ { F } ( $ { c . join ( ) } , 0 ) ;
-- $ { c [ l - 1 ] } ;
$ { F } sourceLocB = $ { F } ( $ { c . join ( ) } , 0 ) ;
-- $ { c [ l - 2 ] } ; ` }else m=l,p= `
$ { u } sourceLocR = coords ;
++ $ { c [ l - 1 ] } ;
$ { u } sourceLocG = coords ;
++ $ { c [ l - 2 ] } ;
$ { u } sourceLocA = coords ;
-- $ { c [ l - 1 ] } ;
$ { u } sourceLocB = coords ;
-- $ { c [ l - 2 ] } ; ` ;let f=["x","y","z","w","u","v"].slice(0,m),d="."+f[m-1],h=f.map(F=>"int "+F),g=qt("sourceLocR",m-1).concat("inIdx.r"),y=qt("sourceLocG",m-1).concat("inIdx.g"),b=qt("sourceLocB",m-1).concat("inIdx.b"),_=qt("sourceLocA",m-1).concat("inIdx.a"),w=o==="max"?"greaterThan":"lessThan",k=n?"": `
inIdx = round ( vec4 ( getBestIndicesAChannel ( $ { g . join ( ) } ) ,
getBestIndicesAChannel ( $ { y . join ( ) } ) ,
getBestIndicesAChannel ( $ { b . join ( ) } ) ,
getBestIndicesAChannel ( $ { _ . join ( ) } ) ) ) ; ` , $ = ` vec4 (
getAChannel ( $ { g . join ( ) } ) ,
hasNextCol ? getAChannel ( $ { y . join ( ) } ) : 0. ,
hasNextRow ? getAChannel ( $ { b . join ( ) } ) : 0. ,
hasNextRow && hasNextCol ? getAChannel ( $ { _ . join ( ) } ) : 0. ) ` ,T=n?"": `
float getBestIndicesAChannel ( $ { h . join ( ) } ) {
return getChannel ( getBestIndicesA ( $ { f . join ( ) } ) ,
vec2 ( $ { f . slice ( - 2 ) . join ( ) } ) ) ;
2020-12-15 14:15:43 +01:00
} ` ;this.userCode= `
2021-01-12 16:01:34 +01:00
float getAChannel ( $ { h . join ( ) } ) {
return getChannel ( getA ( $ { f . join ( ) } ) ,
vec2 ( $ { f . slice ( - 2 ) . join ( ) } ) ) ;
}
$ { T }
void main ( ) {
$ { u } coords = getOutputCoords ( ) ;
bool hasNextCol = $ { c [ l - 1 ] } < $ { i [ l - 1 ] - 1 } ;
bool hasNextRow = $ { c [ l - 2 ] } < $ { i [ l - 2 ] - 1 } ;
$ { p }
ivec4 srcIdx = ivec4 ( sourceLocR$ { d } , sourceLocG$ { d } ,
sourceLocB$ { d } , sourceLocA$ { d } ) * $ { t } ;
2020-12-15 14:15:43 +01:00
ivec4 inIdx = srcIdx ;
vec4 bestIndex = vec4 ( inIdx ) ;
2021-01-12 16:01:34 +01:00
vec4 bestValue = $ { $ } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { t } ; i ++ ) {
2020-12-15 14:15:43 +01:00
inIdx = srcIdx ;
2021-01-12 16:01:34 +01:00
$ { k }
vec4 candidate = $ { $ } ;
2020-12-15 14:15:43 +01:00
bvec4 nan = isnan ( candidate ) ;
bvec4 replace = bvec4 (
2021-01-12 16:01:34 +01:00
vec4 ( $ { w } ( candidate , bestValue ) ) * ( vec4 ( 1.0 ) - vec4 ( nan ) ) ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
bestValue = vec4 ( replace . x ? candidate . x : bestValue . x ,
replace . y ? candidate . y : bestValue . y ,
replace . z ? candidate . z : bestValue . z ,
replace . w ? candidate . w : bestValue . w ) ;
bestIndex = mix ( bestIndex , vec4 ( inIdx ) , vec4 ( replace ) ) ;
srcIdx ++ ;
}
setOutput ( bestIndex ) ;
}
2021-01-12 16:01:34 +01:00
` }};function hF(r,e,t,o=null){let n=e.shape[0],s=e.shape[1];o!=null&&(n=o.shape[0],s=o.shape[1]);let a=S.computeOptimalWindowSize(s),i={windowSize:a,inSize:s,batchSize:n,outSize:Math.ceil(s/a)},l=new Qk(i,t,o==null),u=[e];o!=null&&u.push(o);let c=r.runWebGLProgram(l,u,"int32");if(c.shape[1]===1)return c;let p=hF(r,e,t,c);return r.disposeIntermediateTensorInfo(c),p}function gF(r,e,t,o=null){let n=o!=null?o.shape:e.shape,s=n[n.length-1],a=S.computeOptimalWindowSize(s),i=new eC(n,a,t,o==null),l=o==null?[e]:[e,o],u=r.runWebGLProgram(i,l,"int32");if(u.shape.length===e.shape.length){let c=gF(r,e,t,u);return r.disposeIntermediateTensorInfo(u),c}return u}function Bx(r,e,t,o){let n=[t];if(S.assertAxesAreInnerMostDims("arg"+o.charAt(0).toUpperCase()+o.slice(1),n,e.shape.length),!W().getBool("WEBGL_PACK_REDUCE")||e.shape.length<=2){let s=[],[a,i]=S.computeOutAndReduceShapes(e.shape,n),l=x.sizeFromShape(i),u=me({inputs:{x:e},backend:r,attrs:{shape:[-1,l]}});s.push(u);let c=hF(r,u,o);s.push(c);let p=me({inputs:{x:c},backend:r,attrs:{shape:a}});return s.forEach(m=>r.disposeIntermediateTensorInfo(m)),p}return gF(r,e,o)}function y7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=x.parseAxisParam(s,n.shape),i=S.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=Bt({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=S.getInnerMostAxes(a.length,l.shape.length)),S.assertAxesAreInnerMostDims("argMax",[a[0]],l.shape.length);let c=Bx(t,l,a[0],"max");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var xF={kernelName:Ko,backendName:"webgl",kernelFunc:y7};function b7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=x.parseAxisParam(s,n.shape),i=S.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=Bt({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=S.getInnerMostAxes(a.length,l.shape.length)),S.assertAxesAreInnerMostDims("argMin",[a[0]],l.shape.length);let c=Bx(t,l,a[0],"min");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var yF={kernelName:oa,backendName:"webgl",kernelFunc:b7};var _7=xr+ `
2020-12-15 14:15:43 +01:00
if ( abs ( x ) > 1. ) {
return NAN ;
}
return asin ( x ) ;
2021-01-12 16:01:34 +01:00
` ,w7=Ce({opSnippet:_7}),bF={kernelName:Hs,backendName:"webgl",kernelFunc:w7};var v7=xr+"return log(x + sqrt(x * x + 1.0));",k7=Ce({opSnippet:v7}),_F={kernelName:Ks,backendName:"webgl",kernelFunc:k7};var C7=xr+ `
2020-12-15 14:15:43 +01:00
return atan ( x ) ;
2021-01-12 16:01:34 +01:00
` ,I7=Ce({opSnippet:C7}),wF={kernelName:Xs,backendName:"webgl",kernelFunc:I7};var N7=YR+ `
2020-12-15 14:15:43 +01:00
return atan ( a , b ) ;
2021-01-12 16:01:34 +01:00
` ,S7= `
2020-12-15 14:15:43 +01:00
vec4 result = atan ( a , b ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2021-01-12 16:01:34 +01:00
` +ZR+ `
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,T7=at({opSnippet:N7,packedOpSnippet:S7}),vF={kernelName:Zs,backendName:"webgl",kernelFunc:T7};var E7=xr+ `
2020-12-15 14:15:43 +01:00
if ( ( x < - 1.0 ) || ( x > 1.0 ) ) return NAN ;
2021-01-12 16:01:34 +01:00
return ( log ( 1.0 + x ) - log ( 1.0 - x ) ) / 2.0 ; ` ,A7=Ce({opSnippet:E7}),kF={kernelName:Ys,backendName:"webgl",kernelFunc:A7};var Yi=class{constructor(e,t,o,n=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&o)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,i=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;let h=t==="avg",g= ` ( ( batch * $ { e . inHeight } + xR ) * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,y= ` ( xR * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,b="0.0";if(h||(b="-1.0 / 1e-20"),o){let F=">=";this.userCode= `
const ivec2 strides = ivec2 ( $ { i } , $ { l } ) ;
const ivec2 pads = ivec2 ( $ { f } , $ { d } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
float avgValue = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { p } ;
wR += $ { u } ) {
2020-12-15 14:15:43 +01:00
int xR = xRCorner + wR ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { m } ;
wC += $ { c } ) {
2020-12-15 14:15:43 +01:00
int xC = xCCorner + wC ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2020-12-15 14:15:43 +01:00
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 ) ;
2021-01-12 16:01:34 +01:00
if ( value $ { F } currMinMaxValue ) {
2020-12-15 14:15:43 +01:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
2021-01-12 16:01:34 +01:00
minMaxPosition = $ { n ? s ? g : y : ` wR * ${ m } + wC ` } ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
}
}
2020-12-15 14:15:43 +01:00
setOutput ( float ( minMaxPosition ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;return}let _="max",w= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&(w="avgValue / count");let k=Math.floor(a/4)*4, $ =a%4,T= `
if ( $ { h } ) {
2020-12-15 14:15:43 +01:00
avgValue += dot ( values , ones ) ;
} else {
2021-01-12 16:01:34 +01:00
minMaxValue = $ { _ } ( values , minMaxValue ) ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
` ;this.userCode= `
2021-01-12 16:01:34 +01:00
const ivec2 strides = ivec2 ( $ { i } , $ { l } ) ;
const ivec2 pads = ivec2 ( $ { f } , $ { d } ) ;
const float initializationValue = $ { b } ;
2020-12-15 14:15:43 +01:00
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 ) {
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xR , xC , d ) ;
}
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2020-12-15 14:15:43 +01:00
int d = coords [ 3 ] ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
2021-01-12 16:01:34 +01:00
vec4 minMaxValue = vec4 ( $ { b } ) ;
2020-12-15 14:15:43 +01:00
float avgValue = 0.0 ;
count = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { p } ;
wR += $ { u } ) {
2020-12-15 14:15:43 +01:00
int xR = xRCorner + wR ;
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { k } ; wC += 4 ) {
int xC = xCCorner + wC * $ { c } ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xR , xC + $ { c } , d ) ,
getValue ( batch , xR , xC + 2 * $ { c } , d ) ,
getValue ( batch , xR , xC + 3 * $ { c } , d )
2020-12-15 14:15:43 +01:00
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { T }
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int xC = xCCorner + $ { k } ;
if ( $ { $ === 1 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { T }
} else if ( $ { $ === 2 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xR , xC + $ { c } , d ) ,
2020-12-15 14:15:43 +01:00
initializationValue ,
initializationValue
) ;
2021-01-12 16:01:34 +01:00
$ { T }
} else if ( $ { $ === 3 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xR , xC + $ { c } , d ) ,
getValue ( batch , xR , xC + 2 * $ { c } , d ) ,
2020-12-15 14:15:43 +01:00
initializationValue
) ;
2021-01-12 16:01:34 +01:00
$ { T }
2020-12-02 22:46:41 +01:00
}
}
2021-01-12 16:01:34 +01:00
setOutput ( $ { w } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }},mc=class{constructor(e,t,o,n=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&o)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,i=e.strideDepth,l=e.strideHeight,u=e.strideWidth,c=e.dilationDepth,p=e.dilationHeight,m=e.dilationWidth,f=e.effectiveFilterDepth,d=e.effectiveFilterHeight,h=e.effectiveFilterWidth,g=e.padInfo.front,y=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let _=t==="avg",w="0.0";if(_||(w="-1.0 / 1e-20"),o){let L=">=";this.userCode= `
2020-12-15 14:15:43 +01:00
const ivec3 strides =
2021-01-12 16:01:34 +01:00
ivec3 ( $ { i } , $ { l } , $ { u } ) ;
const ivec3 pads = ivec3 ( $ { g } , $ { y } , $ { b } ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wD = 0 ; wD < $ { f } ;
wD += $ { c } ) {
2020-12-15 14:15:43 +01:00
int xD = xDCorner + wD ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xD < 0 || xD >= $ { e . inDepth } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { d } ;
wR += $ { p } ) {
2020-12-15 14:15:43 +01:00
int xR = xRCorner + wR ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-15 14:15:43 +01:00
continue ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { h } ;
wC += $ { m } ) {
2020-12-15 14:15:43 +01:00
int xC = xCCorner + wC ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float value = getX ( batch , xD , xR , xC , ch ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
2021-01-12 16:01:34 +01:00
if ( value $ { L } currMinMaxValue ) {
2020-12-15 14:15:43 +01:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
2021-01-12 16:01:34 +01:00
minMaxPosition = $ { n ? s ? ` (((batch * ${ e . inDepth } + xD) * ${ e . inHeight } + xR) * ${ e . inWidth } + xC) * ${ e . inChannels } + ch ` : ` ((xD * ${ e . inHeight } + xR) * ${ e . inWidth } + xC) * ${ e . inChannels } + ch ` : ` wD * ${ d } * ${ h } +
wR * $ { h } + wC ` };
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
}
}
}
2020-12-15 14:15:43 +01:00
setOutput ( float ( minMaxPosition ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ;return}let k="max", $ = ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&( $ ="avgValue / count");let T=Math.floor(a/4)*4,F=a%4,M= `
if ( $ { _ } ) {
2020-12-15 14:15:43 +01:00
avgValue += dot ( values , ones ) ;
} else {
2021-01-12 16:01:34 +01:00
minMaxValue = $ { k } ( values , minMaxValue ) ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
` ;this.userCode= `
const ivec3 strides =
2021-01-12 16:01:34 +01:00
ivec3 ( $ { i } , $ { l } , $ { u } ) ;
const ivec3 pads = ivec3 ( $ { g } , $ { y } , $ { b } ) ;
const float initializationValue = $ { w } ;
2020-12-15 14:15:43 +01:00
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float count = 0.0 ;
float getValue ( int batch , int xD , int xR , int xC , int ch ) {
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xD , xR , xC , ch ) ;
}
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
2020-12-15 14:15:43 +01:00
int ch = coords . u ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2021-01-12 16:01:34 +01:00
vec4 minMaxValue = vec4 ( $ { w } ) ;
2020-12-15 14:15:43 +01:00
float avgValue = 0.0 ;
count = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wD = 0 ; wD < $ { f } ;
wD += $ { c } ) {
2020-12-15 14:15:43 +01:00
int xD = xDCorner + wD ;
2021-01-12 16:01:34 +01:00
if ( xD < 0 || xD >= $ { e . inDepth } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { d } ;
wR += $ { p } ) {
2020-12-15 14:15:43 +01:00
int xR = xRCorner + wR ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { T } ; wC += 4 ) {
int xC = xCCorner + wC * $ { m } ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xD , xR , xC + $ { m } , ch ) ,
getValue ( batch , xD , xR , xC + 2 * $ { m } , ch ) ,
getValue ( batch , xD , xR , xC + 3 * $ { m } , ch )
2020-12-15 14:15:43 +01:00
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { M }
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int xC = xCCorner + $ { T } ;
if ( $ { F === 1 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { M }
} else if ( $ { F === 2 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xD , xR , xC + $ { m } , ch ) ,
2020-12-15 14:15:43 +01:00
initializationValue ,
initializationValue
) ;
2021-01-12 16:01:34 +01:00
$ { M }
} else if ( $ { F === 3 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xD , xR , xC + $ { m } , ch ) ,
getValue ( batch , xD , xR , xC + 2 * $ { m } , ch ) ,
2020-12-15 14:15:43 +01:00
initializationValue
) ;
2021-01-12 16:01:34 +01:00
$ { M }
2020-12-02 22:46:41 +01:00
}
}
2021-01-12 16:01:34 +01:00
setOutput ( $ { $ } ) ;
2020-12-02 22:46:41 +01:00
}
}
2021-01-12 16:01:34 +01:00
` }};function D7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;Xi(n,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;x.assert(S.eitherStridesOrDilationsAreOne(a,u),()=> ` Error in avgPool : Either strides or dilations must be 1. Got strides $ { a } and dilations '${u}' ` );let c=S.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))return Ht({inputs:{x:n},backend:t});let p=new Yi(c,"avg",!1);return t.runWebGLProgram(p,[n],"float32")}var CF={kernelName:Xo,backendName:"webgl",kernelFunc:D7};function $ 7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=o,c=[1,1,1],p=S.computePool3DInfo(n.shape,s,a,c,i,l,u),m=new mc(p,"avg",!1);return t.runWebGLProgram(m,[n],"float32")}var IF={kernelName:na,backendName:"webgl",kernelFunc: $ 7};var tC=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,o=e.filterWidth,n=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=l-1-e.padInfo.top,p=u-1-e.padInfo.left,m=1/(t*o);this.userCode= `
const ivec2 pads = ivec2 ( $ { c } , $ { p } ) ;
const float avgMultiplier = float ( $ { m } ) ;
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
2020-12-02 22:46:41 +01:00
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { l } ;
wR += $ { a } ) {
float dyR = float ( dyRCorner + wR ) / $ { n } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2020-12-15 14:15:43 +01:00
int idyR = int ( dyR ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { u } ;
wC += $ { i } ) {
float dyC = float ( dyCCorner + wC ) / $ { s } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2020-12-15 14:15:43 +01:00
int idyC = int ( dyC ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float dyValue = getDy ( b , idyR , idyC , d ) ;
dotProd += dyValue * avgMultiplier ;
2020-12-02 22:46:41 +01:00
}
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }},rC=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,o=e.filterHeight,n=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterDepth,m=e.effectiveFilterHeight,f=e.effectiveFilterWidth,d=p-1-e.padInfo.front,h=m-1-e.padInfo.top,g=f-1-e.padInfo.left,y=1/(t*o*n);this.userCode= `
const ivec3 pads = ivec3 ( $ { d } , $ { h } , $ { g } ) ;
const float avgMultiplier = float ( $ { y } ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +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-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wD = 0 ; wD < $ { p } ;
wD += $ { l } ) {
float dyD = float ( dyDCorner + wD ) / $ { s } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
2020-12-15 14:15:43 +01:00
continue ;
}
int idyD = int ( dyD ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { m } ;
wR += $ { u } ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { f } ;
wC += $ { c } ) {
float dyC = float ( dyCCorner + wC ) / $ { i } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
dotProd += dyValue * avgMultiplier ;
}
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }};function R7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=o,p=[1,1,1],m=S.computePool3DInfo(a.shape,i,l,p,u,c),f=new rC(m);return t.runWebGLProgram(f,[n],a.dtype)}var NF={kernelName:Hl,backendName:"webgl",kernelFunc:R7};function F7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s;Xi([n,s],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=o,c=S.computePool2DInfo(a.shape,i,l,1,u),p=new tC(c);return t.runWebGLProgram(p,[n],a.dtype)}var SF={kernelName:ql,backendName:"webgl",kernelFunc:F7};function O7(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;return pc({a:n,b:s,transposeA:a,transposeB:i,backend:t})}var TF={kernelName:Yo,backendName:"webgl",kernelFunc:O7};var oC=class{constructor(e,t,o,n,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],S.assertAndGetBroadcastShape(e,t),S.assertAndGetBroadcastShape(e,o);let i="0.0";n!=null&&(S.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="1.0";s!=null&&(S.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
float x = getXAtOutCoords ( ) ;
float mean = getMeanAtOutCoords ( ) ;
float variance = getVarianceAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
float offset = $ { i } ;
float scale = $ { l } ;
float inv = scale * inversesqrt ( variance + float ( $ { a } ) ) ;
2020-12-15 14:15:43 +01:00
setOutput ( dot ( vec3 ( x , - mean , offset ) , vec3 ( inv , inv , 1 ) ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var nC=class{constructor(e,t,o,n,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],S.assertAndGetBroadcastShape(e,t),S.assertAndGetBroadcastShape(e,o);let i="vec4(0.0)";n!=null&&(S.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="vec4(1.0)";s!=null&&(S.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
vec4 offset = $ { i } ;
vec4 scale = $ { l } ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
vec4 x = getXAtOutCoords ( ) ;
vec4 mean = getMeanAtOutCoords ( ) ;
vec4 variance = getVarianceAtOutCoords ( ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
vec4 inv = scale * inversesqrt ( variance + vec4 ( $ { a } ) ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
setOutput ( ( x - mean ) * inv + offset ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var P7=({inputs:r,backend:e,attrs:t})=>{let{x:o,mean:n,variance:s,offset:a,scale:i}=r;x.assert(n.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),x.assert(a==null||n.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),x.assert(i==null||n.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=t;l==null&&(l=.001);let u=[o,n,s],c=null;a!=null&&(c=a.shape,u.push(a));let p=null;i!=null&&(p=i.shape,u.push(i));let m=W().getBool("WEBGL_PACK_NORMALIZATION")?new nC(o.shape,n.shape,s.shape,c,p,l):new oC(o.shape,n.shape,s.shape,c,p,l);return e.runWebGLProgram(m,u,u[0].dtype)},EF={kernelName:an,backendName:"webgl",kernelFunc:P7};var sC=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=Be(this.rank),o= ` uniform int start [ $ { this . rank } ] ; ` ,n=M7(this.rank),s,a=e.map((i,l)=> ` sourceLoc . $ { iC [ l ] } = start [ $ { l } ] + coords . $ { iC [ l ] } ; ` );s= `
$ { t } sourceLoc ;
$ { t } coords = getOutputCoords ( ) ;
$ { a . join ( `
2020-12-15 14:15:43 +01:00
` )}
` ,this.userCode= `
2021-01-12 16:01:34 +01:00
$ { o }
void main ( ) {
$ { s }
setOutput ( getSource ( $ { n } ) ) ;
}
` }getCustomSetupFunc(e){if(e.length!==this.rank)throw Error( ` The rank ( $ { this . rank } ) of the program must match the length of start ( $ { e . length } ) ` );return(t,o)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(o,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}},iC=["x","y","z","w","u","v"];function M7(r){if(r===1)return"sourceLoc";if(r<=6)return iC.slice(0,r).map(e=>"sourceLoc."+e).join(",");throw Error( ` Slicing for rank $ { r } is not yet supported ` )}var aC=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=Be(this.rank),o=qt("coords",this.rank),n=qt("sourceLoc",this.rank),s=this.rank===1?"sourceLoc": ` vec2 ( $ { n . slice ( - 2 ) . join ( ) } ) ` ,a= ` getChannel ( getSource ( $ { n . join ( ) } ) , $ { s } ) ` ,i= `
result . x = $ { a } ;
if ( ++ $ { o [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
++ $ { n [ this . rank - 1 ] } ;
result . y = $ { a } ;
-- $ { n [ this . rank - 1 ] } ;
}
` ,l=this.rank===1?"": `
-- $ { o [ this . rank - 1 ] } ;
if ( ++ $ { o [ this . rank - 2 ] } < $ { e [ this . rank - 2 ] } ) {
++ $ { n [ this . rank - 2 ] } ;
result . z = $ { a } ;
if ( ++ $ { o [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
++ $ { n [ this . rank - 1 ] } ;
result . w = $ { a } ;
}
}
` ,u=this.rank<=4? ` sourceLoc = coords +
$ { t } ( $ { e . map ( ( c , p ) => ` start[ ${ p } ] ` ) . join ( ) } ) ; ` :e.map((c,p)=> ` $ { n [ p ] } = $ { o [ p ] } + start [ $ { p } ] ; ` ).join( `
2020-12-15 14:15:43 +01:00
` );this.userCode= `
uniform int start [ $ { this . rank } ] ;
2020-12-02 22:46:41 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { t } coords = getOutputCoords ( ) ;
$ { t } sourceLoc ;
$ { u }
2020-12-02 22:46:41 +01:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
$ { i }
$ { l }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e){if(e.length!==this.rank)throw Error( ` The rank ( $ { this . rank } ) of the program must match the length of start ( $ { e . length } ) ` );return(t,o)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(o,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}};function L7(r,e,t,o){let n=o.texData.get(r.dataId),s=o.makeTensorInfo(t,r.dtype),a=o.texData.get(s.dataId);Object.assign(a,n),a.shape=t,a.dtype=r.dtype;let i=sr.computeFlatOffset(e,x.computeStrides(r.shape));n.slice&&(i+=n.slice.flatOffset),a.slice={flatOffset:i,origDataId:n.slice&&n.slice.origDataId||r.dataId};let l=o.dataRefCount.get(a.slice.origDataId)||1;return o.dataRefCount.set(a.slice.origDataId,l+1),s}function qa(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o,[i,l]=sr.parseSliceParams(n,s,a);if(sr.assertParamsValid(n,i,l),x.sizeFromShape(l)===0)return t.makeTensorInfo(l,n.dtype,[]);if(t.shouldExecuteOnCPU([n])||n.dtype==="string"){let p=t.texData.get(n.dataId),m=SR(p.values,i,l,n.shape,n.dtype);return t.makeTensorInfo(l,n.dtype,m)}let{isPacked:u}=t.texData.get(n.dataId),c=sr.isSliceContinous(n.shape,i,l);if(u||!c){let p=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new aC(l):new sC(l),m=p.getCustomSetupFunc(i);return t.runWebGLProgram(p,[n],n.dtype,m)}return t.uploadToGPU(n.dataId),L7(n,i,l,t)}var AF={kernelName:gs,backendName:"webgl",kernelFunc:qa};var z7=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;x.assert(n.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((b,_)=>b*_),l=S.getReshaped(n.shape,s,i),u=S.getPermuted(l.length,s.length),c=S.getReshapedPermuted(n.shape,s,i),p=S.getSliceBeginCoords(a,s.length),m=S.getSliceSize(c,a,s.length),f=[],d=me({inputs:{x:n},backend:t,attrs:{shape:l}}),h=Bt({inputs:{x:d},backend:t,attrs:{perm:u}}),g=me({inputs:{x:h},backend:t,attrs:{shape:c}}),y=qa({inputs:{x:g},backend:t,attrs:{begin:p,size:m}});return f.push(d),f.push(h),f.push(g),f.forEach(b=>t.disposeIntermediateTensorInfo(b)),y},DF={kernelName:sa,backendName:"webgl",kernelFunc:z7};function B7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a}=o,i=t.readSync(n.dataId),l=t.readSync(s.dataId),u= $ x(i,l,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var $ F={kernelName:Kl,backendName:"webgl",kernelFunc:B7};var V7="return float(a != b);",lC=at({opSnippet:V7,dtype:"bool"}),RF={kernelName:xi,backendName:"webgl",kernelFunc:lC};function Ha(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return Ht({inputs:{x:n.complexTensorInfos.real},backend:t})}var FF={kernelName:fu,backendName:"webgl",kernelFunc:Ha};var W7="return float(int(x));";function OF(r,e){let t=new mo(r.shape,W7),o=e.runWebGLProgram(t,[r],"int32");return{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}function uC(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dtype:s}=o;if(s==="complex64"){if(n.dtype==="complex64")return Ht({inputs:{x:n},backend:t});let a=pt(n.shape),i=uC({inputs:{x:n},backend:t,attrs:{dtype:"float32"}}),l=fo({inputs:{real:i,imag:a},backend:t});return a.dispose(),t.disposeIntermediateTensorInfo(i),l}if(n.dtype==="complex64"){let a=Ha({inputs:{input:n},backend:t}),i=uC({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!x.hasEncodingLoss(n.dtype,s)){let a=Ht({inputs:{x:n},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(s==="int32")return OF(n,t);if(s==="bool"){let a=t.makeTensorInfo([],"bool",x.getTypedArrayFromDType("bool",1)),l=lC({inputs:{a:n,b:a},backend:t});return t.disposeIntermediateTensorInfo(a),l}throw new Error( ` Error in Cast : failed to cast $ { n . dtype } to $ { s } ` )}var PF={kernelName:Fo,backendName:"webgl",kernelFunc:uC};var MF="return ceil(x);",G7=Ce({opSnippet:MF,packedOpSnippet:MF,cpuKernelImpl:uR}),LF={kernelName:Js,backendName:"webgl",kernelFunc:G7};var cC=class{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float minVal ;
uniform float maxVal ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
float value = getAAtOutCoords ( ) ;
if ( isnan ( value ) ) {
setOutput ( value ) ;
return ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
setOutput ( clamp ( value , minVal , maxVal ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e,t){return(o,n)=>{this.minLoc==null&&(this.minLoc=o.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=o.getUniformLocationNoThrow(n,"maxVal")),o.gl.uniform1f(this.minLoc,e),o.gl.uniform1f(this.maxLoc,t)}}};var pC=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float minVal ;
uniform float maxVal ;
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
vec4 value = getAAtOutCoords ( ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
if ( any ( isnan ( value ) ) ) {
setOutput ( value ) ;
return ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
setOutput ( clamp ( value , vec4 ( minVal ) , vec4 ( maxVal ) ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e,t){return(o,n)=>{this.minLoc==null&&(this.minLoc=o.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=o.getUniformLocationNoThrow(n,"maxVal")),o.gl.uniform1f(this.minLoc,e),o.gl.uniform1f(this.maxLoc,t)}}};function U7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{clipValueMin:s,clipValueMax:a}=o,i;W().getBool("WEBGL_PACK_CLIP")?i=new pC(n.shape):i=new cC(n.shape);let l=i.getCustomSetupFunc(s,a);return t.runWebGLProgram(i,[n],n.dtype,l)}var zF={kernelName:Oo,backendName:"webgl",kernelFunc:U7};var mC=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
float re = abs ( getRealAtOutCoords ( ) ) ;
float im = abs ( getImagAtOutCoords ( ) ) ;
float mx = max ( re , im ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// 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 ) )
) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function BF(r,e){return{dataId:e.dataId,dtype:e.dtype,shape:r.shape}}function j7(r){let{inputs:e,backend:t}=r,{x:o}=e,n=t.texData.get(o.dataId),s=new mC(o.shape),a=[BF(o,n.complexTensorInfos.real),BF(o,n.complexTensorInfos.imag)];return t.runWebGLProgram(s,a,a[0].dtype)}var VF={kernelName:ia,backendName:"webgl",kernelFunc:j7};var fC=class{constructor(e){this.outputShape=[],this.outputShape=S.computeOutShape(e,1),this.variableNames=e.map((a,i)=> ` T$ { i } ` );let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let o=[ ` if ( yC < $ { t [ 0 ] } ) setOutput ( getT0 ( yR , yC ) ) ; ` ];for(let a=1;a<t.length;a++){let i=t[a-1];o.push( ` else if ( yC < $ { t [ a ] } ) setOutput ( getT$ { a } ( yR , yC - $ { i } ) ) ; ` )}let n=t.length,s=t[t.length-1];o.push( ` else setOutput ( getT$ { n } ( yR , yC - $ { s } ) ) ; ` ),this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec2 coords = getOutputCoords ( ) ;
int yR = coords . x ;
int yC = coords . y ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { o . join ( `
2020-12-15 14:15:43 +01:00
` )}
}
2021-01-12 16:01:34 +01:00
` }};var dC=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=S.computeOutShape(e,t);let o=this.outputShape,n=o.length,s=Be(n),a=qt("coords",n),i=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((h,g)=> ` T$ { g } ` );let l=new Array(e.length-1);l[0]=e[0][t];for(let h=1;h<l.length;h++)l[h]=l[h-1]+e[h][t];let u=i[t],c=i.slice(-2),p=i.join(),m= ` if ( $ { u } < $ { l [ 0 ] } ) {
2020-12-15 14:15:43 +01:00
return getChannel (
2021-01-12 16:01:34 +01:00
getT0 ( $ { p } ) , vec2 ( $ { c . join ( ) } ) ) ;
} ` ;for(let h=1;h<l.length;h++){let g=l[h-1];m+= `
if ( $ { u } < $ { l [ h ] } && $ { u } >= $ { l [ h - 1 ] } ) {
2020-12-15 14:15:43 +01:00
return getChannel (
2021-01-12 16:01:34 +01:00
getT$ { h } ( $ { Vx ( i , u , g ) } ) ,
vec2 ( $ { Vx ( c , u , g ) } ) ) ;
} ` }let f=l.length,d=l[l.length-1];m+= `
2020-12-15 14:15:43 +01:00
return getChannel (
2021-01-12 16:01:34 +01:00
getT$ { f } ( $ { Vx ( i , u , d ) } ) ,
vec2 ( $ { Vx ( c , u , d ) } ) ) ; ` ,this.userCode= `
float getValue ( $ { i . map ( h => "int " + h ) } ) {
$ { m }
2020-12-02 22:46:41 +01:00
}
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { s } coords = getOutputCoords ( ) ;
vec4 result = vec4 ( getValue ( $ { a } ) , 0. , 0. , 0. ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { a [ n - 1 ] } = $ { a [ n - 1 ] } + 1 ;
if ( $ { a [ n - 1 ] } < $ { o [ n - 1 ] } ) {
result . g = getValue ( $ { a } ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { a [ n - 2 ] } = $ { a [ n - 2 ] } + 1 ;
if ( $ { a [ n - 2 ] } < $ { o [ n - 2 ] } ) {
result . a = getValue ( $ { a } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
$ { a [ n - 1 ] } = $ { a [ n - 1 ] } - 1 ;
if ( $ { a [ n - 2 ] } < $ { o [ n - 2 ] } &&
$ { a [ n - 1 ] } < $ { o [ n - 1 ] } ) {
result . b = getValue ( $ { a } ) ;
2020-12-15 14:15:43 +01:00
}
setOutput ( result ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function Vx(r,e,t){let o=r.indexOf(e);return r.map((s,a)=>a===o? ` $ { s } - $ { t } ` :s).join()}function fc(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return Ht({inputs:{x:n.complexTensorInfos.imag},backend:t})}var WF={kernelName:iu,backendName:"webgl",kernelFunc:fc};function dc(r,e,t){let o=r[0].dtype;if(o==="complex64"){let u=r.map(d=>Ha({inputs:{input:d},backend:t})),c=r.map(d=>fc({inputs:{input:d},backend:t})),p=dc(u,e,t),m=dc(c,e,t),f=fo({inputs:{real:p,imag:m},backend:t});return u.forEach(d=>t.disposeIntermediateTensorInfo(d)),c.forEach(d=>t.disposeIntermediateTensorInfo(d)),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),f}if(o==="string"){let{tensors2D:u,outShape:c}=GF(r,e,t),p=u.map(g=>({vals:t.readSync(g.dataId),shape:g.shape})),m=u[0].shape[0]===1,f=cR(p,c,o,m),d=S.computeOutShape(r.map(g=>g.shape),e),h=t.makeTensorInfo(d,o,f);return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),h}if(r.length>W().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(r.length/2),c=dc(r.slice(0,u),e,t),p=dc(r.slice(u),e,t),m=dc([c,p],e,t);return t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(p),m}if(W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&r[0].shape.length>1){let u=new dC(r.map(c=>c.shape),e);return t.runWebGLProgram(u,r,o)}let{tensors2D:n,outShape:s}=GF(r,e,t),a=new fC(n.map(u=>u.shape)),i=t.runWebGLProgram(a,n,o);n.forEach(u=>t.disposeIntermediateTensorInfo(u));let l=me({inputs:{x:i},attrs:{shape:s},backend:t});return t.disposeIntermediateTensorInfo(i),l}function GF(r,e,t){let o=S.computeOutShape(r.map(s=>s.shape),e);return{tensors2D:r.map(s=>me({inputs:{x:s},attrs:{shape:[-1,x.sizeFromShape(s.shape.slice(e))]},backend:t})),outShape:o}}function hC(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=x.parseAxisParam(n,e[0].shape)[0],a=S.computeOutShape(e.map(u=>u.shape),s);if(x.sizeFromShape(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);let i=e.filter(u=>x.sizeFromShape(u.shape)>0);if(i.length===1)return Ht({inputs:{x:i[0]},backend:t});let l=i.map(u=>u.shape);return S.assertParamsConsistent(l,s),dc(i,s,t)}var UF={kernelName:as,backendName:"webgl",kernelFunc:hC};var sh=class{constructor(e,t=!1,o=null,n=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,i=e.padInfo.left,l=e.strideHeight,u=e.strideWidth,c=e.dilationHeight,p=e.dilationWidth,m=e.filterHeight,f=e.filterWidth,d=Math.floor(e.inChannels/4)*4,h=e.inChannels%4,g=e.dataFormat==="channelsLast",y=g?1:2,b=g?2:3,_=g?3:1,w="",k="";o&&(n?w= ` float activation ( float a ) {
2020-12-15 14:15:43 +01:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { o }
} ` :s?w= ` float activation ( float a ) {
2020-12-15 14:15:43 +01:00
float b = getLeakyreluAlphaAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { o }
} ` :w= `
2020-12-15 14:15:43 +01:00
float activation ( float x ) {
2021-01-12 16:01:34 +01:00
$ { o }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` ,k="result = activation(result);");let $ =t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { w }
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
const ivec2 strides = ivec2 ( $ { l } , $ { u } ) ;
const ivec2 pads = ivec2 ( $ { a } , $ { i } ) ;
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2021-01-12 16:01:34 +01:00
int d2 = coords [ $ { _ } ] ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
ivec2 xRCCorner =
2021-01-12 16:01:34 +01:00
ivec2 ( coords [ $ { y } ] , coords [ $ { b } ] ) * strides - pads ;
2020-12-15 14:15:43 +01:00
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// 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 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { m } ; wR ++ ) {
int xR = xRCorner + wR * $ { c } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { f } ; wC ++ ) {
int xC = xCCorner + wC * $ { p } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int d1 = 0 ; d1 < $ { d } ; d1 += 4 ) {
2020-12-15 14:15:43 +01:00
vec4 wValues = vec4 (
getW ( wR , wC , d1 , d2 ) ,
getW ( wR , wC , d1 + 1 , d2 ) ,
getW ( wR , wC , d1 + 2 , d2 ) ,
getW ( wR , wC , d1 + 3 , d2 )
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( $ { g } ) {
2020-12-15 14:15:43 +01:00
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 ) ;
2020-12-02 22:46:41 +01:00
}
}
2021-01-12 16:01:34 +01:00
if ( $ { h === 1 } ) {
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( $ { g } ) {
2020-12-15 14:15:43 +01:00
dotProd +=
2021-01-12 16:01:34 +01:00
getX ( batch , xR , xC , $ { d } ) *
getW ( wR , wC , $ { d } , d2 ) ;
2020-12-15 14:15:43 +01:00
} else {
dotProd +=
2021-01-12 16:01:34 +01:00
getX ( batch , $ { d } , xR , xC ) *
getW ( wR , wC , $ { d } , d2 ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
} else if ( $ { h === 2 } ) {
2020-12-15 14:15:43 +01:00
vec2 wValues = vec2 (
2021-01-12 16:01:34 +01:00
getW ( wR , wC , $ { d } , d2 ) ,
getW ( wR , wC , $ { d } + 1 , d2 )
2020-12-15 14:15:43 +01:00
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( $ { g } ) {
2020-12-15 14:15:43 +01:00
vec2 xValues = vec2 (
2021-01-12 16:01:34 +01:00
getX ( batch , xR , xC , $ { d } ) ,
getX ( batch , xR , xC , $ { d } + 1 )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec2 xValues = vec2 (
2021-01-12 16:01:34 +01:00
getX ( batch , $ { d } , xR , xC ) ,
getX ( batch , $ { d } + 1 , xR , xC )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
} else if ( $ { h === 3 } ) {
2020-12-15 14:15:43 +01:00
vec3 wValues = vec3 (
2021-01-12 16:01:34 +01:00
getW ( wR , wC , $ { d } , d2 ) ,
getW ( wR , wC , $ { d } + 1 , d2 ) ,
getW ( wR , wC , $ { d } + 2 , d2 )
2020-12-15 14:15:43 +01:00
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( $ { g } ) {
2020-12-15 14:15:43 +01:00
vec3 xValues = vec3 (
2021-01-12 16:01:34 +01:00
getX ( batch , xR , xC , $ { d } ) ,
getX ( batch , xR , xC , $ { d } + 1 ) ,
getX ( batch , xR , xC , $ { d } + 2 )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec3 xValues = vec3 (
2021-01-12 16:01:34 +01:00
getX ( batch , $ { d } , xR , xC ) ,
getX ( batch , $ { d } + 1 , xR , xC ) ,
getX ( batch , $ { d } + 2 , xR , xC )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
2020-12-02 22:46:41 +01:00
}
}
}
}
2020-12-15 14:15:43 +01:00
float result = dotProd ;
2021-01-12 16:01:34 +01:00
$ { $ }
$ { k }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }},gC=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,o=e.padInfo.top,n=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,c=e.dilationWidth,p=e.filterDepth,m=e.filterHeight,f=e.filterWidth,d=Math.floor(e.inChannels/4)*4,h=e.inChannels%4;this.userCode= `
const ivec3 strides = ivec3 ( $ { s } , $ { a } , $ { i } ) ;
const ivec3 pads = ivec3 ( $ { t } , $ { o } , $ { n } ) ;
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
2020-12-15 14:15:43 +01:00
int d2 = coords . u ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
ivec3 xFRCCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xFCorner = xFRCCorner . x ;
int xRCorner = xFRCCorner . y ;
int xCCorner = xFRCCorner . z ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
2020-12-02 22:46:41 +01:00
float dotProd = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wF = 0 ; wF < $ { p } ; wF ++ ) {
int xF = xFCorner + wF * $ { l } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xF < 0 || xF >= $ { e . inDepth } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { m } ; wR ++ ) {
int xR = xRCorner + wR * $ { u } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { f } ; wC ++ ) {
int xC = xCCorner + wC * $ { c } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int d1 = 0 ; d1 < $ { d } ; d1 += 4 ) {
2020-12-15 14:15:43 +01:00
vec4 xValues = vec4 (
getX ( batch , xF , xR , xC , d1 ) ,
getX ( batch , xF , xR , xC , d1 + 1 ) ,
getX ( batch , xF , xR , xC , d1 + 2 ) ,
getX ( batch , xF , xR , xC , d1 + 3 )
) ;
vec4 wValues = vec4 (
getW ( wF , wR , wC , d1 , d2 ) ,
getW ( wF , wR , wC , d1 + 1 , d2 ) ,
getW ( wF , wR , wC , d1 + 2 , d2 ) ,
getW ( wF , wR , wC , d1 + 3 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
}
2021-01-12 16:01:34 +01:00
if ( $ { h === 1 } ) {
2020-12-15 14:15:43 +01:00
dotProd +=
2021-01-12 16:01:34 +01:00
getX ( batch , xF , xR , xC , $ { d } ) *
getW ( wF , wR , wC , $ { d } , d2 ) ;
} else if ( $ { h === 2 } ) {
2020-12-15 14:15:43 +01:00
vec2 xValues = vec2 (
2021-01-12 16:01:34 +01:00
getX ( batch , xF , xR , xC , $ { d } ) ,
getX ( batch , xF , xR , xC , $ { d } + 1 )
2020-12-15 14:15:43 +01:00
) ;
vec2 wValues = vec2 (
2021-01-12 16:01:34 +01:00
getW ( wF , wR , wC , $ { d } , d2 ) ,
getW ( wF , wR , wC , $ { d } + 1 , d2 )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
2021-01-12 16:01:34 +01:00
} else if ( $ { h === 3 } ) {
2020-12-15 14:15:43 +01:00
vec3 xValues = vec3 (
2021-01-12 16:01:34 +01:00
getX ( batch , xF , xR , xC , $ { d } ) ,
getX ( batch , xF , xR , xC , $ { d } + 1 ) ,
getX ( batch , xF , xR , xC , $ { d } + 2 )
2020-12-15 14:15:43 +01:00
) ;
vec3 wValues = vec3 (
2021-01-12 16:01:34 +01:00
getW ( wF , wR , wC , $ { d } , d2 ) ,
getW ( wF , wR , wC , $ { d } + 1 , d2 ) ,
getW ( wF , wR , wC , $ { d } + 2 , d2 )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
}
2020-12-02 22:46:41 +01:00
}
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }};var xC=class{constructor(e,t,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let{filterWidth:n,inChannels:s,strideWidth:a,strideHeight:i,padInfo:l,outWidth:u,dilationWidth:c,dilationHeight:p,dataFormat:m}=o,{left:f,top:d}=l,h=s*n,g=zt(),y=m==="channelsLast",b=y?0:1,_=y?1:2,w="";for(let k=0;k<=1;k++)for(let $ =0; $ <=1; $ ++)w+= `
blockIndex = rc . y + $ { $ } ;
pos = rc . x + $ { k } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( blockIndex < $ { e [ 1 ] } && pos < $ { e [ 0 ] } ) {
offsetY = int ( blockIndex / ( $ { u } ) ) * $ { i } - $ { d } ;
d0 = offsetY + $ { p } * ( pos / $ { h } ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( d0 < $ { t [ b ] } && d0 >= 0 ) {
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
offsetX = int ( mod ( float ( blockIndex ) , $ { u } . ) * $ { a } . - $ { f } . ) ;
d1 = offsetX + $ { c } * ( int ( mod ( float ( pos ) , $ { h } . ) / $ { s } . ) ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( d1 < $ { t [ _ ] } && d1 >= 0 ) {
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
ch = int ( mod ( float ( pos ) , $ { s } . ) ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( $ { y } ) {
2020-12-15 14:15:43 +01:00
innerDims = vec2 ( d1 , ch ) ;
2021-01-12 16:01:34 +01:00
result [ $ { k * 2 + $ } ] = getChannel (
2020-12-15 14:15:43 +01:00
getA ( d0 , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
} else {
innerDims = vec2 ( d0 , d1 ) ;
2021-01-12 16:01:34 +01:00
result [ $ { k * 2 + $ } ] = getChannel (
2020-12-15 14:15:43 +01:00
getA ( ch , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
}
}
}
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
` ;this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec2 rc = getOutputCoords ( ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
int blockIndex , pos , offsetY , d0 , offsetX , d1 , ch ;
vec2 innerDims ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { w }
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { g . output } = result ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function Wx({x:r,filter:e,convInfo:t,backend:o,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let l=r.shape,u=o.texData.get(r.dataId),c=t.inChannels,p=l[0]*l[1]*l[2],m=t.outChannels,f=t.dataFormat==="channelsLast",d=!1,h=!1,g,y=[],b=(p===1||m===1)&&c>Yk,_=l[2]%2!=0&&!!u.isPacked;if(b||!W().getBool("WEBGL_LAZILY_UNPACK")||!W().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!_){let w=f?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],k=me({inputs:{x:r},backend:o,attrs:{shape:[1,w,t.inChannels]}}), $ =me({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}}),T=pc({a:k,b: $ ,transposeA:d,transposeB:h,backend:o,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a});g=me({inputs:{x:T},backend:o,attrs:{shape:t.outShape}}),y.push(k),y.push( $ ),y.push(T)}else{let w=f?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),k={dataId:r.dataId,shape:[1,w,t.inChannels],dtype:r.dtype}, $ =u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,x.assert(uc(u.shape,k.shape),()=> ` packed reshape $ { u . shape } to $ { k . shape } isn ' t free ` );let T=me({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}});y.push(T);let F=pc({a:k,b:T,backend:o,transposeA:d,transposeB:h,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a}),M=o.texData.get(F.dataId);x.assert(M.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape= $ ,M.shape=t.outShape,g=Ht({inputs:{x:F},backend:o}),g.shape=t.outShape,y.push(F)}for(let w of y)o.disposeIntermediateTensorInfo(w);return g}function Gx({x:r,filter:e,convInfo:t,backend:o,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let{filterWidth:l,filterHeight:u,inChannels:c,outWidth:p,outHeight:m,dataFormat:f}=t,d=f==="channelsLast",h=l*u*c,g=m*p,y=[h,g],b=!0,_=!1,w=[],k=me({inputs:{x:r},backend:o,attrs:{shape:r.shape.slice(1)}}), $ =me({inputs:{x:e},backend:o,attrs:{shape:[1,h,x.sizeFromShape(e.shape)/h]}});w.push(k),w.push( $ );let T=new xC(y,k.shape,t),F=o.runWebGLProgram(T,[k],"float32"),M=me({inputs:{x:F},backend:o,attrs:{shape:[1,y[0],y[1]]}});w.push(F),w.push(M);let L=n!=null,G=s!=null,H=i==="leakyrelu",U=i?Dl(i,!0):null,Z=new oh(M.shape, $ .shape,[1,g,t.outChannels],b,_,L,U,G,H),K=[M, $ ];if(n&&K.push(n),G&&K.push(s),H){let Q=o.makeTensorInfo([],"float32",x.createScalarValue(a,"float32"));K.push(Q),w.push(Q)}let X=o.runWebGLProgram(Z,K,"float32"),oe=d?[1,m,p,t.outChannels]:[1,t.outChannels,m,p],J=me({inputs:{x:X},backend:o,attrs:{shape:oe}});w.push(X);for(let Q of w)o.disposeIntermediateTensorInfo(Q);return J}function q7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=o,p=S.convertConv2DDataFormat(l),m=S.computeConv2DInfo(n.shape,s.shape,a,u,i,c,!1,p),f;if(m.filterHeight===1&&m.filterWidth===1&&m.dilationHeight===1&&m.dilationWidth===1&&m.strideHeight===1&&m.strideWidth===1&&(m.padInfo.type==="SAME"||m.padInfo.type==="VALID"))f=Wx({x:n,filter:s,convInfo:m,backend:t});else if(W().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)f=Gx({x:n,filter:s,convInfo:m,backend:t});else{let h=new sh(m);f=t.runWebGLProgram(h,[n,s],"float32")}let d=me({inputs:{x:f},backend:t,attrs:{shape:m.outShape}});return t.disposeIntermediateTensorInfo(f),d}var jF={kernelName:Zo,backendName:"webgl",kernelFunc:q7};var yC=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,o=e.strideWidth,n=e.padInfo.top,s=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int d2 = coords . w ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { t } - $ { n } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { o } - $ { s } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
if ( $ { a } ) {
2020-12-15 14:15:43 +01:00
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 ) ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
2020-12-02 22:46:41 +01:00
}
}
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }},bC=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,o=e.filterWidth,n=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,l=o-1-e.padInfo.left,u=a?1:2,c=a?2:3,p=a?3:1;this.userCode= `
const ivec2 pads = ivec2 ( $ { i } , $ { l } ) ;
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2021-01-12 16:01:34 +01:00
int d1 = coords [ $ { p } ] ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
ivec2 dyCorner = ivec2 ( coords [ $ { u } ] , coords [ $ { c } ] ) - pads ;
2020-12-15 14:15:43 +01:00
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { n } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2020-12-15 14:15:43 +01:00
int idyR = int ( dyR ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int wRPerm = $ { t } - 1 - wR ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { o } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { s } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int wCPerm = $ { o } - 1 - wC ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( $ { a } ) {
2020-12-15 14:15:43 +01:00
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 ;
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
}
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }},_C=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,o=e.strideHeight,n=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,i=e.padInfo.left;this.userCode= `
2020-12-15 14:15:43 +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 ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float dotProd = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yF = 0 ; yF < $ { e . outDepth } ; yF ++ ) {
int xF = wF + yF * $ { t } - $ { s } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xF < 0 || xF >= $ { e . inDepth } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { o } - $ { a } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { n } - $ { i } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2020-12-15 14:15:43 +01:00
float dyValue = getDy ( b , yF , yR , yC , d2 ) ;
float xValue = getX ( b , xF , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
2020-12-02 22:46:41 +01:00
}
}
}
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }},wC=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,o=e.filterHeight,n=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=t-1-e.padInfo.front,u=o-1-e.padInfo.top,c=n-1-e.padInfo.left;this.userCode= `
const ivec3 pads = ivec3 ( $ { l } , $ { u } , $ { c } ) ;
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
2020-12-15 14:15:43 +01:00
int d1 = coords . u ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyFCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float dotProd = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wF = 0 ; wF < $ { t } ; wF ++ ) {
float dyF = float ( dyFCorner + wF ) / $ { s } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyF < 0.0 || dyF >= $ { e . outDepth } . 0 || fract ( dyF ) > 0.0 ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2020-12-15 14:15:43 +01:00
int idyF = int ( dyF ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int wFPerm = $ { t } - 1 - wF ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { o } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyR ) > 0.0 ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2020-12-15 14:15:43 +01:00
int idyR = int ( dyR ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int wRPerm = $ { o } - 1 - wR ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { n } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { i } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int wCPerm = $ { n } - 1 - wC ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
2020-12-15 14:15:43 +01:00
float xValue = getDy ( batch , idyF , idyR , idyC , d2 ) ;
float wValue = getW ( wFPerm , wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
}
2020-12-02 22:46:41 +01:00
}
}
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function H7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=o,p=S.convertConv2DDataFormat(l),m=S.computeConv2DInfo(n.shape,c,a,1,i,u,!1,p),f=new yC(m);return t.runWebGLProgram(f,[n,s],"float32")}var qF={kernelName:Yl,backendName:"webgl",kernelFunc:H7};function K7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{inputShape:a,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=o,p=S.convertConv2DDataFormat(u),m=S.computeConv2DInfo(a,s.shape,i,1,l,c,!1,p),f=new bC(m);return t.runWebGLProgram(f,[n,s],"float32")}var HF={kernelName:Jo,backendName:"webgl",kernelFunc:K7};function X7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o,u=S.computeConv3DInfo(n.shape,s.shape,a,l,i),c=new gC(u);return t.runWebGLProgram(c,[n,s],"float32")}var KF={kernelName:aa,backendName:"webgl",kernelFunc:X7};function Y7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,filterShape:l}=o,u=S.computeConv3DInfo(n.shape,l,a,1,i),c=new _C(u);return t.runWebGLProgram(c,[n,s],"float32")}var XF={kernelName:Zl,backendName:"webgl",kernelFunc:Y7};function Z7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{pad:a,strides:i,inputShape:l}=o,u=S.computeConv3DInfo(l,s.shape,i,1,a),c=new wC(u);return t.runWebGLProgram(c,[n,s],"float32")}var YF={kernelName:Jl,backendName:"webgl",kernelFunc:Z7};var J7=Px+ `
2020-12-15 14:15:43 +01:00
return cos ( x ) ;
2021-01-12 16:01:34 +01:00
` ,Q7=Ce({opSnippet:J7}),ZF={kernelName:Qo,backendName:"webgl",kernelFunc:Q7};var eZ= `
2020-12-15 14:15:43 +01:00
float e2x = exp ( - x ) ;
return ( e2x + 1.0 / e2x ) / 2.0 ;
2021-01-12 16:01:34 +01:00
` ,tZ=Ce({opSnippet:eZ}),JF={kernelName:Qs,backendName:"webgl",kernelFunc:tZ};var vC=class{constructor(e,t,o,n,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,i,l,u]=e,[c]=t,[p,m]=o;this.outputShape=[c,p,m,u];let f=n==="bilinear"?1:0,[d,h]=[ ` $ { i - 1 } . 0 ` , ` $ { l - 1 } . 0 ` ],[g,y,b]=p>1?[ ` $ { ( i - 1 ) / ( p - 1 ) } ` ,"(y2-y1) * height_ratio", ` y1 * $ { d } + float ( y ) * ( height _scale ) ` ]:["0.0","0.0", ` 0.5 * ( y1 + y2 ) * $ { d } ` ],[_,w,k]=m>1?[ ` $ { ( l - 1 ) / ( m - 1 ) } ` ,"(x2-x1) * width_ratio", ` x1 * $ { h } + float ( x ) * ( width _scale ) ` ]:["0.0","0.0", ` 0.5 * ( x1 + x2 ) * $ { h } ` ];this.userCode= `
const float height _ratio = float ( $ { g } ) ;
const float width _ratio = float ( $ { _ } ) ;
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int y = coords [ 1 ] ;
int x = coords [ 2 ] ;
int d = coords [ 3 ] ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// get box vals
float y1 = getBoxes ( b , 0 ) ;
float x1 = getBoxes ( b , 1 ) ;
float y2 = getBoxes ( b , 2 ) ;
float x2 = getBoxes ( b , 3 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// get image in batch index
int bInd = round ( getBoxInd ( b ) ) ;
2021-01-12 16:01:34 +01:00
if ( bInd < 0 || bInd >= $ { a } ) {
2020-12-15 14:15:43 +01:00
return ;
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
float height _scale = $ { y } ;
float width _scale = $ { w } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
float in _y = $ { b } ;
if ( in _y < 0.0 || in _y > $ { d } ) {
setOutput ( float ( $ { s } ) ) ;
2020-12-15 14:15:43 +01:00
return ;
}
2021-01-12 16:01:34 +01:00
float in _x = $ { k } ;
if ( in _x < 0.0 || in _x > $ { h } ) {
setOutput ( float ( $ { s } ) ) ;
2020-12-15 14:15:43 +01:00
return ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
vec2 sourceFracIndexCR = vec2 ( in _x , in _y ) ;
2021-01-12 16:01:34 +01:00
if ( $ { f } == 1 ) {
2020-12-15 14:15:43 +01:00
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2 ( sourceFracIndexCR ) ;
ivec2 sourceCeilCR = ivec2 ( ceil ( sourceFracIndexCR ) ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float topLeft = getImage ( b , sourceFloorCR . y , sourceFloorCR . x , d ) ;
float bottomLeft = getImage ( b , sourceCeilCR . y , sourceFloorCR . x , d ) ;
float topRight = getImage ( b , sourceFloorCR . y , sourceCeilCR . x , d ) ;
float bottomRight = getImage ( b , sourceCeilCR . y , sourceCeilCR . x , d ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
vec2 fracCR = sourceFracIndexCR - vec2 ( sourceFloorCR ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float top = topLeft + ( topRight - topLeft ) * fracCR . x ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracCR . x ;
float newValue = top + ( bottom - top ) * fracCR . y ;
setOutput ( newValue ) ;
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2 ( floor (
sourceFracIndexCR + vec2 ( 0.5 , 0.5 ) ) ) ;
float newValue = getImage ( b , sourceNearestCR . y , sourceNearestCR . x , d ) ;
setOutput ( newValue ) ;
2020-12-02 22:46:41 +01:00
}
}
2021-01-12 16:01:34 +01:00
` }};var rZ=r=>{let{inputs:e,backend:t,attrs:o}=r,{image:n,boxes:s,boxInd:a}=e,{cropSize:i,method:l,extrapolationValue:u}=o,c=new vC(n.shape,s.shape,i,l,u);return t.runWebGLProgram(c,[n,s,a],"float32")},QF={kernelName:ei,backendName:"webgl",kernelFunc:rZ};var Ux=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=e;let n=e.length,s=t?"0.0": ` getX ( $ { eO ( n , "coords" ) } ) ` ,a=e[e.length-1],i="",l="";t?(i=o? ` end != $ { a - 1 } ` :"end != 0",l=o?"end + 1":"end - 1"):(i=o? ` end + pow2 < $ { a } ` :"end >= pow2",l=o?"end + pow2":"end - pow2"),this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float index ;
2020-12-02 22:46:41 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { Be ( n ) } coords = getOutputCoords ( ) ;
int end = $ { tO ( n , "coords" ) } ;
float val = $ { s } ;
2020-12-15 14:15:43 +01:00
int pow2 = int ( pow ( 2.0 , index ) ) ;
2021-01-12 16:01:34 +01:00
if ( $ { i } ) {
int idx = $ { l } ;
$ { tO ( n , "coords" ) } = idx ;
val += getX ( $ { eO ( n , "coords" ) } ) ;
2020-12-15 14:15:43 +01:00
}
setOutput ( val ) ;
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e){return(t,o)=>{this.index==null&&(this.index=t.getUniformLocation(o,"index")),t.gl.uniform1f(this.index,e)}}};function eO(r,e){if(r===1)return ` $ { e } ` ;if(r===2)return ` $ { e } . x , $ { e } . y ` ;if(r===3)return ` $ { e } . x , $ { e } . y , $ { e } . z ` ;if(r===4)return ` $ { e } . x , $ { e } . y , $ { e } . z , $ { e } . w ` ;throw Error( ` Cumulative sum for rank $ { r } is not yet supported ` )}function tO(r,e){if(r===1)return ` $ { e } ` ;if(r===2)return ` $ { e } . y ` ;if(r===3)return ` $ { e } . z ` ;if(r===4)return ` $ { e } . w ` ;throw Error( ` Cumulative sum for rank $ { r } is not yet supported ` )}function oZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o,l=n.shape.length,u=S.getAxesPermutation([s],l),c=n;u!=null&&(c=Bt({inputs:{x:n},backend:t,attrs:{perm:u}}));let p=S.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error( ` WebGL cumsum shader expects an inner - most axis = $ { n . shape . length - 1 } but got axis = $ { s } ` );let m=n.shape[p],f=Ht({inputs:{x:c},backend:t});for(let d=0;d<=Math.ceil(Math.log2(m))-1;d++){let h=new Ux(c.shape,!1,i),g=h.getCustomSetupFunc(d),y=f;f=t.runWebGLProgram(h,[f],f.dtype,g),t.disposeIntermediateTensorInfo(y)}if(a){let d=new Ux(c.shape,a,i),h=f;f=t.runWebGLProgram(d,[f],f.dtype),t.disposeIntermediateTensorInfo(h)}if(u!=null){let d=S.getUndoAxesPermutation(u),h=Bt({inputs:{x:f},backend:t,attrs:{perm:d}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(c),h}return f}var rO={kernelName:en,backendName:"webgl",kernelFunc:oZ};function nZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a,binaryOutput:i}=o;if(n.shape.length===1){let l=t.readSync(n.dataId),u=t.readSync(s.dataId),c= $ x(l,u,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,c)}else if(n.shape.length===2){let l=t.bufferSync(n),u=t.bufferSync(s),c=lR(l,u,a,i);return t.makeTensorInfo(c.shape,s.dtype,c.values)}throw new Error( ` Error in denseBincount : input must be at most rank 2 , but got rank$ { n . shape . length } . ` )}var oO={kernelName:Ql,backendName:"webgl",kernelFunc:nZ};var kC=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=o,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int h = $ { this . getHeightCoordString ( ) } ;
int w = $ { this . getWidthCoordString ( ) } ;
int d = $ { this . getDepthCoordString ( ) } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
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 ) *
2020-12-15 14:15:43 +01:00
$ { this . getOutputDepthSize ( ) } ;
int in _d = d + offset _d ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float result = $ { this . getInputSamplingString ( ) } ;
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01: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 sZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockSize:s,dataFormat:a}=o;x.assert(s>1,()=> ` blockSize should be > 1 for depthToSpace , but was : $ { s } ` );let i=n.shape[0],l=a==="NHWC"?n.shape[1]:n.shape[2],u=a==="NHWC"?n.shape[2]:n.shape[3],c=a==="NHWC"?n.shape[3]:n.shape[1],p=l*s,m=u*s,f=c/(s*s),d=a==="NHWC"?[i,p,m,f]:[i,f,p,m],h=new kC(d,s,a);return t.runWebGLProgram(h,[n],n.dtype)}var nO={kernelName:ti,backendName:"webgl",kernelFunc:sZ};var ih=class{constructor(e,t=!1,o=null,n=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.inHeight,i=e.inWidth,l=e.padInfo.top,u=e.padInfo.left,c=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,f=e.dilationWidth,d=e.filterHeight,h=e.filterWidth,g=e.outChannels/e.inChannels,y="",b="";o&&(n?y= ` float activation ( float a ) {
2020-12-15 14:15:43 +01:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { o }
} ` :s?y= ` float activation ( float a ) {
2020-12-15 14:15:43 +01:00
float b = getLeakyreluAlphaAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { o }
} ` :y= `
2020-12-15 14:15:43 +01:00
float activation ( float x ) {
2021-01-12 16:01:34 +01:00
$ { o }
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ,b="result = activation(result);");let _=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { y }
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
const ivec2 strides = ivec2 ( $ { c } , $ { p } ) ;
const ivec2 pads = ivec2 ( $ { l } , $ { u } ) ;
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
2021-01-12 16:01:34 +01:00
int d1 = d2 / $ { g } ;
int q = d2 - d1 * $ { g } ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { d } ; wR ++ ) {
int xR = xRCorner + wR * $ { m } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { a } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { h } ; wC ++ ) {
int xC = xCCorner + wC * $ { f } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { i } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2020-12-15 14:15:43 +01:00
float xVal = getX ( batch , xR , xC , d1 ) ;
float wVal = getW ( wR , wC , d1 , q ) ;
dotProd += xVal * wVal ;
2020-12-02 22:46:41 +01:00
}
}
2020-12-15 14:15:43 +01:00
float result = dotProd ;
2021-01-12 16:01:34 +01:00
$ { _ }
$ { b }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var ah=class{constructor(e,t=!1,o=null,n=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;let a=e.inHeight,i=e.inWidth,l=e.padInfo.top,u=e.padInfo.left,c=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,f=e.dilationWidth,d=e.filterHeight,h=e.filterWidth,g=h,y="int xR; int xC; int xCOffset;";for(let k=0;k<d;k++)for(let $ =0; $ <h; $ ++)y+= `
vec4 xTexelR$ { k } C$ { $ * 2 } = vec4 ( 0. ) ;
vec4 wR$ { k } C$ { $ } = vec4 ( 0. ) ;
vec4 xR$ { k } C$ { $ } = vec4 ( 0. ) ; ` ;for(let k=0;k<d;k++)for(let $ =0; $ <g; $ ++){let T= $ *2;if(y+= `
xR = xRCorner + $ { k * m } ;
xC = xCCorner + $ { T * f } ;
` ,p===1){if(T<h&&(u%2==1?y+= `
2020-12-15 14:15:43 +01:00
xCOffset = xC + 1 ;
2021-01-12 16:01:34 +01:00
if ( xR >= 0 && xR < $ { a } && xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { k } C$ { T } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
2021-01-12 16:01:34 +01:00
if ( xCOffset + 1 >= $ { i } ) {
xTexelR$ { k } C$ { T } . zw = vec2 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { k } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
xCOffset = xC + 1 - 2 ;
2021-01-12 16:01:34 +01:00
if ( xR >= 0 && xR < $ { a } && xCOffset >= 0 && xCOffset < $ { i } ) {
2020-12-15 14:15:43 +01:00
vec4 previous = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
2021-01-12 16:01:34 +01:00
if ( xCOffset + 1 >= $ { i } ) {
2020-12-15 14:15:43 +01:00
previous . zw = vec2 ( 0. ) ;
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
xR$ { k } C$ { T } = vec4 ( previous . zw , xTexelR$ { k } C$ { T } . xy ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xR$ { k } C$ { T } = vec4 ( 0 , 0 , xTexelR$ { k } C$ { T } . xy ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` :y+= `
if ( xR >= 0 && xR < $ { a } && xC >= 0 && xC < $ { i } ) {
xTexelR$ { k } C$ { T } = getX ( batch , xR , xC , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { k } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
xR$ { k } C$ { T } = xTexelR$ { k } C$ { T } ;
` ,T+1<h)){let F=u%2==0?x.nearestLargerEven(f):f;f%2==0&&u%2==1||f%2!=0&&u%2!=1?(y+= `
xCOffset = xC + $ { u % 2 } + $ { F } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR >= 0 && xR < $ { a } &&
xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { k } C$ { T + 2 } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ,f>1&&(y+= `
2020-12-15 14:15:43 +01:00
xCOffset -= 2 ;
2021-01-12 16:01:34 +01:00
if ( xR >= 0 && xR < $ { a } &&
xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { k } C$ { T } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { k } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ),y+= `
xR$ { k } C$ { T + 1 } = vec4 (
xTexelR$ { k } C$ { T } . zw , xTexelR$ { k } C$ { T + 2 } . xy ) ;
` ):y+= `
xCOffset = xC + $ { F } ;
if ( xR >= 0 && xR < $ { a } &&
xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { k } C$ { T + 2 } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
xR$ { k } C$ { T + 1 } = xTexelR$ { k } C$ { T + 2 } ;
` }}else T<h&&(y+= `
if ( xR >= 0 && xR < $ { a } ) {
` ,u%2==1?(y+= `
xCOffset = xC + 1 - $ { p } ;
if ( xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { k } C$ { T } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { k } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xC + 1 >= 0 && xC + 1 < $ { i } ) {
xTexelR$ { k } C$ { T + 2 } = getX ( batch , xR , xC + 1 , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { k } C$ { T + 2 } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
xR$ { k } C$ { T } = vec4 (
xTexelR$ { k } C$ { T } . zw , xTexelR$ { k } C$ { T + 2 } . zw ) ;
` ,T+1<h&&(y+= `
2020-12-15 14:15:43 +01:00
vec4 final = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
xCOffset = xC + 1 + $ { p } ;
if ( xCOffset >= 0 && xCOffset < $ { i } ) {
2020-12-15 14:15:43 +01:00
final = getX ( batch , xR , xCOffset , d1 ) ;
}
2021-01-12 16:01:34 +01:00
xR$ { k } C$ { T + 1 } = vec4 ( xTexelR$ { k } C$ { T + 2 } . xy , final . xy ) ;
` )):(y+= `
if ( xC >= 0 && xC < $ { i } ) {
xTexelR$ { k } C$ { T } = getX ( batch , xR , xC , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { k } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
xCOffset = xC + $ { p } ;
if ( xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { k } C$ { T + 2 } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { k } C$ { T + 2 } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
xR$ { k } C$ { T } = vec4 (
xTexelR$ { k } C$ { T } . xy , xTexelR$ { k } C$ { T + 2 } . xy ) ;
` ,T+1<h&&(y+= `
xR$ { k } C$ { T + 1 } = vec4 (
xTexelR$ { k } C$ { T } . zw , xTexelR$ { k } C$ { T + 2 } . zw ) ;
` )),y+="}");T<h&&(y+= `
vec4 wTexelR$ { k } C$ { T } = getW ( $ { k } , $ { T } , d1 , q ) ;
wR$ { k } C$ { T } = vec4 ( wTexelR$ { k } C$ { T } . xz , wTexelR$ { k } C$ { T } . xz ) ;
` ,T+1<h&&(y+= `
vec4 wTexelR$ { k } C$ { T + 1 } = getW ( $ { k } , $ { T + 1 } , d1 , q ) ;
wR$ { k } C$ { T + 1 } =
vec4 ( wTexelR$ { k } C$ { T + 1 } . xz , wTexelR$ { k } C$ { T + 1 } . xz ) ; ` ))}for(let k=0;k<d;k++)for(let $ =0; $ <h; $ ++)y+= ` dotProd += xR$ { k } C$ { $ } * wR$ { k } C$ { $ } ; ` ;let b="",_="";o&&(n?b= ` vec4 activation ( vec4 a ) {
2020-12-15 14:15:43 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { o }
} ` :s?b= ` vec4 activation ( vec4 a ) {
2020-12-15 14:15:43 +01:00
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { o }
} ` :b= ` vec4 activation ( vec4 x ) {
$ { o }
} ` ,_="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { b }
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
const ivec2 strides = ivec2 ( $ { c } , $ { p } ) ;
const ivec2 pads = ivec2 ( $ { l } , $ { u } ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
int d1 = d2 ;
int q = 0 ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
vec4 dotProd = vec4 ( 0. ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { y }
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
vec4 result = dotProd ;
2021-01-12 16:01:34 +01:00
$ { w }
$ { _ }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function iZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l,dimRoundingMode:u}=o,c=l;c==null&&(c=[1,1]),x.assert(S.eitherStridesOrDilationsAreOne(a,c),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { a } and dilations '${c}' ` );let p=S.computeConv2DInfo(n.shape,s.shape,a,c,i,u,!0),m;return W().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?m=new ah(p):m=new ih(p),t.runWebGLProgram(m,[n,s],"float32")}var sO={kernelName:tn,backendName:"webgl",kernelFunc:iZ};var CC=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,o=e.strideWidth,n=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int dm = coords . w ;
2021-01-12 16:01:34 +01:00
int d2 = d1 * $ { a } + dm ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float dotProd = 0.0 ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// TO DO: Vec4 over the batch size
2021-01-12 16:01:34 +01:00
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { t } - $ { n } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-02 22:46:41 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { o } - $ { s } ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float dyValue = getDy ( b , yR , yC , d2 ) ;
float xValue = getX ( b , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
2020-12-02 22:46:41 +01:00
}
}
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }},IC=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,o=e.filterWidth,n=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,i=o-1-e.padInfo.left,l=e.outChannels/e.inChannels;this.userCode= `
const ivec2 pads = ivec2 ( $ { a } , $ { i } ) ;
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int batch = coords [ 0 ] ;
int d1 = coords [ 3 ] ;
ivec2 dyCorner = coords . yz - pads ;
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float dotProd = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { n } . 0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2020-12-15 14:15:43 +01:00
continue ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
int idyR = int ( dyR ) ;
2021-01-12 16:01:34 +01:00
int wRPerm = $ { t } - 1 - wR ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { o } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { s } . 0 ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2021-01-12 16:01:34 +01:00
int wCPerm = $ { o } - 1 - wC ;
2020-12-15 14:15:43 +01:00
// TO DO: Vec4 over the channelMul
2021-01-12 16:01:34 +01:00
for ( int dm = 0 ; dm < $ { l } ; dm ++ ) {
int d2 = d1 * $ { l } + dm ;
2020-12-15 14:15:43 +01:00
float xValue = getDy ( batch , idyR , idyC , d2 ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , dm ) ;
dotProd += xValue * wValue ;
2020-12-02 22:46:41 +01:00
}
}
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }};function aZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=o,p=S.computeConv2DInfo(n.shape,c,a,i,l,u,!0),m=new CC(p);return t.runWebGLProgram(m,[n,s],"float32")}var iO={kernelName:eu,backendName:"webgl",kernelFunc:aZ};function lZ(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=o,p=S.computeConv2DInfo(c,s.shape,a,i,l,u,!0),m=new IC(p);return t.runWebGLProgram(m,[n,s],"float32")}var aO={kernelName:tu,backendName:"webgl",kernelFunc:lZ};var NC=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
float val = coords [ 0 ] == coords [ 1 ] ? getX ( coords [ 0 ] ) : 0.0 ;
setOutput ( val ) ;
}
2021-01-12 16:01:34 +01:00
` }};function uZ(r){let{inputs:e,backend:t}=r,{x:o}=e,n=[...o.shape,...o.shape],s=x.sizeFromShape(o.shape),a=me({inputs:{x:o},backend:t,attrs:{shape:[s]}}),i=new NC(s),l=t.runWebGLProgram(i,[a],a.dtype),u=me({inputs:{x:l},backend:t,attrs:{shape:n}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(l),u}var lO={kernelName:ru,backendName:"webgl",kernelFunc:uZ};var SC=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:o,padInfo:n,strideHeight:s,strideWidth:a,filterHeight:i,filterWidth:l,dilationHeight:u,dilationWidth:c}=e,{top:p,left:m}=n;this.userCode= `
const ivec2 strides = ivec2 ( $ { s } , $ { a } ) ;
const ivec2 pads = ivec2 ( $ { p } , $ { m } ) ;
2020-12-15 14:15:43 +01:00
const float neg _infinity = - 3.4 e38 ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d1 = coords . w ;
ivec2 outTopLeftCorner =
coords . yz * strides - pads ;
int hBeg = outTopLeftCorner . x ;
int wBeg = outTopLeftCorner . y ;
float curVal = neg _infinity ;
2021-01-12 16:01:34 +01:00
for ( int h = 0 ; h < $ { i } ; h ++ ) {
int hIn = hBeg + h * $ { u } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( hIn >= 0 && hIn < $ { t } ) {
for ( int w = 0 ; w < $ { l } ; w ++ ) {
int wIn = wBeg + w * $ { c } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( wIn >= 0 && wIn < $ { o } ) {
2020-12-15 14:15:43 +01:00
float xVal = getX ( batch , hIn , wIn , d1 ) ;
float wVal = getW ( h , w , d1 ) ;
float val = xVal + wVal ;
if ( val > curVal ) {
curVal = val ;
}
}
2020-12-02 22:46:41 +01:00
}
}
}
2020-12-15 14:15:43 +01:00
float result = curVal ;
setOutput ( result ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function cZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o,u=S.computeDilation2DInfo(n.shape,s.shape,a,i,"NHWC",l),c,p=new SC(u);c=t.runWebGLProgram(p,[n,s],"float32");let m=me({inputs:{x:c},backend:t,attrs:{shape:u.outShape}});return t.disposeIntermediateTensorInfo(c),m}var uO={kernelName:la,backendName:"webgl",kernelFunc:cZ};var pZ="return (x >= 0.0) ? x : (exp(x) - 1.0);",mZ= `
2020-12-15 14:15:43 +01:00
vec4 result ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
result . r = ( x . r >= 0.0 ) ? x . r : ( exp ( x . r ) - 1.0 ) ;
result . g = ( x . g >= 0.0 ) ? x . g : ( exp ( x . g ) - 1.0 ) ;
result . b = ( x . b >= 0.0 ) ? x . b : ( exp ( x . b ) - 1.0 ) ;
result . a = ( x . a >= 0.0 ) ? x . a : ( exp ( x . a ) - 1.0 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,fZ=Ce({opSnippet:pZ,packedOpSnippet:mZ}),cO={kernelName:ri,backendName:"webgl",kernelFunc:fZ};var dZ="return (b >= 1.0) ? a : a * (b + 1.0);",hZ= `
2020-12-15 14:15:43 +01:00
vec4 bGTEZero = vec4 ( greaterThanEqual ( b , vec4 ( 0. ) ) ) ;
return ( bGTEZero * a ) + ( ( vec4 ( 1.0 ) - bGTEZero ) * ( a * ( b + vec4 ( 1.0 ) ) ) ) ;
2021-01-12 16:01:34 +01:00
` ,gZ=r=>{let{inputs:e,backend:t}=r,{dy:o,y:n}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bs(hZ,o.shape,n.shape):new ts(dZ,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)},pO={kernelName:ou,backendName:"webgl",kernelFunc:gZ};var xZ= `
2020-12-15 14:15:43 +01:00
return vec4 ( equal ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` ,yZ="return float(a == b);",bZ=at({opSnippet:yZ,packedOpSnippet:xZ,dtype:"bool"}),mO={kernelName:ni,backendName:"webgl",kernelFunc:bZ};var _Z= `
2020-12-15 14:15:43 +01:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2021-01-12 16:01:34 +01:00
float p = $ { S . ERF _P } ;
float a1 = $ { S . ERF _A1 } ;
float a2 = $ { S . ERF _A2 } ;
float a3 = $ { S . ERF _A3 } ;
float a4 = $ { S . ERF _A4 } ;
float a5 = $ { S . ERF _A5 } ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +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 ) ) ;
2021-01-12 16:01:34 +01:00
` ,wZ=Ce({opSnippet:_Z}),fO={kernelName:oi,backendName:"webgl",kernelFunc:wZ};var dO="return exp(x);",TC=Ce({opSnippet:dO,packedOpSnippet:dO,cpuKernelImpl:pR}),hO={kernelName:on,backendName:"webgl",kernelFunc:TC};function jx(r){let{inputs:e,attrs:t,backend:o}=r,{dim:n}=t,{input:s}=e,a=s.shape.length,i=s.shape.slice(),l=n;return n<0&&(x.assert(-(a+1)<=n,()=> ` Axis must be in the interval [ $ { - ( a + 1 ) } , $ { a } ] ` ),l=a+n+1),i.splice(l,0,1),me({inputs:{x:s},backend:o,attrs:{shape:i}})}var gO={kernelName:ls,backendName:"webgl",kernelFunc:jx};var xO="return exp(x) - 1.0;",vZ=Ce({opSnippet:xO,packedOpSnippet:xO,cpuKernelImpl:mR}),yO={kernelName:si,backendName:"webgl",kernelFunc:vZ};var qx=class{constructor(e,t,o){this.variableNames=["real","imag"];let n=t[1];this.outputShape=t;let s=o? ` 2.0 * $ { Math . PI } ` : ` - 2.0 * $ { Math . PI } ` ,a=o? ` $ { n } . 0 ` :"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error( ` FFT component must be either "real" or "imag" , got $ { e } . ` );this.userCode= `
const float exponentMultiplier = $ { s } ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float unaryOpComplex ( float real , float expR , float imag , float expI ) {
2021-01-12 16:01:34 +01:00
$ { i }
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float mulMatDFT ( int batch , int index ) {
2021-01-12 16:01:34 +01:00
float indexRatio = float ( index ) / float ( $ { n } ) ;
2020-12-15 14:15:43 +01:00
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float result = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { n } ; i ++ ) {
2020-12-15 14:15:43 +01:00
// 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-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
result +=
2021-01-12 16:01:34 +01:00
unaryOpComplex ( real , expR , imag , expI ) / $ { a } ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
return result ;
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
setOutput ( mulMatDFT ( coords [ 0 ] , coords [ 1 ] ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};function Hx(r,e,t){let o=t.texData.get(r.dataId),n=x.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],a=n/s,l=me({inputs:{x:r},backend:t,attrs:{shape:[a,s]}}).shape,u=new qx("real",l,e),c=new qx("imag",l,e),p=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:l},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:l}],m=t.runWebGLProgram(u,p,"float32"),f=t.runWebGLProgram(c,p,"float32"),d=fo({inputs:{real:m,imag:f},backend:t});t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f);let h=me({inputs:{x:d},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(h),h}function kZ(r){let{inputs:e,backend:t}=r,{input:o}=e;return Hx(o,!1,t)}var bO={kernelName:nu,backendName:"webgl",kernelFunc:kZ};var EC=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float value ;
void main ( ) {
// Input can be obtained from uniform value.
setOutput ( value ) ;
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e){return(t,o)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(o,"value")),t.gl.uniform1f(this.valueLoc,e)}}};function lh(r){let{backend:e,attrs:t}=r,{shape:o,value:n}=t,{dtype:s}=t;if(s=s||x.inferDtype(n),s==="string"){let a=x.getArrayFromDType(s,x.sizeFromShape(o));return a.fill(n),e.makeTensorInfo(o,s,a)}else{let a=new EC(o,n),i=a.getCustomSetupFunc(n);return e.runWebGLProgram(a,[],s,i)}}var _O={kernelName:ua,backendName:"webgl",kernelFunc:lh};var AC=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
int coordX = $ { t } - x ;
2020-12-15 14:15:43 +01:00
float outputValue ;
2021-01-12 16:01:34 +01:00
if ( coordX >= 0 && coordX < $ { t } ) {
2020-12-15 14:15:43 +01:00
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coordX , coords [ 3 ] ) ;
} else {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coords [ 2 ] , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
}
2021-01-12 16:01:34 +01:00
` }};var wO={kernelName:ii,backendName:"webgl",kernelFunc:({inputs:r,backend:e})=>{let{image:t}=r,o=e,n=new AC(t.shape);return o.runWebGLProgram(n,[t],t.dtype)}};var vO="return floor(x);",CZ=Ce({opSnippet:vO,packedOpSnippet:vO,cpuKernelImpl:fR}),kO={kernelName:nn,backendName:"webgl",kernelFunc:CZ};var IZ= `
2020-12-15 14:15:43 +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-01-12 16:01:34 +01:00
` ,NZ= `
2020-12-15 14:15:43 +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 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if ( cond [ 0 ] ) {
result [ 0 ] = idiv ( ia [ 0 ] , ib [ 0 ] , s [ 0 ] ) ;
}
if ( cond [ 1 ] ) {
result [ 1 ] = idiv ( ia [ 1 ] , ib [ 1 ] , s [ 1 ] ) ;
}
if ( cond [ 2 ] ) {
result [ 2 ] = idiv ( ia [ 2 ] , ib [ 2 ] , s [ 2 ] ) ;
}
if ( cond [ 3 ] ) {
result [ 3 ] = idiv ( ia [ 3 ] , ib [ 3 ] , s [ 3 ] ) ;
}
return vec4 ( result ) ;
2021-01-12 16:01:34 +01:00
` ,SZ=at({opSnippet:IZ,packedOpSnippet:NZ,dtype:"int32"}),CO={kernelName:sn,backendName:"webgl",kernelFunc:SZ};var DC=class{constructor(e){this.variableNames=["A"];let t=zt(),[o,n]=e;this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
2021-01-12 16:01:34 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { n } . 0 , $ { o } . 0 ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
vec4 values = $ { t . texture2D } ( A , uv ) ;
2020-12-15 14:15:43 +01:00
float value ;
if ( depth == 0 ) {
value = values . r ;
} else if ( depth == 1 ) {
value = values . g ;
} else if ( depth == 2 ) {
value = values . b ;
} else if ( depth == 3 ) {
value = values . a ;
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
setOutput ( floor ( value * 255.0 + 0.5 ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};var $ C=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=zt(),[o,n]=e;this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
vec4 result = vec4 ( 0. ) ;
for ( int row = 0 ; row <= 1 ; row ++ ) {
for ( int col = 0 ; col <= 1 ; col ++ ) {
texC = coords [ 1 ] + row ;
depth = coords [ 2 ] + col ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { n } . 0 , $ { o } . 0 ) ;
vec4 values = $ { t . texture2D } ( A , uv ) ;
2020-12-15 14:15:43 +01:00
float value ;
if ( depth == 0 ) {
value = values . r ;
} else if ( depth == 1 ) {
value = values . g ;
} else if ( depth == 2 ) {
value = values . b ;
} else if ( depth == 3 ) {
value = values . a ;
}
result [ row * 2 + col ] = floor ( value * 255.0 + 0.5 ) ;
}
}
2021-01-12 16:01:34 +01:00
$ { t . output } = result ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var IO={kernelName:Pc,backendName:"webgl",kernelFunc:TZ},qp;function TZ(r){let{inputs:e,backend:t,attrs:o}=r,{pixels:n}=e,{numChannels:s}=o,a=typeof HTMLVideoElement!="undefined"&&n instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement,l=typeof ImageBitmap!="undefined"&&n instanceof ImageBitmap,[u,c]=a?[n.videoWidth,n.videoHeight]:[n.width,n.height],p=[c,u],m=[c,u,s];(i||a||l)&&(qp==null&&(qp=document.createElement("canvas").getContext("2d")),qp.canvas.width=u,qp.canvas.height=c,qp.drawImage(n,0,0,u,c),n=qp.canvas);let f=t.makeTensorInfo(p,"int32");t.texData.get(f.dataId).usage=Dr.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(f.dataId),n);let d=W().getBool("WEBGL_PACK")?new $ C(m):new DC(m),h=t.runWebGLProgram(d,[f],"int32");return t.disposeData(f.dataId),h}function EZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=o,h=S.convertConv2DDataFormat(c),g=S.computeConv2DInfo(n.shape,s.shape,l,p,u,m,!1,h),y,b=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))y=Wx({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else if(W().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)y=Gx({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else{let w=a!=null,k=i!=null, $ =f==="leakyrelu",T=f?Dl(f,!1):null,F=new sh(g,w,T,k, $ ),M=[n,s];if(a&&M.push(a),i&&M.push(i), $ ){let L=t.makeTensorInfo([],"float32",x.createScalarValue(d,"float32"));M.push(L),b.push(L)}y=t.runWebGLProgram(F,M,"float32")}let _=me({inputs:{x:y},backend:t,attrs:{shape:g.outShape}});return b.push(y),b.forEach(w=>t.disposeIntermediateTensorInfo(w)),_}var NO={kernelName:ws,backendName:"webgl",kernelFunc:EZ};function AZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dimRoundingMode:p,activation:m,leakyreluAlpha:f}=o,d=[],h=c;h==null&&(h=[1,1]),x.assert(S.eitherStridesOrDilationsAreOne(l,h),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { l } and dilations '${h}' ` );let g=S.computeConv2DInfo(n.shape,s.shape,l,h,u,p,!0),y=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=m?Dl(m,y):null,_=[n,s],w=a!=null,k=i!=null, $ =m==="leakyrelu";if(w&&_.push(a),k&&_.push(i), $ ){let M=t.makeTensorInfo([],"float32",x.createScalarValue(f,"float32"));_.push(M),d.push(M)}let T;y?T=new ah(g,w,b,k, $ ):T=new ih(g,w,b,k, $ );let F=t.runWebGLProgram(T,_,"float32");return d.forEach(M=>t.disposeIntermediateTensorInfo(M)),F}var SO={kernelName:vs,backendName:"webgl",kernelFunc:AZ};var RC=class{constructor(e,t,o){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=o;let n=Be(t.length),s=Be(o.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode= `
$ { n } strides = $ { n } ( $ { this . strides } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { s } coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int flattenIndex = 0 ;
for ( int j = 0 ; j < $ { this . sliceDim } ; j ++ ) {
int index = round ( getIndices ( coords [ 0 ] , j ) ) ;
2021-01-12 16:01:34 +01:00
flattenIndex += index * $ { a } ;
2020-12-15 14:15:43 +01:00
}
setOutput ( getX ( flattenIndex , coords [ 1 ] ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};function DZ(r){let{inputs:e,backend:t}=r,{params:o,indices:n}=e,s=n.shape,a=s[s.length-1],[i,l,u,c]=S.prepareAndValidate(o,n),p=me({inputs:{x:n},backend:t,attrs:{shape:[l,a]}}),m=me({inputs:{x:o},backend:t,attrs:{shape:[x.sizeFromShape(o.shape)/u,u]}}),f=new RC(a,c,[l,u]),d=t.runWebGLProgram(f,[m,p],m.dtype),h=me({inputs:{x:d},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(d),h}var TO={kernelName:ai,backendName:"webgl",kernelFunc:DZ};var FC=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let o=Be(this.rank),n= $ Z(e,2);this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { o } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { n } ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function $ Z(r,e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[];for(let n=0;n<r.length;n++)n===2?o.push("int(getIndices(resRC.x, resRC.z))"):o.push( ` $ { t [ n ] } ` );return o.join()}function RZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,indices:s}=e,{axis:a,batchDims:i}=o,l=x.parseAxisParam(a,n.shape)[0],u=S.segment_util.collectGatherOpShapeInfo(n,s,l,i),c=x.sizeFromShape(s.shape),p=[],m=me({inputs:{x:n},backend:t,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),f=me({inputs:{x:s},backend:t,attrs:{shape:[u.batchSize,c/u.batchSize]}});p.push(m),p.push(f);let d=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(t.shouldExecuteOnCPU([n,s])||n.dtype==="string"){let b=t.bufferSync(f),_=t.bufferSync(m),w=dR(_,b,d);return p.forEach(k=>t.disposeIntermediateTensorInfo(k)),t.makeTensorInfo(u.outputShape,w.dtype,w.values)}let h=new FC(m.shape,d),g=t.runWebGLProgram(h,[m,f],m.dtype);p.push(g);let y=me({inputs:{x:g},backend:t,attrs:{shape:u.outputShape}});return p.forEach(b=>t.disposeIntermediateTensorInfo(b)),y}var EO={kernelName:us,backendName:"webgl",kernelFunc:RZ};var FZ="return float(a > b);",OZ= `
2020-12-15 14:15:43 +01:00
return vec4 ( greaterThan ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` ,PZ=at({opSnippet:FZ,packedOpSnippet:OZ,cpuKernelImpl:hR,dtype:"bool"}),AO={kernelName:li,backendName:"webgl",kernelFunc:PZ};var MZ="return float(a >= b);",LZ= `
2020-12-15 14:15:43 +01:00
return vec4 ( greaterThanEqual ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` ,zZ=at({opSnippet:MZ,packedOpSnippet:LZ,dtype:"bool"}),DO={kernelName:ln,backendName:"webgl",kernelFunc:zZ};function BZ(r){let{inputs:e,backend:t}=r,{input:o}=e;return Hx(o,!0,t)}var $ O={kernelName:su,backendName:"webgl",kernelFunc:BZ};var VZ="return float(!isnan(x) && !isinf(x));",WZ=Ce({opSnippet:VZ,dtype:"bool"}),RO={kernelName:ui,backendName:"webgl",kernelFunc:WZ};var GZ="return float(isinf(x));",UZ=Ce({opSnippet:GZ,dtype:"bool"}),FO={kernelName:ci,backendName:"webgl",kernelFunc:UZ};var jZ="return float(isnan(x));",qZ=Ce({opSnippet:jZ,dtype:"bool"}),OO={kernelName:pi,backendName:"webgl",kernelFunc:qZ};var HZ="return float(a < b);",KZ= `
2020-12-15 14:15:43 +01:00
return vec4 ( lessThan ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` ,XZ=at({opSnippet:HZ,packedOpSnippet:KZ,cpuKernelImpl:gR,dtype:"bool"}),PO={kernelName:mi,backendName:"webgl",kernelFunc:XZ};var YZ="return float(a <= b);",ZZ= `
2020-12-15 14:15:43 +01:00
return vec4 ( lessThanEqual ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` ,JZ=at({opSnippet:YZ,packedOpSnippet:ZZ,dtype:"bool"}),MO={kernelName:fi,backendName:"webgl",kernelFunc:JZ};function QZ(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=xR(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var LO={kernelName:au,backendName:"webgl",kernelFunc:QZ};var e9= ` if ( x < 0.0 ) return NAN ;
return log ( x ) ; ` ,t9= `
2020-12-15 14:15:43 +01:00
vec4 result = log ( x ) ;
vec4 isNaN = vec4 ( lessThan ( x , vec4 ( 0.0 ) ) ) ;
result . r = isNaN . r == 1.0 ? NAN : result . r ;
result . g = isNaN . g == 1.0 ? NAN : result . g ;
result . b = isNaN . b == 1.0 ? NAN : result . b ;
result . a = isNaN . a == 1.0 ? NAN : result . a ;
return result ;
2021-01-12 16:01:34 +01:00
` ,r9=Ce({opSnippet:e9,packedOpSnippet:t9,cpuKernelImpl:yR}),zO={kernelName:cn,backendName:"webgl",kernelFunc:r9};var o9="return log(1.0 + x);",n9=Ce({opSnippet:o9}),BO={kernelName:di,backendName:"webgl",kernelFunc:n9};var s9="return float(a >= 1.0 && b >= 1.0);",i9= `
2020-12-15 14:15:43 +01:00
return vec4 (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) *
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ) ;
2021-01-12 16:01:34 +01:00
` ,a9=at({opSnippet:s9,packedOpSnippet:i9,dtype:"bool"}),VO={kernelName:hi,backendName:"webgl",kernelFunc:a9};var l9="return float(!(x >= 1.0));",u9=Ce({opSnippet:l9}),WO={kernelName:Qa,backendName:"webgl",kernelFunc:u9};var c9="return float(a >= 1.0 || b >= 1.0);",p9= `
2020-12-15 14:15:43 +01:00
return min (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) +
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ,
vec4 ( 1.0 ) ) ;
2021-01-12 16:01:34 +01:00
` ,m9=at({opSnippet:c9,packedOpSnippet:p9,dtype:"bool"}),GO={kernelName:el,backendName:"webgl",kernelFunc:m9};var OC=class{constructor(e,t,o,n,s){this.variableNames=["x"],this.outputShape=[];let a=t,i=e[3]-1;this.outputShape=e;let l,u= ` float ( $ { o } ) + float ( $ { n } ) * sum ` ;s===.5?l= ` inversesqrt ( $ { u } ) ` :s===1?l= ` 1.0 / ( $ { u } ) ` :l= ` exp ( log ( $ { u } ) * float ( - $ { s } ) ) ; ` ,this.userCode= `
2020-12-15 14:15:43 +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 ;
2021-01-12 16:01:34 +01:00
for ( int j = - $ { a } ; j <= $ { a } ; j ++ ) {
2020-12-15 14:15:43 +01:00
int idx = d + j ;
2021-01-12 16:01:34 +01:00
if ( idx >= 0 && idx <= $ { i } ) {
2020-12-15 14:15:43 +01:00
float z = getX ( b , r , c , idx ) ;
sum += z * z ;
}
}
2021-01-12 16:01:34 +01:00
float val = x * $ { l } ;
2020-12-15 14:15:43 +01:00
setOutput ( val ) ;
}
2021-01-12 16:01:34 +01:00
` }};var PC=class{constructor(e,t,o,n,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,i=e[3]-1;this.outputShape=e;let l,u= ` float ( $ { o } ) + float ( $ { n } ) * sum ` ;s===.5?l= ` inversesqrt ( $ { u } ) ` :s===1?l= ` 1.0 / ( $ { u } ) ` :l= ` exp ( log ( $ { u } ) * float ( - $ { s } ) ) ; ` ,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords . x ;
int r = coords . y ;
int c = coords . z ;
int d = coords . w ;
bool hasNextCol = d < $ { this . outputShape [ 3 ] } ;
bool hasNextRow = c < $ { this . outputShape [ 2 ] } ;
vec4 sum = vec4 ( 0. ) ;
vec4 xFragAtOutputCoords = getX ( b , r , c , d ) ;
vec4 xAtOutputCoords = vec4 (
getChannel ( xFragAtOutputCoords , vec2 ( c , d ) ) ,
hasNextCol ?
getChannel ( xFragAtOutputCoords , vec2 ( c , d + 1 ) ) : 0.0 ,
hasNextRow ?
getChannel ( xFragAtOutputCoords , vec2 ( c + 1 , d ) ) : 0.0 ,
( hasNextRow && hasNextCol ) ?
getChannel ( xFragAtOutputCoords , vec2 ( c + 1 , d + 1 ) ) : 0.0
) ;
2021-01-12 16:01:34 +01:00
int firstChannel = d - $ { a } ;
2020-12-15 14:15:43 +01:00
vec2 cache = vec2 ( 0. ) ;
if ( firstChannel >= 0 ) {
vec4 firstChannelFrag = getX ( b , r , c , firstChannel ) ;
cache . x = getChannel ( firstChannelFrag , vec2 ( c , firstChannel ) ) ;
if ( hasNextRow ) {
cache . y = getChannel ( firstChannelFrag , vec2 ( c + 1 , firstChannel ) ) ;
}
}
ivec2 depth = ivec2 ( d , d + 1 ) ;
2021-01-12 16:01:34 +01:00
for ( int j = - $ { a } ; j <= $ { a } ; j ++ ) {
2020-12-15 14:15:43 +01:00
ivec2 idx = depth + j ;
bvec2 aboveLowerBound = greaterThanEqual ( idx , ivec2 ( 0 ) ) ;
2021-01-12 16:01:34 +01:00
bvec2 belowUpperBound = lessThanEqual ( idx , ivec2 ( $ { i } ) ) ;
2020-12-15 14:15:43 +01:00
bool depthInRange = aboveLowerBound . x && belowUpperBound . x ;
bool depthPlusOneInRange = aboveLowerBound . y && belowUpperBound . y ;
if ( depthInRange || depthPlusOneInRange ) {
vec4 z = vec4 ( 0. ) ;
vec4 xFragAtCurrentDepth ;
z . xz = cache . xy ;
if ( depthPlusOneInRange && hasNextCol ) {
xFragAtCurrentDepth = idx . y != d ?
getX ( b , r , c , idx . y ) : xFragAtOutputCoords ;
z . y = getChannel ( xFragAtCurrentDepth , vec2 ( c , idx . y ) ) ;
if ( hasNextRow ) {
z . w = getChannel ( xFragAtCurrentDepth , vec2 ( c + 1 , idx . y ) ) ;
}
}
cache . xy = z . yw ;
sum += z * z ;
}
}
2021-01-12 16:01:34 +01:00
vec4 result = xAtOutputCoords * $ { l } ;
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};var f9=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{depthRadius:s,bias:a,alpha:i,beta:l}=o,u=W().getBool("WEBGL_PACK_NORMALIZATION")?new PC(n.shape,s,a,i,l):new OC(n.shape,s,a,i,l);return t.runWebGLProgram(u,[n],n.dtype)},UO={kernelName:ca,backendName:"webgl",kernelFunc:f9};var MC=class{constructor(e,t,o,n,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=o,this.alpha=n,this.beta=s,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
float result = 0.0 ;
for ( int d = 0 ; d < $ { this . depth } ; ++ d ) {
2021-01-12 16:01:34 +01:00
int depthBegin = int ( max ( 0.0 , float ( d - $ { t } ) ) ) ;
2020-12-15 14:15:43 +01:00
int depthEnd = int ( min ( float ( $ { this . depth } ) ,
2021-01-12 16:01:34 +01:00
float ( d + $ { t } + 1 ) ) ) ;
2020-12-15 14:15:43 +01:00
const int MIN _DEPTH _BEGIN = 0 ;
const int MAX _DEPTH _END = $ { this . depth } ;
float norm = 0.0 ;
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
norm += getInputImage ( b , r , c , k ) * getInputImage ( b , r , c , k ) ;
}
else {
break ;
}
}
2021-01-12 16:01:34 +01:00
norm = float ( $ { n } ) * norm + float ( $ { o } ) ;
2020-12-15 14:15:43 +01:00
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
2021-01-12 16:01:34 +01:00
float dyi = - 2.0 * float ( $ { n } )
* float ( $ { s } )
2020-12-15 14:15:43 +01:00
* getInputImage ( b , r , c , k ) * getOutputImage ( b , r , c , d )
/ n o r m ;
if ( k == d ) {
2021-01-12 16:01:34 +01:00
dyi += pow ( norm , - 1.0 * $ { s } ) ;
2020-12-15 14:15:43 +01:00
}
if ( k == coords [ 3 ] ) {
dyi *= getDy ( b , r , c , d ) ;
result += dyi ;
}
}
else {
break ;
}
}
}
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};var d9=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n,y:s,dy:a}=e,{depthRadius:i,bias:l,alpha:u,beta:c}=o,p=new MC(n.shape,i,l,u,c);return t.runWebGLProgram(p,[n,s,a],n.dtype)},jO={kernelName:lu,backendName:"webgl",kernelFunc:d9};function qO(r,e,t,o){let n=x.sizeFromShape(e),a=x.sizeFromShape(r.shape)/n,i=me({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),l=So(i,r.dtype,"max",o),u=me({inputs:{x:l},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(l),u}function LC(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reductionIndices:s,keepDims:a}=o,i=n.shape.length,l=x.parseAxisParam(s,n.shape),u=l,c=S.getAxesPermutation(u,i),p=c!=null,m=t.shouldExecuteOnCPU([n]),f=n;if(p){if(m){let _=t.texData.get(f.dataId).values,w=new Array(i);for(let T=0;T<w.length;T++)w[T]=n.shape[c[T]];let k=jp(_,n.shape,n.dtype,c,w);f=t.makeTensorInfo(w,n.dtype);let $ =t.texData.get(f.dataId); $ .values=k}else f= $ l(n,c,t);u=S.getInnerMostAxes(u.length,i)}S.assertAxesAreInnerMostDims("max",u,i);let[d,h]=S.computeOutAndReduceShapes(f.shape,u),g=d;a&&(g=S.expandShapeToKeepDim(d,l));let y;if(m){let _=t.texData.get(f.dataId).values,w=bR(_,x.sizeFromShape(h),g,n.dtype);y=t.makeTensorInfo(g,n.dtype);let k=t.texData.get(y.dataId);k.values=w}else y=qO(f,h,g,t);return p&&t.disposeIntermediateTensorInfo(f),y}var HO={kernelName:pn,backendName:"webgl",kernelFunc:LC};var h9=Ox+ `
2020-12-15 14:15:43 +01:00
return max ( a , b ) ;
2021-01-12 16:01:34 +01:00
` ,g9= `
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( max ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2021-01-12 16:01:34 +01:00
` +Al+ `
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,x9=at({opSnippet:h9,packedOpSnippet:g9,cpuKernelImpl:_R}),KO={kernelName:mn,backendName:"webgl",kernelFunc:x9};function y9(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;Xi(n,"maxPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;x.assert(S.eitherStridesOrDilationsAreOne(a,u),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { a } and dilations '${u}' ` );let c=S.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))return Ht({inputs:{x:n},backend:t});let p=new Yi(c,"max",!1);return t.runWebGLProgram(p,[n],n.dtype)}var XO={kernelName:fn,backendName:"webgl",kernelFunc:y9};function b9(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dataFormat:l,dimRoundingMode:u}=o,c=[1,1,1],p=S.computePool3DInfo(n.shape,s,a,c,i,u,l),m=new mc(p,"max",!1);return t.runWebGLProgram(m,[n],n.dtype)}var YO={kernelName:pa,backendName:"webgl",kernelFunc:b9};var zC=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,o=e.strideWidth,n=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=s-1-e.padInfo.top,l=a-1-e.padInfo.left,u=s*a-1;this.userCode= `
const ivec2 pads = ivec2 ( $ { i } , $ { l } ) ;
2020-12-15 14:15:43 +01:00
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 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { s } ;
wR += $ { n } ) {
float dyR = float ( dyRCorner + wR ) / $ { t } . 0 ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2020-12-15 14:15:43 +01:00
continue ;
}
int idyR = int ( dyR ) ;
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { a } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { o } . 0 ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( b , idyR , idyC , d ) ;
2021-01-12 16:01:34 +01:00
int maxPosValue = $ { u } - int ( getMaxPos ( b , idyR , idyC , d ) ) ;
2020-12-15 14:15:43 +01:00
// Get the current value, check it against the value from the
// position matrix.
2021-01-12 16:01:34 +01:00
int curPosValue = wR * $ { a } + wC ;
2020-12-15 14:15:43 +01:00
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
dotProd += dyValue * mask ;
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }},BC=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,o=e.strideHeight,n=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,l=e.effectiveFilterDepth,u=e.effectiveFilterHeight,c=e.effectiveFilterWidth,p=l-1-e.padInfo.front,m=u-1-e.padInfo.top,f=c-1-e.padInfo.left,d=l*u*c-1;this.userCode= `
const ivec3 pads = ivec3 ( $ { p } , $ { m } , $ { f } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wD = 0 ; wD < $ { l } ;
wD += $ { s } ) {
float dyD = float ( dyDCorner + wD ) / $ { t } . 0 ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
2020-12-15 14:15:43 +01:00
continue ;
}
int idyD = int ( dyD ) ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { u } ;
wR += $ { a } ) {
float dyR = float ( dyRCorner + wR ) / $ { o } . 0 ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { c } ;
wC += $ { i } ) {
float dyC = float ( dyCCorner + wC ) / $ { n } . 0 ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
2021-01-12 16:01:34 +01:00
int maxPosValue = $ { d } -
2020-12-15 14:15:43 +01:00
int ( getMaxPos ( batch , idyD , idyR , idyC , ch ) ) ;
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
2021-01-12 16:01:34 +01:00
wD * $ { u } * $ { c } +
wR * $ { c } + wC ;
2020-12-15 14:15:43 +01:00
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
dotProd += dyValue * mask ;
}
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }};function _9(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=o,p=[1,1,1],m=S.computePool3DInfo(a.shape,i,l,p,u,c),f=new mc(m,"max",!0),d=t.runWebGLProgram(f,[a],a.dtype),h=new BC(m),g=t.runWebGLProgram(h,[n,d],a.dtype);return t.disposeIntermediateTensorInfo(d),g}var ZO={kernelName:cu,backendName:"webgl",kernelFunc:_9};function w9(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s,output:a}=e,i=s;Xi([s,a],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=o,m=S.computePool2DInfo(i.shape,l,u,1,c,p),f=!0,d=new Yi(m,"max",f),h=t.runWebGLProgram(d,[i],i.dtype),g=new zC(m),y=t.runWebGLProgram(g,[n,h],i.dtype);return t.disposeIntermediateTensorInfo(h),y}var JO={kernelName:uu,backendName:"webgl",kernelFunc:w9};function QO(r,e,t,o){let n=new Yi(t,"max",!1),s=o.runWebGLProgram(n,[r],"float32");n=new Yi(t,"max",!0,!0,e);let a=o.runWebGLProgram(n,[r],"float32");return[s,a]}var eP={kernelName:pu,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{filterSize:n,strides:s,pad:a,includeBatchInIndex:i}=e,l=t;x.assert(o.shape.length===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { o . shape . length } . ` );let u=[1,1];x.assert(S.eitherStridesOrDilationsAreOne(s,u),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { s } and dilations '${u}' ` );let c=S.computePool2DInfo(o.shape,n,s,u,a),[p,m]=QO(o,i,c,l);return[p,m]}};function tP(r,e,t,o){let n=x.sizeFromShape(e),a=x.sizeFromShape(r.shape)/n,i=me({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),l=So(i,"float32","mean",o),u=me({inputs:{x:l},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(l),u}var rP={kernelName:dn,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{keepDims:n,axis:s}=e,a=t,i=o.shape.length,l=x.parseAxisParam(s,o.shape),u=l,c=S.getAxesPermutation(u,i),p=c!=null,m=a.shouldExecuteOnCPU([o]),f=[],d=o;if(p){if(m){let w=a.texData.get(d.dataId).values,k=new Array(i);for(let F=0;F<k.length;F++)k[F]=o.shape[c[F]];let $ =jp(w,o.shape,o.dtype,c,k);d=a.makeTensorInfo(k,o.dtype);let T=a.texData.get(d.dataId);T.values= $ }else d= $ l(o,c,a);f.push(d),u=S.getInnerMostAxes(u.length,i)}S.assertAxesAreInnerMostDims("sum",u,i);let[h,g]=S.computeOutAndReduceShapes(d.shape,u),y=h;n&&(y=S.expandShapeToKeepDim(h,l));let b=tP(d,g,y,a);for(let _ of f)a.disposeIntermediateTensorInfo(_);return b}};function v9(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=x.parseAxisParam(s,n.shape),u=l,c=S.getAxesPermutation(u,i),p=n;c!=null&&(p=Bt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=S.getInnerMostAxes(u.length,n.shape.length)),S.assertAxesAreInnerMostDims("min",u,i);let[m,f]=S.computeOutAndReduceShapes(p.shape,u),d=x.sizeFromShape(f),h=me({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=So(h,h.dtype,"min",t),y;if(a){let b=S.expandShapeToKeepDim(m,l);y=me({inputs:{x:g},backend:t,attrs:{shape:b}})}else y=me({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),y}var oP={kernelName:hn,backendName:"webgl",kernelFunc:v9};var k9=Ox+ `
2020-12-15 14:15:43 +01:00
return min ( a , b ) ;
2021-01-12 16:01:34 +01:00
` ,C9= `
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( min ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2021-01-12 16:01:34 +01:00
` +Al+ `
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,I9=at({opSnippet:k9,packedOpSnippet:C9,cpuKernelImpl:wR}),nP={kernelName:gn,backendName:"webgl",kernelFunc:I9};var VC=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=t.map((c,p)=>c[0]+e[p]+c[1]);let n=e.length,s=Be(n),a=t.map(c=>c[0]).join(","),i=t.map((c,p)=>c[0]+e[p]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n),u=o==="reflect"?0:1;if(n===1){this.userCode= `
int start = $ { a } ;
int end = $ { i } ;
2020-12-15 14:15:43 +01:00
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start ) {
2021-01-12 16:01:34 +01:00
outC = start * 2 - outC - $ { u } ;
2020-12-15 14:15:43 +01:00
} else if ( outC >= end ) {
2021-01-12 16:01:34 +01:00
outC = ( end - 1 ) * 2 - outC + $ { u } ;
2020-12-15 14:15:43 +01:00
}
setOutput ( getX ( outC - start ) ) ;
}
` ;return}this.userCode= `
2021-01-12 16:01:34 +01:00
$ { s } start = $ { s } ( $ { a } ) ;
$ { s } end = $ { s } ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { s } outC = getOutputCoords ( ) ;
for ( int i = 0 ; i < $ { n } ; i ++ ) {
2020-12-15 14:15:43 +01:00
if ( outC [ i ] < start [ i ] ) {
2021-01-12 16:01:34 +01:00
outC [ i ] = start [ i ] * 2 - outC [ i ] - $ { u } ;
2020-12-15 14:15:43 +01:00
} else if ( outC [ i ] >= end [ i ] ) {
2021-01-12 16:01:34 +01:00
outC [ i ] = ( end [ i ] - 1 ) * 2 - outC [ i ] + $ { u } ;
2020-12-15 14:15:43 +01:00
}
}
2021-01-12 16:01:34 +01:00
$ { s } coords = outC - start ;
setOutput ( getX ( $ { l } ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var WC=class{constructor(e,t,o){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((d,h)=>d[0]+e[h]+d[1]);let n=e.length,s=Be(n),a=t.map(d=>d[0]).join(","),i=t.map((d,h)=>d[0]+e[h]).join(","),l=qt("rc",n),u=qt("source",n),c= ` $ { l [ n - 1 ] } < $ { this . outputShape [ n - 1 ] } ` ,p=n===1?"source": ` vec2 ( $ { u . slice ( - 2 ) . join ( ) } ) ` ,m=o==="reflect"?0:1,f="";if(n===1){let d= `
$ { s } source = rc ;
2020-12-15 14:15:43 +01:00
if ( source < start ) {
2021-01-12 16:01:34 +01:00
source = start * 2 - source - $ { m } ;
2020-12-15 14:15:43 +01:00
} else if ( source >= end ) {
2021-01-12 16:01:34 +01:00
source = ( end - 1 ) * 2 - source + $ { m } ;
2020-12-15 14:15:43 +01:00
}
source -= start ;
2021-01-12 16:01:34 +01:00
` ;f= `
$ { s } rc = outputLoc ;
$ { d }
result [ 0 ] = getChannel ( getX ( $ { u . join ( ) } ) , $ { p } ) ;
$ { l [ n - 1 ] } += 1 ;
if ( $ { c } ) {
$ { d }
result [ 1 ] = getChannel ( getX ( $ { u . join ( ) } ) , $ { p } ) ;
}
` }else{let d= `
$ { s } source = rc ;
$ { s } lt = $ { s } ( lessThan ( source , start ) ) ;
$ { s } gte = $ { s } ( greaterThanEqual ( source , end ) ) ;
$ { s } orig = 1 - ( lt + gte ) ;
2020-12-15 14:15:43 +01:00
source = orig * source +
2021-01-12 16:01:34 +01:00
lt * ( start * 2 - source - $ { m } ) +
gte * ( ( end - 1 ) * 2 - source + $ { m } ) ;
2020-12-15 14:15:43 +01:00
source -= start ;
2021-01-12 16:01:34 +01:00
` ;f= `
$ { s } rc = outputLoc ;
$ { d }
result [ 0 ] = getChannel ( getX ( $ { u . join ( ) } ) , $ { p } ) ;
$ { l [ n - 1 ] } += 1 ;
if ( $ { c } ) {
$ { d }
result [ 1 ] = getChannel ( getX ( $ { u . join ( ) } ) , $ { p } ) ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
rc = outputLoc ;
2021-01-12 16:01:34 +01:00
$ { l [ n - 2 ] } += 1 ;
if ( $ { l [ n - 2 ] } < $ { this . outputShape [ n - 2 ] } ) {
$ { d }
result [ 2 ] = getChannel ( getX ( $ { u . join ( ) } ) , $ { p } ) ;
$ { l [ n - 1 ] } += 1 ;
if ( $ { c } ) {
$ { d }
result [ 3 ] = getChannel ( getX ( $ { u . join ( ) } ) , $ { p } ) ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
` }this.userCode= `
2021-01-12 16:01:34 +01:00
const $ { s } start = $ { s } ( $ { a } ) ;
const $ { s } end = $ { s } ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
2020-12-02 22:46:41 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { s } outputLoc = getOutputCoords ( ) ;
2020-12-02 22:46:41 +01:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
$ { f }
2020-12-02 22:46:41 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};var N9=({inputs:r,backend:e,attrs:t})=>{let{x:o}=r,{paddings:n,mode:s}=t,a=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new WC(o.shape,n,s):new VC(o.shape,n,s);return e.runWebGLProgram(a,[o],o.dtype)},sP={kernelName:ma,backendName:"webgl",kernelFunc:N9};var S9= ` if ( b == 0.0 ) return NAN ;
return mod ( a , b ) ; ` ,T9= `
2020-12-15 14:15:43 +01:00
vec4 result = mod ( a , b ) ;
vec4 isNaN = vec4 ( equal ( b , vec4 ( 0.0 ) ) ) ;
2021-01-12 16:01:34 +01:00
` +Al+ `
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,E9=at({opSnippet:S9,packedOpSnippet:T9}),iP={kernelName:gi,backendName:"webgl",kernelFunc:E9};var GC=class{constructor(e,t,o){this.variableNames=["probs"],this.outputShape=[e,o],this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float seed ;
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float r = random ( seed ) ;
float cdf = 0.0 ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { t - 1 } ; i ++ ) {
2020-12-15 14:15:43 +01:00
cdf += getProbs ( batch , i ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
if ( r < cdf ) {
setOutput ( float ( i ) ) ;
return ;
}
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// If no other event happened, last event happened.
2021-01-12 16:01:34 +01:00
setOutput ( float ( $ { t - 1 } ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e){return(t,o)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(o,"seed")),t.gl.uniform1f(this.seedLoc,e)}}};var A9= `
2020-12-15 14:15:43 +01:00
if ( a == b ) {
return 1.0 ;
} ;
2021-01-12 16:01:34 +01:00
return a / b ; ` ,D9= `
2020-12-15 14:15:43 +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. ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
if ( a . y == b . y ) {
result . y = 1. ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
if ( a . z == b . z ) {
result . z = 1. ;
}
if ( a . w == b . w ) {
result . w = 1. ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
2020-12-02 22:46:41 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,UC=at({opSnippet:A9,packedOpSnippet:D9,checkOutOfBounds:!0}),aP={kernelName:rn,backendName:"webgl",kernelFunc:UC};var lP="return a - b;",jC=at({opSnippet:lP,packedOpSnippet:lP,supportsComplex:!0,cpuKernelImpl:ER}),uP={kernelName:Fn,backendName:"webgl",kernelFunc:jC};function qC(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{dim:s}=o,a=x.parseAxisParam([s],n.shape),i=LC({inputs:{x:n},backend:t,attrs:{reductionIndices:a,keepDims:!1}}),l=S.expandShapeToKeepDim(i.shape,a),u=me({inputs:{x:i},backend:t,attrs:{shape:l}}),c=jC({inputs:{a:n,b:u},backend:t}),p=TC({inputs:{x:c},backend:t}),m=nh({inputs:{x:p},backend:t,attrs:{axis:a,keepDims:!1}}),f=me({inputs:{x:m},backend:t,attrs:{shape:l}}),d=UC({inputs:{a:p,b:f},backend:t});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}var cP={kernelName: $ n,backendName:"webgl",kernelFunc:qC};function $ 9(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o,l=i?n:qC({inputs:{logits:n},backend:t,attrs:{dim:n.shape.length-1}}),u=l.shape[0],c=l.shape[1],p=new GC(u,c,s),m=p.getCustomSetupFunc(a),f=t.runWebGLProgram(p,[l],"int32",m);return i||t.disposeIntermediateTensorInfo(l),f}var pP={kernelName:mu,backendName:"webgl",kernelFunc: $ 9};var mP="return -x;";function R9(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])){let s=t.texData.get(o.dataId),[a,i]=kR(s.values,o.shape,o.dtype);return t.makeTensorInfo(i,o.dtype,a)}let n;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new zs(o.shape,mP):n=new mo(o.shape,mP),t.runWebGLProgram(n,[o],o.dtype)}var fP={kernelName:ps,backendName:"webgl",kernelFunc:R9};var F9=Er.nonMaxSuppressionV3Impl;function O9(r){S.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l}=o,u=t.readSync(n.dataId),c=t.readSync(s.dataId),{selectedIndices:p}=F9(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var dP={kernelName:yi,backendName:"webgl",kernelFunc:O9};var P9=Er.nonMaxSuppressionV4Impl;function M9(r){S.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=o,c=t.readSync(n.dataId),p=t.readSync(s.dataId),{selectedIndices:m,validOutputs:f}=P9(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var hP={kernelName:bi,backendName:"webgl",kernelFunc:M9};var L9=Er.nonMaxSuppressionV5Impl;function z9(r){S.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=o,c=t.readSync(n.dataId),p=t.readSync(s.dataId),m=a,f=i,d=l,h=u,{selectedIndices:g,selectedScores:y}=L9(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var gP={kernelName:_i,backendName:"webgl",kernelFunc:z9};var HC=class{constructor(e,t,o,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int index = round ( getIndices ( coords . x ) ) ;
2021-01-12 16:01:34 +01:00
setOutput ( mix ( float ( $ { n } ) , float ( $ { o } ) ,
2020-12-15 14:15:43 +01:00
float ( index == coords . y ) ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};var B9=r=>{let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{depth:s,onValue:a,offValue:i}=o,l=x.sizeFromShape(n.shape),u=new HC(l,s,a,i),c=me({inputs:{x:n},backend:t,attrs:{shape:[l]}}),p=t.runWebGLProgram(u,[c],n.dtype);t.disposeIntermediateTensorInfo(c);let m=[...n.shape,s],f=me({inputs:{x:p},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(p),f},xP={kernelName:yn,backendName:"webgl",kernelFunc:B9};function uh(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="complex64"){let n=Ha({inputs:{input:o},backend:t}),s=uh({inputs:{x:n},backend:t}),a=fc({inputs:{input:o},backend:t}),i=uh({inputs:{x:a},backend:t}),l=fo({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return lh({attrs:{shape:o.shape,dtype:o.dtype,value:o.dtype==="string"?"":0},backend:t})}var yP={kernelName:bs,backendName:"webgl",kernelFunc:uh};function bP(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(o.dtype==="complex64"){let n=Ha({inputs:{input:o},backend:t}),s=bP({inputs:{x:n},backend:t}),a=fc({inputs:{input:o},backend:t}),i=uh({inputs:{x:a},backend:t}),l=fo({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return lh({attrs:{shape:o.shape,dtype:o.dtype,value:1},backend:t})}var _P={kernelName:ms,backendName:"webgl",kernelFunc:bP};function V9(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return jx({inputs:{input:e[0]},backend:t,attrs:{dim:n}});let s=e[0].shape,a=e[0].dtype;e.forEach(c=>{x.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),x.assert(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=e.map(c=>{let p=jx({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=hC({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var wP={kernelName:fs,backendName:"webgl",kernelFunc:V9};var KC=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=t.map((u,c)=>u[0]+e[c]+u[1]);let n=e.length,s=Be(n),a=t.map(u=>u[0]).join(","),i=t.map((u,c)=>u[0]+e[c]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode= `
int start = $ { a } ;
int end = $ { i } ;
2020-12-15 14:15:43 +01:00
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start || outC >= end ) {
2021-01-12 16:01:34 +01:00
setOutput ( float ( $ { o } ) ) ;
2020-12-15 14:15:43 +01:00
} else {
setOutput ( getX ( outC - start ) ) ;
}
}
` ;return}this.userCode= `
2021-01-12 16:01:34 +01:00
$ { s } start = $ { s } ( $ { a } ) ;
$ { s } end = $ { s } ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { s } outC = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
if ( any ( lessThan ( outC , start ) ) || any ( greaterThanEqual ( outC , end ) ) ) {
2021-01-12 16:01:34 +01:00
setOutput ( float ( $ { o } ) ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
$ { s } coords = outC - start ;
setOutput ( getX ( $ { l } ) ) ;
2020-12-15 14:15:43 +01:00
}
}
2021-01-12 16:01:34 +01:00
` }};var XC=class{constructor(e,t,o){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,g)=>h[0]+e[g]+h[1]);let n=e.length,s=Be(n),a=t.map(h=>h[0]).join(","),i=t.map((h,g)=>h[0]+e[g]).join(","),l=qt("rc",n),u=qt("source",n),c= ` $ { l [ n - 1 ] } < $ { this . outputShape [ n - 1 ] } ` ,p=n===1?"source": ` vec2 ( $ { u . slice ( - 2 ) . join ( ) } ) ` ,m=[ ` $ { s } rc = outputLoc ; ` , ` $ { l [ n - 1 ] } += 1 ;
if ( $ { c } ) {
` ,n===1?"": ` }
2020-12-15 14:15:43 +01:00
rc = outputLoc ;
2021-01-12 16:01:34 +01:00
$ { l [ n - 2 ] } += 1 ;
if ( $ { l [ n - 2 ] } < $ { this . outputShape [ n - 2 ] } ) { ` ,n===1?"": ` $ { l [ n - 1 ] } += 1 ;
if ( $ { c } ) { ` ],f=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="";for(let h=0,g=n===1?2:4;h<g;h++)d+= `
$ { m [ h ] }
if ( $ { f } ) {
result [ $ { h } ] = float ( $ { o } ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
$ { s } source = rc - start ;
result [ $ { h } ] = getChannel ( getX ( $ { u . join ( ) } ) , $ { p } ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ;d+=n===1?"} ":"}}",this.userCode= `
const $ { s } start = $ { s } ( $ { a } ) ;
const $ { s } end = $ { s } ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { s } outputLoc = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
$ { d }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};var YC=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,constantValue:a}=o,i=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new XC(n.shape,s,a):new KC(n.shape,s,a);return t.runWebGLProgram(i,[n],n.dtype)},vP={kernelName:bn,backendName:"webgl",kernelFunc:YC};var W9= `
2020-12-15 14:15:43 +01:00
if ( a < 0.0 && floor ( b ) < b ) {
2020-12-02 22:46:41 +01:00
return NAN ;
}
2020-12-15 14:15:43 +01:00
if ( b == 0.0 ) {
return 1.0 ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
return ( round ( mod ( b , 2.0 ) ) != 1 ) ?
pow ( abs ( a ) , b ) : sign ( a ) * pow ( abs ( a ) , b ) ;
2021-01-12 16:01:34 +01:00
` ,G9= `
2020-12-15 14:15:43 +01:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4 ( equal ( round ( mod ( b , 2.0 ) ) , ivec4 ( 1 ) ) ) ;
vec4 multiplier = sign ( a ) * isModRound1 + ( vec4 ( 1.0 ) - isModRound1 ) ;
vec4 result = multiplier * pow ( abs ( a ) , b ) ;
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal ( b , vec4 ( 0.0 ) ) ;
result . r = isExpZero . r ? 1.0 : result . r ;
result . g = isExpZero . g ? 1.0 : result . g ;
result . b = isExpZero . b ? 1.0 : result . b ;
result . a = isExpZero . a ? 1.0 : result . a ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
vec4 isNaN = vec4 ( lessThan ( a , vec4 ( 0.0 ) ) ) * vec4 ( lessThan ( floor ( b ) , b ) ) ;
2021-01-12 16:01:34 +01:00
` +Al+ `
2020-12-02 22:46:41 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,U9=at({opSnippet:W9,packedOpSnippet:G9}),kP={kernelName:_n,backendName:"webgl",kernelFunc:U9};function j9(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=[],u=x.parseAxisParam(s,n.shape),c=u,p=S.getAxesPermutation(c,i),m=n;p!=null&&(m=Bt({inputs:{x:n},backend:t,attrs:{perm:p}}),c=S.getInnerMostAxes(c.length,i),l.push(m)),S.assertAxesAreInnerMostDims("prod",c,i);let f;if(t.shouldExecuteOnCPU([m])){let d=t.texData.get(m.dataId).values,{outVals:h,outShape:g,outDtype:y}=CR(m.shape,m.dtype,d,c);f=t.makeTensorInfo(g,y,h)}else{let[d,h]=S.computeOutAndReduceShapes(m.shape,c),g=x.sizeFromShape(h),y=me({inputs:{x:m},backend:t,attrs:{shape:[-1,g]}}),b=yu(n.dtype),_=So(y,b,"prod",t);f=me({inputs:{x:_},backend:t,attrs:{shape:d}}),l.push(y),l.push(_)}if(a){l.push(f);let d=S.expandShapeToKeepDim(f.shape,u);f=me({inputs:{x:f},backend:t,attrs:{shape:d}})}return l.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var CP={kernelName:wi,backendName:"webgl",kernelFunc:j9};var ZC=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=IR(o,n,s,a);return e.makeTensorInfo([i.length],a,i)},IP={kernelName:fa,backendName:"webgl",kernelFunc:ZC};var q9="return 1.0 / x;",H9=Ce({opSnippet:q9}),NP={kernelName:vi,backendName:"webgl",kernelFunc:H9};var K9=xr+ `
2020-12-15 14:15:43 +01:00
return ( x < 0.0 ) ? 0.0 : x ;
2021-01-12 16:01:34 +01:00
` ,X9= `
2020-12-02 22:46:41 +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 ;
2021-01-12 16:01:34 +01:00
` ,Y9=Ce({opSnippet:K9,packedOpSnippet:X9}),SP={kernelName:vn,backendName:"webgl",kernelFunc:Y9};var Z9=xr+ `
2020-12-15 14:15:43 +01:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2021-01-12 16:01:34 +01:00
` ,J9= `
2020-12-02 22:46:41 +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 ;
2021-01-12 16:01:34 +01:00
` ,Q9=Ce({opSnippet:Z9,packedOpSnippet:J9}),TP={kernelName:Cn,backendName:"webgl",kernelFunc:Q9};var JC=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,o,u];let c=[n&&t>1?i-1:i,n&&o>1?l-1:l],p=[n&&t>1?t-1:t,n&&o>1?o-1:o],m;s?m="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":m="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2020-12-15 14:15:43 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
2021-01-12 16:01:34 +01:00
$ { c [ 0 ] / p [ 0 ] } ,
$ { c [ 1 ] / p [ 1 ] } ) ;
const vec2 inputShapeRC = vec2 ( $ { i } . 0 , $ { l } . 0 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Fractional source index.
2021-01-12 16:01:34 +01:00
vec2 sourceFracIndexRC = $ { m } ;
2020-12-15 14:15:43 +01:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2 ( max ( sourceFracIndexRC , vec2 ( 0.0 ) ) ) ;
ivec2 sourceCeilRC = ivec2 (
min ( inputShapeRC - 1.0 , ceil ( sourceFracIndexRC ) ) ) ;
float topLeft = getA ( b , sourceFloorRC . x , sourceFloorRC . y , d ) ;
float bottomLeft = getA ( b , sourceCeilRC . x , sourceFloorRC . y , d ) ;
float topRight = getA ( b , sourceFloorRC . x , sourceCeilRC . y , d ) ;
float bottomRight = getA ( b , sourceCeilRC . x , sourceCeilRC . y , d ) ;
vec2 fracRC = sourceFracIndexRC - vec2 ( sourceFloorRC ) ;
float top = topLeft + ( topRight - topLeft ) * fracRC . y ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracRC . y ;
float newValue = top + ( bottom - top ) * fracRC . x ;
setOutput ( newValue ) ;
}
2021-01-12 16:01:34 +01:00
` }};var QC=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,o,u];let c=[n&&t>1?i-1:i,n&&o>1?l-1:l],p=[n&&t>1?t-1:t,n&&o>1?o-1:o],m;s?m="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":m="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2020-12-15 14:15:43 +01:00
const vec3 effectiveInputOverOutputRatioRC = vec3 (
2021-01-12 16:01:34 +01:00
$ { c [ 0 ] / p [ 0 ] } ,
$ { c [ 1 ] / p [ 1 ] } ,
$ { c [ 1 ] / p [ 1 ] } ) ;
const vec3 inputShapeRC = vec3 ( $ { i } . 0 , $ { l } . 0 ,
$ { l } . 0 ) ;
2020-12-15 14:15:43 +01:00
float getAValue ( int b , int r , int c , int d ) {
return getChannel ( getA ( b , r , c , d ) , vec2 ( c , d ) ) ;
2020-12-02 22:46:41 +01:00
}
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
// Calculate values for next column in yRC.z.
ivec3 yRC = coords . yzz + ivec3 ( 0 , 0 , 1 ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Fractional source index.
2021-01-12 16:01:34 +01:00
vec3 sourceFracIndexRC = $ { m } ;
2020-12-15 14:15:43 +01:00
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3 ( max ( sourceFracIndexRC , vec3 ( 0.0 ) ) ) ;
ivec3 sourceCeilRC = ivec3 (
min ( inputShapeRC - 1.0 , ceil ( sourceFracIndexRC ) ) ) ;
// Should we calculate next column and row elements in 2x2 packed cell.
2021-01-12 16:01:34 +01:00
bool hasNextCol = d < $ { u - 1 } ;
bool hasNextRow = coords . z < $ { o - 1 } ;
2020-12-15 14:15:43 +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 ) ;
vec4 bottomLeft = vec4 (
getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d + 1 ) : 0.0 ) ;
vec4 topRight = vec4 (
getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
vec4 bottomRight = vec4 (
getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
vec3 fracRC = sourceFracIndexRC - vec3 ( sourceFloorRC ) ;
vec4 top = mix ( topLeft , topRight , fracRC . yyzz ) ;
vec4 bottom = mix ( bottomLeft , bottomRight , fracRC . yyzz ) ;
vec4 newValue = mix ( top , bottom , fracRC . x ) ;
setOutput ( newValue ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function eJ(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[l,u]=i,c=W().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new QC(n.shape,l,u,s,a):new JC(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],"float32")}var EP={kernelName:kn,backendName:"webgl",kernelFunc:eJ};var eI=class{constructor(e,t,o){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,s]=t,[,a,i]=e,l=[o&&a>1?n-1:n,o&&i>1?s-1:s],u=[o&&a>1?a-1:a,o&&i>1?i-1:i],c=l[0]/u[0],p=l[1]/u[1],m=1/c,f=1/p,d=Math.ceil(m)*2+2,h=Math.ceil(f)*2+2;this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float accumulator = 0.0 ;
2021-01-12 16:01:34 +01:00
const float heightScale = float ( $ { c } ) ;
const float widthScale = float ( $ { p } ) ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
const float invHeightScale = float ( $ { m } ) ;
const float invWidthScale = float ( $ { f } ) ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
const int winHeight = int ( $ { d } ) ;
const int winWidth = int ( $ { h } ) ;
2020-12-15 14:15:43 +01:00
// Compute bounds for where in dy we will look
float startRLerp = floor ( float ( r ) * invHeightScale ) ;
int startDyR = int ( startRLerp - float ( winHeight / 2 ) ) ;
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( startCLerp - float ( winWidth / 2 ) ) ;
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
// Guard against the window exceeding the bounds of dy
2021-01-12 16:01:34 +01:00
if ( dyR < 0 || dyR >= $ { a } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
// Guard against the window exceeding the bounds of dy
2021-01-12 16:01:34 +01:00
if ( dyC < 0 || dyC >= $ { i } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
float dxR = float ( dyR ) * heightScale ;
int topDxRIndex = int ( floor ( dxR ) ) ;
2021-01-12 16:01:34 +01:00
int bottomDxRIndex = int ( min ( ceil ( dxR ) , $ { n - 1 } . 0 ) ) ;
2020-12-15 14:15:43 +01:00
float dxRLerp = dxR - float ( topDxRIndex ) ;
float inverseDxRLerp = 1.0 - dxRLerp ;
float dxC = float ( dyC ) * widthScale ;
int leftDxCIndex = int ( floor ( dxC ) ) ;
2021-01-12 16:01:34 +01:00
int rightDxCIndex = int ( min ( ceil ( dxC ) , $ { s - 1 } . 0 ) ) ;
2020-12-15 14:15:43 +01:00
float dxCLerp = dxC - float ( leftDxCIndex ) ;
float inverseDxCLerp = 1.0 - dxCLerp ;
if ( r == topDxRIndex && c == leftDxCIndex ) {
// topLeft
accumulator +=
getDy ( b , dyR , dyC , d ) * inverseDxRLerp * inverseDxCLerp ;
}
if ( r == topDxRIndex && c == rightDxCIndex ) {
// topRight
accumulator += getDy ( b , dyR , dyC , d ) * inverseDxRLerp * dxCLerp ;
}
if ( r == bottomDxRIndex && c == leftDxCIndex ) {
// bottomLeft
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * inverseDxCLerp ;
}
if ( r == bottomDxRIndex && c == rightDxCIndex ) {
// bottomRight
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * dxCLerp ;
}
}
}
// End loop over dy
setOutput ( accumulator ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function tJ(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new eI(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var AP={kernelName:hu,backendName:"webgl",kernelFunc:tJ};var tI=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,o,u];let c=[n&&t>1?i-1:i,n&&o>1?l-1:l],p=[n&&t>1?t-1:t,n&&o>1?o-1:o],m=n?"0.5":"0.0",f;s?f="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":f="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2020-12-15 14:15:43 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
2021-01-12 16:01:34 +01:00
$ { c [ 0 ] / p [ 0 ] } ,
$ { c [ 1 ] / p [ 1 ] } ) ;
const vec2 inputShapeRC = vec2 ( $ { i } . 0 , $ { l } . 0 ) ;
2020-12-15 14:15:43 +01:00
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
// Fractional source index.
2021-01-12 16:01:34 +01:00
vec2 sourceFracIndexRC = $ { f } ;
2020-12-15 14:15:43 +01:00
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2 (
2021-01-12 16:01:34 +01:00
min ( inputShapeRC - 1.0 , floor ( sourceFracIndexRC + $ { m } ) ) ) ;
2020-12-15 14:15:43 +01:00
float newValue = getA ( b , sourceNearestRC . x , sourceNearestRC . y , d ) ;
setOutput ( newValue ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function rJ(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[l,u]=i,c=new tI(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],n.dtype)}var DP={kernelName:da,backendName:"webgl",kernelFunc:rJ};var rI=class{constructor(e,t,o){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,s]=t,[,a,i]=e,l=[o&&a>1?n-1:n,o&&i>1?s-1:s],u=[o&&a>1?a-1:a,o&&i>1?i-1:i],c=l[0]/u[0],p=l[1]/u[1],m=1/c,f=1/p,d=Math.ceil(m)*2+2,h=Math.ceil(f)*2+2;this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float accumulator = 0.0 ;
2021-01-12 16:01:34 +01:00
const float heightScale = float ( $ { c } ) ;
const float widthScale = float ( $ { p } ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
const float invHeightScale = float ( $ { m } ) ;
const float invWidthScale = float ( $ { f } ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
const int winHeight = int ( $ { d } ) ;
const int winWidth = int ( $ { h } ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +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-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( floor ( startCLerp - float ( winWidth / 2 ) ) ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Guard against the window exceeding the bounds of dy
2021-01-12 16:01:34 +01:00
if ( dyR < 0 || dyR >= $ { a } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
// Guard against the window exceeding the bounds of dy
2021-01-12 16:01:34 +01:00
if ( dyC < 0 || dyC >= $ { i } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float sourceFracRow =
2021-01-12 16:01:34 +01:00
float ( $ { l [ 0 ] } ) *
( float ( dyR ) / float ( $ { u [ 0 ] } ) ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
float sourceFracCol =
2021-01-12 16:01:34 +01:00
float ( $ { l [ 1 ] } ) *
( float ( dyC ) / float ( $ { u [ 1 ] } ) ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
int sourceNearestRow = int ( min (
2021-01-12 16:01:34 +01:00
float ( int ( $ { n } ) - 1 ) ,
$ { o } ? float ( round ( sourceFracRow ) ) :
2020-12-15 14:15:43 +01:00
float ( floor ( sourceFracRow ) ) ) ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
int sourceNearestCol = int ( min (
2021-01-12 16:01:34 +01:00
float ( int ( $ { s } ) - 1 ) ,
$ { o } ? float ( round ( sourceFracCol ) ) :
2020-12-15 14:15:43 +01:00
float ( floor ( sourceFracCol ) ) ) ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
if ( r == sourceNearestRow && c == sourceNearestCol ) {
accumulator += getDy ( b , dyR , dyC , d ) ;
}
}
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
// End loop over dy
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
setOutput ( accumulator ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function oJ(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new rI(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var $ P={kernelName:du,backendName:"webgl",kernelFunc:oJ};var oI=class{constructor(e,t){this.variableNames=["x"];let o=e.length;if(o>4)throw new Error( ` WebGL backend : Reverse of rank - $ { o } tensor is not yet supported ` );if(this.outputShape=e,o===1){this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
int coord = getOutputCoords ( ) ;
2021-01-12 16:01:34 +01:00
setOutput ( getX ( $ { e [ 0 ] } - coord - 1 ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ;return}let n=i=>t.indexOf(i)!==-1&&e[i]!==1? ` $ { e [ i ] } - coords [ $ { i } ] - 1 ` : ` coords [ $ { i } ] ` ,s=e.map((i,l)=>n(l)).join(","),a=Be(o);this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { a } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { s } ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};var nI=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let o=e.length;if(o>4)throw new Error( ` WebGL backend : Reverse of rank - $ { o } tensor is not yet supported ` );this.outputShape=e;let n=qt("rc",o),s= ` $ { n [ o - 1 ] } + 1 < $ { this . outputShape [ o - 1 ] } ` ,a= ` $ { n [ o - 2 ] } + 1 < $ { this . outputShape [ o - 2 ] } ` ,i=Be(o);o===1?this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
int rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
result . r = getChannel ( getX ( $ { e [ 0 ] } - rc - 1 ) ,
$ { e [ 0 ] } - rc - 1 ) ;
if ( $ { s } ) {
result . g = getChannel ( getX ( $ { e [ 0 ] } - ( rc + 1 ) - 1 ) ,
$ { e [ 0 ] } - ( rc + 1 ) - 1 ) ;
2020-12-15 14:15:43 +01:00
}
setOutput ( result ) ;
}
` :this.userCode= `
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { i } rc = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
result . r = $ { l ( n . slice ( ) ) } ;
if ( $ { s } ) {
result . g = $ { u ( n . slice ( ) ) } ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
if ( $ { a } ) {
result . b = $ { c ( n . slice ( ) ) } ;
if ( $ { s } ) {
result . a = $ { p ( n . slice ( ) ) } ;
2020-12-15 14:15:43 +01:00
}
}
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` ;function l(d){return m(d)}function u(d){return d[o-1]="("+d[o-1]+" + 1)",m(d)}function c(d){return d[o-2]="("+d[o-2]+" + 1)",m(d)}function p(d){return d[o-1]="("+d[o-1]+" + 1)",d[o-2]="("+d[o-2]+" + 1)",m(d)}function m(d){let h=e.map((b,_)=>f(_,d)),g=h.join(","),y=h.slice(-2).join(",");return ` getChannel ( getX ( $ { g } ) , vec2 ( $ { y } ) ) ` }function f(d,h){return t.indexOf(d)!==-1&&e[d]!==1? ` $ { e [ d ] } - $ { h [ d ] } - 1 ` : ` $ { h [ d ] } ` }}};function nJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o,a=n.shape.length,i=x.parseAxisParam(s,n.shape);if(a===0)return Ht({inputs:{x:n},backend:t});let l=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new nI(n.shape,i):new oI(n.shape,i);return t.runWebGLProgram(l,[n],n.dtype)}var RP={kernelName:In,backendName:"webgl",kernelFunc:nJ};var sI=class{constructor(e,t,o,n){this.variableNames=["Image"],this.outputShape=[];let s=e[1],a=e[2],i=Math.sin(t).toFixed(3),l=Math.cos(t).toFixed(3);this.outputShape=e;let[u,c]=S.getImageCenter(n,s,a),p=u.toFixed(3),m=c.toFixed(3),f="";typeof o=="number"?f= ` float outputValue = $ { o . toFixed ( 2 ) } ; ` :f= `
vec3 fill = vec3 ( $ { o . join ( "," ) } ) ;
2020-12-15 14:15:43 +01:00
float outputValue = fill [ coords [ 3 ] ] ; ` ,this.userCode= `
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
2020-12-15 14:15:43 +01:00
int y = coords [ 1 ] ;
2021-01-12 16:01:34 +01:00
float coordXFloat = ( float ( x ) - $ { p } ) * $ { l } - ( float ( y ) - $ { m } ) * $ { i } ;
float coordYFloat = ( float ( x ) - $ { p } ) * $ { i } + ( float ( y ) - $ { m } ) * $ { l } ;
int coordX = int ( round ( coordXFloat + $ { p } ) ) ;
int coordY = int ( round ( coordYFloat + $ { m } ) ) ;
$ { f }
if ( coordX >= 0 && coordX < $ { a } && coordY >= 0 && coordY < $ { s } ) {
2020-12-15 14:15:43 +01:00
outputValue = getImage ( coords [ 0 ] , coordY , coordX , coords [ 3 ] ) ;
2020-12-02 22:46:41 +01:00
}
setOutput ( outputValue ) ;
}
2021-01-12 16:01:34 +01:00
` }};var FP={kernelName: $ i,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:o}=r,{radians:n,fillValue:s,center:a}=e,i=t,l=new sI(o.shape,n,s,a);return i.runWebGLProgram(l,[o],o.dtype)}};var sJ= `
2020-12-15 14:15:43 +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-01-12 16:01:34 +01:00
` ,iJ=Ce({opSnippet:sJ}),OP={kernelName:Nn,backendName:"webgl",kernelFunc:iJ};var aJ="return inversesqrt(x);",lJ=Ce({opSnippet:aJ,cpuKernelImpl:NR}),PP={kernelName:Sn,backendName:"webgl",kernelFunc:lJ};var ch=class{constructor(e,t,o,n,s,a,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let l=Be(s.length),u=Be(a.length),c="";o===1?c="i":o===2&&(c="i, j");let p= ` getIndices ( $ { c } ) ` ,m="";n===1?m="i":n===2&&(m="i, coords[1]");let f= ` getUpdates ( $ { m } ) ` ,d=t>1?"strides[j]":"strides";this.userCode= `
$ { l } strides = $ { l } ( $ { s } ) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { u } coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
float sum = 0.0 ;
bool found = false ;
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { e } ; i ++ ) {
2020-12-15 14:15:43 +01:00
int flattenedIndex = 0 ;
2021-01-12 16:01:34 +01:00
for ( int j = 0 ; j < $ { t } ; j ++ ) {
int index = round ( $ { p } ) ;
flattenedIndex += index * $ { d } ;
2020-12-15 14:15:43 +01:00
}
if ( flattenedIndex == coords [ 0 ] ) {
2021-01-12 16:01:34 +01:00
sum += $ { f } ;
2020-12-15 14:15:43 +01:00
found = true ;
2020-12-02 22:46:41 +01:00
}
}
2020-12-15 14:15:43 +01:00
setOutput ( mix ( getDefaultValue ( ) , sum , float ( found ) ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};function uJ(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n,updates:s}=e,{shape:a}=o,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=S.calculateShapes(s,n,a),m=[p/u,u];if(p===0)return t.makeTensorInfo(a,n.dtype);let f=me({inputs:{x:n},backend:t,attrs:{shape:[l,i]}}),d=me({inputs:{x:s},backend:t,attrs:{shape:[l,u]}}),h=t.makeTensorInfo([],"float32",new Float32Array([0])),g=new ch(l,i,f.shape.length,d.shape.length,c,m),y=t.runWebGLProgram(g,[d,f,h],d.dtype),b=me({inputs:{x:y},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(h),b}var MP={kernelName:ki,backendName:"webgl",kernelFunc:uJ};var iI=class{constructor(e,t,o){this.variableNames=["c","a","b"],this.outputShape=t;let n,s;if(o>4)throw Error( ` Where for rank $ { o } is not yet supported ` );if(o===1)s="resRC",n="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],u=[];for(let c=0;c<t.length;c++)u.push( ` $ { i [ c ] } ` ),c<e&&l.push( ` $ { i [ c ] } ` );n=l.join(),s=u.join()}let a=Be(o);this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { a } resRC = getOutputCoords ( ) ;
float cVal = getC ( $ { n } ) ;
2020-12-15 14:15:43 +01:00
if ( cVal >= 1.0 ) {
2021-01-12 16:01:34 +01:00
setOutput ( getA ( $ { s } ) ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
setOutput ( getB ( $ { s } ) ) ;
2020-12-02 22:46:41 +01:00
}
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function cJ(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e,a=new iI(o.shape.length,n.shape,n.shape.length);return t.runWebGLProgram(a,[o,n,s],fr(n.dtype,s.dtype))}var LP={kernelName:hs,backendName:"webgl",kernelFunc:cJ};var pJ= `
2020-12-15 14:15:43 +01:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2021-01-12 16:01:34 +01:00
float scaleAlpha = $ { S . SELU _SCALEALPHA } ;
float scale = $ { S . SELU _SCALE } ;
2020-12-15 14:15:43 +01:00
return ( x >= 0.0 ) ? scale * x : scaleAlpha * ( exp ( x ) - 1.0 ) ;
2021-01-12 16:01:34 +01:00
` ,mJ=Ce({opSnippet:pJ}),zP={kernelName:Ci,backendName:"webgl",kernelFunc:mJ};var fJ="return 1.0 / (1.0 + exp(-1.0 * x));",dJ=Ce({opSnippet:fJ}),BP={kernelName:En,backendName:"webgl",kernelFunc:dJ};var hJ= `
2020-12-15 14:15:43 +01:00
if ( isnan ( x ) ) { return 0.0 ; }
return sign ( x ) ;
2021-01-12 16:01:34 +01:00
` ,gJ=Ce({opSnippet:hJ}),VP={kernelName:Ni,backendName:"webgl",kernelFunc:gJ};var xJ=Px+ `
2020-12-15 14:15:43 +01:00
return sin ( x ) ;
2021-01-12 16:01:34 +01:00
` ,yJ=Ce({opSnippet:xJ}),WP={kernelName:Tn,backendName:"webgl",kernelFunc:yJ};var bJ= `
2020-12-15 14:15:43 +01:00
float e2x = exp ( x ) ;
return ( e2x - 1.0 / e2x ) / 2.0 ;
2021-01-12 16:01:34 +01:00
` ,_J=Ce({opSnippet:bJ}),GP={kernelName:Ii,backendName:"webgl",kernelFunc:_J};var wJ= `
2020-12-15 14:15:43 +01:00
float epsilon = 1.1920928955078125 e - 7 ;
float threshold = log ( epsilon ) + 2.0 ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +01:00
bool too _large = x > - threshold ;
bool too _small = x < threshold ;
float result ;
float exp _x = exp ( x ) ;
if ( too _large ) {
result = x ;
}
else if ( too _small ) {
result = exp _x ;
}
else {
result = log ( exp _x + 1.0 ) ;
}
return result ;
2021-01-12 16:01:34 +01:00
` ,vJ=Ce({opSnippet:wJ}),UP={kernelName:Si,backendName:"webgl",kernelFunc:vJ};var kJ=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,paddings:a}=o;x.assert(n.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((y,b)=>y*b),l=[[0,0]];l.push(...a);for(let y=1+s.length;y<n.shape.length;++y)l.push([0,0]);let u=[],c=YC({inputs:{x:n},backend:t,attrs:{paddings:l,constantValue:0}}),p=S.getReshaped(c.shape,s,i,!1),m=S.getPermuted(p.length,s.length,!1),f=S.getReshapedPermuted(c.shape,s,i,!1),d=me({inputs:{x:c},backend:t,attrs:{shape:p}}),h=Bt({inputs:{x:d},backend:t,attrs:{perm:m}}),g=me({inputs:{x:h},backend:t,attrs:{shape:f}});return u.push(c),u.push(d),u.push(h),u.forEach(y=>t.disposeIntermediateTensorInfo(y)),g},jP={kernelName:ha,backendName:"webgl",kernelFunc:kJ};function CJ(r){let{inputs:e,backend:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=e,{outputShape:i}=o,{sliceRank:l,numUpdates:u,strides:c,outputSize:p}=S.calculateShapes(s,n,i),m=!1,f=new ch(u,l,n.shape.length,s.shape.length,c,[p,1],m),d=t.runWebGLProgram(f,[s,n,a],s.dtype),h=me({inputs:{x:d},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(d),h}var qP={kernelName:gu,backendName:"webgl",kernelFunc:CJ};function IJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=o,i=x.parseAxisParam(a,n.shape)[0],l=S.prepareSplitSize(n,s,i),u=n.shape.length,c=new Array(u).fill(0),p=n.shape.slice();return l.map(m=>{let f=[...p];f[i]=m;let d=qa({inputs:{x:n},backend:t,attrs:{begin:c,size:f}});return c[i]+=m,d})}var HP={kernelName:xs,backendName:"webgl",kernelFunc:IJ};var NJ="return sqrt(x);",SJ=Ce({opSnippet:NJ}),KP={kernelName:An,backendName:"webgl",kernelFunc:SJ};var TJ="return x * x;",EJ=Ce({opSnippet:TJ}),XP={kernelName:ga,backendName:"webgl",kernelFunc:EJ};var YP="return (a - b) * (a - b);",AJ=at({opSnippet:YP,packedOpSnippet:YP}),ZP={kernelName:Rn,backendName:"webgl",kernelFunc:AJ};function DJ({inputs:r,attrs:e,backend:t}){let{x:o}=r,n=xr+ `
return x > 0.0 ? 1.0 : float ( $ { e . alpha } ) ;
` ,s=new mo(o.shape,n);return t.runWebGLProgram(s,[o],o.dtype)}var JP={kernelName:Di,backendName:"webgl",kernelFunc:DJ};var aI=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=o;let n=o.length,s=Be(o.length),a=Be(o.length),i="";if(n===1)i="coords * strides + begin";else{let l=0;i=o.map((u,c)=>(l++,o.length===1? ` coords * strides [ $ { c } ] + begin [ $ { c } ] ` : ` coords [ $ { l - 1 } ] * strides [ $ { c } ] + begin [ $ { c } ] ` )).join(",")}this.userCode= `
$ { s } begin = $ { s } ( $ { e } ) ;
$ { s } strides = $ { s } ( $ { t } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { a } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { i } ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function $ J(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,end:a,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=o,{nonStrided:f, $ begin:d, $ strides:h,size:g,newShape:y,outShape:b}=sr.sliceInfo(n.shape,s,a,i,l,u,c,p,m),_=me({inputs:{x:n},backend:t,attrs:{shape:y}}),w;if(f){let $ =qa({inputs:{x:_},backend:t,attrs:{begin:d,size:g}});w=me({inputs:{x: $ },backend:t,attrs:{shape:b}}),t.disposeIntermediateTensorInfo( $ )}else if(b.some( $ => $ ===0))w=t.makeTensorInfo(b,n.dtype,[]);else if(t.shouldExecuteOnCPU([_])){let F=t.texData.get(_.dataId).values,M=Ie(_.shape,_.dtype,F),L=TR(b,M,h,d);w=t.makeTensorInfo(b,_.dtype,L.values)}else{let T=new aI(d,h,b);w=t.runWebGLProgram(T,[_],_.dtype)}let k=me({inputs:{x:w},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(_),t.disposeIntermediateTensorInfo(w),k}var QP={kernelName:Ti,backendName:"webgl",kernelFunc: $ J};var RJ="return tan(x);",FJ=Ce({opSnippet:RJ}),eM={kernelName:Ei,backendName:"webgl",kernelFunc:FJ};var OJ= `
2020-12-15 14:15:43 +01:00
float e2x = exp ( - 2.0 * abs ( x ) ) ;
return sign ( x ) * ( 1.0 - e2x ) / ( 1.0 + e2x ) ;
2021-01-12 16:01:34 +01:00
` ,PJ=Ce({opSnippet:OJ}),tM={kernelName:On,backendName:"webgl",kernelFunc:PJ};var lI=class{constructor(e,t){this.variableNames=["A"];let o=new Array(e.length);for(let a=0;a<o.length;a++)o[a]=e[a]*t[a];this.outputShape=o,this.rank=o.length;let n=Be(this.rank),s=MJ(e);this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { n } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { s } ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function MJ(r){let e=r.length;if(e>5)throw Error( ` Tile for rank $ { e } is not yet supported ` );if(e===1)return ` imod ( resRC , $ { r [ 0 ] } ) ` ;let t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],o=[];for(let n=0;n<r.length;n++)o.push( ` imod ( $ { t [ n ] } , $ { r [ n ] } ) ` );return o.join()}function uI(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;if(n.dtype==="string"){let u=t.readSync(n.dataId).map(m=>x.decodeString(m)),c=Ie(n.shape,n.dtype,u),p=AR(c,s);return t.makeTensorInfo(p.shape,p.dtype,p.values)}let a=new lI(n.shape,s);return t.runWebGLProgram(a,[n],n.dtype)}var rM={kernelName:_o,backendName:"webgl",kernelFunc:uI};function LJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o,i=t.readSync(n.dataId),[l,u]=DR(i,n.shape,n.dtype,s,a);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(u.shape,u.dtype,u.values)]}var oM={kernelName:Ai,backendName:"webgl",kernelFunc:LJ};function zJ(r){let{inputs:e,attrs:t,backend:o}=r,{axis:n}=t,{x:s}=e;Xi(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let a=o.readSync(s.dataId),{outputValues:i,outputShape:l,indices:u}= $ R(a,n,s.shape,s.dtype);return[o.makeTensorInfo(l,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var nM={kernelName:xu,backendName:"webgl",kernelFunc:zJ};function BJ(r){let{inputs:e,backend:t,attrs:o}=r,{value:n}=e,{axis:s}=o;s<0&&(s+=n.shape.length);let a=n,i=a.shape.length,l=n.shape[s],u=new Array(i-1),c=0;for(let h=0;h<i;h++)h!==s&&(u[c++]=a.shape[h]);let p=[],m=new Array(i).fill(0),f=a.shape.slice();f[s]=1;let d=new Array(l);for(let h=0;h<d.length;h++){m[s]=h;let g=qa({inputs:{x:a},backend:t,attrs:{begin:m,size:f}}),y=me({inputs:{x:g},backend:t,attrs:{shape:u}});d[h]=y,p.push(g)}return p.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var sM={kernelName:ys,backendName:"webgl",kernelFunc:BJ};var cI=class{constructor(e,t){this.variableNames=["x","segmentIds"];let o=e.windowSize,n=e.batchSize,s=e.inSize,a=e.numSegments,i=a*Math.ceil(s/o);this.outputShape=[n,i];let l="0.0",u="sumValue",c=Math.floor(o/4)*4,p=o%4,m= `
2020-12-15 14:15:43 +01:00
sumValue += dot ( values , segFilter ) ;
2021-01-12 16:01:34 +01:00
` ,f="";s%o>0&&(f= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
2020-12-15 14:15:43 +01:00
return initializationValue ;
}
2021-01-12 16:01:34 +01:00
` );let d="";s%o>0&&(d= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
2020-12-15 14:15:43 +01:00
return - 1.0 ;
2020-12-02 22:46:41 +01:00
}
` ),this.userCode= `
2021-01-12 16:01:34 +01:00
const float initializationValue = $ { l } ;
2020-12-02 22:46:41 +01:00
float getValue ( int batch , int inIdx ) {
2021-01-12 16:01:34 +01:00
$ { f }
2020-12-02 22:46:41 +01:00
return getX ( batch , inIdx ) ;
}
2020-12-15 14:15:43 +01:00
float getSegmentIdAtIndex ( int inIdx ) {
2021-01-12 16:01:34 +01:00
$ { d }
2020-12-15 14:15:43 +01:00
return getSegmentIds ( inIdx ) ;
}
2020-12-02 22:46:41 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
2020-12-15 14:15:43 +01:00
int inOffset = int ( floor ( float ( outIdx ) / float (
2021-01-12 16:01:34 +01:00
$ { a } ) ) * float ( $ { o } ) ) ;
int currentSeg = int ( mod ( float ( outIdx ) , float ( $ { a } ) ) ) ;
2020-12-02 22:46:41 +01:00
float sumValue = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { c } ; i += 4 ) {
2020-12-02 22:46:41 +01:00
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2020-12-15 14:15:43 +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-01-12 16:01:34 +01:00
$ { m }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
int inIdx = inOffset + $ { c } ;
if ( $ { p === 1 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
int inIdxSeg = int ( getSegmentIdAtIndex ( inIdx ) ) ;
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
0 ,
0 ,
0
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { m }
} else if ( $ { p === 2 } ) {
2020-12-02 22:46:41 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
0 ,
0
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { m }
} else if ( $ { p === 3 } ) {
2020-12-02 22:46:41 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
2020-12-02 22:46:41 +01:00
2020-12-15 14:15:43 +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
) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
$ { m }
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
setOutput ( $ { u } ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function VJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,segmentIds:s}=e,{numSegments:a}=o,i=n.shape.length,l=[],u=0,c=S.getAxesPermutation([u],i),p=n;c!=null&&(p=Bt({inputs:{x:n},backend:t,attrs:{perm:c}}),l.push(p),u=S.getInnerMostAxes(1,i)[0]);let m=S.segment_util.computeOutShape(p.shape,u,a),f=x.sizeFromShape([p.shape[u]]),d=me({inputs:{x:p},backend:t,attrs:{shape:[-1,f]}});l.push(d);let h=yu(n.dtype),g=(w,k, $ ,T,F)=>{let M=w.shape[0],L=w.shape[1],G=S.segment_util.segOpComputeOptimalWindowSize(L,F),H={windowSize:G,inSize:L,batchSize:M,numSegments:F},U=new cI(H,k),Z=t.compileAndRun(U,[w, $ ],T);if(l.push(Z),Z.shape[1]===F)return Z;let K=ZC({backend:t,attrs:{start:0,stop:F,step:1,dtype:"float32"}}),X=uI({inputs:{x:K},backend:t,attrs:{reps:[L/G]}});return l.push(K),l.push(X),g(Z,k,X,T,F)},y=g(d,"unsortedSegmentSum",s,h,a),b=me({inputs:{x:y},backend:t,attrs:{shape:m}}),_=b;if(c!=null){l.push(b);let w=S.getUndoAxesPermutation(c);_=Bt({inputs:{x:_},backend:t,attrs:{perm:w}})}return l.forEach(w=>t.disposeIntermediateTensorInfo(w)),_}var iM={kernelName:xa,backendName:"webgl",kernelFunc:VJ};var WJ=[UO,jO,sF,aF,lF,uF,pF,mF,fF,dF,xF,yF,bF,_F,vF,wF,kF,IF,CF,NF,SF,TF,EF,DF, $ F,PF,LF,zF,VF,HR,UF,qF,HF,jF,XF,YF,KF,ZF,JF,QF,rO,oO,nO,iO,aO,sO,lO,uO,cO,pO,mO,fO,hO,gO,yO,bO,_O,wO,kO,CO,IO,NO,SO,TO,EO,AO,DO,qR, $ O,WF,RO,FO,OO,KR,PO,MO,LO,BO,zO,VO,WO,GO,HO,YO,XO,ZO,JO,eP,KO,rP,oP,nP,sP,iP,pP,QR,fP,dP,hP,gP,RF,xP,_P,wP,vP,kP,XR,CP,IP,FF,aP,NP,TP,SP,tF,EP,AP,DP, $ P,RP,FP,OP,PP,MP,LP,zP,BP,VP,WP,GP,AF,cP,UP,jP,qP,HP,KP,XP,ZP,JP,QP,uP,oF,eM,tM,rM,oM,nF,nM,sM,iM,yP];for(let r of WJ)tl(r);var aM="2.8.3";var GJ={"tfjs-core":Zb,"tfjs-backend-cpu":GA,"tfjs-backend-webgl":jR,"tfjs-data":_x,"tfjs-layers":xl,"tfjs-converter":fx,tfjs:aM};var Vt;(function(r){r[r.float32=0]="float32",r[r.int32=1]="int32",r[r.bool=2]="bool",r[r.string=3]="string",r[r.complex64=4]="complex64"})(Vt||(Vt={}));var Rl;(function(r){r[r.linear=0]="linear",r[r.relu=1]="relu",r[r.relu6=2]="relu6",r[r.prelu=3]="prelu",r[r.leakyrelu=4]="leakyrelu"})(Rl||(Rl={}));var lM;function UJ(r){lM=r.wasm.cwrap(_s,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function jJ(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e;if(n.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=o,m=t.dataIdMap.get(n.dataId).id,f=t.dataIdMap.get(s.dataId).id,d=0;if(a!=null){let F=t.dataIdMap.get(a.dataId);if(F.shape.length!==1)throw new Error( ` _FusedMatMul only supports rank - 1 bias but got rank $ { F . shape . length } . ` );d=F.id}let h=i==null?0:t.dataIdMap.get(i.dataId).id,g=Rl[c];if(g==null)throw new Error( ` $ { c } activation not yet supported for FusedConv2D in the wasm backend . ` );let y=l?n.shape[2]:n.shape[1],b=u?s.shape[1]:s.shape[2],_=n.shape[0],w=t.makeOutput([_,y,b],n.dtype),k=t.dataIdMap.get(w.dataId).id, $ =new Uint8Array(new Int32Array(n.shape).buffer),T=new Uint8Array(new Int32Array(s.shape).buffer);return lM(m, $ ,n.shape.length,f,T,s.shape.length,l,u,g,d,h,p||0,k),w}var uM={kernelName:_s,backendName:"wasm",setupFunc:UJ,kernelFunc:jJ};function Ft(r){let e;function t(n){e=n.wasm.cwrap(r,null,["number","number"])}function o(n){let{backend:s,inputs:{x:a}}=n,i=s.dataIdMap.get(a.dataId).id,l=s.makeOutput(a.shape,a.dtype),u=s.dataIdMap.get(l.dataId).id;return x.sizeFromShape(l.shape)===0||e(i,u),l}return{kernelName:r,backendName:"wasm",setupFunc:t,kernelFunc:o}}var cM=Ft(is);function kt(r,e,t){let o;function n(a){o=a.wasm.cwrap(r,null,["number","array","number","number","array","number","number","number"])}function s(a){let{backend:i,inputs:l}=a,{a:u,b:c}=l,p=i.dataIdMap.get(u.dataId).id,m=i.dataIdMap.get(c.dataId).id,f=t!=null?t:u.dtype,d=S.assertAndGetBroadcastShape(u.shape,c.shape),h=i.makeOutput(d,f);if(x.sizeFromShape(d)===0)return h;let g=new Uint8Array(new Int32Array(u.shape).buffer),y=new Uint8Array(new Int32Array(c.shape).buffer),b=i.dataIdMap.get(h.dataId).id,_=()=>o(p,g,u.shape.
2020-12-02 22:46:41 +01: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 .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
2021-01-10 16:35:51 +01: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
*
* 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 .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
2020-12-02 22:46:41 +01:00
/** @license See the LICENSE file. */
//# sourceMappingURL=tfjs.esm.js.map