2020-11-04 16:18:22 +01:00
var BS = Object . create , zs = Object . defineProperty , zS = Object . getPrototypeOf , PS = Object . prototype . hasOwnProperty , MS = Object . getOwnPropertyNames , HS = Object . getOwnPropertyDescriptor , bf = n => zs ( n , "__esModule" , { value : ! 0 } ) , xe = ( n , t ) => ( ) => ( t || ( t = { exports : { } } , n ( t . exports , t ) ) , t . exports ) , ki = ( n , t ) => { bf ( n ) ; for ( var e in t ) zs ( n , e , { get : t [ e ] , enumerable : ! 0 } ) } , VS = ( n , t , e ) => { if ( bf ( n ) , typeof t == "object" || typeof t == "function" ) for ( let r of MS ( t ) ) ! PS . call ( n , r ) && r !== "default" && zs ( n , r , { get : ( ) => t [ r ] , enumerable : ! ( e = HS ( t , r ) ) || e . enumerable } ) ; return n } , Ea = n => n && n . _ _esModule ? n : VS ( zs ( BS ( zS ( n ) ) , "default" , { value : n , enumerable : ! 0 } ) , n ) , Rf = xe ( qS => { ki ( qS , { FetchError : ( ) => zt , Headers : ( ) => yn , Request : ( ) => Xr , Response : ( ) => Dn , default : ( ) => nL } ) ; const pn = Ea ( require ( "stream" ) ) , Ec = Ea ( require ( "http" ) ) , Ps = Ea ( require ( "url" ) ) , xf = Ea ( require ( "https" ) ) , vr = Ea ( require ( "zlib" ) ) , GS = pn . default . Readable , Zn = Symbol ( "buffer" ) , Dc = Symbol ( "type" ) ; class Da { constructor ( ) { this [ Dc ] = "" ; const n = arguments [ 0 ] , t = arguments [ 1 ] , e = [ ] ; let r = 0 ; if ( n ) { const a = n , s = Number ( a . length ) ; for ( let o = 0 ; o < s ; o ++ ) { const c = a [ o ] ; let l ; c instanceof Buffer ? l = c : ArrayBuffer . isView ( c ) ? l = Buffer . from ( c . buffer , c . byteOffset , c . byteLength ) : c instanceof ArrayBuffer ? l = Buffer . from ( c ) : c instanceof Da ? l = c [ Zn ] : l = Buffer . from ( typeof c == "string" ? c : String ( c ) ) , r += l . length , e . push ( l ) } } this [ Zn ] = Buffer . concat ( e ) ; let i = t && t . type !== void 0 && String ( t . type ) . toLowerCase ( ) ; i && ! /[^\u0020-\u007E]/ . test ( i ) && ( this [ Dc ] = i ) } get size ( ) { return this [ Zn ] . length } get type ( ) { return this [ Dc ] } text ( ) { return Promise . resolve ( this [ Zn ] . toString ( ) ) } arrayBuffer ( ) { const n = this [ Zn ] , t = n . buffer . slice ( n . byteOffset , n . byteOffset + n . byteLength ) ; return Promise . resolve ( t ) } stream ( ) { const n = new GS ; return n . _read = function ( ) { } , n . push ( this [ Zn ] ) , n . push ( null ) , n } toString ( ) { return "[object Blob]" } slice ( ) { const n = this . size , t = arguments [ 0 ] , e = arguments [ 1 ] ; let r , i ; t === void 0 ? r = 0 : t < 0 ? r = Math . max ( n + t , 0 ) : r = Math . min ( t , n ) , e === void 0 ? i = n : e < 0 ? i = Math . max ( n + e , 0 ) : i = Math . min ( e , n ) ; const a = Math . max ( i - r , 0 ) , s = this [ Zn ] , o = s . slice ( r , r + a ) , c = new Da ( [ ] , { type : arguments [ 2 ] } ) ; return c [ Zn ] = o , c } } Object . defineProperties ( Da . prototype , { size : { enumerable : ! 0 } , type : { enumerable : ! 0 } , slice : { enumerable : ! 0 } } ) ; Object . defineProperty ( Da . prototype , Symbol . toStringTag , { value : "Blob" , writable : ! 1 , enumerable : ! 1 , configurable : ! 0 } ) ; function zt ( n , t , e ) { Error . call ( this , n ) , this . message = n , this . type = t , e && ( this . code = this . errno = e . code ) , Error . captureStackTrace ( this , this . constructor ) } zt . prototype = Object . create ( Error . prototype ) ; zt . prototype . constructor = zt ; zt . prototype . name = "FetchError" ; let kc ; try { kc = require ( "encoding" ) . convert } catch ( n ) { } const Qn = Symbol ( "Body internals" ) , Sf = pn . default . PassThrough ; function Dt ( n ) { var t = this , e = arguments . length > 1 && arguments [ 1 ] !== void 0 ? arguments [ 1 ] : { } , r = e . size ; let i = r === void 0 ? 0 : r ; var a = e . timeout ; let s = a === void 0 ? 0 : a ; n == null ? n = null : Lf ( n ) ? n = Buffer . from ( n . toString ( ) ) : ka ( n ) || ( Buffer . isBuffer ( n ) || ( Object . prototype . toString . call ( n ) === "[object ArrayBuffer]" ? n = Buffer . from ( n ) : ArrayBuffer . isView ( n ) ? n = Buffer . from ( n . buffer , n . byteOffset , n . byteLength ) : n instanceof pn . default || ( n = Buffer . from ( String ( n ) ) ) ) ) , this [ Qn ] = { body : n , disturbed : ! 1 , error : null } , this . size = i , this . timeout = s , n instanceof pn . default && n . on ( "error" , function ( o ) { const c = o . name === "AbortError" ? o : new zt ( ` Invalid response body while trying to fetch ${ t . url } : ${ o . message } ` , "system" , o ) ; t [ Qn ] . error = c } ) } Dt . prototype = { get body ( ) { return this [ Qn ] . body } , get bodyUsed ( ) { return this [ Qn ] . disturbed } , arrayBuffer ( ) { return Fi . call ( this ) . then ( function ( n ) { return n . buffer . slice ( n . byteOffset , n . byteOffset + n . byteLength ) } ) } , blob ( ) { let n = this . headers && this . headers . get ( "content-type" ) || "" ; return Fi . call ( this ) . then ( function ( t ) { return Object . assign ( new Da ( [ ] , { type : n . toLowerCase ( ) } ) , { [ Zn ] : t } ) } ) } , json ( ) { var n = this ; return Fi . call ( this ) . then ( function ( t ) { try { return JSON . parse ( t . toString ( ) ) } catch ( e ) { return Dt . Promise . reject ( new zt ( ` invalid json response body at ${ n . url } reason: ${ e . message } ` , "invalid-json" ) ) } } ) } , text ( ) { return Fi . call ( this ) . then ( function ( n ) { return n . toString ( ) } ) } , buffer ( ) { return Fi . call ( this ) } , textConverted ( ) { var n = this ; return Fi . call ( this ) . then ( function ( t ) { return YS ( t , n . headers ) } ) } } ; Object . defineProperties ( Dt . prototype , {
2020-11-03 15:34:36 +01:00
` )),c.join( `
2020-11-04 16:18:22 +01:00
` )}function WL(n,t,e,r){var i=dt(t),a=r[r.length-1],s=new Array(a).fill(0),o=t.length,c=e==="complex64"?Ha(n):n;if(o>1)for(var l=0;l<i/a;l++)for(var u=l*a,h=0;h<a;h++)s[h]=Math.max(s[h],Ma(c[u+h],0,e).length);return s}function Ma(n,t,e){var r;return Array.isArray(n)?r=parseFloat(n[0].toFixed(Pu))+" + "+(parseFloat(n[1].toFixed(Pu))+"j"):xr(n)?r="'"+n+"'":e==="bool"?r=Km(n):r=parseFloat(n.toFixed(Pu)).toString(),Ba(r,t)}function Km(n){return n===0?"false":"true"}function $ s(n,t,e,r,i,a){a===void 0&&(a=!0);var s=e==="complex64"?2:1,o=t[0],c=t.length;if(c===0){if(e==="complex64"){var l=Ha(n);return[Ma(l[0],0,e)]}return e==="bool"?[Km(n[0])]:[n[0].toString()]}if(c===1){if(o>jm){var u=Pa*s,h=Array.from(n.slice(0,u)),d=Array.from(n.slice((o-Pa)*s,o*s));return e==="complex64"&&(h=Ha(h),d=Ha(d)),["["+h.map(function(I,C){return Ma(I,i[C],e)}).join(", ")+", ..., "+d.map(function(I,C){return Ma(I,i[o-Pa+C],e)}).join(", ")+"]"]}var p=e==="complex64"?Ha(n):Array.from(n);return["["+p.map(function(I,C){return Ma(I,i[C],e)}).join(", ")+"]"]}var f=t.slice(1),m=r.slice(1),g=r[0]*s,y=[];if(o>jm){for(var w=0;w<Pa;w++){var b=w*g,x=b+g;y.push.apply(y, $ s(n.slice(b,x),f,e,m,i,!1))}y.push("...");for(var w=o-Pa;w<o;w++){var b=w*g,x=b+g;y.push.apply(y, $ s(n.slice(b,x),f,e,m,i,w===o-1))}}else for(var w=0;w<o;w++){var b=w*g,x=b+g;y.push.apply(y, $ s(n.slice(b,x),f,e,m,i,w===o-1))}var S=c===2?",":"";y[0]="["+y[0]+S;for(var w=1;w<y.length-1;w++)y[w]=" "+y[w]+S;for(var N= ` ,
2020-11-03 15:34:36 +01:00
` ,w=2;w<c;w++)N+= `
2020-11-04 16:18:22 +01:00
` ;return y[y.length-1]=" "+y[y.length-1]+"]"+(a?"":N),y}function Ha(n){for(var t=[],e=0;e<n.length;e+=2)t.push([n[e],n[e+1]]);return t}var Xs=function(){function n(t,e,r){var i=this;if(this.dtype=e,this.shape=t.slice(),this.size=dt(t),r!=null){var a=r.length;E(a===this.size,function(){return"Length of values '"+a+"' does not match the size "+("inferred by the shape '"+i.size+"'.")})}if(e==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=r||Ff(e,this.size),this.strides=Ui(t)}return n.prototype.set=function(t){for(var e=this,r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];r.length===0&&(r=[0]),E(r.length===this.rank,function(){return"The number of provided coordinates ("+r.length+") must "+("match the rank ("+e.rank+")")});var a=this.locToIndex(r);this.values[a]=t},n.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];t.length===0&&(t=[0]);for(var r=0,i=0,a=t;i<a.length;i++){var s=a[i];if(s<0||s>=this.shape[r]){var o="Requested out of range element at "+t+". "+(" Buffer shape="+this.shape);throw new Error(o)}r++}for(var c=t[t.length-1],l=0;l<t.length-1;++l)c+=this.strides[l]*t[l];return this.values[c]},n.prototype.locToIndex=function(t){if(this.rank===0)return 0;if(this.rank===1)return t[0];for(var e=t[t.length-1],r=0;r<t.length-1;++r)e+=this.strides[r]*t[r];return e},n.prototype.indexToLoc=function(t){if(this.rank===0)return[];if(this.rank===1)return[t];for(var e=new Array(this.shape.length),r=0;r<e.length-1;++r)e[r]=Math.floor(t/this.strides[r]),t-=e[r]*this.strides[r];return e[e.length-1]=t,e},Object.defineProperty(n.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),n.prototype.toTensor=function(){return kn().makeTensor(this.values,this.shape,this.dtype)},n}(),kn=null,Mi=null;function BL(n){kn=n}function zL(n){Mi=n}var j=function(){function n(t,e,r,i){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=dt(t),this.strides=Ui(t),this.dataId=r,this.id=i,this.rankType=this.rank<5?this.rank.toString():"higher"}return Object.defineProperty(n.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),n.prototype.buffer=function(){return pe(this,void 0,void 0,function(){var t;return fe(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,Mi.buffer(this.shape,this.dtype,t)]}})})},n.prototype.bufferSync=function(){return Mi.buffer(this.shape,this.dtype,this.dataSync())},n.prototype.array=function(){return pe(this,void 0,void 0,function(){var t;return fe(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,Bi(this.shape,t)]}})})},n.prototype.arraySync=function(){return Bi(this.shape,this.dataSync())},n.prototype.data=function(){return pe(this,void 0,void 0,function(){var t,e;return fe(this,function(r){switch(r.label){case 0:return this.throwIfDisposed(),t=kn().read(this.dataId),this.dtype==="string"?[4,t]:[3,2];case 1:e=r.sent();try{return[2,e.map(function(i){return zu(i)})]}catch(i){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}r.label=2;case 2:return[2,t]}})})},n.prototype.dataSync=function(){this.throwIfDisposed();var t=kn().readSync(this.dataId);if(this.dtype==="string")try{return t.map(function(e){return zu(e)})}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t},n.prototype.bytes=function(){return pe(this,void 0,void 0,function(){var t;return fe(this,function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,kn().read(this.dataId)];case 1:return t=e.sent(),this.dtype==="string"?[2,t]:[2,new Uint8Array(t.buffer)]}})})},n.prototype.dispose=function(){if(this.isDisposed)return;kn().disposeTensor(this),this.isDisposedInternal=!0},Object.defineProperty(n.prototype,"isDisposed",{get:function(){return this.is
` )+"Manifest JSON has weights with names: "+(c.join(", ")+"."));return u=a.reduce(function(g,y,w){return y&&g.push(w),g},[]),h=[],u.forEach(function(g){e[g].paths.forEach(function(y){var w=r+(r.endsWith("/")?"":"/")+y;h.push(w)})}),[4,n(h)];case 1:return d=m.sent(),p={},f=0,u.forEach(function(g){for(var y=e[g].paths.length,w=0,b=0;b<y;b++)w+=d[f+b].byteLength;for(var x=new ArrayBuffer(w),S=new Uint8Array(x),N=0,I=0;I<y;I++){var C=new Uint8Array(d[f+I]);S.set(C,N),N+=C.byteLength}var O=s[g];O.forEach(function(D){var F=x.slice(D.groupOffset,D.groupOffset+D.sizeBytes),k=rg(F,[D.manifestEntry]);for(var B in k)p[B]=k[B]}),f+=y}),[2,p]}})})}}var zI="application/octet-stream",PI="application/json",yg=function(){function n(t,e){if(this.DEFAULT_METHOD="POST",e==null&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,this.weightUrlConverter=e.weightUrlConverter,e.fetchFunc!=null?(E(typeof e.fetchFunc=="function",function(){return"Must pass a function that matches the signature of ` fetch ` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"}),this.fetch=e.fetchFunc):this.fetch=Ge().platform.fetch,E(t!=null&&t.length>0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&E(t.length===2,function(){return"URL paths for http must have a length of 2, "+("(actual length is "+t.length+").")}),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return n.prototype.save=function(t){return pe(this,void 0,void 0,function(){var e,r,i,a;return fe(this,function(s){switch(s.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit),e.body=new FormData,r=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],i={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:r},e.body.append("model.json",new Blob([JSON.stringify(i)],{type:PI}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:zI}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if(a=s.sent(),a.ok)return[2,{modelArtifactsInfo:Ga(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+(a.status+"."))}})})},n.prototype.load=function(){return pe(this,void 0,void 0,function(){var t,e,r,i,a,s,o,c,l,u,h,d,p,f,m;return fe(this,function(g){switch(g.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(t=g.sent(),!t.ok)throw new Error("Request to "+this.path+" failed with status code "+(t.status+". Please verify this URL points to ")+"the model JSON of the model to load.");g.label=2;case 2:return g.trys.push([2,4,,5]),[4,t.json()];case 3:return e=g.sent(),[3,5];case 4:throw r=g.sent(),i="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?i+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":i+=" Please make sure the server is serving valid JSON for this request.",new Error(i);case 5:if(a=e.modelTopology,s=e.weightsManifest,o=e.generatedBy,c=e.convertedBy,l=e.format,u=e.userDefinedMetadata,a==null&&s==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return s!=null?[4,this.loadWeights(s)]:[3,7];case 6:p=g.sent(),h=p[0],d=p[1],g.label=7;case 7:return f={modelTopology:a,weightSpecs:h,weightData:d,userDefinedMetadata:u,generatedBy:o,convertedBy:c,format:l},m=e.modelInitializer,m&&(f.modelInitializer=m),[2,f]}})})},n.prototype.loadWe
2020-11-03 15:34:36 +01:00
` )+("Actual: "+c+ ` .
` )+("Expected: "+l+"."));for(var u=0;u<l.length;++u){var h=c[u],d=l[u];if(!e(h,d))throw new Error("Arrays differ: actual["+u+"] = "+h+", expected["+u+"] = "+d+ ` .
` +("Actual: "+c+ ` .
2020-11-04 16:18:22 +01:00
` )+("Expected: "+l+"."))}}function hA(n,t){n().then(function(){return t.fail()},function(){return t()})}function dA(n,t){var e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return xr(n)||xr(n[0])||xr(t)||xr(t[0])?oh(n,e,function(r,i){return r==i}):oh(n,t,function(r,i){return ch(r,i,0)})}function pA(n,t,e){if(e==null&&(e=sh()),!ch(n,t,e))throw new Error("Numbers differ: actual === "+n+", expected === "+t)}function ch(n,t,e){return!isFinite(n)&&!isFinite(t)?!0:!(isNaN(n)||isNaN(t)||Math.abs(n-t)>e)}function fA(n,t,e){for(var r=0;r<n.length;r++)if(n[r]<t||n[r]>e)throw new Error("Value out of range:"+n[r]+" low: "+t+", high: "+e)}function mA(n,t){expect(new Float32Array(n)).toEqual(new Float32Array(t))}var gA={__proto__:null,TEST_EPSILON_FLOAT16:Wg,expectArraysClose:uA,testEpsilon:sh,expectPromiseToFail:hA,expectArraysEqual:dA,expectNumbersClose:pA,expectValuesInRange:fA,expectArrayBuffersEqual:mA};var yA="2.7.0";function vA(){Ge().set("PROD",!0)}function wA(){Ge().set("DEBUG",!0)}function bA(){Ge().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function _t(n){Ge().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function xA(){z.disposeVariables()}function SA(){return z}function LA(){return z.memory()}function IA(n){return z.profile(n)}function bt(n,t){return z.tidy(n,t)}function Vt(n){var t=Gu(n);t.forEach(function(e){return e.dispose()})}function Ug(n){return z.keep(n)}function AA(n){return z.time(n)}function TA(n){return z.setBackend(n)}function NA(){return z.ready()}function _A(){return z.backendName}function CA(n){z.removeBackend(n)}function RA(n){return z.findBackend(n)}function OA(n){return z.findBackendFactory(n)}function EA(n,t,e){return e===void 0&&(e=1),z.registerBackend(n,t,e)}function DA(){return z.backend}function kA(n,t){Ge().setPlatform(n,t)}function FA(n,t){var e,r=R(n,"a","add"),i=R(t,"b","add");e=ct(r,i),r=e[0],i=e[1];var a=function(o,c){var l=o.add(r,i);return c([r,i]),l},s={a:r,b:i};return z.runKernelFunc(a,s,null,Gs)}var ge=U({add_:FA});function WA(n,t){var e,r=R(n,"a","floorDiv"),i=R(t,"b","floorDiv");e=ct(r,i),r=e[0],i=e[1];var a=function(o,c){var l=o.floorDiv(r,i);return c([r,i]),l},s={a:r,b:i};return z.runKernelFunc(a,s,null,Al)}var lh=U({floorDiv_:WA});function UA(n,t){var e,r=R(n,"a","div"),i=R(t,"b","div");if(e=ct(r,i),r=e[0],i=e[1],r.dtype==="int32"&&i.dtype==="int32")return lh(r,i);var a=function(c,l){var u=c.realDivide(r,i);return l([r,i]),u},s={a:r,b:i},o={};return z.runKernelFunc(a,s,null,wl,o)}var Ne=U({div_:UA});function BA(n,t){var e,r=R(n,"a","mul"),i=R(t,"b","mul");e=ct(r,i),r=e[0],i=e[1];var a=function(o,c){var l=o.multiply(r,i);return c([r,i]),l},s={a:r,b:i};return z.runKernelFunc(a,s,null,Gl)}var Z=U({mul_:BA});function zA(n){var t=R(n,"x","abs"),e={x:t};return z.runKernelFunc(function(r,i){return i([t]),t.dtype==="complex64"?r.complexAbs(t):r.abs(t)},e,null,Yc)}var Jt=U({abs_:zA});function PA(n){var t=R(n,"x","acos"),e={x:t};return z.runKernelFunc(function(r,i){var a=r.acos(t);return i([t]),a},e,null,jc)}var Bg=U({acos_:PA});function MA(n){var t=R(n,"x","acosh"),e={x:t};return z.runKernelFunc(function(r,i){var a=r.acosh(t);return i([t]),a},e,null,Kc)}var zg=U({acosh_:MA});function HA(n){E(Array.isArray(n),function(){return"The argument passed to tf.addN() must be a list of tensors"}),E(n.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+(""+n.length)});var t=n.map(function(a,s){return R(a,"tensors"+s,"addN")}),e=t[0];t.forEach(function(a){if(a.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(a){if(!vn(a.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=function(a,s){var o=a.addN(t);return s(t),o},i=t;return z.runKernelFunc(r,i,null, $ c)}var VA=U({addN_:HA});function uh(n,t){for(var e=0;e<n.length;++e)if(n[n.length-e-1]!==t-1-e)return!1;return!0}function Pg(n,t,e){for(var r=n
with dtype ` +s.dtype+". ")});var r=function(s,o){var c=rt(t,e[0].shape)[0],l=Zg(e.map(function(d){return d.shape}),c);if(dt(l)===0)return Ar([],l);if(e=e.filter(function(d){return d.size>0}),e.length===1)return e[0];var u=e.map(function(d){return d.shape});Jg(u,c);var h=s.concat(e,c);return o(e),h},i=e,a={axis:t};return z.runKernelFunc(r,i,null,ul,a)}var kt=U({concat_:c5});function l5(n){var t=R(n,"x","sigmoid"),e={x:t};return z.runKernelFunc(function(r,i){var a=r.sigmoid(t);return i([a]),a},e,null,pu)}var ni=U({sigmoid_:l5});function u5(n,t,e){var r=R(n,"x","slice");if(r.rank===0)throw new Error("Slicing scalar is not possible");var i=function(o,c){var l=ah(r,t,e),u=l[0],h=l[1];return Sg(r,u,h),c([r]),o.slice(r,u,h)},a={x:r},s={begin:t,size:e};return z.runKernelFunc(i,a,null,lu,s)}var Me=U({slice_:u5});function h5(n){var t=R(n,"x","tanh"),e={x:t};return z.runKernelFunc(function(r,i){var a=r.tanh(t);return i([a]),a},e,null,Lu)}var io=U({tanh_:h5});function d5(n,t,e,r,i,a){var s=R(n,"forgetBias","basicLSTMCell"),o=R(t,"lstmKernel","basicLSTMCell"),c=R(e,"lstmBias","basicLSTMCell"),l=R(r,"data","basicLSTMCell"),u=R(i,"c","basicLSTMCell"),h=R(a,"h","basicLSTMCell"),d=kt([l,h],1),p=Ue(d,o),f=ge(p,c),m=f.shape[0],g=f.shape[1]/4,y=[m,g],w=Me(f,[0,0],y),b=Me(f,[0,g],y),x=Me(f,[0,g*2],y),S=Me(f,[0,g*3],y),N=ge(Z(ni(w),io(b)),Z(u,ni(ge(s,x)))),I=Z(io(N),ni(S));return[N,I]}var p5=U({basicLSTMCell_:d5});function f5(n,t,e){var r=R(n,"x","batchToSpaceND"),i=t.reduce(function(c,l){return c*l});E(r.rank>=1+t.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+t.length}),E(e.length===t.length,function(){return"crops.length is "+e.length+" but should be equal to blockShape.length "+t.length}),E(r.shape[0]%i===0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of "+("the elements of blockShape "+t.join(" * ")+" === "+i)});var a=function(c){return c.batchToSpaceND(r,t,e)},s={x:r},o={blockShape:t,crops:e};return z.runKernelFunc(a,s,null,sl,o)}var ao=U({batchToSpaceND_:f5});function m5(n){var t;return n.rank===0||n.rank===1?t=Y(n,[1,1,1,n.size]):n.rank===2?t=Y(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?t=Y(n,[1,n.shape[0],n.shape[1],n.shape[2]]):t=n,t}function g5(n,t,e,r,i,a){a==null&&(a=.001);var s=R(n,"x","batchNorm"),o=R(t,"mean","batchNorm"),c=R(e,"variance","batchNorm"),l;i!=null&&(l=R(i,"scale","batchNorm"));var u;r!=null&&(u=R(r,"offset","batchNorm")),E(o.rank===c.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),E(u==null||o.rank===u.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),E(l==null||o.rank===l.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var h=m5(s),d=function(g,y){return y([h,o,c,l]),g.batchNorm(h,so(o),so(c),so(u),so(l),a)},p={x:h,scale:l,offset:u,mean:o,variance:c},f={varianceEpsilon:a},m=z.runKernelFunc(d,p,null,Tl,f);return Y(m,s.shape)}function so(n){return n==null?null:n.rank===0?Y(n,[n.size]):n.rank===1?n:n.rank===2?Y(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?Y(n,[1,n.shape[0],n.shape[1],n.shape[2]]):n}var $ a=U({batchNorm_:g5});function y5(n,t,e,r,i,a){var s=R(n,"x","batchNorm"),o=R(t,"mean","batchNorm"),c=R(e,"variance","batchNorm"),l;i!=null&&(l=R(i,"scale","batchNorm"));var u;return r!=null&&(u=R(r,"offset","batchNorm")),E(s.rank===2,function(){return"Error in batchNorm2D: x must be rank 2 but got rank "+(s.rank+".")}),E(o.rank===2||o.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but "+("got rank "+o.rank+".")}),E(c.rank===2||c.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 "+("but got rank "+c.rank+".")}),l!=null&&E(l.rank===2||l.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 "+("but got rank "+l.rank+".")}),u!=null&&E(u.rank===2||u.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 "+("but got rank "+u.rank+".")}), $ a(s,o,c,u,l,a)}var
2020-11-03 15:34:36 +01:00
` +i+" and "+t+ ` for depthToSpace with input shape
` +r.shape}),E(a*t>=0,function(){return ` Negative dimension size caused by overflow when multiplying
` +a+" and "+t+ ` for depthToSpace with input shape
2020-11-04 16:18:22 +01:00
` +r.shape}),E(s%(t*t)===0,function(){return"Dimension size must be evenly divisible by "+t*t+" but is "+s+" for depthToSpace with input shape "+r.shape});var o=function(u){return u.depthToSpace(r,t,e)},c={x:r},l={blockSize:t,dataFormat:e};return z.runKernelFunc(o,c,null,rm,l)}var i0=U({depthToSpace_:Y5});function j5(n,t,e,r,i,a,s){i===void 0&&(i="NHWC"),a===void 0&&(a=[1,1]);var o=R(n,"x","depthwiseConv2d"),c=R(t,"filter","depthwiseConv2d"),l=o,u=!1;o.rank===3&&(u=!0,l=Y(o,[1,o.shape[0],o.shape[1],o.shape[2]])),E(l.rank===4,function(){return"Error in depthwiseConv2d: input must be rank 4, but got "+("rank "+l.rank+".")}),E(c.rank===4,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+(c.rank+".")}),E(l.shape[3]===c.shape[2],function(){return"Error in depthwiseConv2d: number of input channels "+("("+l.shape[3]+") must match the inChannels dimension in ")+("filter "+c.shape[2]+".")}),s!=null&&E(ot(r),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+s+" but got pad "+r+".")});var h=function(m,g){a==null&&(a=[1,1]),E(qt(e,a),function(){return"Error in depthwiseConv2d: Either strides or dilations must be "+("1. Got strides "+e+" and dilations '"+a+"'")});var y=bn(l.shape,c.shape,e,a,r,s,!0),w=m.depthwiseConv2D(l,c,y);return g([l,c]),w},d={x:l,filter:c},p={strides:e,pad:r,dataFormat:i,dilations:a,dimRoundingMode:s},f=z.runKernelFunc(h,d,null,yl,p);return u?Y(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Xa=U({depthwiseConv2d_:j5});function K5(n){var t=R(n,"x","diag"),e=function(i){var a=Y(t,[t.size]),s=i.diag(a),o=n.shape.concat(n.shape);return Y(s,o)},r={x:t};return z.runKernelFunc(e,r,null,sm)}var $ 5=U({diag_:K5});function X5(n,t,e,r,i,a){i===void 0&&(i=[1,1]),a===void 0&&(a="NHWC");var s=R(n,"x","dilation2d"),o=R(t,"filter","dilation2d");E(s.rank===3||s.rank===4,function(){return"Error in dilation2d: input must be rank 3 or 4, but got rank "+(s.rank+".")}),E(o.rank===3,function(){return"Error in dilation2d: filter must be rank 3, but got rank "+(o.rank+".")}),E(a==="NHWC",function(){return"Error in dilation2d: Only NHWC is currently supported, "+("but got dataFormat of "+a)});var c=s,l=!1;s.rank===3&&(c=Y(s,[1,s.shape[0],s.shape[1],s.shape[2]]),l=!0);var u={x:c,filter:o},h={strides:e,pad:r,dilations:i},d=z.runKernel(vl,u,h);return l?Y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var a0=U({dilation2d_:X5});function J5(n,t){for(var e=n.length,r=[],i=0;i<e;i++){var a=e-1-i,s=n[a]||1,o=t[t.length-1-i]||1;o>1&&s===1&&r.unshift(a)}return r}function xt(n,t){for(var e=[],r=0;r<t.length;r++){var i=n[n.length-r-1],a=t.length-r-1,s=t[a];(i==null||i===1&&s>1)&&e.unshift(a)}return e}function it(n,t){for(var e=[],r=Math.max(n.length,t.length),i=0;i<r;i++){var a=n[n.length-i-1];a==null&&(a=1);var s=t[t.length-i-1];if(s==null&&(s=1),a===1)e.unshift(s);else if(s===1)e.unshift(a);else if(a!==s){var o="Operands could not be broadcast together with shapes "+(n+" and "+t+".");throw Error(o)}else e.unshift(a)}return e}function Z5(n,t){var e,r=R(n,"a","equal"),i=R(t,"b","equal");e=ct(r,i),r=e[0],i=e[1],it(r.shape,i.shape);var a=function(o){return o.equal(r,i)},s={a:r,b:i};return z.runKernelFunc(a,s,null,um)}var Ja=U({equal_:Z5});function Q5(n,t,e){var r=R(t,"a","where"),i=R(e,"b","where"),a=R(n,"condition","where","bool"),s=it(r.shape,i.shape),o=oo(r,s),c=oo(i,s);a.rank===1&&E(a.shape[0]===r.shape[0],function(){return"The first dimension of ` a ` must match the size of ` condition ` ."}),a.rank!==1&&Pe(a.shape,c.shape,"Error in where: ");var l=function(h,d){var p=h.select(a,o,c);return d([a]),p},u={condition:a,t:o,e:c};return z.runKernelFunc(l,u,null,ou)}var xn=U({where_:Q5});function eT(n){var t=R(n,"x","zerosLike"),e={x:t};return z.runKernelFunc(function(r){return r.zerosLike(t)},e,null,_u)}var ke=U({zerosLike_:eT});function tT(n,t){var e,r=R(n,"a","div"),i=R(t,"b","div");e=ct(r,i),r=e[0],i=e[1];var a=Ne(r,i),s=ke(a),o=Ja(i,s);return xn(o,s,a)}var s0=U({divNoNan_:tT});function nT(n,t){var e=R(n,"t1","dot"),r=R(t,"t2","dot");E((e.rank===1||e.rank===2)&&(r.rank===1||r
rank ` +a.rank+"."}),E(ot(t),function(){return"Error in localResponseNormalization: depthRadius must be an "+("integer but got depthRadius "+t+".")});var s=a,o=!1;a.rank===3&&(o=!0,s=Y(a,[1,a.shape[0],a.shape[1],a.shape[2]]));var c=function(d,p){var f=d.localResponseNormalization4D(s,t,e,r,i);return p([s,f]),f},l={x:s},u={depthRadius:t,bias:e,alpha:r,beta:i},h=z.runKernelFunc(c,l,null,Wl,u);return o?Y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var g0=U({localResponseNormalization_:NT});function _T(n){var t=R(n,"x","log"),e={x:t};return z.runKernelFunc(function(r,i){var a=r.log(t);return i([t]),a},e,null,Dl)}var ai=U({log_:_T});function CT(n){var t=R(n,"x","log1p"),e={x:t};return z.runKernelFunc(function(r,i){var a=r.log1p(t);return i([t]),a},e,null,kl)}var bh=U({log1p_:CT});function RT(n){return E(Sr(n),function(){return"The f passed in grad(f) must be a function"}),function(t,e){var r=R(t,"x","tf.grad",null),i=e!=null?R(e,"dy","tf.grad"):null;return z.tidy(function(){var a=z.gradients(function(){return n(r)},[r],i),s=a.value,o=a.grads;return i!=null&&Pe(s.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),fo(o),o[0]})}}function OT(n){return E(Sr(n),function(){return"The f passed in grads(f) must be a function"}),function(t,e){E(Array.isArray(t),function(){return"The args passed in grads(f)(args) must be an array of ` Tensor ` s or ` TensorLike ` s"});var r=qa(t,"args","tf.grads",null),i=e!=null?R(e,"dy","tf.grads"):null;return z.tidy(function(){var a=z.gradients(function(){return n.apply(void 0,r)},r,i),s=a.value,o=a.grads;return i!=null&&Pe(s.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),fo(o),o})}}function ET(n){return E(Sr(n),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(t,e){E(t instanceof j,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),E(e==null||e instanceof j,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var r=z.gradients(function(){return n(t)},[t],e),i=r.grads,a=r.value;return fo(i),{grad:i[0],value:a}}}function DT(n){return E(Sr(n),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(t,e){E(Array.isArray(t)&&t.every(function(i){return i instanceof j}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),E(e==null||e instanceof j,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var r=z.gradients(function(){return n.apply(void 0,t)},t,e);return e!=null&&Pe(r.value.shape,e.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),fo(r.grads),r}}function y0(n,t){E(Sr(n),function(){return"The f passed in variableGrads(f) must be a function"}),E(t==null||Array.isArray(t)&&t.every(function(h){return h instanceof Va}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"});var e=t!=null;if(!e){t=[];for(var r in z.registeredVariables)t.push(z.registeredVariables[r])}var i=e?t.filter(function(h){return!h.trainable}):null,a=t.length;t=t.filter(function(h){return h.trainable}),E(t.length>0,function(){return"variableGrads() expects at least one of the input variables to "+("be trainable, but none of the "+a+" variables is ")+"trainable."});var s=!0,o=z.gradients(n,t,null,s),c=o.value,l=o.grads;E(l.some(function(h){return h!=null}),function(){return"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(c.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it "+("returned a rank-"+c.rank+" tensor")});var u={};return t.forEach(function(h,d){l[d]!=null&&(u[h.name]=l[d])}),i!=null&&i.forEach(function(h){return u[h.name]=null}),{value:c,grads:u}}function Bn(n){return z.customGrad(n)}function fo(n){var t=n.filter(function(e){return e==null}).length;if(t>0)throw ne
the f you passed encloses all operations that lead from x to y . ` )}function kT(n){var t=R(n,"x","neg"),e={x:t};return z.runKernelFunc(function(r){return r.neg(t)},e,null,Yl)}var St=U({neg_:kT});function FT(n){var t=R(n,"x","softplus"),e={x:t};return z.runKernelFunc(function(r,i){var a=r.softplus(t);return i([t]),a},e,null,fu)}var xh=U({softplus_:FT});function WT(n){var t=R(n,"x","logSigmoid"),e=Bn(function(r){var i=St(xh(St(r))),a=function(s){var o=Z(s,ni(St(r)));return o};return{value:i,gradFunc:a}});return e(t)}var v0=U({logSigmoid_:WT});function UT(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var r=R(n,"x","max"),i=function(o,c){var l=rt(t,r.shape),u=l,h=wn(u,r.rank),d=r;h!=null&&(d=Nt(r,h),u=Un(u.length,d.rank));var p=o.max(d,u);h!=null&&d.dispose();var f=p;if(e){var m=cn(f.shape,rt(t,r.shape));f=Y(f,m),p.dispose()}return c([r,f]),f},a={x:r},s={reductionIndices:t,keepDims:e};return z.runKernelFunc(i,a,null,Ul,s)}var si=U({max_:UT});function BT(n,t){var e,r=R(n,"a","sub"),i=R(t,"b","sub");e=ct(r,i),r=e[0],i=e[1];var a=function(o,c){var l=o.subtract(r,i);return c([r,i]),l},s={a:r,b:i};return z.runKernelFunc(a,s,null,xu)}var we=U({sub_:BT});function zT(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var r=R(n,"x","sum");r.dtype==="bool"&&(r=he(r,"int32"));var i=function(o,c){c([r]);var l=rt(t,r.shape),u=wn(l,r.rank),h=l,d=r;u!=null&&(d=Nt(r,u),h=Un(h.length,r.rank));var p=o.sum(d,h);if(e){var f=cn(p.shape,l);p=Y(p,f)}return p},a={x:r},s={axis:t,keepDims:e};return z.runKernelFunc(i,a,null,gu,s)}var _e=U({sum_:zT});function PT(n,t){t===void 0&&(t=-1);var e=R(n,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. "+("Logits was rank "+e.rank+" and axis was "+t));var r=function(s,o){var c=!0,l=si(n,t,!0),u=we(n,l),h=we(he(u,"float32"),ai(_e(Sn(u),t,c)));return o([h]),h},i={logits:e},a={axis:t};return z.runKernelFunc(r,i,null,Fl,a)}var w0=U({logSoftmax_:PT});function MT(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var r=R(n,"x","logSumExp"),i=rt(t,r.shape),a=si(r,i,!0),s=we(r,a),o=Sn(s),c=_e(o,i),l=ai(c),u=ge(Y(a,l.shape),l);if(e){var h=cn(u.shape,i);return Y(u,h)}return u}var Sh=U({logSumExp_:MT});function HT(n,t){var e=R(n,"a","logicalAnd","bool"),r=R(t,"b","logicalAnd","bool");it(e.shape,r.shape);var i={a:e,b:r};return z.runKernelFunc(function(a){return a.logicalAnd(e,r)},i,null,xm)}var oi=U({logicalAnd_:HT});function VT(n){var t=R(n,"x","logicalNot","bool"),e={x:t};return z.runKernelFunc(function(r){return r.logicalNot(t)},e,null,Sm)}var mo=U({logicalNot_:VT});function qT(n,t){var e=R(n,"a","logicalOr","bool"),r=R(t,"b","logicalOr","bool");it(e.shape,r.shape);var i={a:e,b:r};return z.runKernelFunc(function(a){return a.logicalOr(e,r)},i,null,Lm)}var Lh=U({logicalOr_:qT});function GT(n,t){var e=R(n,"a","logicalXor","bool"),r=R(t,"b","logicalXor","bool");return it(e.shape,r.shape),oi(Lh(n,t),mo(oi(n,t)))}var b0=U({logicalXor_:GT});function YT(n,t,e,r,i){var a=R(n,"x","maxPool"),s=1,o=a,c=!1;a.rank===3&&(c=!0,o=Y(a,[1,a.shape[0],a.shape[1],a.shape[2]])),E(o.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+o.rank+"."}),E(qt(e,s),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+s+"'")}),i!=null&&E(ot(r),function(){return"Error in maxPool: pad must be an integer when using, "+("dimRoundingMode "+i+" but got pad "+r+".")});var l=function(p,f){var m=ji(o.shape,t,e,1,r,i),g;return m.filterWidth===1&&m.filterHeight===1&&vn(m.inShape,m.outShape)?g=o.clone():g=p.maxPool(o,m),f([o,g]),g},u={x:o},h={filterSize:t,strides:e,pad:r,dimRoundingMode:i},d=z.runKernelFunc(l,u,null,zl,h);return c?Y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Ih=U({maxPool_:YT});function jT(n,t,e,r,i,a,s){t===void 0&&(t=[1,1,1]),a===void 0&&(a="NDHWC"),s==null?s=[1,1,1]:_t("dilations is deprecated, this field will be gone in v3.0.0.");var o=R(n,"x","maxPool3d"),c=o,l=!1;o.rank===4&&(l=!0,c=Y(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),E(c.rank===5,function(){return"Error i
2020-11-03 15:34:36 +01:00
` +("1. The "+r+" is defined in Python, in which ")+ ` case it needs to be ported to TensorFlow . js or your JavaScript code .
` +("2. The custom "+r+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");return l}else{var u=n;if(u.className==null||u.config==null)throw new M(r+": Improper config format: "+(JSON.stringify(u)+ ` .
2020-11-04 16:18:22 +01:00
` )+"'className' and 'config' must set.");var h=u.className,d=void 0,p=void 0;if(h in e?(a=e[h],d=a[0],p=a[1]):h in fn?(s=fn.className,d=s[0],p=s[1]):h in t&&(o=t[h],d=o[0],p=o[1]),d==null)throw new M("Unknown "+r+": "+h+ ` . This may be due to one of the following reasons :
2020-11-03 15:34:36 +01:00
` +("1. The "+r+" is defined in Python, in which ")+ ` case it needs to be ported to TensorFlow . js or your JavaScript code .
2020-11-04 16:18:22 +01:00
` +("2. The custom "+r+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");if(p!=null){for(var f={},m=0,g=Object.keys(fn);m<g.length;m++){var y=g[m];f[y]=fn[y]}for(var w=0,b=Object.keys(e);w<b.length;w++){var y=b[w];f[y]=e[y]}var x=u.config;x.customObjects=f;for(var S=Zt({},fn),N=0,I=Object.keys(e);N<I.length;N++){var y=I[N];fn[y]=e[y]}Xh(u.config);var C=p(d,u.config,e,i);return fn=Zt({},S),C}else{for(var S=Zt({},fn),O=0,D=Object.keys(e);O<D.length;O++){var y=D[O];fn[y]=e[y]}var C=new d(u.config);return fn=Zt({},S),C}}}function bE(n,t){return n<t?-1:n>t?1:0}function Oo(n,t){return-1*bE(n,t)}function Dr(n){if(n==null)return n;for(var t=[],e=0,r=n;e<r.length;e++){var i=r[e];t.indexOf(i)===-1&&t.push(i)}return t}function xE(n){if(n==null)throw new M("Invalid value in obj: "+JSON.stringify(n));for(var t in n)if(n.hasOwnProperty(t))return!1;return!0}function ia(n,t,e){if(e==null)return;if(n.indexOf(e)<0)throw new M(e+" is not a valid "+t+". Valid values are "+n+" or null/undefined.")}function Jh(n,t,e,r){return e===void 0&&(e=0),r===void 0&&(r=Infinity),Pn(e>=0),Pn(r>=e),Array.isArray(n)&&n.length>=e&&n.length<=r&&n.every(function(i){return typeof i===t})}function Ct(n,t){Array.isArray(n)?(v.util.assert(n.length>0,function(){return t+" is unexpectedly an empty array."}),n.forEach(function(e,r){return Ct(e,"element "+(r+1)+" of "+t)})):v.util.assert(Number.isInteger(n)&&n>0,function(){return"Expected "+t+" to be a positive integer, but got "+(Ly(n)+".")})}function Ly(n){return n===null?"null":Array.isArray(n)?"["+n.map(function(t){return Ly(t)}).join(",")+"]":typeof n=="string"?'"'+n+'"':""+n}function SE(n,t){var e=v.util.now(),r,i=function(){for(var a=[],s=0;s<arguments.length;s++)a[s]=arguments[s];var o=v.util.now();return o-e<t||(e=o,r=n.apply(void 0,a)),r};return i}function Iy(n){return n==="relu"?"relu":n==="linear"?"linear":n==="elu"?"elu":null}function Zh(n,t){return v.tidy(function(){return v.sqrt(v.sum(v.mul(n,n),t,!0))})}var is=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.getConfig=function(){return{}},t}(v.serialization.Serializable),Ay=function(n){Q(t,n);function t(e){var r=n.call(this)||this;return r.defaultMaxValue=2,r.defaultAxis=0,r.maxValue=e.maxValue!=null?e.maxValue:r.defaultMaxValue,r.axis=e.axis!=null?e.axis:r.defaultAxis,r}return t.prototype.apply=function(e){var r=this;return v.tidy(function(){var i=Zh(e,r.axis),a=v.clipByValue(i,0,r.maxValue);return v.mul(e,v.div(a,v.add(Lt(),i)))})},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},t.className="MaxNorm",t}(is);v.serialization.registerClass(Ay);var Ty=function(n){Q(t,n);function t(e){var r=n.call(this)||this;return r.defaultAxis=0,r.axis=e.axis!=null?e.axis:r.defaultAxis,r}return t.prototype.apply=function(e){var r=this;return v.tidy(function(){return v.div(e,v.add(Lt(),Zh(e,r.axis)))})},t.prototype.getConfig=function(){return{axis:this.axis}},t.className="UnitNorm",t}(is);v.serialization.registerClass(Ty);var Ny=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.apply=function(e){return v.relu(e)},t.className="NonNeg",t}(is);v.serialization.registerClass(Ny);var _y=function(n){Q(t,n);function t(e){var r=n.call(this)||this;return r.defaultMinValue=0,r.defaultMaxValue=1,r.defaultRate=1,r.defaultAxis=0,r.minValue=e.minValue!=null?e.minValue:r.defaultMinValue,r.maxValue=e.maxValue!=null?e.maxValue:r.defaultMaxValue,r.rate=e.rate!=null?e.rate:r.defaultRate,r.axis=e.axis!=null?e.axis:r.defaultAxis,r}return t.prototype.apply=function(e){var r=this;return v.tidy(function(){var i=Zh(e,r.axis),a=v.add(v.mul(r.rate,v.clipByValue(i,r.minValue,r.maxValue)),v.mul(1-r.rate,i));return v.mul(e,v.div(a,v.add(Lt(),i)))})},t.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},t.className="MinMaxNorm",t}(is);v.serialization.registerClass(_y);var Cy={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};fun
because the value dtype is ` +e.dtype+", but TensorArray dtype is "+this.dtype+".");if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=e.shape),gn(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+t+"."),r.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been read.");if(r.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been written.");r.tensor=e,W.keep(e),r.written=!0,this.tensors[t]=r},n.prototype.writeMany=function(t,e){var r=this;if(t.length!==e.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,"+("because the index size: "+t.length+" is not the same as tensors size: "+e.length+"."));t.forEach(function(i,a){return r.write(i,e[a])})},n.prototype.gather=function(t,e){if(!!e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+e);if(t)t=t.slice(0,this.size());else{t=[];for(var r=0;r<this.size();r++)t.push(r)}if(t.length===0)return W.tensor([],[0].concat(this.elementShape));var i=this.readMany(t);return gn(this.elementShape,i[0].shape,"TensorArray shape mismatch: "),W.stack(i,0)},n.prototype.concat=function(t){if(!!t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but concat requested dtype "+t);if(this.size()===0)return W.tensor([],[0].concat(this.elementShape));for(var e=[],r=0;r<this.size();r++)e.push(r);var i=this.readMany(e);return gn(this.elementShape,i[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+i[0].shape+")"),W.concat(i,0)},n.prototype.scatter=function(t,e){if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);if(t.length!==e.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+t.length+" vs. "+e.shape[0]);var r=Math.max.apply(Math,Hr(t));if(!this.dynamicSize&&r>=this.maxSize)throw new Error("Max index must be < array size ("+r+" vs. "+this.maxSize+")");this.writeMany(t,W.unstack(e,0))},n.prototype.split=function(t,e){var r=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var i=0,a=t.map(function(u){return i+=u,i});if(i!==e.shape[0])throw new Error( ` Expected sum of lengths to be equal to
2020-11-03 15:34:36 +01:00
tensor . shape [ 0 ] , but sum of lengths is
2020-11-04 16:18:22 +01:00
` +i+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var s=i===0?0:e.size/i,o=[];W.tidy(function(){e=W.reshape(e,[1,i,s]);for(var u=0;u<t.length;++u){var h=u===0?0:a[u-1],d=[0,h,0],p=[1,t[u],s];o[u]=W.reshape(W.slice(e,d,p),r.elementShape)}return o});for(var c=[],l=0;l<t.length;l++)c[l]=l;this.writeMany(c,o)},n}();var tc=function(){function n(t,e,r,i){i===void 0&&(i=-1),this.tensors=t,this.elementShape=e,this.elementDtype=r,t!=null&&t.forEach(function(a){if(r!==a.dtype)throw new Error("Invalid data types; op elements "+r+", but list elements "+a.dtype);gn(e,a.shape,"TensorList shape mismatch: "),W.keep(a)}),this.idTensor=W.scalar(0),this.maxNumElements=i,W.keep(this.idTensor)}return Object.defineProperty(n.prototype,"id",{get:function(){return this.idTensor.id},enumerable:!0,configurable:!0}),n.prototype.copy=function(){return new n(Hr(this.tensors),this.elementShape,this.elementDtype)},n.prototype.clearAndClose=function(t){this.tensors.forEach(function(e){(t==null||!t.has(e.id))&&e.dispose()}),this.tensors.length=0,this.idTensor.dispose()},n.prototype.size=function(){return this.tensors.length},n.prototype.stack=function(t,e,r){var i=this;if(r===void 0&&(r=-1),e!==this.elementDtype)throw new Error("Invalid data types; op elements "+e+", but list elements "+this.elementDtype);if(r!==-1&&this.tensors.length!==r)throw new Error("Operation expected a list with "+r+" elements but got a list with "+this.tensors.length+" elements.");return gn(t,this.elementShape,"TensorList shape mismatch: "),W.tidy(function(){var a=i.tensors.map(function(s){return W.reshape(s,t)});return W.stack(a,0)})},n.prototype.popBack=function(t,e){if(e!==this.elementDtype)throw new Error("Invalid data types; op elements "+e+", but list elements "+this.elementDtype);if(this.size()===0)throw new Error("Trying to pop from an empty list.");var r=this.tensors.pop();return gn(r.shape,t,"TensorList shape mismatch: "),W.reshape(r,t)},n.prototype.pushBack=function(t){if(t.dtype!==this.elementDtype)throw new Error("Invalid data types; op elements "+t.dtype+", but list elements "+this.elementDtype);if(gn(t.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");W.keep(t),this.tensors.push(t)},n.prototype.resize=function(t){if(t<0)throw new Error("TensorListResize expects size to be non-negative. Got: "+t);if(this.maxNumElements!==-1&&t>this.maxNumElements)throw new Error("TensorListResize input size "+t+" is greater maxNumElement "+this.maxNumElements+".");this.tensors.length=t},n.prototype.getItem=function(t,e,r){if(r!==this.elementDtype)throw new Error("Invalid data types; op elements "+r+", but list elements "+this.elementDtype);if(t<0||t>this.tensors.length)throw new Error("Trying to access element "+t+" in a list with "+this.tensors.length+" elements.");if(this.tensors[t]==null)throw new Error("element at index "+t+" is null.");return gn(this.tensors[t].shape,e,"TensorList shape mismatch: "),this.tensors[t]},n.prototype.setItem=function(t,e){if(e.dtype!==this.elementDtype)throw new Error("Invalid data types; op elements "+e.dtype+", but list elements "+this.elementDtype);if(t<0||this.maxNumElements!==-1&&t>=this.maxNumElements)throw new Error("Trying to set element "+t+" in a list with max "+this.maxNumElements+" elements.");gn(this.elementShape,e.shape,"TensorList shape mismatch: "),W.keep(e),this.tensors[t]=e},n.prototype.gather=function(t,e,r){var i=this;if(e!==this.elementDtype)throw new Error("Invalid data types; op elements "+e+", but list elements "+this.elementDtype);return gn(this.elementShape,r,"TensorList shape mismatch: "),t=t.slice(0,this.size()),t.length===0?W.tensor([],[0].concat(this.elementShape)):W.tidy(function(){var a=t.map(function(s){return W.reshape(i.tensors[s],r)});return W.stack(a,0)})},n.prototype.concat=function(t,e){var r=this;if
2020-11-03 15:34:36 +01:00
tensor . shape [ 0 ] , but sum of lengths is
2020-11-04 16:18:22 +01:00
` +r+", and tensor's shape is: "+n.shape);for(var a=r===0?0:n.size/r,s=W.tidy(function(){var l=[];n=W.reshape(n,[1,r,a]);for(var u=0;u<t.length;++u){var h=u===0?0:i[u-1],d=[0,h,0],p=[1,t[u],a];l[u]=W.reshape(W.slice(n,d,p),e)}return n.dispose(),l}),o=new tc([],e,n.dtype,t.length),c=0;c<s.length;c++)o.setItem(c,s[c]);return o}var f6=void 0,m6=function(n,t,e){return un(f6,void 0,void 0,function(){var r,i,a,s,o,c,l,u,o,h,d,c,p,f,m,m,g,y,g,w,g,g,g,b,x,S,N,I,C,O,D,F,k,B,V,P,q,K,G,H,J, $ ,ee,te,ne,re,ie,oe,se,me,ye,ve,Ee,Be,We,je,ze,Ie,k,B,ue,Ie,q,S,et,ue,te,ne,S,pt,ue,S,He,pt,ue,G,H,S,He,ue,Ie,S,He,pt,ue,Et,S,He,ue,ie,ue,se,S,Ie,B,ue,Ie,S,et,ue,ye,S,ve,ue;return tn(this,function(ut){switch(ut.label){case 0:r=n.op;switch(r){case"If":return[3,1];case"StatelessIf":return[3,1];case"While":return[3,3];case"StatelessWhile":return[3,3];case"LoopCond":return[3,9];case"Switch":return[3,10];case"Merge":return[3,12];case"Enter":return[3,13];case"Exit":return[3,14];case"NextIteration":return[3,15];case"TensorArrayV3":return[3,16];case"TensorArrayWriteV3":return[3,17];case"TensorArrayReadV3":return[3,18];case"TensorArrayGatherV3":return[3,19];case"TensorArrayScatterV3":return[3,20];case"TensorArrayConcatV3":return[3,21];case"TensorArraySplitV3":return[3,22];case"TensorArraySizeV3":return[3,23];case"TensorArrayCloseV3":return[3,24];case"TensorListSetItem":return[3,25];case"TensorListGetItem":return[3,26];case"TensorListScatterV2":return[3,27];case"TensorListScatter":return[3,27];case"TensorListReserve":return[3,28];case"TensorListGather":return[3,29];case"TensorListStack":return[3,30];case"TensorListFromTensor":return[3,31];case"TensorListConcat":return[3,32];case"TensorListPushBack":return[3,33];case"TensorListPopBack":return[3,34];case"TensorListSplit":return[3,35]}return[3,36];case 1:return i=T("thenBranch",n,t,e),a=T("elseBranch",n,t,e),s=T("cond",n,t,e),o=T("args",n,t,e),[4,s.data()];case 2:return c=ut.sent(),c[0]?[2,e.functionMap[i].executeFunctionAsync(o,e.tensorArrayMap,e.tensorListMap)]:[2,e.functionMap[a].executeFunctionAsync(o,e.tensorArrayMap,e.tensorListMap)];case 3:return l=T("body",n,t,e),u=T("cond",n,t,e),o=T("args",n,t,e),[4,e.functionMap[u].executeFunctionAsync(o,e.tensorArrayMap,e.tensorListMap)];case 4:return h=ut.sent(),d=o.map(function(wt){return wt.id}),[4,h[0].data()];case 5:c=ut.sent(),h.forEach(function(wt){!wt.kept&&d.indexOf(wt.id)===-1&&wt.dispose()}),p=o,f=function(){var wt,Te,ht;return tn(this,function(ft){switch(ft.label){case 0:return wt=p,[4,e.functionMap[l].executeFunctionAsync(p,e.tensorArrayMap,e.tensorListMap)];case 1:return p=ft.sent(),Te=p.map(function(qe){return qe.id}),wt.forEach(function(qe){!qe.kept&&d.indexOf(qe.id)===-1&&Te.indexOf(qe.id)===-1&&qe.dispose()}),[4,e.functionMap[u].executeFunctionAsync(p,e.tensorArrayMap,e.tensorListMap)];case 2:return ht=ft.sent(),[4,ht[0].data()];case 3:return c=ft.sent(),ht.forEach(function(qe){!qe.kept&&d.indexOf(qe.id)===-1&&Te.indexOf(qe.id)===-1&&qe.dispose()}),[2]}})},ut.label=6;case 6:return c[0]?[5,f()]:[3,8];case 7:return ut.sent(),[3,6];case 8:return[2,p];case 9:return m=T("pred",n,t,e),[2,[ur(m)]];case 10:return m=T("pred",n,t,e),g=T("data",n,t,e),g.kept||(g=ur(g)),[4,m.data()];case 11:return[2,ut.sent()[0]?[void 0,g]:[g,void 0]];case 12:return y=n.inputNames.find(function(wt){return jt(wt,t,e)!==void 0}),y?(g=jt(y,t,e),[2,[ur(g)]]):[2,void 0];case 13:return w=T("frameName",n,t,e),g=T("tensor",n,t,e),e.enterFrame(w),[2,[ur(g)]];case 14:return g=T("tensor",n,t,e),e.exitFrame(),[2,[ur(g)]];case 15:return g=T("tensor",n,t,e),e.nextIteration(),[2,[ur(g)]];case 16:return b=T("size",n,t,e),x=T("dtype",n,t,e),S=T("elementShape",n,t,e),N=T("dynamicSize",n,t,e),I=T("clearAfterRead",n,t,e),C=T("identicalElementShapes",n,t,e),O=T("name",n,t,e),D=new l6(O,x,b,S,C,N,I),e.addTensorArray(D),[2,[D.idTensor,W.scalar(1)]];case 17:return F=T("tensorArrayId",n,t,e),k=T("index",n,t,e),B=T("tensor",n,t,e),V=e.getTensorArray(F.id),V.write(k,B),[2,[V.idTensor]];case 18:return P=T("tensorArrayId",n,t,e),q=T("index",n,t,e),K=e.getTensorArray(P.id),[2,[K.read(q)]];case 19
` +t});var a;return this.size===Infinity||this.size==null?a=this.size:e?a=Math.ceil(this.size/t):a=Math.floor(this.size/t),rn(function(){return ce(r,void 0,void 0,function(){return le(this,function(s){switch(s.label){case 0:return[4,i.iterator()];case 1:return[2,s.sent().columnMajorBatch(t,e,v8)]}})})},a)},n.prototype.concatenate=function(t){var e=this,r=this,i;return this.size===Infinity||t.size===Infinity?i=Infinity:this.size!=null&&t.size!=null?i=this.size+t.size:i=null,rn(function(){return ce(e,void 0,void 0,function(){var a,s;return le(this,function(o){switch(o.label){case 0:return[4,r.iterator()];case 1:return s=(a=o.sent()).concatenate,[4,t.iterator()];case 2:return[2,s.apply(a,[o.sent()])]}})})},i)},n.prototype.filter=function(t){var e=this,r=this,i;return this.size===Infinity?i=Infinity:i=null,rn(function(){return ce(e,void 0,void 0,function(){return le(this,function(a){switch(a.label){case 0:return[4,r.iterator()];case 1:return[2,a.sent().filter(function(s){return Ce.tidy(function(){return t(s)})})]}})})},i)},n.prototype.forEachAsync=function(t){return ce(this,void 0,void 0,function(){return le(this,function(e){switch(e.label){case 0:return[4,this.iterator()];case 1:return[2,e.sent().forEachAsync(t)]}})})},n.prototype.map=function(t){var e=this,r=this;return rn(function(){return ce(e,void 0,void 0,function(){return le(this,function(i){switch(i.label){case 0:return[4,r.iterator()];case 1:return[2,i.sent().map(function(a){return Ce.tidy(function(){return t(a)})})]}})})},this.size)},n.prototype.mapAsync=function(t){var e=this,r=this;return rn(function(){return ce(e,void 0,void 0,function(){return le(this,function(i){switch(i.label){case 0:return[4,r.iterator()];case 1:return[2,i.sent().mapAsync(t)]}})})},this.size)},n.prototype.prefetch=function(t){var e=this;if(t==null)throw new RangeError(" ` Dataset . prefetch ( ) ` requires bufferSize to be specified.");var r=this;return rn(function(){return ce(e,void 0,void 0,function(){return le(this,function(i){switch(i.label){case 0:return[4,r.iterator()];case 1:return[2,i.sent().prefetch(t)]}})})},this.size)},n.prototype.repeat=function(t){var e=this,r=this,i;return this.size!=null&&t>0?i=this.size*t:t===0?i=0:this.size!=null&&(t===void 0||t<0)?i=Infinity:i=null,rn(function(){return ce(e,void 0,void 0,function(){var a,s=this;return le(this,function(o){return a=Qd(function(){return ce(s,void 0,void 0,function(){var c;return le(this,function(l){switch(l.label){case 0:return c={},[4,r.iterator()];case 1:return[2,(c.value=l.sent(),c.done=!1,c)]}})})}),[2,s8(a.take(t))]})})},i)},n.prototype.skip=function(t){var e=this,r=this,i;return this.size!=null&&t>=0&&this.size>=t?i=this.size-t:this.size!=null&&(this.size<t||t===void 0||t<0)?i=0:i=null,rn(function(){return ce(e,void 0,void 0,function(){return le(this,function(a){switch(a.label){case 0:return[4,r.iterator()];case 1:return[2,a.sent().skip(t)]}})})},i)},n.prototype.shuffle=function(t,e,r){var i=this;if(r===void 0&&(r=!0),t==null||t<0)throw this.size==null?new RangeError(" ` Dataset . shuffle ( ) ` requires bufferSize to be specified."):new RangeError(" ` Dataset . shuffle ( ) ` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for ` tf . Tensor ` s), consider setting "+("bufferSize to the dataset size ("+this.size+" elements)"));var a=this,s=uw(e||Ce.util.now().toString());return rn(function(){return ce(i,void 0,void 0,function(){var o;return le(this,function(c){switch(c.label){case 0:return o=s.int32(),r&&(o+=s.int32()),[4,a.iterator()];case 1:return[2,c.sent().shuffle(t,o.toString())]}})})},this.size)},n.prototype.take=function(t){var e=this,r=this,i;return this.size!=null&&this.size>t?i=t:this.size!=null&&this.size<=t?i=this.size:i=null,rn(function(){return ce(e,void 0,void 0,function(){return le(this,function(a){switch(a.label){case 0:return[4,r.iterator()];case 1:return[2,a.sent().take(t)]}})})},i)},n.prototype.toArray=function(){return ce(this,void 0,void 0,function(){return le(this,function(t){switch(t.label){case 0:if(this.size===Infinity)throw new Error("Can not convert
` ).map(function(s){return s.endsWith(" \r ")&&(s=s.slice(0,-1)),s}),[2,i]}})})},t}(ys);var rc='"',vs=Symbol("out"),bw=Symbol("field"),ic=Symbol("quote"),tp=Symbol("quoteafterquote"),xw=Symbol("quoteinquote"),Sw=function(n){Ye(t,n);function t(e,r){var i=n.call(this)||this;return i.input=e,i.hasHeader=!0,i.fullColumnNames=null,i.columnNamesValidated=!1,i.columnConfigs=null,i.configuredColumnsOnly=!1,i.delimiter=",",i.delimWhitespace=!1,i.base=new ww(e),r||(r={}),i.hasHeader=!(r.hasHeader===!1),i.fullColumnNames=r.columnNames,i.columnConfigs=r.columnConfigs,i.configuredColumnsOnly=r.configuredColumnsOnly,r.delimWhitespace?(Ce.util.assert(r.delimiter==null,function(){return"Delimiter should not be provided when delimWhitespace is true."}),i.delimWhitespace=!0,i.delimiter=" "):i.delimiter=r.delimiter?r.delimiter:",",i}return t.prototype.columnNames=function(){return ce(this,void 0,void 0,function(){return le(this,function(e){switch(e.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:e.sent(),e.label=2;case 2:return[2,this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames]}})})},t.prototype.setColumnNames=function(){return ce(this,void 0,void 0,function(){var e,r,i,a,s,o,c,l=this;return le(this,function(u){switch(u.label){case 0:return[4,this.maybeReadHeaderLine()];case 1:if(e=u.sent(),!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");if(this.fullColumnNames&&e&&Ce.util.assert(e.length===this.fullColumnNames.length,function(){return"The length of provided columnNames ("+l.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=e),r=this.fullColumnNames.reduce(function(h,d){return h[d]=h[d]+1||1,h},{}),i=Object.keys(r).filter(function(h){return r[h]>1}),Ce.util.assert(i.length===0,function(){return"Duplicate column names found: "+i.toString()}),this.columnConfigs){for(a=0,s=Object.keys(this.columnConfigs);a<s.length;a++)if(o=s[a],c=this.fullColumnNames.indexOf(o),c===-1)throw new Error('The key "'+o+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}return this.columnNamesValidated=!0,[2]}})})},t.prototype.maybeReadHeaderLine=function(){return ce(this,void 0,void 0,function(){var e,r,i,a;return le(this,function(s){switch(s.label){case 0:return this.hasHeader?[4,this.base.iterator()]:[3,3];case 1:return e=s.sent(),[4,e.next()];case 2:if(r=s.sent(),r.done)throw new Error("No data was found for CSV parsing.");return i=r.value,a=this.parseRow(i,!1),[2,a];case 3:return[2,null]}})})},t.prototype.iterator=function(){return ce(this,void 0,void 0,function(){var e,r=this;return le(this,function(i){switch(i.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:i.sent(),i.label=2;case 2:return[4,this.base.iterator()];case 3:return e=i.sent(),this.hasHeader&&(e=e.skip(1)),[2,e.map(function(a){return r.makeDataElement(a)})]}})})},t.prototype.makeDataElement=function(e){for(var r=this.parseRow(e),i={},a={},s=0;s<this.fullColumnNames.length;s++){var o=this.fullColumnNames[s],c=this.columnConfigs?this.columnConfigs[o]:null;if(this.configuredColumnsOnly&&!c)continue;var l=r[s],u=null;if(l==="")if(c&&c.default!==void 0)u=c.default;else{if(c&&(c.required||c.isLabel))throw new Error("Required column "+o+" is empty in this line: "+e);u=void 0}else{var h=Number(l);if(isNaN(h))c&&c.dtype==="bool"?u=this.getBoolean(l):u=l;else if(!c||!c.dtype)u=h;else switch(c.dtype){case"float32":u=h;break;case"int32":u=Math.floor(h);break;case"bool":u=this.getBoolean(l);break;default:u=h}}c&&c.isLabel?a[o]=u:i[o]=u}return Object.keys(a).length===0?i:{xs:i,ys:a}},t.prototype.getBoolean=function(e){return e==="1"||e.toLowerCase()==="true"?1:0},t.prototype.parseRow=function(e,r){r===void 0&&(r=!0);for(var i=[],a=0,s=e.length,o=vs,c=0;c<s;c++)switch(o){case vs:switch(e.charAt(c)){case rc:a=c+1,o=ic;break;case this.delimiter:if(a=c+1,this.delimiter===" "&&this
2020-11-03 15:34:36 +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.
2020-11-04 16:18:22 +01:00
=== === === === === === === === === = ` ));var a={};return this.data.set(a,{values:e,dtype:i,refCount:1}),a},t.prototype.makeTensorInfo=function(e,r,i){var a;if(r==="string"&&i!=null&&i.length>0&&L.util.isString(i[0])){var s=i.map(function(o){return L.util.encodeString(o)});a=this.write(s,e,r)}else a=this.write(i,e,r);return{dataId:a,shape:e,dtype:r}},t.prototype.incRef=function(e){var r=this.data.get(e);r.refCount++},t.prototype.decRef=function(e){if(this.data.has(e)){var r=this.data.get(e);r.refCount--}},t.prototype.move=function(e,r,i,a){this.data.set(e,{values:r,dtype:a,refCount:1})},t.prototype.numDataIds=function(){return this.data.numDataIds()},t.prototype.read=function(e){return Gw(this,void 0,void 0,function(){return Yw(this,function(r){return[2,this.readSync(e)]})})},t.prototype.readSync=function(e){var r=this.data.get(e),i=r.dtype,a=r.complexTensorInfos;if(i==="complex64"){var s=this.readSync(a.real.dataId),o=this.readSync(a.imag.dataId);return L.backend_util.mergeRealAndImagArrays(s,o)}return this.data.get(e).values},t.prototype.bufferSync=function(e){var r=this.readSync(e.dataId),i=r;if(e.dtype==="string")try{i=r.map(function(a){return L.util.decodeString(a)})}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return L.buffer(e.shape,e.dtype,i)},t.prototype.makeOutput=function(e,r,i){var a=this.write(e,r,i);return L.engine().makeTensorFromDataId(a,r,i,this)},t.prototype.disposeData=function(e){if(this.data.has(e)){var r=this.data.get(e).complexTensorInfos;r!=null&&(this.disposeData(r.real.dataId),this.disposeData(r.imag.dataId)),this.data.delete(e)}},t.prototype.disposeIntermediateTensorInfo=function(e){var r=e.dataId;if(this.data.has(r)){var i=this.data.get(r);i.refCount--,i.refCount<1&&this.disposeData(r)}},t.prototype.time=function(e){return Gw(this,void 0,void 0,function(){var r,i;return Yw(this,function(a){return r=L.util.now(),e(),i=L.util.now()-r,[2,{kernelMs:i}]})})},t.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},t.prototype.stridedSlice=function(e,r,i,a){ae(e,"stridedSlice");var s=L.slice_util.computeOutShape(r,i,a);if(s.some(function(p){return p===0}))return L.tensor([],s);for(var o=L.buffer(s,e.dtype),c=this.bufferSync(e),l=0;l<o.size;l++){for(var u=o.indexToLoc(l),h=new Array(u.length),d=0;d<h.length;d++)h[d]=u[d]*a[d]+r[d];o.set.apply(o,[c.get.apply(c,h)].concat(u))}return o.toTensor()},t.prototype.diag=function(e){for(var r=this.readSync(e.dataId),i=L.buffer([e.size,e.size],e.dtype),a=i.values,s=0;s<r.length;s++)a[s*e.size+s]=r[s];return i.toTensor()},t.prototype.unstack=function(e,r){for(var i=e.shape[r],a=new Array(e.rank-1),s=0,o=0;o<e.rank;o++)o!==r&&(a[s++]=e.shape[o]);var c=new Array(e.rank).fill(0),l=e.shape.slice();l[r]=1;for(var u=new Array(i),o=0;o<u.length;o++)c[r]=o,u[o]=L.slice(e,c,l).reshape(a);return u},t.prototype.reverse=function(e,r){ae(e,"reverse");for(var i=L.buffer(e.shape,e.dtype),a=this.bufferSync(e),s=function(c){var l=i.indexToLoc(c),u=l.slice();r.forEach(function(h){return u[h]=e.shape[h]-1-u[h]}),i.set.apply(i,[a.get.apply(a,u)].concat(l))},o=0;o<i.size;o++)s(o);return i.toTensor()},t.prototype.neg=function(e){return ae(e,"neg"),L.mul(L.scalar(-1),e)},t.prototype.addN=function(e){var r=this;ae(e,"addN");for(var i=e.map(function(u){return r.readSync(u.dataId)}),a=L.buffer(e[0].shape,e[0].dtype),s=a.values,o=0;o<e.length;o++)for(var c=i[o],l=0;l<s.length;l++)s[l]+=c[l];return a.toTensor()},t.prototype.softmax=function(e,r){var i=L.util.parseAxisParam([r],e.shape),a=L.max(e,i),s=L.backend_util.expandShapeToKeepDim(a.shape,i),o=L.sub(e,a.reshape(s)),c=L.exp(o),l=this.sum(c,i).reshape(s);return L.div(c,l)},t.prototype.pow=function(e,r){return ae([e,r],"pow"),this.broadcastedBinaryOp(e,r,e.dtype,function(i,a){return Math.pow(i,a)})},t.prototype.floorDiv=function(e,r){ae([e,r],"floorDiv");var i=function(s,o){return Math.floor(s/o)},a="int32";return this.broadcastedBinaryOp(e,r,a,i)},t.prototype.sum=function(e,r){ae(e,"sum"),L.ba
2020-11-03 15:34:36 +01:00
` ),a=i.length.toString().length+2,s=i.map(function(d,p){return _.util.rightPad((p+1).toString(),a)+d}),o=0,c=0;c<s.length;c++)o=Math.max(s[c].length,o);var l=s.slice(0,r-1),u=s.slice(r-1,r),h=s.slice(r);console.log(l.join( `
` )),console.log(t.split( `
` )[0]),console.log("%c "+_.util.rightPad(u[0],o),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(h.join( `
2020-11-04 16:18:22 +01:00
` ))}function Rb(n){return hr(n,function(){return n.createProgram()},"Unable to create WebGLProgram.")}function Ob(n,t){if(de(n,function(){return n.linkProgram(t)}),n.getProgramParameter(t,n.LINK_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function lc(n,t){if(de(n,function(){return n.validateProgram(t)}),n.getProgramParameter(t,n.VALIDATE_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Eb(n,t){var e=hr(n,function(){return n.createBuffer()},"Unable to create WebGLBuffer");return de(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,e)}),de(n,function(){return n.bufferData(n.ARRAY_BUFFER,t,n.STATIC_DRAW)}),e}function Db(n,t){var e=hr(n,function(){return n.createBuffer()},"Unable to create WebGLBuffer");return de(n,function(){return n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e)}),de(n,function(){return n.bufferData(n.ELEMENT_ARRAY_BUFFER,t,n.STATIC_DRAW)}),e}function fU(){return _.env().getNumber("WEBGL_VERSION")===2?1:4}function kb(n){return hr(n,function(){return n.createTexture()},"Unable to create WebGLTexture.")}function Fb(n,t){var e=_.env().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n<=0||t<=0){var r="["+n+"x"+t+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(n>e||t>e){var r="["+n+"x"+t+"]",i="["+e+"x"+e+"]";throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+i+".")}}function Wb(n){return hr(n,function(){return n.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function bp(n,t,e,r,i,a,s){var o=n.getAttribLocation(t,e);return o===-1?!1:(de(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,r)}),de(n,function(){return n.vertexAttribPointer(o,i,n.FLOAT,!1,a,s)}),de(n,function(){return n.enableVertexAttribArray(o)}),!0)}function Bb(n,t,e){Ub(n,e),de(n,function(){return n.activeTexture(n.TEXTURE0+e)}),de(n,function(){return n.bindTexture(n.TEXTURE_2D,t)})}function mU(n,t){Ub(n,t),de(n,function(){return n.activeTexture(n.TEXTURE0+t)}),de(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function zb(n,t,e){return hr(n,function(){return n.getUniformLocation(t,e)},'uniform "'+e+'" not present in program.')}function Pb(n,t,e){return n.getUniformLocation(t,e)}function Mb(n,t,e,r){de(n,function(){return Bb(n,t,r)}),de(n,function(){return n.uniform1i(e,r)})}function gU(n){de(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,null)}),de(n,function(){return n.viewport(0,0,n.canvas.width,n.canvas.height)}),de(n,function(){return n.scissor(0,0,n.canvas.width,n.canvas.height)})}function uc(n,t,e){de(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,e)}),de(n,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0)})}function xp(n,t){de(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,t)}),de(n,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0)})}function _s(n){var t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Hb(n,t))}function Hb(n,t){switch(t){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function hr(n,t,e){var r=de(n,function(){return t()});if(r==null)throw new Error(e);return r}function Ub(n,t){var e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+n.TEXTURE0;if(r<n.TEXTURE0||r>e){var i="[gl.TEXTURE0, gl.TEXTURE"+e+"]";throw new Error("textureUnit must be in "+i+".")}}function Ni(n,t){return t===void 0&&(t=2),_.util.sizeFromShape(n.slice(0,n.length-t))}function _i(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function hc(n){var t=[1,1,1],e=n.length===0||n.length===1&&n[0]===1;return e||(t=[Ni(n)]
2020-11-03 15:34:36 +01:00
void main ( ) {
` +r.join( `
` )+ `
2020-10-28 20:02:59 +01:00
2020-11-03 15:34:36 +01:00
float result = ` +i+ ` ;
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var $ U=function(){function n(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map(function(a,s){return"T"+s});var r=[];this.variableNames.forEach(function(a){r.push("vec4 v"+a+" = get"+a+"AtOutCoords();")});var i=this.variableNames.map(function(a){return"v"+a}).join(" + ");this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
` +r.join( `
` )+ `
vec4 result = ` +i+ ` ;
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var XU=function(){function n(t,e,r){this.variableNames=["A"];var i=t.windowSize,a=t.batchSize,s=t.outSize;r||this.variableNames.push("bestIndicesA"),this.outputShape=[a,s];var o=e==="max"?">":"<",c=r?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * ` +i+ ` ;
int bestIndex = inOffset ;
float bestValue = getA ( batch , bestIndex ) ;
for ( int i = 0 ; i < ` +i+ ` ; i ++ ) {
int inIdx = ` +c+ ` ;
float candidate = getA ( batch , inIdx ) ;
if ( candidate ` +o+ ` bestValue ) {
bestValue = candidate ;
bestIndex = inIdx ;
2020-10-28 20:02:59 +01:00
}
}
2020-11-03 15:34:36 +01:00
setOutput ( float ( bestIndex ) ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();function Xb(n,t){return["x","y","z","w","u","v"].slice(0,t).map(function(e){return n+"."+e})}function Pt(n,t){return t===1?[n]:Xb(n,t)}function JU(n,t){if(n===1)return"rc";for(var e="",r=0;r<n;r++)e+=t[r],r<n-1&&(e+=",");return e}function Mt(){var n,t,e,r,i,a,s,o,c,l;return _.env().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",t="in",e="out",r="in",i="texture",a="outputColor",s="out vec4 outputColor;",o= `
2020-11-03 15:34:36 +01:00
bool isnan _custom ( float val ) {
return ( val > 0.0 || val < 0.0 ) ? false : val != 0.0 ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan _custom ( val . x ) ,
isnan _custom ( val . y ) , isnan _custom ( val . z ) , isnan _custom ( val . w ) ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
# define isnan ( value ) isnan _custom ( value )
` ,c="",l= `
# define round ( value ) newRound ( value )
int newRound ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
ivec4 newRound ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
` ):(n="",t="attribute",e="varying",r="varying",i="texture2D",a="gl_FragColor",s="",o= `
# define isnan ( value ) isnan _custom ( value )
bool isnan _custom ( float val ) {
return ( val > 0. || val < 1. || val == 0. ) ? false : true ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan ( val . x ) , isnan ( val . y ) , isnan ( val . z ) , isnan ( val . w ) ) ;
}
` ,c= `
uniform float INFINITY ;
bool isinf ( float val ) {
return abs ( val ) == INFINITY ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
bvec4 isinf ( vec4 val ) {
return equal ( abs ( val ) , vec4 ( INFINITY ) ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
` ,l= `
int round ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
ivec4 round ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
}
2020-11-04 16:18:22 +01:00
` ),{version:n,attribute:t,varyingVs:e,varyingFs:r,texture2D:i,output:a,defineOutput:s,defineSpecialNaN:o,defineSpecialInf:c,defineRound:l}}function Ci(n,t,e){e===void 0&&(e="index");var r=_.util.computeStrides(t);return r.map(function(i,a){var s="int "+n[a]+" = "+e+" / "+i,o=a===r.length-1?"int "+n[a+1]+" = "+e+" - "+n[a]+" * "+i:"index -= "+n[a]+" * "+i;return s+"; "+o+";"}).join("")}function Tp(n){var t=_.util.computeStrides(n).map(function(e){return e.toString()});return `
2020-11-03 15:34:36 +01:00
int getFlatIndex ( ivec3 coords ) {
return coords . x * ` +t[0]+" + coords.y * "+t[1]+ ` + coords . z ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }var Jb= `
2020-11-03 15:34:36 +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 ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
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 ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
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 ;
}
2020-11-04 16:18:22 +01:00
` ;var Zb=_.backend_util.getBroadcastDims;function sB(n,t,e,r){var i=[];n.forEach(function(f){var m=_.util.sizeFromShape(f.shapeInfo.logicalShape);f.shapeInfo.isUniform?i.push("uniform float "+f.name+(m>1?"["+m+"]":"")+";"):(i.push("uniform sampler2D "+f.name+";"),i.push("uniform int offset"+f.name+";"))});var a=i.join( `
` ),s=n.map(function(f){return ZU(f,t,r)}).join( `
` ),o=t.texShape,c=Mt(),l=tB(c),u,h,d=iB(c);t.isPacked?(u=QU(t.logicalShape,o),h=rB(c)):(u=eB(t.logicalShape,o),h=nB(c)),r&&(d+=aB);var p=[d,l,h,a,u,s,e].join( `
` );return p}function ba(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return oB(n);case 1:return cB(n);case 2:return lB(n);case 3:return uB(n);case 4:return hB(n);case 5:return dB(n);case 6:return pB(n);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function Qb(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return fB(n);case 1:return mB(n);case 2:return gB(n);case 3:return yB(n);default:return vB(n)}}function ZU(n,t,e){e===void 0&&(e=!1);var r="";e?r+=Qb(n):r+=ba(n);var i=n.shapeInfo.logicalShape,a=t.logicalShape;return i.length<=a.length&&(e?r+=wB(n,t):r+=bB(n,t)),r}function QU(n,t){switch(n.length){case 0:return e2();case 1:return xB(n,t);case 2:return IB(n,t);case 3:return SB(n,t);default:return LB(n,t)}}function eB(n,t){switch(n.length){case 0:return e2();case 1:return AB(n,t);case 2:return RB(n,t);case 3:return TB(n,t);case 4:return NB(n,t);case 5:return _B(n,t);case 6:return CB(n,t);default:throw new Error(n.length+"-D output sampling is not yet supported")}}function tB(n){return `
2020-11-03 15:34:36 +01:00
float sampleTexture ( sampler2D textureSampler , vec2 uv ) {
return ` +n.texture2D+ ` ( textureSampler , uv ) . r ;
}
2020-11-04 16:18:22 +01:00
` }function nB(n){return `
2020-11-03 15:34:36 +01:00
void setOutput ( float val ) {
` +n.output+ ` = vec4 ( val , 0 , 0 , 0 ) ;
}
2020-11-04 16:18:22 +01:00
` }function rB(n){return `
2020-11-03 15:34:36 +01:00
void setOutput ( vec4 val ) {
` +n.output+ ` = val ;
}
2020-11-04 16:18:22 +01:00
` }function iB(n){var t=n.version+ `
2020-11-03 15:34:36 +01:00
precision highp float ;
precision highp int ;
precision highp sampler2D ;
` +n.varyingFs+ ` vec2 resultUV ;
` +n.defineOutput+ `
const vec2 halfCR = vec2 ( 0.5 , 0.5 ) ;
struct ivec5
{
int x ;
int y ;
int z ;
int w ;
int u ;
} ;
struct ivec6
{
int x ;
int y ;
int z ;
int w ;
int u ;
int v ;
} ;
uniform float NAN ;
` +n.defineSpecialNaN+ `
` +n.defineSpecialInf+ `
` +n.defineRound+ `
int imod ( int x , int y ) {
return x - y * ( x / y ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
int idiv ( int a , int b , float sign ) {
int res = a / b ;
int mod = imod ( a , b ) ;
if ( sign < 0. && mod != 0 ) {
res -= 1 ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
return res ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
# define HASHSCALE1 443.8975
float random ( float seed ) {
vec2 p = resultUV * seed ;
vec3 p3 = fract ( vec3 ( p . xyx ) * HASHSCALE1 ) ;
p3 += dot ( p3 , p3 . yzx + 19.19 ) ;
return fract ( ( p3 . x + p3 . y ) * p3 . z ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
2020-11-04 16:18:22 +01:00
` +OB+ `
` +EB+ `
` +DB+ `
` ;return t}var OB= `
2020-11-03 15:34:36 +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 ) ;
}
2020-11-04 16:18:22 +01:00
` ,EB= `
2020-11-03 15:34:36 +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 ) ;
}
2020-11-04 16:18:22 +01:00
` ,DB= `
2020-11-03 15:34:36 +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 ) ;
}
2020-11-04 16:18:22 +01:00
` ,aB= `
2020-11-03 15:34:36 +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 ;
}
2020-11-04 16:18:22 +01:00
` ;function e2(){return `
2020-11-03 15:34:36 +01:00
int getOutputCoords ( ) {
return 0 ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }function xB(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return e[0]===1? `
2020-11-03 15:34:36 +01:00
int getOutputCoords ( ) {
return 2 * int ( resultUV . x * ` +e[1]+ ` . 0 ) ;
}
` :e[1]===1? `
int getOutputCoords ( ) {
return 2 * int ( resultUV . y * ` +e[0]+ ` . 0 ) ;
}
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +e[0]+", "+e[1]+ ` ) ) ;
return 2 * ( resTexRC . x * ` +e[1]+ ` + resTexRC . y ) ;
}
2020-11-04 16:18:22 +01:00
` }function AB(n,t){return t[0]===1? `
2020-11-03 15:34:36 +01:00
int getOutputCoords ( ) {
return int ( resultUV . x * ` +t[1]+ ` . 0 ) ;
}
` :t[1]===1? `
int getOutputCoords ( ) {
return int ( resultUV . y * ` +t[0]+ ` . 0 ) ;
}
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +t[0]+", "+t[1]+ ` ) ) ;
return resTexRC . x * ` +t[1]+ ` + resTexRC . y ;
}
2020-11-04 16:18:22 +01:00
` }function SB(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[2]/2),i=r*Math.ceil(n[1]/2);return `
2020-11-03 15:34:36 +01:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +e[0]+", "+e[1]+ ` ) ) ;
int index = resTexRC . x * ` +e[1]+ ` + resTexRC . y ;
int b = index / ` +i+ ` ;
index -= b * ` +i+ ` ;
int r = 2 * ( index / ` +r+ ` ) ;
int c = imod ( index , ` +r+ ` ) * 2 ;
return ivec3 ( b , r , c ) ;
}
2020-11-04 16:18:22 +01:00
` }function TB(n,t){var e=Ci(["r","c","d"],n);return `
2020-11-03 15:34:36 +01:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +t[0]+", "+t[1]+ ` ) ) ;
int index = resTexRC . x * ` +t[1]+ ` + resTexRC . y ;
` +e+ `
return ivec3 ( r , c , d ) ;
}
2020-11-04 16:18:22 +01:00
` }function LB(n,t){for(var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[n.length-1]/2),i=r*Math.ceil(n[n.length-2]/2),a=i,s="",o="b, r, c",c=2;c<n.length-1;c++)a*=n[n.length-c-1],s= `
2020-11-03 15:34:36 +01:00
int b ` +c+" = index / "+a+ ` ;
index -= b ` +c+" * "+a+ ` ;
` +s,o="b"+c+", "+o;return `
ivec ` +n.length+ ` getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +e[0]+", "+e[1]+ ` ) ) ;
int index = resTexRC . x * ` +e[1]+ ` + resTexRC . y ;
` +s+ `
int b = index / ` +i+ ` ;
index -= b * ` +i+ ` ;
int r = 2 * ( index / ` +r+ ` ) ;
int c = imod ( index , ` +r+ ` ) * 2 ;
return ivec ` +n.length+"("+o+ ` ) ;
}
2020-11-04 16:18:22 +01:00
` }function NB(n,t){var e=Ci(["r","c","d","d2"],n);return `
2020-11-03 15:34:36 +01:00
ivec4 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +t[0]+", "+t[1]+ ` ) ) ;
int index = resTexRC . x * ` +t[1]+ ` + resTexRC . y ;
` +e+ `
return ivec4 ( r , c , d , d2 ) ;
}
2020-11-04 16:18:22 +01:00
` }function _B(n,t){var e=Ci(["r","c","d","d2","d3"],n);return `
2020-11-03 15:34:36 +01:00
ivec5 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( ` +t[0]+ ` ,
` +t[1]+ ` ) ) ;
int index = resTexRC . x * ` +t[1]+ ` + resTexRC . y ;
` +e+ `
ivec5 outShape = ivec5 ( r , c , d , d2 , d3 ) ;
return outShape ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }function CB(n,t){var e=Ci(["r","c","d","d2","d3","d4"],n);return `
2020-11-03 15:34:36 +01:00
ivec6 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +t[0]+", "+t[1]+ ` ) ) ;
int index = resTexRC . x * ` +t[1]+ ` + resTexRC . y ;
` +e+ `
ivec6 result = ivec6 ( r , c , d , d2 , d3 , d4 ) ;
return result ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }function IB(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(_.util.arraysEqual(n,t))return `
2020-11-03 15:34:36 +01:00
ivec2 getOutputCoords ( ) {
return 2 * ivec2 ( resultUV . yx * vec2 ( ` +e[0]+", "+e[1]+ ` ) ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
` ;var r=Math.ceil(n[1]/2);return `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +e[0]+", "+e[1]+ ` ) ) ;
int index = resTexRC . x * ` +e[1]+ ` + resTexRC . y ;
int r = 2 * ( index / ` +r+ ` ) ;
int c = imod ( index , ` +r+ ` ) * 2 ;
return ivec2 ( r , c ) ;
}
2020-11-04 16:18:22 +01:00
` }function RB(n,t){return _.util.arraysEqual(n,t)? `
2020-11-03 15:34:36 +01:00
ivec2 getOutputCoords ( ) {
return ivec2 ( resultUV . yx * vec2 ( ` +t[0]+", "+t[1]+ ` ) ) ;
}
` :n[1]===1? `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +t[0]+", "+t[1]+ ` ) ) ;
int index = resTexRC . x * ` +t[1]+ ` + resTexRC . y ;
return ivec2 ( index , 0 ) ;
}
` :n[0]===1? `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +t[0]+", "+t[1]+ ` ) ) ;
int index = resTexRC . x * ` +t[1]+ ` + resTexRC . y ;
return ivec2 ( 0 , index ) ;
}
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +t[0]+", "+t[1]+ ` ) ) ;
int index = resTexRC . x * ` +t[1]+ ` + resTexRC . y ;
int r = index / ` +n[1]+ ` ;
int c = index - r * ` +n[1]+ ` ;
return ivec2 ( r , c ) ;
}
2020-11-04 16:18:22 +01:00
` }function Ri(n){return"offset"+n}function fB(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),r=Mt();return `
2020-11-03 15:34:36 +01:00
vec4 ` +e+ ` ( ) {
return ` +r.texture2D+"("+t+ ` , halfCR ) ;
}
2020-11-04 16:18:22 +01:00
` }function oB(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(n.shapeInfo.isUniform)return"float "+e+"() {return "+t+";}";var r=n.shapeInfo.texShape,i=r[0],a=r[1];if(i===1&&a===1)return `
2020-11-03 15:34:36 +01:00
float ` +e+ ` ( ) {
return sampleTexture ( ` +t+ ` , halfCR ) ;
}
2020-11-04 16:18:22 +01:00
` ;var s=n.shapeInfo.texShape,o=s[0],c=s[1],l=Ri(t);return `
2020-11-03 15:34:36 +01:00
float ` +e+ ` ( ) {
vec2 uv = uvFromFlat ( ` +o+", "+c+", "+l+ ` ) ;
return sampleTexture ( ` +t+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function mB(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),r=n.shapeInfo.texShape,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=Mt();return `
2020-11-03 15:34:36 +01:00
vec4 ` +e+ ` ( int index ) {
vec2 uv = packedUVfrom1D (
` +i[0]+", "+i[1]+ ` , index ) ;
return ` +a.texture2D+"("+t+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function cB(n){var t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(n.shapeInfo.isUniform)return `
2020-11-03 15:34:36 +01:00
float ` +e+ ` ( int index ) {
2020-11-04 16:18:22 +01:00
` +xa(n)+ `
2020-11-03 15:34:36 +01:00
}
` ;var r=n.shapeInfo.texShape,i=r[0],a=r[1];if(a===1&&i===1)return `
float ` +e+ ` ( int index ) {
return sampleTexture ( ` +t+ ` , halfCR ) ;
}
2020-11-04 16:18:22 +01:00
` ;var s=Ri(t);return a===1? `
2020-11-03 15:34:36 +01:00
float ` +e+ ` ( int index ) {
vec2 uv = vec2 ( 0.5 , ( float ( index + ` +s+") + 0.5) / "+i+ ` . 0 ) ;
return sampleTexture ( ` +t+ ` , uv ) ;
}
` :i===1? `
float ` +e+ ` ( int index ) {
vec2 uv = vec2 ( ( float ( index + ` +s+") + 0.5) / "+a+ ` . 0 , 0.5 ) ;
return sampleTexture ( ` +t+ ` , uv ) ;
}
` : `
float ` +e+ ` ( int index ) {
vec2 uv = uvFromFlat ( ` +i+", "+a+", index + "+s+ ` ) ;
return sampleTexture ( ` +t+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function gB(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=n.shapeInfo.texShape,a=i[0],s=i[1],o=Mt();if(i!=null&&_.util.arraysEqual(t,i))return `
2020-11-03 15:34:36 +01:00
vec4 ` +r+ ` ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( ` +s+".0, "+a+ ` . 0 ) ;
return ` +o.texture2D+"("+e+ ` , uv ) ;
}
` ;var c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=Math.ceil(t[1]/2);return `
vec4 ` +r+ ` ( int row , int col ) {
vec2 uv = packedUVfrom2D ( ` +l+", "+c[0]+", "+c[1]+ ` , row , col ) ;
return ` +o.texture2D+"("+e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function lB(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=n.shapeInfo.texShape;if(i!=null&&_.util.arraysEqual(t,i)){var a=i[0],s=i[1];return `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( ` +s+".0, "+a+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }var o=_.util.squeezeShape(t),c=o.newShape,l=o.keptDims,u=c;if(u.length<t.length){var h=Sa(n,u),d=["row","col"];return `
` +ba(h)+ `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col ) {
2020-11-04 16:18:22 +01:00
return ` +r+"("+La(d,l)+ ` ) ;
2020-11-03 15:34:36 +01:00
}
` }if(n.shapeInfo.isUniform)return `
float ` +r+ ` ( int row , int col ) {
int index = round ( dot ( vec2 ( row , col ) , vec2 ( ` +t[1]+ ` , 1 ) ) ) ;
2020-11-04 16:18:22 +01:00
` +xa(n)+ `
2020-11-03 15:34:36 +01:00
}
2020-11-04 16:18:22 +01:00
` ;var p=i[0],f=i[1],m=Ri(e);return f===1? `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col ) {
float index = dot ( vec3 ( row , col , ` +m+"), vec3("+t[1]+ ` , 1 , 1 ) ) ;
vec2 uv = vec2 ( 0.5 , ( index + 0.5 ) / ` +p+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
` :p===1? `
float ` +r+ ` ( int row , int col ) {
float index = dot ( vec3 ( row , col , ` +m+"), vec3("+t[1]+ ` , 1 , 1 ) ) ;
vec2 uv = vec2 ( ( index + 0.5 ) / ` +f+ ` . 0 , 0.5 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
` : `
float ` +r+ ` ( int row , int col ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ` +t[1]+" + col + "+m+ ` ;
vec2 uv = uvFromFlat ( ` +p+", "+f+ ` , index ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function yB(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=n.shapeInfo.texShape,a=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){var s=t.slice(1),o=[1,2],c=Sa(n,s),l=["b","row","col"];return `
` +Qb(c)+ `
2020-11-03 15:34:36 +01:00
vec4 ` +r+ ` ( int b , int row , int col ) {
2020-11-04 16:18:22 +01:00
return ` +r+"("+La(l,o)+ ` ) ;
2020-11-03 15:34:36 +01:00
}
` }var u=a[0],h=a[1],d=Math.ceil(t[2]/2),p=d*Math.ceil(t[1]/2),f=Mt();return `
vec4 ` +r+ ` ( int b , int row , int col ) {
vec2 uv = packedUVfrom3D (
` +u+", "+h+", "+p+", "+d+ ` , b , row , col ) ;
return ` +f.texture2D+"("+e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function uB(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=t[1]*t[2],a=t[2],s=_.util.squeezeShape(t),o=s.newShape,c=s.keptDims,l=o;if(l.length<t.length){var u=Sa(n,l),h=["row","col","depth"];return `
` +ba(u)+ `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col , int depth ) {
2020-11-04 16:18:22 +01:00
return ` +r+"("+La(h,c)+ ` ) ;
2020-11-03 15:34:36 +01:00
}
` }if(n.shapeInfo.isUniform)return `
float ` +r+ ` ( int row , int col , int depth ) {
int index = round ( dot ( vec3 ( row , col , depth ) ,
vec3 ( ` +i+", "+a+ ` , 1 ) ) ) ;
2020-11-04 16:18:22 +01:00
` +xa(n)+ `
2020-11-03 15:34:36 +01:00
}
` ;var d=n.shapeInfo.texShape,p=d[0],f=d[1],m=n.shapeInfo.flatOffset;if(f===i&&m==null)return `
float ` +r+ ` ( int row , int col , int depth ) {
float texR = float ( row ) ;
float texC = dot ( vec2 ( col , depth ) , vec2 ( ` +a+ ` , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( ` +f+".0, "+p+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
` ;if(f===a&&m==null)return `
float ` +r+ ` ( int row , int col , int depth ) {
float texR = dot ( vec2 ( row , col ) , vec2 ( ` +t[1]+ ` , 1 ) ) ;
float texC = float ( depth ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( ` +f+".0, "+p+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` ;var g=Ri(e);return `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col , int depth ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ` +i+" + col * "+a+" + depth + "+g+ ` ;
vec2 uv = uvFromFlat ( ` +p+", "+f+ ` , index ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function vB(n){for(var t=n.shapeInfo.logicalShape,e=t.length,r=n.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n.shapeInfo.texShape,s=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],o=s[0],c=s[1],l=Math.ceil(t[e-1]/2),u=l*Math.ceil(t[e-2]/2),h="int b, int row, int col",d="b * "+u+" + (row / 2) * "+l+" + (col / 2)",p=2;p<e-1;p++)h="int b"+p+", "+h,u*=t[e-p-1],d="b"+p+" * "+u+" + "+d;var f=Mt();return `
2020-11-03 15:34:36 +01:00
vec4 ` +i+"("+h+ ` ) {
int index = ` +d+ ` ;
int texR = index / ` +c+ ` ;
int texC = index - texR * ` +c+ ` ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( ` +c+", "+o+ ` ) ;
return ` +f.texture2D+"("+r+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function hB(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=t[3],a=t[2]*i,s=t[1]*a,o=_.util.squeezeShape(t),c=o.newShape,l=o.keptDims;if(c.length<t.length){var u=Sa(n,c),h=["row","col","depth","depth2"];return `
` +ba(u)+ `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col , int depth , int depth2 ) {
2020-11-04 16:18:22 +01:00
return ` +r+"("+La(h,l)+ ` ) ;
2020-11-03 15:34:36 +01:00
}
` }if(n.shapeInfo.isUniform)return `
float ` +r+ ` ( int row , int col , int depth , int depth2 ) {
int index = round ( dot ( vec4 ( row , col , depth , depth2 ) ,
vec4 ( ` +s+", "+a+", "+i+ ` , 1 ) ) ) ;
2020-11-04 16:18:22 +01:00
` +xa(n)+ `
2020-11-03 15:34:36 +01:00
}
` ;var d=n.shapeInfo.flatOffset,p=n.shapeInfo.texShape,f=p[0],m=p[1];if(m===s&&d==null)return `
float ` +r+ ` ( int row , int col , int depth , int depth2 ) {
float texR = float ( row ) ;
float texC =
dot ( vec3 ( col , depth , depth2 ) ,
vec3 ( ` +a+", "+i+ ` , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( ` +m+".0, "+f+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
` ;if(m===i&&d==null)return `
float ` +r+ ` ( int row , int col , int depth , int depth2 ) {
float texR = dot ( vec3 ( row , col , depth ) ,
vec3 ( ` +t[1]*t[2]+", "+t[2]+ ` , 1 ) ) ;
float texC = float ( depth2 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( ` +m+".0, "+f+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` ;var g=Ri(e);return `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col , int depth , int depth2 ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ` +s+" + col * "+a+ ` +
depth * ` +i+ ` + depth2 ;
vec2 uv = uvFromFlat ( ` +f+", "+m+", index + "+g+ ` ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function dB(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=t[4],a=t[3]*i,s=t[2]*a,o=t[1]*s,c=_.util.squeezeShape(t),l=c.newShape,u=c.keptDims;if(l.length<t.length){var h=Sa(n,l),d=["row","col","depth","depth2","depth3"];return `
` +ba(h)+ `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col , int depth , int depth2 , int depth3 ) {
2020-11-04 16:18:22 +01:00
return ` +r+"("+La(d,u)+ ` ) ;
2020-11-03 15:34:36 +01:00
}
` }if(n.shapeInfo.isUniform)return `
float ` +r+ ` ( int row , int col , int depth , int depth2 , int depth3 ) {
float index = dot (
vec4 ( row , col , depth , depth2 ) ,
vec4 ( ` +o+", "+s+", "+a+", "+i+ ` ) ) +
depth3 ;
2020-11-04 16:18:22 +01:00
` +xa(n)+ `
2020-11-03 15:34:36 +01:00
}
` ;var p=n.shapeInfo.flatOffset,f=n.shapeInfo.texShape,m=f[0],g=f[1];if(g===o&&p==null)return `
float ` +r+ ` ( int row , int col , int depth , int depth2 , int depth3 ) {
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
vec4 ( ` +s+", "+a+", "+i+ ` , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( ` +g+".0, "+m+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
` ;if(g===i&&p==null)return `
float ` +r+ ` ( int row , int col , int depth , int depth2 , int depth3 ) {
float texR = dot (
vec4 ( row , col , depth , depth2 ) ,
vec4 ( ` +t[1]*t[2]*t[3]+ ` ,
` +t[2]*t[3]+", "+t[3]+ ` , 1 ) ) ;
int texC = depth3 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( ` +g+".0, "+m+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` ;var y=Ri(e);return `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col , int depth , int depth2 , int depth3 ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ` +o+" + col * "+s+" + depth * "+a+ ` +
depth2 * ` +i+" + depth3 + "+y+ ` ;
vec2 uv = uvFromFlat ( ` +m+", "+g+ ` , index ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function pB(n){var t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),i=_.util.squeezeShape(t),a=i.newShape,s=i.keptDims;if(a.length<t.length){var o=Sa(n,a),c=["row","col","depth","depth2","depth3","depth4"];return `
` +ba(o)+ `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
2020-11-04 16:18:22 +01:00
return ` +r+"("+La(c,s)+ ` ) ;
2020-11-03 15:34:36 +01:00
}
` }var l=t[5],u=t[4]*l,h=t[3]*u,d=t[2]*h,p=t[1]*d;if(n.shapeInfo.isUniform)return `
float ` +r+ ` ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
int index = round ( dot (
vec4 ( row , col , depth , depth2 ) ,
vec4 ( ` +p+", "+d+", "+h+", "+u+ ` ) ) +
dot (
vec2 ( depth3 , depth4 ) ,
vec2 ( ` +l+ ` , 1 ) ) ) ;
2020-11-04 16:18:22 +01:00
` +xa(n)+ `
2020-11-03 15:34:36 +01:00
}
` ;var f=n.shapeInfo.flatOffset,m=n.shapeInfo.texShape,g=m[0],y=m[1];if(y===p&&f==null)return `
float ` +r+ ` ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
vec4 ( ` +d+", "+h+", "+u+", "+l+ ` ) ) +
float ( depth4 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( ` +y+".0, "+g+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
` ;if(y===l&&f==null)return `
float ` +r+ ` ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
float texR = dot ( vec4 ( row , col , depth , depth2 ) ,
vec4 ( ` +t[1]*t[2]*t[3]*t[4]+ ` ,
` +t[2]*t[3]*t[4]+ ` ,
` +t[3]*t[4]+ ` ,
` +t[4]+ ` ) ) + float ( depth3 ) ;
int texC = depth4 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( ` +y+".0, "+g+ ` . 0 ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` ;var w=Ri(e);return `
2020-11-03 15:34:36 +01:00
float ` +r+ ` ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ` +p+" + col * "+d+" + depth * "+h+ ` +
depth2 * ` +u+" + depth3 * "+l+" + depth4 + "+w+ ` ;
vec2 uv = uvFromFlat ( ` +g+", "+y+ ` , index ) ;
return sampleTexture ( ` +e+ ` , uv ) ;
}
2020-11-04 16:18:22 +01:00
` }function xa(n){var t=n.name,e=_.util.sizeFromShape(n.shapeInfo.logicalShape);return e<2?"return "+t+";": `
2020-11-03 15:34:36 +01:00
for ( int i = 0 ; i < ` +e+ ` ; i ++ ) {
if ( i == index ) {
return ` +t+ ` [ i ] ;
}
}
2020-11-04 16:18:22 +01:00
` }function wB(n,t){var e=n.name,r=e.charAt(0).toUpperCase()+e.slice(1),i="get"+r+"AtOutCoords",a=n.shapeInfo.logicalShape.length,s=t.logicalShape.length,o=Zb(n.shapeInfo.logicalShape,t.logicalShape),c=Qe(s),l=s-a,u,h=["x","y","z","w","u","v"];a===0?u="":s<2&&o.length>=1?u="coords = 0;":u=o.map(function(x){return"coords."+h[x+l]+" = 0;"}).join( `
2020-11-03 15:34:36 +01:00
` );var d="";s<2&&a>0?d="coords":d=n.shapeInfo.logicalShape.map(function(x,S){return"coords."+h[S+l]}).join(", ");var p="return outputValue;",f=_.util.sizeFromShape(n.shapeInfo.logicalShape),m=f===1,g=_.util.sizeFromShape(t.logicalShape),y=g===1;if(a===1&&!m&&!y)p= `
return vec4 ( outputValue . xy , outputValue . xy ) ;
` ;else if(m&&!y)s===1?p= `
return vec4 ( outputValue . x , outputValue . x , 0. , 0. ) ;
` :p= `
return vec4 ( outputValue . x ) ;
` ;else if(o.length){var w=a-2,b=a-1;o.indexOf(w)>-1&&o.indexOf(b)>-1?p="return vec4(outputValue.x);":o.indexOf(w)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(b)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}return `
vec4 ` +i+ ` ( ) {
` +c+ ` coords = getOutputCoords ( ) ;
` +u+ `
vec4 outputValue = get ` +r+"("+d+ ` ) ;
` +p+ `
}
2020-11-04 16:18:22 +01:00
` }function bB(n,t){var e=n.name,r=e.charAt(0).toUpperCase()+e.slice(1),i="get"+r+"AtOutCoords",a=t.texShape,s=n.shapeInfo.texShape,o=n.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!n.shapeInfo.isUniform&&o===c&&n.shapeInfo.flatOffset==null&&_.util.arraysEqual(s,a))return `
2020-11-03 15:34:36 +01:00
float ` +i+ ` ( ) {
return sampleTexture ( ` +e+ ` , resultUV ) ;
}
2020-11-04 16:18:22 +01:00
` ;var l=Qe(c),u=Zb(n.shapeInfo.logicalShape,t.logicalShape),h=c-o,d,p=["x","y","z","w","u","v"];o===0?d="":c<2&&u.length>=1?d="coords = 0;":d=u.map(function(m){return"coords."+p[m+h]+" = 0;"}).join( `
2020-11-03 15:34:36 +01:00
` );var f="";return c<2&&o>0?f="coords":f=n.shapeInfo.logicalShape.map(function(m,g){return"coords."+p[g+h]}).join(", "), `
float ` +i+ ` ( ) {
` +l+ ` coords = getOutputCoords ( ) ;
` +d+ `
return get ` +r+"("+f+ ` ) ;
}
2020-11-04 16:18:22 +01:00
` }function Qe(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error("GPU for rank "+n+" is not yet supported")}function Sa(n,t){var e=JSON.parse(JSON.stringify(n));return e.shapeInfo.logicalShape=t,e}function La(n,t){return t.map(function(e){return n[e]}).join(", ")}var kB=function(){function n(t,e,r,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,_.util.assert(t.length>2,function(){return"Packed arg"+(r.charAt(0).toUpperCase()+r.slice(1))+" supports only inputs with rank above 2."});var a=t[t.length-1],s=Math.ceil(a/e);this.outputShape=t.slice(0,-1),s>1&&this.outputShape.push(s),i||this.variableNames.push("bestIndicesA");var o=this.outputShape,c=o.length,l=Qe(c),u=Pt("coords",c),h,d;if(s===1){d=c+1;var p=Qe(d);h= `
2020-11-03 15:34:36 +01:00
` +p+" sourceLocR = "+p+"("+u.join()+ ` , 0 ) ;
++ ` +u[c-1]+ ` ;
` +p+" sourceLocG = "+p+"("+u.join()+ ` , 0 ) ;
++ ` +u[c-2]+ ` ;
` +p+" sourceLocA = "+p+"("+u.join()+ ` , 0 ) ;
-- ` +u[c-1]+ ` ;
` +p+" sourceLocB = "+p+"("+u.join()+ ` , 0 ) ;
-- ` +u[c-2]+";"}else d=c,h= `
` +l+ ` sourceLocR = coords ;
++ ` +u[c-1]+ ` ;
` +l+ ` sourceLocG = coords ;
++ ` +u[c-2]+ ` ;
` +l+ ` sourceLocA = coords ;
-- ` +u[c-1]+ ` ;
` +l+ ` sourceLocB = coords ;
-- ` +u[c-2]+";";var f=["x","y","z","w","u","v"].slice(0,d),m="."+f[d-1],g=f.map(function(O){return"int "+O}),y=Pt("sourceLocR",d-1).concat("inIdx.r"),w=Pt("sourceLocG",d-1).concat("inIdx.g"),b=Pt("sourceLocB",d-1).concat("inIdx.b"),x=Pt("sourceLocA",d-1).concat("inIdx.a"),S=r==="max"?"greaterThan":"lessThan",N=i?"": `
inIdx = round ( vec4 ( getBestIndicesAChannel ( ` +y.join()+ ` ) ,
getBestIndicesAChannel ( ` +w.join()+ ` ) ,
getBestIndicesAChannel ( ` +b.join()+ ` ) ,
getBestIndicesAChannel ( ` +x.join()+")));",I= ` vec4 (
getAChannel ( ` +y.join()+ ` ) ,
hasNextCol ? getAChannel ( ` +w.join()+ ` ) : 0. ,
hasNextRow ? getAChannel ( ` +b.join()+ ` ) : 0. ,
hasNextRow && hasNextCol ? getAChannel ( ` +x.join()+") : 0.)",C=i?"": `
float getBestIndicesAChannel ( ` +g.join()+ ` ) {
return getChannel ( getBestIndicesA ( ` +f.join()+ ` ) ,
vec2 ( ` +f.slice(-2).join()+ ` ) ) ;
} ` ;this.userCode= `
float getAChannel ( ` +g.join()+ ` ) {
return getChannel ( getA ( ` +f.join()+ ` ) ,
vec2 ( ` +f.slice(-2).join()+ ` ) ) ;
}
` +C+ `
void main ( ) {
` +l+ ` coords = getOutputCoords ( ) ;
bool hasNextCol = ` +u[c-1]+" < "+(o[c-1]-1)+ ` ;
bool hasNextRow = ` +u[c-2]+" < "+(o[c-2]-1)+ ` ;
` +h+ `
ivec4 srcIdx = ivec4 ( sourceLocR ` +m+", sourceLocG"+m+ ` ,
sourceLocB ` +m+", sourceLocA"+m+") * "+e+ ` ;
ivec4 inIdx = srcIdx ;
vec4 bestIndex = vec4 ( inIdx ) ;
vec4 bestValue = ` +I+ ` ;
for ( int i = 0 ; i < ` +e+ ` ; i ++ ) {
inIdx = srcIdx ;
` +N+ `
vec4 candidate = ` +I+ ` ;
bvec4 nan = isnan ( candidate ) ;
bvec4 replace = bvec4 (
vec4 ( ` +S+ ` ( candidate , bestValue ) ) * ( vec4 ( 1.0 ) - vec4 ( nan ) ) ) ;
bestValue = vec4 ( replace . x ? candidate . x : bestValue . x ,
replace . y ? candidate . y : bestValue . y ,
replace . z ? candidate . z : bestValue . z ,
replace . w ? candidate . w : bestValue . w ) ;
bestIndex = mix ( bestIndex , vec4 ( inIdx ) , vec4 ( replace ) ) ;
srcIdx ++ ;
}
setOutput ( bestIndex ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var FB=function(){function n(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,r=t.filterWidth,i=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,o=t.dilationWidth,c=t.effectiveFilterHeight,l=t.effectiveFilterWidth,u=c-1-t.padInfo.top,h=l-1-t.padInfo.left,d=1/(e*r);this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec2 pads = ivec2 ( ` +u+", "+h+ ` ) ;
const float avgMultiplier = float ( ` +d+ ` ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < ` +c+ ` ;
wR += ` +s+ ` ) {
float dyR = float ( dyRCorner + wR ) / ` +i+ ` . 0 ;
if ( dyR < 0.0 || dyR >= ` +t.outHeight+ ` . 0 || fract ( dyR ) > 0.0 ) {
continue ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
int idyR = int ( dyR ) ;
for ( int wC = 0 ; wC < ` +l+ ` ;
wC += ` +o+ ` ) {
float dyC = float ( dyCCorner + wC ) / ` +a+ ` . 0 ;
if ( dyC < 0.0 || dyC >= ` +t.outWidth+ ` . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
int idyC = int ( dyC ) ;
float dyValue = getDy ( b , idyR , idyC , d ) ;
dotProd += dyValue * avgMultiplier ;
2020-10-28 20:02:59 +01:00
}
}
2020-11-03 15:34:36 +01:00
setOutput ( dotProd ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}(),WB=function(){function n(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,r=t.filterHeight,i=t.filterWidth,a=t.strideDepth,s=t.strideHeight,o=t.strideWidth,c=t.dilationDepth,l=t.dilationHeight,u=t.dilationWidth,h=t.effectiveFilterDepth,d=t.effectiveFilterHeight,p=t.effectiveFilterWidth,f=h-1-t.padInfo.front,m=d-1-t.padInfo.top,g=p-1-t.padInfo.left,y=1/(e*r*i);this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec3 pads = ivec3 ( ` +f+", "+m+", "+g+ ` ) ;
const float avgMultiplier = float ( ` +y+ ` ) ;
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wD = 0 ; wD < ` +h+ ` ;
wD += ` +c+ ` ) {
float dyD = float ( dyDCorner + wD ) / ` +a+ ` . 0 ;
if ( dyD < 0.0 || dyD >= ` +t.outDepth+ ` . 0 || fract ( dyD ) > 0.0 ) {
2020-10-28 20:02:59 +01:00
continue ;
}
2020-11-03 15:34:36 +01:00
int idyD = int ( dyD ) ;
for ( int wR = 0 ; wR < ` +d+ ` ;
wR += ` +l+ ` ) {
float dyR = float ( dyRCorner + wR ) / ` +s+ ` . 0 ;
if ( dyR < 0.0 || dyR >= ` +t.outHeight+ ` . 0 ||
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
for ( int wC = 0 ; wC < ` +p+ ` ;
wC += ` +u+ ` ) {
float dyC = float ( dyCCorner + wC ) / ` +o+ ` . 0 ;
if ( dyC < 0.0 || dyC >= ` +t.outWidth+ ` . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
dotProd += dyValue * avgMultiplier ;
}
2020-10-28 20:02:59 +01:00
}
}
2020-11-03 15:34:36 +01:00
setOutput ( dotProd ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var t2= `
2020-11-03 15:34:36 +01:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2020-11-04 16:18:22 +01:00
` ,UB= `
2020-11-03 15:34:36 +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 ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` ,BB= `
2020-11-03 15:34:36 +01:00
if ( a < 0.0 && floor ( b ) < b ) {
return NAN ;
}
if ( b == 0.0 ) {
return 1.0 ;
}
return ( round ( mod ( b , 2.0 ) ) != 1 ) ?
pow ( abs ( a ) , b ) : sign ( a ) * pow ( abs ( a ) , b ) ;
2020-11-04 16:18:22 +01:00
` ,zB="return float(a == b);",PB="return float(a < b);",MB="return float(a <= b);",HB="return float(a > b);",VB="return float(a >= b);",qB="return float(a >= 1.0 && b >= 1.0);",GB="return float(a >= 1.0 || b >= 1.0);",YB=t2+ `
2020-11-03 15:34:36 +01:00
return max ( a , b ) ;
2020-11-04 16:18:22 +01:00
` ,jB=t2+ `
2020-11-03 15:34:36 +01:00
return min ( a , b ) ;
2020-11-04 16:18:22 +01:00
` ,KB= ` if ( b == 0.0 ) return NAN ;
return mod ( a , b ) ; ` , $ B="return (b >= 1.0) ? a : a * (b + 1.0);",n2="return (a < 0.) ? b * a : a;",Bt=function(){function n(t,e,r){this.variableNames=["A","B"],this.outputShape=_.backend_util.assertAndGetBroadcastShape(e,r),this.userCode= `
2020-11-03 15:34:36 +01:00
float binaryOperation ( float a , float b ) {
` +t+ `
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
void main ( ) {
float a = getAAtOutCoords ( ) ;
float b = getBAtOutCoords ( ) ;
setOutput ( binaryOperation ( a , b ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var mc= `
2020-11-03 15:34:36 +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 ;
2020-11-04 16:18:22 +01:00
` ,XB= `
2020-11-03 15:34:36 +01:00
ivec4 ia = round ( a ) ;
ivec4 ib = round ( b ) ;
bvec4 cond = notEqual ( ib , ivec4 ( 0 ) ) ;
ivec4 result = ivec4 ( 0 ) ;
vec4 s = sign ( a ) * sign ( b ) ;
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if ( cond [ 0 ] ) {
result [ 0 ] = idiv ( ia [ 0 ] , ib [ 0 ] , s [ 0 ] ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
if ( cond [ 1 ] ) {
result [ 1 ] = idiv ( ia [ 1 ] , ib [ 1 ] , s [ 1 ] ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
if ( cond [ 2 ] ) {
result [ 2 ] = idiv ( ia [ 2 ] , ib [ 2 ] , s [ 2 ] ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
if ( cond [ 3 ] ) {
result [ 3 ] = idiv ( ia [ 3 ] , ib [ 3 ] , s [ 3 ] ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
return vec4 ( result ) ;
2020-11-04 16:18:22 +01:00
` ,JB= `
2020-11-03 15:34:36 +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 ;
vec4 isNaN = vec4 ( lessThan ( a , vec4 ( 0.0 ) ) ) * vec4 ( lessThan ( floor ( b ) , b ) ) ;
2020-11-04 16:18:22 +01:00
` +mc+ `
2020-11-03 15:34:36 +01:00
return result ;
2020-11-04 16:18:22 +01:00
` ,r2= `
2020-11-03 15:34:36 +01:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2020-11-04 16:18:22 +01:00
` ,ZB= `
2020-11-03 15:34:36 +01:00
vec4 bGTEZero = vec4 ( greaterThanEqual ( b , vec4 ( 0. ) ) ) ;
return ( bGTEZero * a ) + ( ( vec4 ( 1.0 ) - bGTEZero ) * ( a * ( b + vec4 ( 1.0 ) ) ) ) ;
2020-11-04 16:18:22 +01:00
` ,QB= `
2020-11-03 15:34:36 +01:00
return vec4 ( equal ( a , b ) ) ;
2020-11-04 16:18:22 +01:00
` ,ez= `
2020-11-03 15:34:36 +01:00
return vec4 ( lessThan ( a , b ) ) ;
2020-11-04 16:18:22 +01:00
` ,tz= `
2020-11-03 15:34:36 +01:00
return vec4 ( lessThanEqual ( a , b ) ) ;
2020-11-04 16:18:22 +01:00
` ,nz= `
2020-11-03 15:34:36 +01:00
return vec4 ( greaterThan ( a , b ) ) ;
2020-11-04 16:18:22 +01:00
` ,rz= `
2020-11-03 15:34:36 +01:00
return vec4 ( greaterThanEqual ( a , b ) ) ;
2020-11-04 16:18:22 +01:00
` ,iz= `
2020-11-03 15:34:36 +01:00
return vec4 (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) *
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ) ;
2020-11-04 16:18:22 +01:00
` ,az= `
2020-11-03 15:34:36 +01:00
return min (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) +
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ,
vec4 ( 1.0 ) ) ;
2020-11-04 16:18:22 +01:00
` ,sz= `
2020-11-03 15:34:36 +01:00
vec4 result = vec4 ( max ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2020-11-04 16:18:22 +01:00
` +mc+ `
2020-11-03 15:34:36 +01:00
return result ;
2020-11-04 16:18:22 +01:00
` ,oz= `
2020-11-03 15:34:36 +01:00
vec4 result = vec4 ( min ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2020-11-04 16:18:22 +01:00
` +mc+ `
2020-11-03 15:34:36 +01:00
return result ;
2020-11-04 16:18:22 +01:00
` ,cz= `
2020-11-03 15:34:36 +01:00
vec4 result = mod ( a , b ) ;
vec4 isNaN = vec4 ( equal ( b , vec4 ( 0.0 ) ) ) ;
2020-11-04 16:18:22 +01:00
` +mc+ `
2020-11-03 15:34:36 +01:00
return result ;
2020-11-04 16:18:22 +01:00
` ,dr=function(){function n(t,e,r,i){i===void 0&&(i=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.backend_util.assertAndGetBroadcastShape(e,r);var a=this.outputShape.length,s="";if(i)if(a===0||_.util.sizeFromShape(this.outputShape)===1)s= `
2020-11-03 15:34:36 +01:00
result . y = 0. ;
result . z = 0. ;
result . w = 0. ;
2020-11-04 07:11:24 +01:00
` ;else{var o=Qe(a);if(s= `
2020-11-03 15:34:36 +01:00
` +o+ ` coords = getOutputCoords ( ) ;
` ,a===1)s+= `
result . y = ( coords + 1 ) >= ` +this.outputShape[0]+ ` ? 0. : result . y ;
result . z = 0. ;
result . w = 0. ;
` ;else{var c=Pt("coords",a);s+= `
bool nextRowOutOfBounds =
( ` +c[a-2]+" + 1) >= "+this.outputShape[a-2]+ ` ;
bool nextColOutOfBounds =
( ` +c[a-1]+" + 1) >= "+this.outputShape[a-1]+ ` ;
result . y = nextColOutOfBounds ? 0. : result . y ;
result . z = nextRowOutOfBounds ? 0. : result . z ;
result . w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result . w ;
` }}this.userCode= `
vec4 binaryOperation ( vec4 a , vec4 b ) {
` +t+ `
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
void main ( ) {
vec4 a = getAAtOutCoords ( ) ;
vec4 b = getBAtOutCoords ( ) ;
vec4 result = binaryOperation ( a , b ) ;
` +s+ `
setOutput ( result ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var lz=function(){function n(t){this.variableNames=["A"],this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
uniform float minVal ;
uniform float maxVal ;
void main ( ) {
float value = getAAtOutCoords ( ) ;
if ( isnan ( value ) ) {
setOutput ( value ) ;
2020-10-28 20:02:59 +01:00
return ;
}
2020-11-03 15:34:36 +01:00
setOutput ( clamp ( value , minVal , maxVal ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n.prototype.getCustomSetupFunc=function(t,e){var r=this;return function(i,a){r.minLoc==null&&(r.minLoc=i.getUniformLocationNoThrow(a,"minVal"),r.maxLoc=i.getUniformLocationNoThrow(a,"maxVal")),i.gl.uniform1f(r.minLoc,t),i.gl.uniform1f(r.maxLoc,e)}},n}();var uz=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
uniform float minVal ;
uniform float maxVal ;
void main ( ) {
vec4 value = getAAtOutCoords ( ) ;
if ( any ( isnan ( value ) ) ) {
setOutput ( value ) ;
2020-10-28 20:02:59 +01:00
return ;
}
2020-11-03 15:34:36 +01:00
setOutput ( clamp ( value , vec4 ( minVal ) , vec4 ( maxVal ) ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n.prototype.getCustomSetupFunc=function(t,e){var r=this;return function(i,a){r.minLoc==null&&(r.minLoc=i.getUniformLocationNoThrow(a,"minVal"),r.maxLoc=i.getUniformLocationNoThrow(a,"maxVal")),i.gl.uniform1f(r.minLoc,t),i.gl.uniform1f(r.maxLoc,e)}},n}();var hz=function(){function n(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
float re = abs ( getRealAtOutCoords ( ) ) ;
float im = abs ( getImagAtOutCoords ( ) ) ;
float mx = max ( re , im ) ;
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput (
mx == 0.0 ? 0.0 : mx * length ( vec2 ( 1 , min ( re , im ) / mx ) )
) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var dz=function(){function n(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,r=t.strideWidth,i=t.padInfo.top,a=t.padInfo.left,s=t.dataFormat==="channelsLast";this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int d2 = coords . w ;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int b = 0 ; b < ` +t.batchSize+ ` ; b ++ ) {
for ( int yR = 0 ; yR < ` +t.outHeight+ ` ; yR ++ ) {
int xR = wR + yR * ` +e+" - "+i+ ` ;
if ( xR < 0 || xR >= ` +t.inHeight+ ` ) {
continue ;
}
for ( int yC = 0 ; yC < ` +t.outWidth+ ` ; yC ++ ) {
int xC = wC + yC * ` +r+" - "+a+ ` ;
if ( xC < 0 || xC >= ` +t.inWidth+ ` ) {
continue ;
}
if ( ` +s+ ` ) {
float dyValue = getDy ( b , yR , yC , d2 ) ;
float xValue = getX ( b , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
} else {
float dyValue = getDy ( b , d2 , yR , yC ) ;
float xValue = getX ( b , d1 , xR , xC ) ;
dotProd += ( xValue * dyValue ) ;
}
}
}
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
setOutput ( dotProd ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}(),pz=function(){function n(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,r=t.filterWidth,i=t.strideHeight,a=t.strideWidth,s=t.dataFormat==="channelsLast",o=e-1-t.padInfo.top,c=r-1-t.padInfo.left,l=s?1:2,u=s?2:3,h=s?3:1;this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec2 pads = ivec2 ( ` +o+", "+c+ ` ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d1 = coords [ ` +h+ ` ] ;
ivec2 dyCorner = ivec2 ( coords [ ` +l+"], coords["+u+ ` ] ) - pads ;
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < ` +e+ ` ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / ` +i+ ` . 0 ;
if ( dyR < 0.0 || dyR >= ` +t.outHeight+ ` . 0 || fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
int wRPerm = ` +e+ ` - 1 - wR ;
for ( int wC = 0 ; wC < ` +r+ ` ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / ` +a+ ` . 0 ;
if ( dyC < 0.0 || dyC >= ` +t.outWidth+ ` . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
int wCPerm = ` +r+ ` - 1 - wC ;
for ( int d2 = 0 ; d2 < ` +t.outChannels+ ` ; d2 ++ ) {
if ( ` +s+ ` ) {
float xValue = getDy ( batch , idyR , idyC , d2 ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
} else {
float xValue = getDy ( batch , d2 , idyR , idyC ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
}
}
}
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
setOutput ( dotProd ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}(),fz=function(){function n(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,r=t.strideHeight,i=t.strideWidth,a=t.padInfo.front,s=t.padInfo.top,o=t.padInfo.left;this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int wF = coords . x ;
int wR = coords . y ;
int wC = coords . z ;
int d1 = coords . w ;
int d2 = coords . u ;
float dotProd = 0.0 ;
for ( int b = 0 ; b < ` +t.batchSize+ ` ; b ++ ) {
for ( int yF = 0 ; yF < ` +t.outDepth+ ` ; yF ++ ) {
int xF = wF + yF * ` +e+" - "+a+ ` ;
if ( xF < 0 || xF >= ` +t.inDepth+ ` ) {
continue ;
}
for ( int yR = 0 ; yR < ` +t.outHeight+ ` ; yR ++ ) {
int xR = wR + yR * ` +r+" - "+s+ ` ;
if ( xR < 0 || xR >= ` +t.inHeight+ ` ) {
continue ;
}
for ( int yC = 0 ; yC < ` +t.outWidth+ ` ; yC ++ ) {
int xC = wC + yC * ` +i+" - "+o+ ` ;
if ( xC < 0 || xC >= ` +t.inWidth+ ` ) {
continue ;
}
float dyValue = getDy ( b , yF , yR , yC , d2 ) ;
float xValue = getX ( b , xF , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
}
}
}
}
setOutput ( dotProd ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}(),mz=function(){function n(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,r=t.filterHeight,i=t.filterWidth,a=t.strideDepth,s=t.strideHeight,o=t.strideWidth,c=e-1-t.padInfo.front,l=r-1-t.padInfo.top,u=i-1-t.padInfo.left;this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec3 pads = ivec3 ( ` +c+", "+l+", "+u+ ` ) ;
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d1 = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyFCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
float dotProd = 0.0 ;
for ( int wF = 0 ; wF < ` +e+ ` ; wF ++ ) {
float dyF = float ( dyFCorner + wF ) / ` +a+ ` . 0 ;
if ( dyF < 0.0 || dyF >= ` +t.outDepth+ ` . 0 || fract ( dyF ) > 0.0 ) {
continue ;
}
int idyF = int ( dyF ) ;
int wFPerm = ` +e+ ` - 1 - wF ;
for ( int wR = 0 ; wR < ` +r+ ` ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / ` +s+ ` . 0 ;
if ( dyR < 0.0 || dyR >= ` +t.outHeight+ ` . 0 ||
fract ( dyR ) > 0.0 ) {
2020-10-28 20:02:59 +01:00
continue ;
2020-11-03 15:34:36 +01:00
}
int idyR = int ( dyR ) ;
int wRPerm = ` +r+ ` - 1 - wR ;
for ( int wC = 0 ; wC < ` +i+ ` ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / ` +o+ ` . 0 ;
if ( dyC < 0.0 || dyC >= ` +t.outWidth+ ` . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
int wCPerm = ` +i+ ` - 1 - wC ;
for ( int d2 = 0 ; d2 < ` +t.outChannels+ ` ; d2 ++ ) {
float xValue = getDy ( batch , idyF , idyR , idyC , d2 ) ;
float wValue = getW ( wFPerm , wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
}
}
}
}
setOutput ( dotProd ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var gz=function(){function n(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,r=t.strideWidth,i=t.padInfo.top,a=t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int dm = coords . w ;
int d2 = d1 * ` +s+ ` + dm ;
float dotProd = 0.0 ;
// TO DO: Vec4 over the batch size
for ( int b = 0 ; b < ` +t.batchSize+ ` ; b ++ ) {
for ( int yR = 0 ; yR < ` +t.outHeight+ ` ; yR ++ ) {
int xR = wR + yR * ` +e+" - "+i+ ` ;
if ( xR < 0 || xR >= ` +t.inHeight+ ` ) {
2020-10-28 20:02:59 +01:00
continue ;
2020-11-03 15:34:36 +01:00
}
for ( int yC = 0 ; yC < ` +t.outWidth+ ` ; yC ++ ) {
int xC = wC + yC * ` +r+" - "+a+ ` ;
if ( xC < 0 || xC >= ` +t.inWidth+ ` ) {
2020-10-28 20:02:59 +01:00
continue ;
}
2020-11-03 15:34:36 +01:00
float dyValue = getDy ( b , yR , yC , d2 ) ;
float xValue = getX ( b , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
}
}
}
setOutput ( dotProd ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}(),yz=function(){function n(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,r=t.filterWidth,i=t.strideHeight,a=t.strideWidth,s=e-1-t.padInfo.top,o=r-1-t.padInfo.left,c=t.outChannels/t.inChannels;this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec2 pads = ivec2 ( ` +s+", "+o+ ` ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d1 = coords [ 3 ] ;
ivec2 dyCorner = coords . yz - pads ;
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < ` +e+ ` ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / ` +i+ ` . 0 ;
if ( dyR < 0.0 || dyR >= ` +t.outHeight+ ` . 0 || fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
int wRPerm = ` +e+ ` - 1 - wR ;
for ( int wC = 0 ; wC < ` +r+ ` ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / ` +a+ ` . 0 ;
if ( dyC < 0.0 || dyC >= ` +t.outWidth+ ` . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
int wCPerm = ` +r+ ` - 1 - wC ;
// TO DO: Vec4 over the channelMul
for ( int dm = 0 ; dm < ` +c+ ` ; dm ++ ) {
int d2 = d1 * ` +c+ ` + dm ;
float xValue = getDy ( batch , idyR , idyC , d2 ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , dm ) ;
dotProd += xValue * wValue ;
}
}
}
setOutput ( dotProd ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var i2=function(){function n(t,e,r,i){e===void 0&&(e=!1),r===void 0&&(r=null),i===void 0&&(i=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.padInfo.top,s=t.padInfo.left,o=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,u=t.dilationWidth,h=t.filterHeight,d=t.filterWidth,p=Math.floor(t.inChannels/4)*4,f=t.inChannels%4,m=t.dataFormat==="channelsLast",g=m?1:2,y=m?2:3,w=m?3:1,b="",x="";r&&(i?b= ` float activation ( float a ) {
2020-11-03 15:34:36 +01:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
` +r+ `
} ` :b= `
float activation ( float x ) {
` +r+ `
}
` ,x="result = activation(result);");var S=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode= `
` +b+ `
const ivec2 strides = ivec2 ( ` +o+", "+c+ ` ) ;
const ivec2 pads = ivec2 ( ` +a+", "+s+ ` ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d2 = coords [ ` +w+ ` ] ;
ivec2 xRCCorner =
ivec2 ( coords [ ` +g+"], coords["+y+ ` ] ) * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < ` +h+ ` ; wR ++ ) {
int xR = xRCorner + wR * ` +l+ ` ;
if ( xR < 0 || xR >= ` +t.inHeight+ ` ) {
continue ;
}
for ( int wC = 0 ; wC < ` +d+ ` ; wC ++ ) {
int xC = xCCorner + wC * ` +u+ ` ;
if ( xC < 0 || xC >= ` +t.inWidth+ ` ) {
continue ;
}
for ( int d1 = 0 ; d1 < ` +p+ ` ; d1 += 4 ) {
vec4 wValues = vec4 (
getW ( wR , wC , d1 , d2 ) ,
getW ( wR , wC , d1 + 1 , d2 ) ,
getW ( wR , wC , d1 + 2 , d2 ) ,
getW ( wR , wC , d1 + 3 , d2 )
) ;
if ( ` +m+ ` ) {
vec4 xValues = vec4 (
getX ( batch , xR , xC , d1 ) ,
getX ( batch , xR , xC , d1 + 1 ) ,
getX ( batch , xR , xC , d1 + 2 ) ,
getX ( batch , xR , xC , d1 + 3 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec4 xValues = vec4 (
getX ( batch , d1 , xR , xC ) ,
getX ( batch , d1 + 1 , xR , xC ) ,
getX ( batch , d1 + 2 , xR , xC ) ,
getX ( batch , d1 + 3 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
}
}
if ( ` +(f===1)+ ` ) {
if ( ` +m+ ` ) {
dotProd +=
getX ( batch , xR , xC , ` +p+ ` ) *
getW ( wR , wC , ` +p+ ` , d2 ) ;
} else {
dotProd +=
getX ( batch , ` +p+ ` , xR , xC ) *
getW ( wR , wC , ` +p+ ` , d2 ) ;
}
} else if ( ` +(f===2)+ ` ) {
vec2 wValues = vec2 (
getW ( wR , wC , ` +p+ ` , d2 ) ,
getW ( wR , wC , ` +p+ ` + 1 , d2 )
) ;
if ( ` +m+ ` ) {
vec2 xValues = vec2 (
getX ( batch , xR , xC , ` +p+ ` ) ,
getX ( batch , xR , xC , ` +p+ ` + 1 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec2 xValues = vec2 (
getX ( batch , ` +p+ ` , xR , xC ) ,
getX ( batch , ` +p+ ` + 1 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
}
} else if ( ` +(f===3)+ ` ) {
vec3 wValues = vec3 (
getW ( wR , wC , ` +p+ ` , d2 ) ,
getW ( wR , wC , ` +p+ ` + 1 , d2 ) ,
getW ( wR , wC , ` +p+ ` + 2 , d2 )
) ;
if ( ` +m+ ` ) {
vec3 xValues = vec3 (
getX ( batch , xR , xC , ` +p+ ` ) ,
getX ( batch , xR , xC , ` +p+ ` + 1 ) ,
getX ( batch , xR , xC , ` +p+ ` + 2 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec3 xValues = vec3 (
getX ( batch , ` +p+ ` , xR , xC ) ,
getX ( batch , ` +p+ ` + 1 , xR , xC ) ,
getX ( batch , ` +p+ ` + 2 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
}
}
}
float result = dotProd ;
` +S+ `
` +x+ `
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}(),vz=function(){function n(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,r=t.padInfo.top,i=t.padInfo.left,a=t.strideDepth,s=t.strideHeight,o=t.strideWidth,c=t.dilationDepth,l=t.dilationHeight,u=t.dilationWidth,h=t.filterDepth,d=t.filterHeight,p=t.filterWidth,f=Math.floor(t.inChannels/4)*4,m=t.inChannels%4;this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec3 strides = ivec3 ( ` +a+", "+s+", "+o+ ` ) ;
const ivec3 pads = ivec3 ( ` +e+", "+r+", "+i+ ` ) ;
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d2 = coords . u ;
ivec3 xFRCCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xFCorner = xFRCCorner . x ;
int xRCorner = xFRCCorner . y ;
int xCCorner = xFRCCorner . z ;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0 ;
for ( int wF = 0 ; wF < ` +h+ ` ; wF ++ ) {
int xF = xFCorner + wF * ` +c+ ` ;
if ( xF < 0 || xF >= ` +t.inDepth+ ` ) {
continue ;
}
for ( int wR = 0 ; wR < ` +d+ ` ; wR ++ ) {
int xR = xRCorner + wR * ` +l+ ` ;
if ( xR < 0 || xR >= ` +t.inHeight+ ` ) {
continue ;
}
for ( int wC = 0 ; wC < ` +p+ ` ; wC ++ ) {
int xC = xCCorner + wC * ` +u+ ` ;
if ( xC < 0 || xC >= ` +t.inWidth+ ` ) {
continue ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
for ( int d1 = 0 ; d1 < ` +f+ ` ; d1 += 4 ) {
vec4 xValues = vec4 (
getX ( batch , xF , xR , xC , d1 ) ,
getX ( batch , xF , xR , xC , d1 + 1 ) ,
getX ( batch , xF , xR , xC , d1 + 2 ) ,
getX ( batch , xF , xR , xC , d1 + 3 )
) ;
vec4 wValues = vec4 (
getW ( wF , wR , wC , d1 , d2 ) ,
getW ( wF , wR , wC , d1 + 1 , d2 ) ,
getW ( wF , wR , wC , d1 + 2 , d2 ) ,
getW ( wF , wR , wC , d1 + 3 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
if ( ` +(m===1)+ ` ) {
dotProd +=
getX ( batch , xF , xR , xC , ` +f+ ` ) *
getW ( wF , wR , wC , ` +f+ ` , d2 ) ;
} else if ( ` +(m===2)+ ` ) {
vec2 xValues = vec2 (
getX ( batch , xF , xR , xC , ` +f+ ` ) ,
getX ( batch , xF , xR , xC , ` +f+ ` + 1 )
) ;
vec2 wValues = vec2 (
getW ( wF , wR , wC , ` +f+ ` , d2 ) ,
getW ( wF , wR , wC , ` +f+ ` + 1 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else if ( ` +(m===3)+ ` ) {
vec3 xValues = vec3 (
getX ( batch , xF , xR , xC , ` +f+ ` ) ,
getX ( batch , xF , xR , xC , ` +f+ ` + 1 ) ,
getX ( batch , xF , xR , xC , ` +f+ ` + 2 )
) ;
vec3 wValues = vec3 (
getW ( wF , wR , wC , ` +f+ ` , d2 ) ,
getW ( wF , wR , wC , ` +f+ ` + 1 , d2 ) ,
getW ( wF , wR , wC , ` +f+ ` + 2 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
}
}
}
}
setOutput ( dotProd ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var a2=function(){function n(t,e,r,i){e===void 0&&(e=!1),r===void 0&&(r=null),i===void 0&&(i=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.inHeight,s=t.inWidth,o=t.padInfo.top,c=t.padInfo.left,l=t.strideHeight,u=t.strideWidth,h=t.dilationHeight,d=t.dilationWidth,p=t.filterHeight,f=t.filterWidth,m=t.outChannels/t.inChannels,g="",y="";r&&(i?g= ` float activation ( float a ) {
2020-11-03 15:34:36 +01:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
` +r+ `
} ` :g= `
float activation ( float x ) {
` +r+ `
}
` ,y="result = activation(result);");var w=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode= `
` +g+ `
const ivec2 strides = ivec2 ( ` +l+", "+u+ ` ) ;
const ivec2 pads = ivec2 ( ` +o+", "+c+ ` ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
int d1 = d2 / ` +m+ ` ;
int q = d2 - d1 * ` +m+ ` ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for ( int wR = 0 ; wR < ` +p+ ` ; wR ++ ) {
int xR = xRCorner + wR * ` +h+ ` ;
if ( xR < 0 || xR >= ` +a+ ` ) {
continue ;
}
for ( int wC = 0 ; wC < ` +f+ ` ; wC ++ ) {
int xC = xCCorner + wC * ` +d+ ` ;
if ( xC < 0 || xC >= ` +s+ ` ) {
2020-10-28 20:02:59 +01:00
continue ;
2020-11-03 15:34:36 +01:00
}
float xVal = getX ( batch , xR , xC , d1 ) ;
float wVal = getW ( wR , wC , d1 , q ) ;
dotProd += xVal * wVal ;
2020-10-28 20:02:59 +01:00
}
}
2020-11-03 15:34:36 +01:00
float result = dotProd ;
` +w+ `
` +y+ `
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var s2=function(){function n(t,e,r,i){e===void 0&&(e=!1),r===void 0&&(r=null),i===void 0&&(i=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var a=t.inHeight,s=t.inWidth,o=t.padInfo.top,c=t.padInfo.left,l=t.strideHeight,u=t.strideWidth,h=t.dilationHeight,d=t.dilationWidth,p=t.filterHeight,f=t.filterWidth,m=f,g="int xR; int xC; int xCOffset;",y=0;y<p;y++)for(var w=0;w<f;w++)g+= `
2020-11-03 15:34:36 +01:00
vec4 xTexelR ` +y+"C"+w*2+ ` = vec4 ( 0. ) ;
vec4 wR ` +y+"C"+w+ ` = vec4 ( 0. ) ;
vec4 xR ` +y+"C"+w+" = vec4(0.);";for(var y=0;y<p;y++)for(var b=0;b<m;b++){var w=b*2;if(g+= `
xR = xRCorner + ` +y*h+ ` ;
xC = xCCorner + ` +w*d+ ` ;
` ,u===1){if(w<f&&(c%2===1?g+= `
xCOffset = xC + 1 ;
if ( xR >= 0 && xR < ` +a+" && xCOffset >= 0 && xCOffset < "+s+ ` ) {
xTexelR ` +y+"C"+w+ ` = getX ( batch , xR , xCOffset , d1 ) ;
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= ` +s+ ` ) {
xTexelR ` +y+"C"+w+ ` . zw = vec2 ( 0. ) ;
}
} else {
xTexelR ` +y+"C"+w+ ` = vec4 ( 0. ) ;
}
xCOffset = xC + 1 - 2 ;
if ( xR >= 0 && xR < ` +a+" && xCOffset >= 0 && xCOffset < "+s+ ` ) {
vec4 previous = getX ( batch , xR , xCOffset , d1 ) ;
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= ` +s+ ` ) {
previous . zw = vec2 ( 0. ) ;
}
xR ` +y+"C"+w+" = vec4(previous.zw, xTexelR"+y+"C"+w+ ` . xy ) ;
} else {
xR ` +y+"C"+w+" = vec4(0, 0, xTexelR"+y+"C"+w+ ` . xy ) ;
}
` :g+= `
if ( xR >= 0 && xR < ` +a+" && xC >= 0 && xC < "+s+ ` ) {
xTexelR ` +y+"C"+w+ ` = getX ( batch , xR , xC , d1 ) ;
} else {
xTexelR ` +y+"C"+w+ ` = vec4 ( 0. ) ;
}
xR ` +y+"C"+w+" = xTexelR"+y+"C"+w+ ` ;
` ,w+1<f)){var x=c%2===0?_.util.nearestLargerEven(d):d;d%2===0&&c%2===1||d%2!==0&&c%2!==1?(g+= `
xCOffset = xC + ` +c%2+" + "+x+ ` ;
if ( xR >= 0 && xR < ` +a+ ` &&
xCOffset >= 0 && xCOffset < ` +s+ ` ) {
xTexelR ` +y+"C"+(w+2)+ ` = getX ( batch , xR , xCOffset , d1 ) ;
}
` ,d>1&&(g+= `
xCOffset -= 2 ;
if ( xR >= 0 && xR < ` +a+ ` &&
xCOffset >= 0 && xCOffset < ` +s+ ` ) {
xTexelR ` +y+"C"+w+ ` = getX ( batch , xR , xCOffset , d1 ) ;
} else {
xTexelR ` +y+"C"+w+ ` = vec4 ( 0. ) ;
}
` ),g+= `
xR ` +y+"C"+(w+1)+ ` = vec4 (
xTexelR ` +y+"C"+w+".zw, xTexelR"+y+"C"+(w+2)+ ` . xy ) ;
` ):g+= `
xCOffset = xC + ` +x+ ` ;
if ( xR >= 0 && xR < ` +a+ ` &&
xCOffset >= 0 && xCOffset < ` +s+ ` ) {
xTexelR ` +y+"C"+(w+2)+ ` = getX ( batch , xR , xCOffset , d1 ) ;
}
xR ` +y+"C"+(w+1)+" = xTexelR"+y+"C"+(w+2)+ ` ;
` }}else w<f&&(g+= `
if ( xR >= 0 && xR < ` +a+ ` ) {
` ,c%2===1?(g+= `
xCOffset = xC + 1 - ` +u+ ` ;
if ( xCOffset >= 0 && xCOffset < ` +s+ ` ) {
xTexelR ` +y+"C"+w+ ` = getX ( batch , xR , xCOffset , d1 ) ;
} else {
xTexelR ` +y+"C"+w+ ` = vec4 ( 0. ) ;
}
if ( xC + 1 >= 0 && xC + 1 < ` +s+ ` ) {
xTexelR ` +y+"C"+(w+2)+ ` = getX ( batch , xR , xC + 1 , d1 ) ;
} else {
xTexelR ` +y+"C"+(w+2)+ ` = vec4 ( 0. ) ;
}
xR ` +y+"C"+w+ ` = vec4 (
xTexelR ` +y+"C"+w+".zw, xTexelR"+y+"C"+(w+2)+ ` . zw ) ;
` ,w+1<f&&(g+= `
vec4 final = vec4 ( 0. ) ;
xCOffset = xC + 1 + ` +u+ ` ;
if ( xCOffset >= 0 && xCOffset < ` +s+ ` ) {
final = getX ( batch , xR , xCOffset , d1 ) ;
}
xR ` +y+"C"+(w+1)+" = vec4(xTexelR"+y+"C"+(w+2)+ ` . xy , final . xy ) ;
` )):(g+= `
if ( xC >= 0 && xC < ` +s+ ` ) {
xTexelR ` +y+"C"+w+ ` = getX ( batch , xR , xC , d1 ) ;
} else {
xTexelR ` +y+"C"+w+ ` = vec4 ( 0. ) ;
}
xCOffset = xC + ` +u+ ` ;
if ( xCOffset >= 0 && xCOffset < ` +s+ ` ) {
xTexelR ` +y+"C"+(w+2)+ ` = getX ( batch , xR , xCOffset , d1 ) ;
} else {
xTexelR ` +y+"C"+(w+2)+ ` = vec4 ( 0. ) ;
}
xR ` +y+"C"+w+ ` = vec4 (
xTexelR ` +y+"C"+w+".xy, xTexelR"+y+"C"+(w+2)+ ` . xy ) ;
` ,w+1<f&&(g+= `
xR ` +y+"C"+(w+1)+ ` = vec4 (
xTexelR ` +y+"C"+w+".zw, xTexelR"+y+"C"+(w+2)+ ` . zw ) ;
` )),g+="}");w<f&&(g+= `
vec4 wTexelR ` +y+"C"+w+" = getW("+y+", "+w+ ` , d1 , q ) ;
wR ` +y+"C"+w+" = vec4(wTexelR"+y+"C"+w+".xz, wTexelR"+y+"C"+w+ ` . xz ) ;
` ,w+1<f&&(g+= `
vec4 wTexelR ` +y+"C"+(w+1)+" = getW("+y+", "+(w+1)+ ` , d1 , q ) ;
wR ` +y+"C"+(w+1)+ ` =
vec4 ( wTexelR ` +y+"C"+(w+1)+".xz, wTexelR"+y+"C"+(w+1)+".xz);"))}for(var y=0;y<p;y++)for(var w=0;w<f;w++)g+="dotProd += xR"+y+"C"+w+" * wR"+y+"C"+w+";";var S="",N="";r&&(i?S= ` vec4 activation ( vec4 a ) {
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
` +r+ `
} ` :S= ` vec4 activation ( vec4 x ) {
` +r+ `
} ` ,N="result = activation(result);");var I=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode= `
` +S+ `
const ivec2 strides = ivec2 ( ` +l+", "+u+ ` ) ;
const ivec2 pads = ivec2 ( ` +o+", "+c+ ` ) ;
void main ( ) {
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 ;
vec4 dotProd = vec4 ( 0. ) ;
` +g+ `
vec4 result = dotProd ;
` +I+ `
` +N+ `
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var wz=function(){function n(t,e,r,i,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var s=t[0],o=t[1],c=t[2],l=t[3],u=e[0],h=r[0],d=r[1];this.outputShape=[u,h,d,l];var p=i==="bilinear"?1:0,f=[o-1+".0",c-1+".0"],m=f[0],g=f[1],y=h>1?[""+(o-1)/(h-1),"(y2-y1) * height_ratio","y1*"+m+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+m],w=y[0],b=y[1],x=y[2],S=d>1?[""+(c-1)/(d-1),"(x2-x1) * width_ratio","x1*"+g+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+g],N=S[0],I=S[1],C=S[2];this.userCode= `
2020-11-03 15:34:36 +01:00
const float height _ratio = float ( ` +w+ ` ) ;
const float width _ratio = float ( ` +N+ ` ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int y = coords [ 1 ] ;
int x = coords [ 2 ] ;
int d = coords [ 3 ] ;
// get box vals
float y1 = getBoxes ( b , 0 ) ;
float x1 = getBoxes ( b , 1 ) ;
float y2 = getBoxes ( b , 2 ) ;
float x2 = getBoxes ( b , 3 ) ;
// get image in batch index
int bInd = round ( getBoxInd ( b ) ) ;
if ( bInd < 0 || bInd >= ` +s+ ` ) {
return ;
}
float height _scale = ` +b+ ` ;
float width _scale = ` +I+ ` ;
float in _y = ` +x+ ` ;
if ( in _y < 0.0 || in _y > ` +m+ ` ) {
setOutput ( float ( ` +a+ ` ) ) ;
return ;
}
float in _x = ` +C+ ` ;
if ( in _x < 0.0 || in _x > ` +g+ ` ) {
setOutput ( float ( ` +a+ ` ) ) ;
return ;
}
vec2 sourceFracIndexCR = vec2 ( in _x , in _y ) ;
if ( ` +p+ ` == 1 ) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2 ( sourceFracIndexCR ) ;
ivec2 sourceCeilCR = ivec2 ( ceil ( sourceFracIndexCR ) ) ;
float topLeft = getImage ( b , sourceFloorCR . y , sourceFloorCR . x , d ) ;
float bottomLeft = getImage ( b , sourceCeilCR . y , sourceFloorCR . x , d ) ;
float topRight = getImage ( b , sourceFloorCR . y , sourceCeilCR . x , d ) ;
float bottomRight = getImage ( b , sourceCeilCR . y , sourceCeilCR . x , d ) ;
vec2 fracCR = sourceFracIndexCR - vec2 ( sourceFloorCR ) ;
float top = topLeft + ( topRight - topLeft ) * fracCR . x ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracCR . x ;
float newValue = top + ( bottom - top ) * fracCR . y ;
setOutput ( newValue ) ;
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2 ( floor (
sourceFracIndexCR + vec2 ( 0.5 , 0.5 ) ) ) ;
float newValue = getImage ( b , sourceNearestCR . y , sourceNearestCR . x , d ) ;
setOutput ( newValue ) ;
}
}
2020-11-04 16:18:22 +01:00
` }return n}(),l2=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=t;var i=t.length,a=e?"0.0":"getX("+o2(i,"coords")+")",s=t[t.length-1],o="",c="";e?(o=r?"end != "+(s-1):"end != 0",c=r?"end + 1":"end - 1"):(o=r?"end + pow2 < "+s:"end >= pow2",c=r?"end + pow2":"end - pow2"),this.userCode= `
2020-11-03 15:34:36 +01:00
uniform float index ;
void main ( ) {
2020-11-04 07:11:24 +01:00
` +Qe(i)+ ` coords = getOutputCoords ( ) ;
2020-11-04 16:18:22 +01:00
int end = ` +c2(i,"coords")+ ` ;
2020-11-03 15:34:36 +01:00
float val = ` +a+ ` ;
int pow2 = int ( pow ( 2.0 , index ) ) ;
if ( ` +o+ ` ) {
int idx = ` +c+ ` ;
2020-11-04 16:18:22 +01:00
` +c2(i,"coords")+ ` = idx ;
val += getX ( ` +o2(i,"coords")+ ` ) ;
2020-11-03 15:34:36 +01:00
}
setOutput ( val ) ;
}
2020-11-04 16:18:22 +01:00
` }return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(r,i){e.index==null&&(e.index=r.getUniformLocation(i,"index")),r.gl.uniform1f(e.index,t)}},n}();function o2(n,t){if(n===1)return""+t;if(n===2)return t+".x, "+t+".y";if(n===3)return t+".x, "+t+".y, "+t+".z";if(n===4)return t+".x, "+t+".y, "+t+".z, "+t+".w";throw Error("Cumulative sum for rank "+n+" is not yet supported")}function c2(n,t){if(n===1)return""+t;if(n===2)return t+".y";if(n===3)return t+".z";if(n===4)return t+".w";throw Error("Cumulative sum for rank "+n+" is not yet supported")}var bz=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Is.DENSE;var e=Ts(t),r=Mt();this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2020-11-04 16:18:22 +01:00
` +Ci(["r","c","d"],t)+ `
2020-11-03 15:34:36 +01:00
return ivec3 ( r , c , d ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +e[0]+", "+e[1]+ ` ) ) ;
int index = 4 * ( resTexRC . x * ` +e[1]+ ` + resTexRC . y ) ;
vec4 result = vec4 ( 0. ) ;
for ( int i = 0 ; i < 4 ; i ++ ) {
int flatIndex = index + i ;
ivec3 rc = outCoordsFromFlatIndex ( flatIndex ) ;
result [ i ] = getA ( rc . x , rc . y , rc . z ) ;
}
` +r.output+ ` = result ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var xz=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Is.DENSE;var e=Ts(t),r=Mt();this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2020-11-04 16:18:22 +01:00
` +Ci(["r","c","d"],t)+ `
2020-11-03 15:34:36 +01:00
return ivec3 ( r , c , d ) ;
}
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( ` +e[0]+", "+e[1]+ ` ) ) ;
int index = 4 * ( resTexRC . x * ` +e[1]+ ` + resTexRC . y ) ;
vec4 result = vec4 ( 0. ) ;
for ( int i = 0 ; i < 4 ; i ++ ) {
int flatIndex = index + i ;
ivec3 rc = outCoordsFromFlatIndex ( flatIndex ) ;
result [ i ] = getChannel ( getA ( rc . x , rc . y , rc . z ) , vec2 ( rc . y , rc . z ) ) ;
}
` +r.output+ ` = result ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var Sz=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=r,this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int h = ` +this.getHeightCoordString()+ ` ;
int w = ` +this.getWidthCoordString()+ ` ;
int d = ` +this.getDepthCoordString()+ ` ;
int in _h = h / ` +e+ ` ;
int offset _h = imod ( h , ` +e+ ` ) ;
int in _w = w / ` +e+ ` ;
int offset _w = imod ( w , ` +e+ ` ) ;
int offset _d = ( offset _h * ` +e+ ` + offset _w ) *
` +this.getOutputDepthSize()+ ` ;
int in _d = d + offset _d ;
float result = ` +this.getInputSamplingString()+ ` ;
setOutput ( result ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},n.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},n.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},n.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},n.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},n}();var Lz=function(){function n(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
float val = coords [ 0 ] == coords [ 1 ] ? getX ( coords [ 0 ] ) : 0.0 ;
setOutput ( val ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var Iz=function(){function n(t){this.variableNames=["A"],this.outTexUsage=hn.DOWNLOAD;var e=Mt();this.outputShape=t,this.userCode= `
` +Jb+ `
2020-11-03 15:34:36 +01:00
void main ( ) {
float x = getAAtOutCoords ( ) ;
` +e.output+ ` = encode _float ( x ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var Az=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=hn.DOWNLOAD;var e=Mt();this.outputShape=t,this.userCode= `
` +Jb+ `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
float x = getChannel ( getAAtOutCoords ( ) , vec2 ( coords . y , coords . z ) ) ;
` +e.output+ ` = encode _float ( x ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var Tz=function(){function n(t,e,r){r===void 0&&(r=!1),this.variableNames=["A"];var i=Mt(),a=e[0],s=e[1];this.outputShape=t;var o="result";r&&(o="floor(result * 255. + 0.5)"),this.userCode= `
` +Tp(t)+ `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int flatIndex = getFlatIndex ( coords ) ;
int offset = imod ( flatIndex , 4 ) ;
flatIndex = idiv ( flatIndex , 4 , 1. ) ;
int r = flatIndex / ` +s+ ` ;
int c = imod ( flatIndex , ` +s+ ` ) ;
vec2 uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( ` +s+".0, "+a+ ` . 0 ) ;
vec4 values = ` +i.texture2D+ ` ( A , uv ) ;
float result ;
if ( offset == 0 ) {
result = values [ 0 ] ;
} else if ( offset == 1 ) {
result = values [ 1 ] ;
} else if ( offset == 2 ) {
result = values [ 2 ] ;
} else {
result = values [ 3 ] ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
` +i.output+" = vec4("+o+ ` , 0. , 0. , 0. ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var Nz=function(){function n(t,e,r){r===void 0&&(r=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var i=Mt(),a=e[0],s=e[1];this.outputShape=t;var o="",c="result";r&&(c="floor(result * 255. + 0.5)");for(var l=0;l<=1;l++)for(var u=0;u<=1;u++){var h=l*2+u;o+= `
2020-11-03 15:34:36 +01:00
localCoords = coords ;
if ( localCoords [ 2 ] + ` +u+" < "+t[2]+ ` ) {
localCoords [ 2 ] += ` +u+ ` ;
if ( localCoords [ 1 ] + ` +l+" < "+t[1]+ ` ) {
localCoords [ 1 ] += ` +l+ ` ;
flatIndex = getFlatIndex ( localCoords ) ;
offset = imod ( flatIndex , 4 ) ;
flatIndex = idiv ( flatIndex , 4 , 1. ) ;
r = flatIndex / ` +s+ ` ;
c = imod ( flatIndex , ` +s+ ` ) ;
uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( ` +s+".0, "+a+ ` . 0 ) ;
values = ` +i.texture2D+ ` ( A , uv ) ;
if ( offset == 0 ) {
result [ ` +h+ ` ] = values [ 0 ] ;
} else if ( offset == 1 ) {
result [ ` +h+ ` ] = values [ 1 ] ;
} else if ( offset == 2 ) {
result [ ` +h+ ` ] = values [ 2 ] ;
} else {
result [ ` +h+ ` ] = values [ 3 ] ;
}
}
}
` }this.userCode= `
2020-11-04 16:18:22 +01:00
` +Tp(t)+ `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
int flatIndex , r , c , offset ;
ivec3 localCoords ;
vec2 uv ;
vec4 values ;
` +o+ `
` +i.output+" = "+c+ ` ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var _z=function(){function n(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
uniform float value ;
void main ( ) {
// Input can be obtained from uniform value.
setOutput ( value ) ;
}
2020-11-04 16:18:22 +01:00
` }return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(r,i){e.valueLoc==null&&(e.valueLoc=r.getUniformLocationNoThrow(i,"value")),r.gl.uniform1f(e.valueLoc,t)}},n}();var Rz=function(){function n(t,e,r){this.variableNames=["A","indices"];var i=t.slice();i[r]=e,this.outputShape=i,this.rank=i.length;var a=Qe(this.rank),s=Cz(t,r);this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
` +a+ ` resRC = getOutputCoords ( ) ;
setOutput ( getA ( ` +s+ ` ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();function Cz(n,t){var e=n.length;if(e>4)throw Error("Gather for rank "+e+" is not yet supported");if(e===1)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],a=0;a<n.length;a++)a===t?i.push("int(getIndices("+r[a]+"))"):i.push(""+r[a]);return i.join()}var Oz=function(){function n(t,e,r){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=r;var i=Qe(e.length),a=Qe(r.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode= `
2020-11-03 15:34:36 +01:00
` +i+" strides = "+i+"("+this.strides+ ` ) ;
void main ( ) {
` +a+ ` coords = getOutputCoords ( ) ;
int flattenIndex = 0 ;
for ( int j = 0 ; j < ` +this.sliceDim+ ` ; j ++ ) {
int index = round ( getIndices ( coords [ 0 ] , j ) ) ;
flattenIndex += index * ` +s+ ` ;
}
setOutput ( getX ( flattenIndex , coords [ 1 ] ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();function u2(n){var t=Mt(),e=t.version+ `
2020-11-03 15:34:36 +01:00
precision highp float ;
` +t.attribute+ ` vec3 clipSpacePos ;
` +t.attribute+ ` vec2 uv ;
` +t.varyingVs+ ` vec2 resultUV ;
void main ( ) {
gl _Position = vec4 ( clipSpacePos , 1 ) ;
resultUV = uv ;
2020-11-04 16:18:22 +01:00
} ` ;return _b(n,e)}function h2(n){var t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return Eb(n,t)}function d2(n){var t=new Uint16Array([0,1,2,2,1,3]);return Db(n,t)}function Rs(n,t,e,r,i,a){Fb(t,e);var s=kb(n),o=n.TEXTURE_2D;return de(n,function(){return n.bindTexture(o,s)}),de(n,function(){return n.texParameteri(o,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)}),de(n,function(){return n.texParameteri(o,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}),de(n,function(){return n.texParameteri(o,n.TEXTURE_MIN_FILTER,n.NEAREST)}),de(n,function(){return n.texParameteri(o,n.TEXTURE_MAG_FILTER,n.NEAREST)}),de(n,function(){return n.texImage2D(o,0,r,t,e,0,i,a,null)}),de(n,function(){return n.bindTexture(n.TEXTURE_2D,null)}),s}function Np(n){return n.internalFormatFloat}function p2(n,t,e,r){var i=As(t,e),a=i[0],s=i[1];return Rs(n,a,s,Np(r),r.textureFormatFloat,n.FLOAT)}function _p(n){return n.internalFormatHalfFloat}function f2(n,t,e,r){var i=As(t,e),a=i[0],s=i[1];return Rs(n,a,s,_p(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function Cp(n){return n.downloadTextureFormat}function m2(n,t,e,r){var i=As(t,e),a=i[0],s=i[1];return Rs(n,a,s,Cp(r),n.RGBA,n.UNSIGNED_BYTE)}function Rp(n){return n.internalFormatPackedFloat}function g2(n,t,e,r){var i=ya(t,e),a=i[0],s=i[1];return Rs(n,a,s,Rp(r),n.RGBA,n.FLOAT)}function Op(n){return n.internalFormatPackedHalfFloat}function y2(n,t,e,r){var i=ya(t,e),a=i[0],s=i[1];return Rs(n,a,s,Op(r),n.RGBA,r.textureTypeHalfFloat)}function v2(n,t,e){var r=0,i=3*4,a=3*4+2*4;de(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,e)});var s=bp(n,t,"clipSpacePos",e,3,a,r);return s&&bp(n,t,"uv",e,2,a,i)}function w2(n,t,e,r,i,a){de(n,function(){return n.bindTexture(n.TEXTURE_2D,t)});var s,o,c;i instanceof Uint8Array?(s=new Uint8Array(e*r*4),o=n.UNSIGNED_BYTE,c=n.RGBA):(s=new Float32Array(e*r*4),o=n.FLOAT,c=a.internalFormatPackedFloat),s.set(i),de(n,function(){return n.texImage2D(n.TEXTURE_2D,0,c,e,r,0,n.RGBA,o,s)}),de(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function b2(n,t,e){de(n,function(){return n.bindTexture(n.TEXTURE_2D,t)}),e.data instanceof Uint8Array?de(n,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e.width,e.height,0,n.RGBA,n.UNSIGNED_BYTE,e.data)}):de(n,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e)}),de(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function x2(n,t,e,r){var i=n.createBuffer();de(n,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,i)});var a=4,s=4,o=a*s*t*e;return de(n,function(){return n.bufferData(n.PIXEL_PACK_BUFFER,o,n.STREAM_READ)}),de(n,function(){return n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,0)}),de(n,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,null)}),i}function S2(n,t,e){var r=n,i=new Float32Array(e);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,i),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),i}function L2(n,t,e,r){var i=As(t,e),a=i[0],s=i[1],o=4,c=new Uint8Array(oU(t*e,o));return de(n,function(){return n.readPixels(0,0,a,s,r.downloadTextureFormat,n.UNSIGNED_BYTE,c)}),new Float32Array(c.buffer)}function I2(n,t,e,r,i,a,s,o){var c=n,l=new Float32Array(cU(a,s));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,l),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),l}function A2(n,t,e){var r=new Float32Array(t*e*4);return de(n,function(){return n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,r)}),r}var Ez={__proto__:null,createVertexShader:u2,createVertexBuffer:h2,createIndexBuffer:d2,getInternalFormatForFloat32MatrixTexture:Np,createFloat32MatrixTexture:p2,getInternalFormatForFloat16MatrixTexture:_p,createFloat16MatrixTexture:f2,getInternalFormatForUnsignedBytesMatrixTexture:Cp,createUnsignedBytesMatrixTexture:m2,getInternalFormatForPackedMatrixTexture:Rp,createPackedMatrixTexture:g2,getInternalFormatForFloat16PackedMatrixTexture:Op,createFloat16PackedMatrixTexture:y2,bindVertexProgramAttributeStreams:v2,uploadDenseMatrixToTexture:w2,uploadPixelDataToTexture:b2,createBufferFromOutputTexture:x2,downloadFloat32MatrixFromBuffer:S2,downloadByteEncodedFloatMatrixFromOutputTexture:L2,
2020-11-03 15:34:36 +01:00
blockIndex = rc . y + ` +N+ ` ;
pos = rc . x + ` +S+ ` ;
if ( blockIndex < ` +t[1]+" && pos < "+t[0]+ ` ) {
offsetY = int ( blockIndex / ( ` +l+")) * "+o+" - "+f+ ` ;
d0 = offsetY + ` +h+" * (pos / "+m+ ` ) ;
if ( d0 < ` +e[w]+ ` && d0 >= 0 ) {
offsetX = int ( mod ( float ( blockIndex ) , ` +l+".) * "+s+". - "+p+ ` . ) ;
d1 = offsetX + ` +u+" * (int(mod(float(pos), "+m+".) / "+a+ ` . ) ) ;
if ( d1 < ` +e[b]+ ` && d1 >= 0 ) {
ch = int ( mod ( float ( pos ) , ` +a+ ` . ) ) ;
if ( ` +y+ ` ) {
innerDims = vec2 ( d1 , ch ) ;
result [ ` +(S*2+N)+ ` ] = getChannel (
getA ( d0 , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
} else {
innerDims = vec2 ( d0 , d1 ) ;
result [ ` +(S*2+N)+ ` ] = getChannel (
getA ( ch , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
}
}
}
}
` ;this.userCode= `
void main ( ) {
ivec2 rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0 ) ;
int blockIndex , pos , offsetY , d0 , offsetX , d1 , ch ;
vec2 innerDims ;
` +x+ `
` +g.output+ ` = result ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var Bz=function(){function n(t,e,r,i,a){this.variableNames=["x"],this.outputShape=[];var s=e,o=t[3]-1;this.outputShape=t;var c,l="float("+r+") + float("+i+") * sum";a===.5?c="inversesqrt("+l+")":a===1?c="1.0/("+l+")":c="exp(log("+l+") * float(-"+a+"));",this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
int d = coords [ 3 ] ;
float x = getX ( b , r , c , d ) ;
float sum = 0.0 ;
for ( int j = - ` +s+"; j <= "+s+ ` ; j ++ ) {
int idx = d + j ;
if ( idx >= 0 && idx <= ` +o+ ` ) {
float z = getX ( b , r , c , idx ) ;
sum += z * z ;
}
}
float val = x * ` +c+ ` ;
setOutput ( val ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var zz=function(){function n(t,e,r,i,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=r,this.alpha=i,this.beta=a,this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
float result = 0.0 ;
for ( int d = 0 ; d < ` +this.depth+ ` ; ++ d ) {
int depthBegin = int ( max ( 0.0 , float ( d - ` +e+ ` ) ) ) ;
int depthEnd = int ( min ( float ( ` +this.depth+ ` ) ,
float ( d + ` +e+ ` + 1 ) ) ) ;
const int MIN _DEPTH _BEGIN = 0 ;
const int MAX _DEPTH _END = ` +this.depth+ ` ;
float norm = 0.0 ;
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
norm += getInputImage ( b , r , c , k ) * getInputImage ( b , r , c , k ) ;
}
else {
break ;
}
}
norm = float ( ` +i+") * norm + float("+r+ ` ) ;
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
float dyi = - 2.0 * float ( ` +i+ ` )
* float ( ` +a+ ` )
* getInputImage ( b , r , c , k ) * getOutputImage ( b , r , c , d )
/ n o r m ;
if ( k == d ) {
dyi += pow ( norm , - 1.0 * ` +a+ ` ) ;
}
if ( k == coords [ 3 ] ) {
dyi *= getDy ( b , r , c , d ) ;
result += dyi ;
}
}
else {
break ;
}
}
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
setOutput ( result ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var Pz=function(){function n(t,e,r,i,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var s=e,o=t[3]-1;this.outputShape=t;var c,l="float("+r+") + float("+i+") * sum";a===.5?c="inversesqrt("+l+")":a===1?c="1.0/("+l+")":c="exp(log("+l+") * float(-"+a+"));",this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords . x ;
int r = coords . y ;
int c = coords . z ;
int d = coords . w ;
bool hasNextCol = d < ` +this.outputShape[3]+ ` ;
bool hasNextRow = c < ` +this.outputShape[2]+ ` ;
vec4 sum = vec4 ( 0. ) ;
vec4 xFragAtOutputCoords = getX ( b , r , c , d ) ;
vec4 xAtOutputCoords = vec4 (
getChannel ( xFragAtOutputCoords , vec2 ( c , d ) ) ,
hasNextCol ?
getChannel ( xFragAtOutputCoords , vec2 ( c , d + 1 ) ) : 0.0 ,
hasNextRow ?
getChannel ( xFragAtOutputCoords , vec2 ( c + 1 , d ) ) : 0.0 ,
( hasNextRow && hasNextCol ) ?
getChannel ( xFragAtOutputCoords , vec2 ( c + 1 , d + 1 ) ) : 0.0
) ;
int firstChannel = d - ` +s+ ` ;
vec2 cache = vec2 ( 0. ) ;
if ( firstChannel >= 0 ) {
vec4 firstChannelFrag = getX ( b , r , c , firstChannel ) ;
cache . x = getChannel ( firstChannelFrag , vec2 ( c , firstChannel ) ) ;
if ( hasNextRow ) {
cache . y = getChannel ( firstChannelFrag , vec2 ( c + 1 , firstChannel ) ) ;
}
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
ivec2 depth = ivec2 ( d , d + 1 ) ;
for ( int j = - ` +s+"; j <= "+s+ ` ; j ++ ) {
ivec2 idx = depth + j ;
bvec2 aboveLowerBound = greaterThanEqual ( idx , ivec2 ( 0 ) ) ;
bvec2 belowUpperBound = lessThanEqual ( idx , ivec2 ( ` +o+ ` ) ) ;
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 ;
2020-10-28 20:02:59 +01:00
}
}
2020-11-03 15:34:36 +01:00
vec4 result = xAtOutputCoords * ` +c+ ` ;
setOutput ( result ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var Mz=function(){function n(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,r=t.strideWidth,i=t.dilationHeight,a=t.effectiveFilterHeight,s=t.effectiveFilterWidth,o=a-1-t.padInfo.top,c=s-1-t.padInfo.left,l=a*s-1;this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec2 pads = ivec2 ( ` +o+", "+c+ ` ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < ` +a+ ` ;
wR += ` +i+ ` ) {
float dyR = float ( dyRCorner + wR ) / ` +e+ ` . 0 ;
if ( dyR < 0.0 || dyR >= ` +t.outHeight+ ` . 0 || fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
for ( int wC = 0 ; wC < ` +s+ ` ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / ` +r+ ` . 0 ;
if ( dyC < 0.0 || dyC >= ` +t.outWidth+ ` . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
int idyC = int ( dyC ) ;
float dyValue = getDy ( b , idyR , idyC , d ) ;
int maxPosValue = ` +l+ ` - int ( getMaxPos ( b , idyR , idyC , d ) ) ;
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ` +s+ ` + wC ;
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
dotProd += dyValue * mask ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
}
setOutput ( dotProd ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}(),Hz=function(){function n(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,r=t.strideHeight,i=t.strideWidth,a=t.dilationDepth,s=t.dilationHeight,o=t.dilationWidth,c=t.effectiveFilterDepth,l=t.effectiveFilterHeight,u=t.effectiveFilterWidth,h=c-1-t.padInfo.front,d=l-1-t.padInfo.top,p=u-1-t.padInfo.left,f=c*l*u-1;this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec3 pads = ivec3 ( ` +h+", "+d+", "+p+ ` ) ;
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wD = 0 ; wD < ` +c+ ` ;
wD += ` +a+ ` ) {
float dyD = float ( dyDCorner + wD ) / ` +e+ ` . 0 ;
if ( dyD < 0.0 || dyD >= ` +t.outDepth+ ` . 0 || fract ( dyD ) > 0.0 ) {
continue ;
}
int idyD = int ( dyD ) ;
for ( int wR = 0 ; wR < ` +l+ ` ;
wR += ` +s+ ` ) {
float dyR = float ( dyRCorner + wR ) / ` +r+ ` . 0 ;
if ( dyR < 0.0 || dyR >= ` +t.outHeight+ ` . 0 ||
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
for ( int wC = 0 ; wC < ` +u+ ` ;
wC += ` +o+ ` ) {
float dyC = float ( dyCCorner + wC ) / ` +i+ ` . 0 ;
if ( dyC < 0.0 || dyC >= ` +t.outWidth+ ` . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
int maxPosValue = ` +f+ ` -
int ( getMaxPos ( batch , idyD , idyR , idyC , ch ) ) ;
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ` +l+" * "+u+ ` +
wR * ` +u+ ` + wC ;
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
dotProd += dyValue * mask ;
}
}
}
setOutput ( dotProd ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var Ep=function(){function n(t,e,r,i,a,s,o,c){i===void 0&&(i=!1),a===void 0&&(a=!1),s===void 0&&(s=!1),o===void 0&&(o=null),c===void 0&&(c=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;var l=i?t[1]:t[2],u=Math.ceil(l/2),h=i?"i * 2, rc.y":"rc.y, i * 2",d=a?"rc.z, i * 2":"i * 2, rc.z",p=i?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(c?m= ` vec4 activation ( vec4 a ) {
2020-11-03 15:34:36 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
` +o+ `
} ` :m= ` vec4 activation ( vec4 x ) {
` +o+ `
} ` ,g="result = activation(result);");var y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights");var w="rc.x",b="rc.x";t[0]<e[0]?w="int(min(float(rc.x), "+(t[0]-1)+".))":e[0]<t[0]&&(b="int(min(float(rc.x), "+(e[0]-1)+".))"),this.userCode= `
` +m+ `
const float sharedDimension = ` +u+ ` . 0 ;
vec4 dot2x2ARowBCol ( ivec3 rc ) {
vec4 result = vec4 ( 0 ) ;
for ( int i = 0 ; i < ` +u+ ` ; i ++ ) {
int batchA = ` +w+ ` ;
int batchB = ` +b+ ` ;
vec4 a = getMatrixA ( batchA , ` +h+ ` ) ;
vec4 b = getMatrixB ( batchB , ` +d+ ` ) ;
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += ( ` +p[0]+" * "+f[0]+ ` ) ;
result += ( ` +p[1]+" * "+f[1]+ ` ) ;
}
return result ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
vec4 result = dot2x2ARowBCol ( rc ) ;
` +y+ `
` +g+ `
setOutput ( result ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var Vz=function(){function n(t,e,r){this.variableNames=["probs"],this.outputShape=[t,r],this.userCode= `
2020-11-03 15:34:36 +01:00
uniform float seed ;
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
float r = random ( seed ) ;
float cdf = 0.0 ;
for ( int i = 0 ; i < ` +(e-1)+ ` ; i ++ ) {
cdf += getProbs ( batch , i ) ;
if ( r < cdf ) {
setOutput ( float ( i ) ) ;
return ;
}
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
// If no other event happened, last event happened.
setOutput ( float ( ` +(e-1)+ ` ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(r,i){e.seedLoc==null&&(e.seedLoc=r.getUniformLocation(i,"seed")),r.gl.uniform1f(e.seedLoc,t)}},n}();var qz=function(){function n(t,e,r,i){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int index = round ( getIndices ( coords . x ) ) ;
setOutput ( mix ( float ( ` +i+"), float("+r+ ` ) ,
float ( index == coords . y ) ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var Kz=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(e===0)this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
setOutput ( vec4 ( getA ( ) , 0. , 0. , 0. ) ) ;
}
2020-11-04 16:18:22 +01:00
` ;else{var r=Pt("rc",e),i=Qe(e),a=Gz(e,t,r),s=Yz(e,t[t.length-1],t[t.length-2],r),o=jz(t,r);this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
` +i+ ` rc = getOutputCoords ( ) ;
if ( ` +a+ ` ) {
setOutput ( vec4 ( 0 ) ) ;
} else {
` +s+ `
setOutput ( vec4 ( ` +o+ ` ) ) ;
}
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }}return n}();function $ z(n,t){for(var e=[],r=0;r<=1;r++)for(var i=0;i<=1;i++){for(var a=(r===0?"r":"rp1")+", "+(i===0?"c":"cp1"),s=2;s<n;s++)a=t[t.length-1-s]+","+a;e.push(a)}return e}function Gz(n,t,e){if(n===1)return"rc > "+t[0];for(var r="",i=n-2;i<n;i++)r+=e[i]+" >= "+t[i],i<n-1&&(r+="||");return r}function Yz(n,t,e,r){if(n===1)return"";var i=r.slice(-2);return `
2020-11-03 15:34:36 +01:00
int r = ` +i[0]+ ` ;
int c = ` +i[1]+ ` ;
int rp1 = r + 1 ;
int cp1 = c + 1 ;
bool cEdge = cp1 >= ` +t+ ` ;
bool rEdge = rp1 >= ` +e+ ` ;
2020-11-04 16:18:22 +01:00
` }function jz(n,t){var e=n.length,r= $ z(e,t);return e===1? ` getA ( rc ) ,
2020-11-03 15:34:36 +01:00
rc + 1 >= ` +n[0]+ ` ? 0. : getA ( rc + 1 ) ,
0 , 0 ` :"getA("+r[0]+ ` ) ,
cEdge ? 0. : getA ( ` +r[1]+ ` ) ,
rEdge ? 0. : getA ( ` +r[2]+ ` ) ,
2020-11-04 16:18:22 +01:00
rEdge || cEdge ? 0. : getA ( ` +r[3]+")"}var Xz=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=e.map(function(l,u){return l[0]+t[u]+l[1]});var i=t.length,a=Qe(i),s=e.map(function(l){return l[0]}).join(","),o=e.map(function(l,u){return l[0]+t[u]}).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,i);if(i===1){this.userCode= `
2020-11-03 15:34:36 +01:00
int start = ` +s+ ` ;
int end = ` +o+ ` ;
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start || outC >= end ) {
setOutput ( float ( ` +r+ ` ) ) ;
} else {
setOutput ( getX ( outC - start ) ) ;
}
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
` ;return}this.userCode= `
` +a+" start = "+a+"("+s+ ` ) ;
` +a+" end = "+a+"("+o+ ` ) ;
void main ( ) {
` +a+ ` outC = getOutputCoords ( ) ;
if ( any ( lessThan ( outC , start ) ) || any ( greaterThanEqual ( outC , end ) ) ) {
setOutput ( float ( ` +r+ ` ) ) ;
} else {
` +a+ ` coords = outC - start ;
setOutput ( getX ( ` +c+ ` ) ) ;
}
}
2020-11-04 16:18:22 +01:00
` }return n}();var Jz=function(){function n(t,e,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map(function(y,w){return y[0]+t[w]+y[1]});for(var i=t.length,a=Qe(i),s=e.map(function(y){return y[0]}).join(","),o=e.map(function(y,w){return y[0]+t[w]}).join(","),c=Pt("rc",i),l=Pt("source",i),u=c[i-1]+" < "+this.outputShape[i-1],h=i===1?"source":"vec2("+l.slice(-2).join()+")",d=[a+" rc = outputLoc;",c[i-1]+ ` += 1 ;
2020-11-03 15:34:36 +01:00
if ( ` +u+ ` ) {
` ,i===1?"": ` }
rc = outputLoc ;
` +c[i-2]+ ` += 1 ;
if ( ` +c[i-2]+" < "+this.outputShape[i-2]+") {",i===1?"":" "+c[i-1]+ ` += 1 ;
if ( ` +u+") {"],p=i===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",m=0,g=i===1?2:4;m<g;m++)f+= `
` +d[m]+ `
if ( ` +p+ ` ) {
result [ ` +m+"] = float("+r+ ` ) ;
} else {
` +a+ ` source = rc - start ;
result [ ` +m+"] = getChannel(getX("+l.join()+"), "+h+ ` ) ;
}
` ;f+=i===1?"} ":"}}",this.userCode= `
const ` +a+" start = "+a+"("+s+ ` ) ;
const ` +a+" end = "+a+"("+o+ ` ) ;
void main ( ) {
` +a+ ` outputLoc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
` +f+ `
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var Os=function(){function n(t,e,r,i,a){if(i===void 0&&(i=!1),a===void 0&&(a=!1),this.variableNames=["x"],e==="avg"&&r)throw new Error("Cannot compute positions for average pool.");var s=t.filterWidth,o=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,u=t.dilationWidth,h=t.effectiveFilterHeight,d=t.effectiveFilterWidth,p=t.padInfo.top,f=t.padInfo.left;this.outputShape=t.outShape;var m=e==="avg",g="((batch * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + d",y="(xR * "+t.inWidth+" + xC) * "+t.inChannels+" + d",w="0.0";if(m||(w="-1.0 / 1e-20"),r){var b=">=";this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec2 strides = ivec2 ( ` +o+", "+c+ ` ) ;
const ivec2 pads = ivec2 ( ` +p+", "+f+ ` ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
float avgValue = 0.0 ;
for ( int wR = 0 ; wR < ` +h+ ` ;
wR += ` +l+ ` ) {
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= ` +t.inHeight+ ` ) {
continue ;
}
for ( int wC = 0 ; wC < ` +d+ ` ;
wC += ` +u+ ` ) {
int xC = xCCorner + wC ;
if ( xC < 0 || xC >= ` +t.inWidth+ ` ) {
continue ;
}
float value = getX ( batch , xR , xC , d ) ;
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
if ( value ` +b+ ` currMinMaxValue ) {
minMaxValue = value ;
minMaxValueFound = 1.0 ;
minMaxPosition = ` +(i?a?g:y:"wR * "+d+" + wC")+ ` ;
}
}
2020-11-01 19:07:53 +01:00
}
2020-11-03 15:34:36 +01:00
setOutput ( float ( minMaxPosition ) ) ;
2020-11-01 19:07:53 +01:00
}
2020-11-03 15:34:36 +01:00
` ;return}var x="max",S=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";e==="avg"&&(S="avgValue / count");var N=Math.floor(s/4)*4,I=s%4,C= `
if ( ` +m+ ` ) {
avgValue += dot ( values , ones ) ;
2020-11-01 20:16:47 +01:00
} else {
2020-11-03 15:34:36 +01:00
minMaxValue = ` +x+ ` ( values , minMaxValue ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
` ;this.userCode= `
const ivec2 strides = ivec2 ( ` +o+", "+c+ ` ) ;
const ivec2 pads = ivec2 ( ` +p+", "+f+ ` ) ;
const float initializationValue = ` +w+ ` ;
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float count = 0.0 ;
float getValue ( int batch , int xR , int xC , int d ) {
if ( xC < 0 || xC >= ` +t.inWidth+ ` ) {
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xR , xC , d ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +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
vec4 minMaxValue = vec4 ( ` +w+ ` ) ;
float avgValue = 0.0 ;
count = 0.0 ;
for ( int wR = 0 ; wR < ` +h+ ` ;
wR += ` +l+ ` ) {
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= ` +t.inHeight+ ` ) {
continue ;
}
for ( int wC = 0 ; wC < ` +N+ ` ; wC += 4 ) {
int xC = xCCorner + wC * ` +u+ ` ;
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
getValue ( batch , xR , xC + ` +u+ ` , d ) ,
getValue ( batch , xR , xC + 2 * ` +u+ ` , d ) ,
getValue ( batch , xR , xC + 3 * ` +u+ ` , d )
) ;
` +C+ `
}
int xC = xCCorner + ` +N+ ` ;
if ( ` +(I===1)+ ` ) {
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
` +C+ `
} else if ( ` +(I===2)+ ` ) {
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
getValue ( batch , xR , xC + ` +u+ ` , d ) ,
initializationValue ,
initializationValue
) ;
` +C+ `
} else if ( ` +(I===3)+ ` ) {
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
getValue ( batch , xR , xC + ` +u+ ` , d ) ,
getValue ( batch , xR , xC + 2 * ` +u+ ` , d ) ,
initializationValue
) ;
` +C+ `
2020-10-28 20:02:59 +01:00
}
}
2020-11-03 15:34:36 +01:00
setOutput ( ` +S+ ` ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}(),Dp=function(){function n(t,e,r,i,a){if(i===void 0&&(i=!1),a===void 0&&(a=!1),this.variableNames=["x"],e==="avg"&&r)throw new Error("Cannot compute positions for average pool.");var s=t.filterWidth,o=t.strideDepth,c=t.strideHeight,l=t.strideWidth,u=t.dilationDepth,h=t.dilationHeight,d=t.dilationWidth,p=t.effectiveFilterDepth,f=t.effectiveFilterHeight,m=t.effectiveFilterWidth,g=t.padInfo.front,y=t.padInfo.top,w=t.padInfo.left;this.outputShape=t.outShape;var b=e==="avg",x="0.0";if(b||(x="-1.0 / 1e-20"),r){var S=">=";this.userCode= `
2020-11-03 15:34:36 +01:00
const ivec3 strides =
ivec3 ( ` +o+", "+c+", "+l+ ` ) ;
const ivec3 pads = ivec3 ( ` +g+", "+y+", "+w+ ` ) ;
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
for ( int wD = 0 ; wD < ` +p+ ` ;
wD += ` +u+ ` ) {
int xD = xDCorner + wD ;
if ( xD < 0 || xD >= ` +t.inDepth+ ` ) {
continue ;
}
for ( int wR = 0 ; wR < ` +f+ ` ;
wR += ` +h+ ` ) {
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= ` +t.inHeight+ ` ) {
continue ;
}
for ( int wC = 0 ; wC < ` +m+ ` ;
wC += ` +d+ ` ) {
int xC = xCCorner + wC ;
if ( xC < 0 || xC >= ` +t.inWidth+ ` ) {
continue ;
}
float value = getX ( batch , xD , xR , xC , ch ) ;
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
if ( value ` +S+ ` currMinMaxValue ) {
minMaxValue = value ;
minMaxValueFound = 1.0 ;
minMaxPosition = ` +(i?a?"(((batch * "+t.inDepth+" + xD) * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"((xD * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"wD * "+f+" * "+m+ ` +
wR * ` +m+" + wC")+ ` ;
}
}
}
}
setOutput ( float ( minMaxPosition ) ) ;
}
` ;return}var N="max",I=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";e==="avg"&&(I="avgValue / count");var C=Math.floor(s/4)*4,O=s%4,D= `
if ( ` +b+ ` ) {
avgValue += dot ( values , ones ) ;
2020-10-28 20:02:59 +01:00
} else {
2020-11-03 15:34:36 +01:00
minMaxValue = ` +N+ ` ( values , minMaxValue ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
` ;this.userCode= `
const ivec3 strides =
ivec3 ( ` +o+", "+c+", "+l+ ` ) ;
const ivec3 pads = ivec3 ( ` +g+", "+y+", "+w+ ` ) ;
const float initializationValue = ` +x+ ` ;
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float count = 0.0 ;
float getValue ( int batch , int xD , int xR , int xC , int ch ) {
if ( xC < 0 || xC >= ` +t.inWidth+ ` ) {
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xD , xR , xC , ch ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4 ( ` +x+ ` ) ;
float avgValue = 0.0 ;
count = 0.0 ;
for ( int wD = 0 ; wD < ` +p+ ` ;
wD += ` +u+ ` ) {
int xD = xDCorner + wD ;
if ( xD < 0 || xD >= ` +t.inDepth+ ` ) {
continue ;
2020-11-01 20:16:47 +01:00
}
2020-11-03 15:34:36 +01:00
for ( int wR = 0 ; wR < ` +f+ ` ;
wR += ` +h+ ` ) {
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= ` +t.inHeight+ ` ) {
continue ;
}
for ( int wC = 0 ; wC < ` +C+ ` ; wC += 4 ) {
int xC = xCCorner + wC * ` +d+ ` ;
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
getValue ( batch , xD , xR , xC + ` +d+ ` , ch ) ,
getValue ( batch , xD , xR , xC + 2 * ` +d+ ` , ch ) ,
getValue ( batch , xD , xR , xC + 3 * ` +d+ ` , ch )
) ;
` +D+ `
}
int xC = xCCorner + ` +C+ ` ;
if ( ` +(O===1)+ ` ) {
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
` +D+ `
} else if ( ` +(O===2)+ ` ) {
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
getValue ( batch , xD , xR , xC + ` +d+ ` , ch ) ,
initializationValue ,
initializationValue
) ;
` +D+ `
} else if ( ` +(O===3)+ ` ) {
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
getValue ( batch , xD , xR , xC + ` +d+ ` , ch ) ,
getValue ( batch , xD , xR , xC + 2 * ` +d+ ` , ch ) ,
initializationValue
) ;
` +D+ `
}
}
setOutput ( ` +I+ ` ) ;
2020-11-01 20:16:47 +01:00
}
}
2020-11-04 16:18:22 +01:00
` }return n}();var _2=function(){function n(t,e){this.variableNames=["x"];var r=t.windowSize,i=t.batchSize,a=t.inSize,s=t.outSize;this.outputShape=[i,s];var o="0.0",c="";e==="prod"?o="1.0":e==="min"?(o="1.0 / 1e-20",c="min"):e==="max"&&(o="-1.0 / 1e-20",c="max");var l=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";e==="sum"?l="sumValue":e==="prod"?l="prodValue":e==="all"?l="allValue":e==="any"&&(l="anyValue");var u=Math.floor(r/4)*4,h=r%4,d= `
2020-11-03 15:34:36 +01:00
if ( ` +(e==="sum")+ ` ) {
sumValue += dot ( values , ones ) ;
} else if ( ` +(e==="prod")+ ` ) {
vec2 tmp = vec2 ( values [ 0 ] , values [ 1 ] ) * vec2 ( values [ 2 ] , values [ 3 ] ) ;
prodValue *= tmp [ 0 ] * tmp [ 1 ] ;
2020-11-01 20:16:47 +01:00
} else {
2020-11-03 15:34:36 +01:00
minMaxValue = ` +c+ ` ( values , minMaxValue ) ;
2020-11-01 20:16:47 +01:00
}
2020-11-03 15:34:36 +01:00
` ,p="vec4";e==="all"?(o="1.0",d= `
bool reducedAllValue = all ( values ) ;
float floatedReducedAllValue = float ( reducedAllValue ) ;
allValue = float ( allValue >= 1.0 && floatedReducedAllValue >= 1.0 ) ;
` ,p="bvec4"):e==="any"&&(o="0.0",d= `
bool reducedAnyValue = any ( values ) ;
float floatedReducedAnyValue = float ( reducedAnyValue ) ;
anyValue = float ( anyValue >= 1.0 || floatedReducedAnyValue >= 1.0 ) ;
` ,p="bvec4");var f="";a%r>0&&(f= `
if ( inIdx < 0 || inIdx >= ` +a+ ` ) {
return initializationValue ;
2020-11-01 20:16:47 +01:00
}
2020-11-03 15:34:36 +01:00
` ),this.userCode= `
const float initializationValue = ` +o+ ` ;
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float getValue ( int batch , int inIdx ) {
` +f+ `
return getX ( batch , inIdx ) ;
2020-10-28 20:02:59 +01:00
}
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * ` +r+ ` ;
vec4 minMaxValue = vec4 ( ` +o+ ` ) ;
float prodValue = 1.0 ;
float sumValue = 0.0 ;
float allValue = 1.0 ;
float anyValue = 0.0 ;
for ( int i = 0 ; i < ` +u+ ` ; i += 4 ) {
int inIdx = inOffset + i ;
` +p+" values = "+p+ ` (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
` +d+ `
2020-10-28 20:02:59 +01:00
}
2020-10-15 14:16:34 +02:00
2020-11-03 15:34:36 +01:00
int inIdx = inOffset + ` +u+ ` ;
if ( ` +(h===1)+ ` ) {
` +p+" values = "+p+ ` (
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
` +d+ `
} else if ( ` +(h===2)+ ` ) {
` +p+" values = "+p+ ` (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
` +d+ `
} else if ( ` +(h===3)+ ` ) {
` +p+" values = "+p+ ` (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
` +d+ `
2020-10-15 14:16:34 +02:00
}
2020-11-03 15:34:36 +01:00
setOutput ( ` +l+ ` ) ;
2020-10-15 14:16:34 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var C2=function(){function n(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r="",i=0;i<4;i++){var a="thisRC = rc;";i%2===1&&(a+="thisRC.z += 1;"),i>1&&(a+="thisRC.y += 1;"),r+= `
2020-11-03 15:34:36 +01:00
` +a+ `
` +(i>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+ `
int flatIndex = getFlatIndex ( thisRC ) ;
ivec3 inputRC = inputCoordsFromReshapedOutCoords ( flatIndex ) ;
vec2 inputRCInnerDims = vec2 ( float ( inputRC . y ) , float ( inputRC . z ) ) ;
result [ ` +i+ ` ] =
getChannel ( getA ( inputRC . x , inputRC . y , inputRC . z ) , inputRCInnerDims ) ;
` +(i>0?"}":"")+ `
` }this.userCode= `
2020-11-04 16:18:22 +01:00
` +Zz(e)+ `
` +Tp(t)+ `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
ivec3 thisRC ;
int rows = ` +t[1]+ ` ;
int cols = ` +t[2]+ ` ;
` +r+ `
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();function Zz(n){var t=Ci(["r","c","d"],n);return `
2020-11-03 15:34:36 +01:00
ivec3 inputCoordsFromReshapedOutCoords ( int index ) {
` +t+ `
return ivec3 ( r , c , d ) ;
}
2020-11-04 16:18:22 +01:00
` }var Qz=function(){function n(t,e,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var i=e.shape,a=i[1],s=i[2],o=t.shape,c=o[1],l=o[2],u=[r&&c>1?a-1:a,r&&l>1?s-1:s],h=[r&&c>1?c-1:c,r&&l>1?l-1:l],d=u[0]/h[0],p=u[1]/h[1],f=1/d,m=1/p,g=Math.ceil(f)*2+2,y=Math.ceil(m)*2+2;this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
float accumulator = 0.0 ;
const float heightScale = float ( ` +d+ ` ) ;
const float widthScale = float ( ` +p+ ` ) ;
const float invHeightScale = float ( ` +f+ ` ) ;
const float invWidthScale = float ( ` +m+ ` ) ;
const int winHeight = int ( ` +g+ ` ) ;
const int winWidth = int ( ` +y+ ` ) ;
// Compute bounds for where in dy we will look
float startRLerp = floor ( float ( r ) * invHeightScale ) ;
int startDyR = int ( startRLerp - float ( winHeight / 2 ) ) ;
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( startCLerp - float ( winWidth / 2 ) ) ;
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
// Guard against the window exceeding the bounds of dy
if ( dyR < 0 || dyR >= ` +c+ ` ) {
continue ;
}
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
// Guard against the window exceeding the bounds of dy
if ( dyC < 0 || dyC >= ` +l+ ` ) {
continue ;
}
float dxR = float ( dyR ) * heightScale ;
int topDxRIndex = int ( floor ( dxR ) ) ;
int bottomDxRIndex = int ( min ( ceil ( dxR ) , ` +(a-1)+ ` . 0 ) ) ;
float dxRLerp = dxR - float ( topDxRIndex ) ;
float inverseDxRLerp = 1.0 - dxRLerp ;
float dxC = float ( dyC ) * widthScale ;
int leftDxCIndex = int ( floor ( dxC ) ) ;
int rightDxCIndex = int ( min ( ceil ( dxC ) , ` +(s-1)+ ` . 0 ) ) ;
float dxCLerp = dxC - float ( leftDxCIndex ) ;
float inverseDxCLerp = 1.0 - dxCLerp ;
if ( r == topDxRIndex && c == leftDxCIndex ) {
// topLeft
accumulator +=
getDy ( b , dyR , dyC , d ) * inverseDxRLerp * inverseDxCLerp ;
}
if ( r == topDxRIndex && c == rightDxCIndex ) {
// topRight
accumulator += getDy ( b , dyR , dyC , d ) * inverseDxRLerp * dxCLerp ;
}
if ( r == bottomDxRIndex && c == leftDxCIndex ) {
// bottomLeft
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * inverseDxCLerp ;
}
if ( r == bottomDxRIndex && c == rightDxCIndex ) {
// bottomRight
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * dxCLerp ;
}
}
2020-10-15 14:16:34 +02:00
}
2020-11-03 15:34:36 +01:00
// End loop over dy
setOutput ( accumulator ) ;
2020-11-03 00:54:03 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var eP=function(){function n(t,e,r,i){this.variableNames=["A"],this.outputShape=[];var a=t[0],s=t[1],o=t[2],c=t[3];this.outputShape=[a,e,r,c];var l=[i&&e>1?s-1:s,i&&r>1?o-1:o],u=[i&&e>1?e-1:e,i&&r>1?r-1:r];this.userCode= `
2020-11-03 15:34:36 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
` +l[0]/u[0]+ ` ,
` +l[1]/u[1]+ ` ) ;
const vec2 inputShapeRC = vec2 ( ` +s+".0, "+o+ ` . 0 ) ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
// Fractional source index.
vec2 sourceFracIndexRC = vec2 ( yRC ) * effectiveInputOverOutputRatioRC ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2 ( sourceFracIndexRC ) ;
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 ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var tP=function(){function n(t,e,r,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var a=t[0],s=t[1],o=t[2],c=t[3];this.outputShape=[a,e,r,c];var l=[i&&e>1?s-1:s,i&&r>1?o-1:o],u=[i&&e>1?e-1:e,i&&r>1?r-1:r];this.userCode= `
2020-11-03 15:34:36 +01:00
const vec3 effectiveInputOverOutputRatioRC = vec3 (
` +l[0]/u[0]+ ` ,
` +l[1]/u[1]+ ` ,
` +l[1]/u[1]+ ` ) ;
const vec3 inputShapeRC = vec3 ( ` +s+".0, "+o+ ` . 0 ,
` +o+ ` . 0 ) ;
float getAValue ( int b , int r , int c , int d ) {
return getChannel ( getA ( b , r , c , d ) , vec2 ( c , d ) ) ;
2020-10-15 14:16:34 +02:00
}
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
// Calculate values for next column in yRC.z.
ivec3 yRC = coords . yzz + ivec3 ( 0 , 0 , 1 ) ;
// Fractional source index.
vec3 sourceFracIndexRC = vec3 ( yRC ) * effectiveInputOverOutputRatioRC ;
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3 ( sourceFracIndexRC ) ;
ivec3 sourceCeilRC = ivec3 (
min ( inputShapeRC - 1.0 , ceil ( sourceFracIndexRC ) ) ) ;
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ` +(c-1)+ ` ;
bool hasNextRow = coords . z < ` +(r-1)+ ` ;
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4 (
getAValue ( b , sourceFloorRC . x , sourceFloorRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceFloorRC . x , sourceFloorRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceFloorRC . x , sourceFloorRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceFloorRC . x , sourceFloorRC . z , d + 1 ) : 0.0 ) ;
vec4 bottomLeft = vec4 (
getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d + 1 ) : 0.0 ) ;
vec4 topRight = vec4 (
getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
vec4 bottomRight = vec4 (
getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
vec3 fracRC = sourceFracIndexRC - vec3 ( sourceFloorRC ) ;
vec4 top = mix ( topLeft , topRight , fracRC . yyzz ) ;
vec4 bottom = mix ( bottomLeft , bottomRight , fracRC . yyzz ) ;
vec4 newValue = mix ( top , bottom , fracRC . x ) ;
setOutput ( newValue ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var nP=function(){function n(t,e,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var i=e.shape,a=i[1],s=i[2],o=t.shape,c=o[1],l=o[2],u=[r&&c>1?a-1:a,r&&l>1?s-1:s],h=[r&&c>1?c-1:c,r&&l>1?l-1:l],d=u[0]/h[0],p=u[1]/h[1],f=1/d,m=1/p,g=Math.ceil(f)*2+2,y=Math.ceil(m)*2+2;this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
float accumulator = 0.0 ;
const float heightScale = float ( ` +d+ ` ) ;
const float widthScale = float ( ` +p+ ` ) ;
const float invHeightScale = float ( ` +f+ ` ) ;
const float invWidthScale = float ( ` +m+ ` ) ;
const int winHeight = int ( ` +g+ ` ) ;
const int winWidth = int ( ` +y+ ` ) ;
// Compute bounds for where in dy we will look
float startRLerp = floor ( float ( r ) * invHeightScale ) ;
int startDyR = int ( floor ( startRLerp - float ( winHeight / 2 ) ) ) ;
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( floor ( startCLerp - float ( winWidth / 2 ) ) ) ;
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
// Guard against the window exceeding the bounds of dy
if ( dyR < 0 || dyR >= ` +c+ ` ) {
continue ;
}
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
// Guard against the window exceeding the bounds of dy
if ( dyC < 0 || dyC >= ` +l+ ` ) {
continue ;
}
float sourceFracRow =
float ( ` +u[0]+ ` ) *
( float ( dyR ) / float ( ` +h[0]+ ` ) ) ;
float sourceFracCol =
float ( ` +u[1]+ ` ) *
( float ( dyC ) / float ( ` +h[1]+ ` ) ) ;
int sourceNearestRow = int ( min (
float ( int ( ` +a+ ` ) - 1 ) ,
` +r+ ` ? float ( round ( sourceFracRow ) ) :
float ( floor ( sourceFracRow ) ) ) ) ;
int sourceNearestCol = int ( min (
float ( int ( ` +s+ ` ) - 1 ) ,
` +r+ ` ? float ( round ( sourceFracCol ) ) :
float ( floor ( sourceFracCol ) ) ) ) ;
if ( r == sourceNearestRow && c == sourceNearestCol ) {
accumulator += getDy ( b , dyR , dyC , d ) ;
}
}
2020-10-15 14:16:34 +02:00
}
2020-11-03 15:34:36 +01:00
// End loop over dy
setOutput ( accumulator ) ;
2020-10-15 14:16:34 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var rP=function(){function n(t,e,r,i){this.variableNames=["A"],this.outputShape=[];var a=t[0],s=t[1],o=t[2],c=t[3];this.outputShape=[a,e,r,c];var l=[i&&e>1?s-1:s,i&&r>1?o-1:o],u=[i&&e>1?e-1:e,i&&r>1?r-1:r],h=i?"0.5":"0.0";this.userCode= `
2020-11-03 15:34:36 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
` +l[0]/u[0]+ ` ,
` +l[1]/u[1]+ ` ) ;
const vec2 inputShapeRC = vec2 ( ` +s+".0, "+o+ ` . 0 ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
// Fractional source index.
vec2 sourceFracIndexRC = vec2 ( yRC ) * effectiveInputOverOutputRatioRC ;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2 (
min ( inputShapeRC - 1.0 , floor ( sourceFracIndexRC + ` +h+ ` ) ) ) ;
float newValue = getA ( b , sourceNearestRC . x , sourceNearestRC . y , d ) ;
setOutput ( newValue ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var iP=function(){function n(t,e){this.variableNames=["x"];var r=t.length;if(r>4)throw new Error("WebGL backend: Reverse of rank-"+r+" tensor is not yet supported");if(this.outputShape=t,r===1){this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
int coord = getOutputCoords ( ) ;
setOutput ( getX ( ` +t[0]+ ` - coord - 1 ) ) ;
}
2020-11-04 07:11:24 +01:00
` ;return}var i=function(o){return e.indexOf(o)!==-1&&t[o]!==1?t[o]+" - coords["+o+"] - 1":"coords["+o+"]"},a=t.map(function(o,c){return i(c)}).join(","),s=Qe(r);this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
` +s+ ` coords = getOutputCoords ( ) ;
setOutput ( getX ( ` +a+ ` ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var aP=function(){function n(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var r=t.length;if(r>4)throw new Error("WebGL backend: Reverse of rank-"+r+" tensor is not yet supported");this.outputShape=t;var i=Pt("rc",r),a=i[r-1]+" + 1 < "+this.outputShape[r-1],s=i[r-2]+" + 1 < "+this.outputShape[r-2],o=Qe(r);r===1?this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
int rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
result . r = getChannel ( getX ( ` +t[0]+ ` - rc - 1 ) ,
` +t[0]+ ` - rc - 1 ) ;
if ( ` +a+ ` ) {
result . g = getChannel ( getX ( ` +t[0]+ ` - ( rc + 1 ) - 1 ) ,
` +t[0]+ ` - ( rc + 1 ) - 1 ) ;
}
setOutput ( result ) ;
}
` :this.userCode= `
void main ( ) {
` +o+ ` rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
result . r = ` +c(i.slice())+ ` ;
if ( ` +a+ ` ) {
result . g = ` +l(i.slice())+ ` ;
}
if ( ` +s+ ` ) {
result . b = ` +u(i.slice())+ ` ;
if ( ` +a+ ` ) {
result . a = ` +h(i.slice())+ ` ;
}
}
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` ;function c(f){return d(f)}function l(f){return f[r-1]="("+f[r-1]+" + 1)",d(f)}function u(f){return f[r-2]="("+f[r-2]+" + 1)",d(f)}function h(f){return f[r-1]="("+f[r-1]+" + 1)",f[r-2]="("+f[r-2]+" + 1)",d(f)}function d(f){var m=t.map(function(w,b){return p(b,f)}),g=m.join(","),y=m.slice(-2).join(",");return"getChannel(getX("+g+"), vec2("+y+"))"}function p(f,m){return e.indexOf(f)!==-1&&t[f]!==1?t[f]+" - "+m[f]+" - 1":""+m[f]}}return n}();var R2=function(){function n(t,e,r,i,a,s,o){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;var c=Qe(a.length),l=Qe(s.length),u="";r===1?u="i":r===2&&(u="i, j");var h="getIndices("+u+")",d="";i===1?d="i":i===2&&(d="i, coords[1]");var p="getUpdates("+d+")",f=e>1?"strides[j]":"strides";this.userCode= `
2020-11-03 15:34:36 +01:00
` +c+" strides = "+c+"("+a+ ` ) ;
void main ( ) {
` +l+ ` coords = getOutputCoords ( ) ;
float sum = 0.0 ;
bool found = false ;
for ( int i = 0 ; i < ` +t+ ` ; i ++ ) {
int flattenedIndex = 0 ;
for ( int j = 0 ; j < ` +e+ ` ; j ++ ) {
int index = round ( ` +h+ ` ) ;
flattenedIndex += index * ` +f+ ` ;
}
if ( flattenedIndex == coords [ 0 ] ) {
sum += ` +p+ ` ;
found = true ;
}
}
setOutput ( mix ( getDefaultValue ( ) , sum , float ( found ) ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var sP=function(){function n(t,e){this.variableNames=["x","segmentIds"];var r=t.windowSize,i=t.batchSize,a=t.inSize,s=t.numSegments,o=s*Math.ceil(a/r);this.outputShape=[i,o];var c="0.0",l="sumValue",u=Math.floor(r/4)*4,h=r%4,d= `
2020-11-03 15:34:36 +01:00
sumValue += dot ( values , segFilter ) ;
` ,p="";a%r>0&&(p= `
if ( inIdx < 0 || inIdx >= ` +a+ ` ) {
return initializationValue ;
}
` );var f="";a%r>0&&(f= `
if ( inIdx < 0 || inIdx >= ` +a+ ` ) {
return - 1.0 ;
}
` ),this.userCode= `
const float initializationValue = ` +c+ ` ;
float getValue ( int batch , int inIdx ) {
` +p+ `
return getX ( batch , inIdx ) ;
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
float getSegmentIdAtIndex ( int inIdx ) {
` +f+ `
return getSegmentIds ( inIdx ) ;
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = int ( floor ( float ( outIdx ) / float (
` +s+")) * float("+r+ ` ) ) ;
int currentSeg = int ( mod ( float ( outIdx ) , float ( ` +s+ ` ) ) ) ;
float sumValue = 0.0 ;
for ( int i = 0 ; i < ` +u+ ` ; i += 4 ) {
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
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
) ;
` +d+ `
2020-10-15 14:16:34 +02:00
}
2020-11-03 15:34:36 +01:00
int inIdx = inOffset + ` +u+ ` ;
if ( ` +(h===1)+ ` ) {
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
) ;
` +d+ `
} else if ( ` +(h===2)+ ` ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
0 ,
0
) ;
` +d+ `
} else if ( ` +(h===3)+ ` ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 2 ) ) == currentSeg ? 1 : 0 ,
0
) ;
` +d+ `
2020-10-15 14:16:34 +02:00
}
2020-11-03 15:34:36 +01:00
setOutput ( ` +l+ ` ) ;
2020-10-17 12:30:00 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var oP=function(){function n(t,e,r){this.variableNames=["c","a","b"],this.outputShape=e;var i,a;if(r>4)throw Error("Where for rank "+r+" is not yet supported");if(r===1)a="resRC",i="resRC";else{for(var s=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],c=[],l=0;l<e.length;l++)c.push(""+s[l]),l<t&&o.push(""+s[l]);i=o.join(),a=c.join()}var u=Qe(r);this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
` +u+ ` resRC = getOutputCoords ( ) ;
float cVal = getC ( ` +i+ ` ) ;
if ( cVal >= 1.0 ) {
setOutput ( getA ( ` +a+ ` ) ) ;
} else {
setOutput ( getB ( ` +a+ ` ) ) ;
}
}
2020-11-04 16:18:22 +01:00
` }return n}();var lP=function(){function n(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e=Qe(this.rank),r="uniform int start["+this.rank+"];",i=cP(this.rank),a,s=t.map(function(o,c){return"sourceLoc."+kp[c]+" = start["+c+"] + coords."+kp[c]+";"});a= `
2020-11-03 15:34:36 +01:00
` +e+ ` sourceLoc ;
` +e+ ` coords = getOutputCoords ( ) ;
` +s.join( `
` )+ `
` ,this.userCode= `
` +r+ `
void main ( ) {
` +a+ `
setOutput ( getSource ( ` +i+ ` ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the "+("length of start ("+t.length+")"));return function(r,i){if(e.startLoc==null&&(e.startLoc=r.getUniformLocationNoThrow(i,"start"),e.startLoc==null))return;r.gl.uniform1iv(e.startLoc,t)}},n}(),kp=["x","y","z","w","u","v"];function cP(n){if(n===1)return"sourceLoc";if(n<=6)return kp.slice(0,n).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+n+" is not yet supported")}var uP=function(){function n(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=Qe(this.rank),r=Pt("coords",this.rank),i=Pt("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":"vec2("+i.slice(-2).join()+")",s="getChannel(getSource("+i.join()+"), "+a+")",o= `
2020-11-03 15:34:36 +01:00
result . x = ` +s+ ` ;
if ( ++ ` +r[this.rank-1]+" < "+t[this.rank-1]+ ` ) {
++ ` +i[this.rank-1]+ ` ;
result . y = ` +s+ ` ;
-- ` +i[this.rank-1]+ ` ;
}
` ,c=this.rank===1?"": `
-- ` +r[this.rank-1]+ ` ;
if ( ++ ` +r[this.rank-2]+" < "+t[this.rank-2]+ ` ) {
++ ` +i[this.rank-2]+ ` ;
result . z = ` +s+ ` ;
if ( ++ ` +r[this.rank-1]+" < "+t[this.rank-1]+ ` ) {
++ ` +i[this.rank-1]+ ` ;
result . w = ` +s+ ` ;
}
}
` ,l=this.rank<=4? ` sourceLoc = coords +
` +e+"("+t.map(function(u,h){return"start["+h+"]"}).join()+");":t.map(function(u,h){return i[h]+" = "+r[h]+" + start["+h+"];"}).join( `
` );this.userCode= `
uniform int start [ ` +this.rank+ ` ] ;
void main ( ) {
` +e+ ` coords = getOutputCoords ( ) ;
` +e+ ` sourceLoc ;
` +l+ `
vec4 result = vec4 ( 0. ) ;
` +o+ `
` +c+ `
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` }return n.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the "+("length of start ("+t.length+")"));return function(r,i){if(e.startLoc==null&&(e.startLoc=r.getUniformLocationNoThrow(i,"start"),e.startLoc==null))return;r.gl.uniform1iv(e.startLoc,t)}},n}();var hP=function(){function n(t,e,r){this.variableNames=["x"],this.outputShape=r;var i=r.length,a=Qe(r.length),s=Qe(r.length),o="";if(i===1)o="coords * strides + begin";else{var c=0;o=r.map(function(l,u){return c++,r.length===1?"coords * strides["+u+"] + begin["+u+"]":"coords["+(c-1)+"] * strides["+u+"] + begin["+u+"]"}).join(",")}this.userCode= `
2020-11-03 15:34:36 +01:00
` +a+" begin = "+a+"("+t+ ` ) ;
` +a+" strides = "+a+"("+e+ ` ) ;
void main ( ) {
` +s+ ` coords = getOutputCoords ( ) ;
setOutput ( getX ( ` +o+ ` ) ) ;
2020-10-15 14:16:34 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var dP=function(){function n(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return n.prototype.acquireTexture=function(t,e,r){var i=E2(e,r),a=D2(t,i,r);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);var s=O2(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,r);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();var o=this.freeTextures[a].shift();return this.usedTextures[a].push(o),o}var c;return i===Ft.PACKED_2X2_FLOAT32?c=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===Ft.PACKED_2X2_FLOAT16?c=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===Ft.UNPACKED_FLOAT32?c=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===Ft.UNPACKED_FLOAT16?c=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===Ft.PACKED_4X1_UNSIGNED_BYTE&&(c=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(c),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),c},n.prototype.releaseTexture=function(t,e,r,i){if(this.freeTextures==null)return;var a=E2(r,i),s=D2(e,a,i);s in this.freeTextures||(this.freeTextures[s]=[]);var o=O2(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,i),c=_.env().get("WEBGL_DELETE_TEXTURE_THRESHOLD");c!==-1&&this._numBytesAllocated>c?(this.gpgpu.deleteMatrixTexture(t),this._numBytesAllocated-=o):(this.freeTextures[s].push(t),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;var l=this.usedTextures[s],u=l.indexOf(t);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),this.log()},n.prototype.log=function(){if(!this.logEnabled)return;var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")");var e=this._numBytesFree/this._numBytesAllocated;console.log("Bytes allocated: "+this._numBytesAllocated),console.log("Bytes unused: "+this._numBytesFree+" ("+Math.round(100*e)+"%)")},Object.defineProperty(n.prototype,"numBytesAllocated",{get:function(){return this._numBytesAllocated},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"numBytesFree",{get:function(){return this._numBytesFree},enumerable:!0,configurable:!0}),n.prototype.getNumUsedTextures=function(){return this.numUsedTextures},n.prototype.getNumFreeTextures=function(){return this.numFreeTextures},n.prototype.dispose=function(){var t=this;if(this.freeTextures==null)return;for(var e in this.freeTextures)this.freeTextures[e].forEach(function(r){t.gpgpu.deleteMatrixTexture(r)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(i){t.gpgpu.deleteMatrixTexture(i)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0},n}();function pP(n,t){var e=n;if(t===e.R32F)return 4;if(t===e.R16F)return 2;if(t===e.RGBA32F)return 16;if(t===n.RGBA)return 16;if(t===e.RGBA16F)return 8;throw new Error("Unknown internal format "+t)}function O2(n,t,e,r,i){var a=fP(t,r),s;if(i){var o=ya(n[0],n[1]),c=o[0],l=o[1];s=c*l}else{var u=As(n[0],n[1]),h=u[0],d=u[1];s=h*d}var p=pP(e,a);return s*p}function fP(n,t){switch(n){case Ft.PACKED_2X2_FLOAT32:return Rp(t);case Ft.PACKED_2X2_FLOAT16:return Op(t);case Ft.UNPACKED_FLOAT32:return Np(t);case Ft.UNPACKED_FLOAT16:return _p(t);case Ft.PACKED_4X1_UNSIGNED_BYTE:return Cp(t);default:throw new Error("Unknown physical texture type "+n)}}function mP(n){return _.env().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?Ft.PACKED_2X2_FLOAT32:Ft.UNPACKED_FLOAT32:n?Ft.PACKED_2X2_FLOAT16:Ft.UNPACKED_FLOAT16}function E2(n,t){if(n===hn.UPLOAD)return Ft.PACKED_2X2_FLOAT32;if(n===hn.RENDER||n==null)return mP(t);if(n===hn.DOWNLOAD||n===hn.PIXELS)return Ft.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+n)}function D2(n,t,e){return n[0]+"_"+n[1]+"_"+t+"_"+e}var yP=function(){function n(t,e){this.variableNames=["A"];for
2020-11-03 15:34:36 +01:00
void main ( ) {
` +a+ ` resRC = getOutputCoords ( ) ;
setOutput ( getA ( ` +s+ ` ) ) ;
2020-10-15 14:16:34 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();function gP(n){var t=n.length;if(t>5)throw Error("Tile for rank "+t+" is not yet supported");if(t===1)return"imod(resRC, "+n[0]+")";for(var e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],i=0;i<n.length;i++)r.push("imod("+e[i]+", "+n[i]+")");return r.join()}var De=function(){function n(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
float unaryOperation ( float x ) {
` +e+ `
}
void main ( ) {
float x = getAAtOutCoords ( ) ;
float y = unaryOperation ( x ) ;
setOutput ( y ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}(),pr="if (isnan(x)) return x;",vP="return x;",k2="return abs(x);",F2=pr+ `
2020-11-03 15:34:36 +01:00
return ( x < 0.0 ) ? 0.0 : x ;
2020-11-04 16:18:22 +01:00
` ,W2=pr+ `
2020-11-03 15:34:36 +01:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2020-11-04 16:18:22 +01:00
` ,U2="return (x >= 0.0) ? x : (exp(x) - 1.0);",wP= `
2020-11-03 15:34:36 +01:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ` +_.backend_util.SELU_SCALEALPHA+ ` ;
float scale = ` +_.backend_util.SELU_SCALE+ ` ;
return ( x >= 0.0 ) ? scale * x : scaleAlpha * ( exp ( x ) - 1.0 ) ;
2020-11-04 16:18:22 +01:00
` ;function bP(n){return n===void 0&&(n=0),pr+( `
2020-11-03 15:34:36 +01:00
return x > 0.0 ? 1.0 : float ( ` +n+ ` ) ;
2020-11-04 16:18:22 +01:00
` )}var B2="return -x;",z2="return ceil(x);",P2="return floor(x);",xP= `
2020-11-03 15:34:36 +01:00
if ( isnan ( x ) ) { return 0.0 ; }
return sign ( x ) ;
2020-11-04 16:18:22 +01:00
` ,SP="return float(isnan(x));",LP="return float(isinf(x));",IP="return float(!isnan(x) && !isinf(x));",AP= `
2020-11-03 15:34:36 +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 ;
}
}
2020-11-04 16:18:22 +01:00
` ,M2="return exp(x);",H2="return exp(x) - 1.0;",TP= ` if ( x < 0.0 ) return NAN ;
return log ( x ) ; ` ,NP="return log(1.0 + x);",_P="return sqrt(x);",CP="return inversesqrt(x);",RP="return 1.0 / (1.0 + exp(-1.0 * x));",OP= `
2020-11-03 15:34:36 +01:00
float epsilon = 1.1920928955078125 e - 7 ;
float threshold = log ( epsilon ) + 2.0 ;
bool too _large = x > - threshold ;
bool too _small = x < threshold ;
float result ;
float exp _x = exp ( x ) ;
if ( too _large ) {
result = x ;
}
else if ( too _small ) {
result = exp _x ;
}
else {
result = log ( exp _x + 1.0 ) ;
}
return result ;
2020-11-04 16:18:22 +01:00
` ,EP=pr+ `
2020-11-03 15:34:36 +01:00
if ( abs ( x ) > 1. ) {
return NAN ;
}
return asin ( x ) ;
2020-11-04 16:18:22 +01:00
` ,DP=pr+ `
2020-11-03 15:34:36 +01:00
if ( abs ( x ) > 1. ) {
return NAN ;
}
return acos ( x ) ;
2020-11-04 16:18:22 +01:00
` ,kP=pr+ `
2020-11-03 15:34:36 +01:00
return atan ( x ) ;
2020-11-04 16:18:22 +01:00
` ,FP= `
2020-11-03 15:34:36 +01:00
float e2x = exp ( x ) ;
return ( e2x - 1.0 / e2x ) / 2.0 ;
2020-11-04 16:18:22 +01:00
` ,WP= `
2020-11-03 15:34:36 +01:00
float e2x = exp ( - x ) ;
return ( e2x + 1.0 / e2x ) / 2.0 ;
2020-11-04 16:18:22 +01:00
` ,UP= `
2020-11-03 15:34:36 +01:00
float e2x = exp ( - 2.0 * abs ( x ) ) ;
return sign ( x ) * ( 1.0 - e2x ) / ( 1.0 + e2x ) ;
2020-11-04 16:18:22 +01:00
` ,BP=pr+"return log(x + sqrt(x * x + 1.0));",zP=pr+ `
2020-11-03 15:34:36 +01:00
if ( x < 1.0 ) return NAN ;
2020-11-04 16:18:22 +01:00
return log ( x + sqrt ( x * x - 1.0 ) ) ; ` ,PP=pr+ `
2020-11-03 15:34:36 +01:00
if ( ( x < - 1.0 ) || ( x > 1.0 ) ) return NAN ;
2020-11-04 16:18:22 +01:00
return ( log ( 1.0 + x ) - log ( 1.0 - x ) ) / 2.0 ; ` ,MP= `
2020-11-03 15:34:36 +01:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ` +_.backend_util.ERF_P+ ` ;
float a1 = ` +_.backend_util.ERF_A1+ ` ;
float a2 = ` +_.backend_util.ERF_A2+ ` ;
float a3 = ` +_.backend_util.ERF_A3+ ` ;
float a4 = ` +_.backend_util.ERF_A4+ ` ;
float a5 = ` +_.backend_util.ERF_A5+ ` ;
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 ) ) ;
2020-11-04 16:18:22 +01:00
` ,HP="return 1.0 / x;",VP="return float(!(x >= 1.0));",gc="return x;";var qP="return x;",GP= `
2020-11-03 15:34:36 +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 ;
2020-11-04 16:18:22 +01:00
` ,V2= `
2020-11-03 15:34:36 +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 ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
return result ;
2020-11-04 16:18:22 +01:00
` ,q2= `
2020-11-03 15:34:36 +01:00
vec4 result = min ( x , vec4 ( 6. ) ) * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
return result ;
2020-11-04 16:18:22 +01:00
` ,G2= `
2020-11-03 15:34:36 +01:00
vec4 result ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +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-11-01 19:07:53 +01:00
2020-11-03 15:34:36 +01:00
return result ;
2020-11-04 16:18:22 +01:00
` ,Es=function(){function n(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
vec4 unaryOperation ( vec4 x ) {
` +e+ `
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
void main ( ) {
vec4 x = getAAtOutCoords ( ) ;
vec4 y = unaryOperation ( x ) ;
setOutput ( y ) ;
2020-10-17 12:30:00 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var YP=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,r=Pt("rc",e),i=Qe(e),a=JU(e,r),s=r.slice(-2),o=e<=1?"rc":"vec2("+s.join(",")+")";this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
` +i+ ` rc = getOutputCoords ( ) ;
vec4 packedInput = getA ( ` +a+ ` ) ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
setOutput ( getChannel ( packedInput , ` +o+ ` ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var Y2=_.backend_util.segment_util,jP=_.kernel_impls.split,KP=_.kernel_impls.tile, $ P=_.kernel_impls.topkImpl,XP=_.kernel_impls.whereImpl,JP=1e-7,ZP=1e-4,yc={};function QP(n){return n in yc||(yc[n]={}),yc[n]}function vc(n,t){if(t===void 0&&(t=!1),n==="linear")return t?qP:vP;if(n==="relu")return t?V2:F2;if(n==="elu")return t?G2:U2;if(n==="relu6")return t?q2:W2;if(n==="prelu")return t?r2:n2;throw new Error("Activation "+n+" has not been implemented for the WebGL backend.")}var eM=128,tM=600;function nM(){return _.env().global.screen==null?1024:_.env().global.screen.height*_.env().global.screen.width*window.devicePixelRatio*tM/1024/1024}var j2=1e3,K2=function(n){iU(t,n);function t(e){var r=n.call(this)||this;if(r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.warnedAboutCPUBackend=!1,r.pendingDeletes=0,r.disposed=!1,!_.env().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){var i=Gn(_.env().getNumber("WEBGL_VERSION"));r.binaryCache=QP(_.env().getNumber("WEBGL_VERSION")),r.gpgpu=new T2(i),r.canvas=i.canvas,r.gpgpuCreatedLocally=!0}else r.gpgpu=e,r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=e.gl.canvas;return r.textureManager=new dP(r.gpgpu),r.numMBBeforeWarning=nM(),r.texData=new _.DataStorage(r,_.engine()),r}return t.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},t.prototype.write=function(e,r,i){if((_.env().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||_.env().getBool("DEBUG"))&&this.checkNumericalProblems(e),i==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var a={};return this.texData.set(a,{shape:r,dtype:i,values:e,usage:hn.UPLOAD,refCount:1,complexParentRefCount:0}),a},t.prototype.incRef=function(e){var r=this.texData.get(e);r.refCount++},t.prototype.decRef=function(e){if(this.texData.has(e)){var r=this.texData.get(e);r.refCount--}},t.prototype.move=function(e,r,i,a){if(_.env().getBool("DEBUG")&&this.checkNumericalProblems(r),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:i,dtype:a,values:r,usage:hn.UPLOAD,refCount:1,complexParentRefCount:0})},t.prototype.disposeIntermediateTensorInfo=function(e){var r=e.dataId;if(this.texData.has(r)){var i=this.texData.get(r);i.refCount--,i.refCount<1&&this.disposeData(r)}},t.prototype.readSync=function(e){var r=this.texData.get(e),i=r.values,a=r.dtype,s=r.complexTensorInfos,o=r.slice,c=r.shape,l=r.isPacked;if(o!=null){var u=void 0;l?u=new Es(c,gc):u=new De(c,gc);var h=this.runWebGLProgram(u,[{dataId:e,shape:c,dtype:a}],a),d=this.readSync(h.dataId);return this.disposeIntermediateTensorInfo(h),d}if(i!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return i;var p=this.activeTimers!=null,f;p&&(f=_.util.now());var m;if(a==="complex64"){var g=this.readSync(s.real.dataId),y=this.readSync(s.imag.dataId);m=_.backend_util.mergeRealAndImagArrays(g,y)}else m=this.getValuesFromTexture(e);return p&&(this.downloadWaitMs+=_.util.now()-f),this.convertAndCacheOnCPU(e,m)},t.prototype.read=function(e){return oc(this,void 0,void 0,function(){var r,i,a,s,o,c,l,u,h,d,p,f,m,g,y,w,b,x,S,N,I,C;return cc(this,function(O){switch(O.label){case 0:if(this.pendingRead.has(e))return r=this.pendingRead.get(e),[2,new Promise(function(D){return r.push(D)})];if(i=this.texData.get(e),a=i.values,s=i.shape,o=i.slice,c=i.dtype,l=i.complexTensorInfos,u=i.isPacked,o!=null)return h=void 0,u?h=new Es(s,gc):h=new De(s,gc),d=this.runWebGLProgram(h,[{dataId:e,shape:s,dtype:c}],c),p=this.read(d.dataId),this.disposeIntermediateTensorInfo(d),[2,p];if(a!=null)return[2,this.convertAndCacheOnCPU(e)];if(!_.env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&_.env().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return f=null,c!=="comple
2020-11-03 15:34:36 +01:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2020-11-04 16:18:22 +01:00
` ,lM= `
2020-11-03 15:34:36 +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 ;
2020-11-04 16:18:22 +01:00
` ;function wc(n){return function(t){var e=t.inputs,r=t.backend,i=e.x,a=r,s=new De(i.shape,n);return a.runWebGLProgram(s,[i],i.dtype)}}function Aa(n){var t=n.opSnippet,e=n.packedOpSnippet,r=n.checkOutOfBounds,i=r===void 0?!1:r,a=n.supportsComplex,s=a===void 0?!1:a,o=n.cpuKernelImpl,c=n.dtype;return function(l){var u=l.inputs,h=l.backend,d=u,p=d.a,f=d.b,m=h;if(s&&p.dtype==="complex64"){var g=m.texData.get(p.dataId),y=m.texData.get(f.dataId),w=[[g.complexTensorInfos.real,y.complexTensorInfos.real],[g.complexTensorInfos.imag,y.complexTensorInfos.imag]].map(function(V){var P=V[0],q=V[1],K={dataId:P.dataId,dtype:P.dtype,shape:p.shape},G={dataId:q.dataId,dtype:q.dtype,shape:f.shape},H=new Bt(t,p.shape,f.shape);return m.runWebGLProgram(H,[K,G],_.upcastType(P.dtype,q.dtype))}),b=w[0],x=w[1],S=Ia({inputs:{real:b,imag:x},backend:m});return m.disposeIntermediateTensorInfo(b),m.disposeIntermediateTensorInfo(x),S}var N=c||_.upcastType(p.dtype,f.dtype);if(m.shouldExecuteOnCPU([p,f])&&o!=null){var g=m.texData.get(p.dataId),y=m.texData.get(f.dataId),I=o(p.shape,f.shape,g.values,y.values,N),C=I[0],O=I[1],D=m.makeTensorInfo(O,N),F=m.texData.get(D.dataId);return F.values=C,D}var k=_.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null,B;return k?B=new dr(e,p.shape,f.shape,i):B=new Bt(t,p.shape,f.shape),m.runWebGLProgram(B,[p,f],N)}}var J2="return a + b;",uM=Aa({opSnippet:J2,packedOpSnippet:J2,supportsComplex:!0,cpuKernelImpl:WU}),hM={kernelName:_.Add,backendName:"webgl",kernelFunc:uM};var dM=cM+ `
2020-11-03 15:34:36 +01:00
return atan ( a , b ) ;
2020-11-04 16:18:22 +01:00
` ,pM= `
2020-11-03 15:34:36 +01:00
vec4 result = atan ( a , b ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2020-11-04 16:18:22 +01:00
` +lM+ `
2020-11-03 15:34:36 +01:00
return result ;
2020-11-04 16:18:22 +01:00
` ,fM=Aa({opSnippet:dM,packedOpSnippet:pM}),mM={kernelName:_.Atan2,backendName:"webgl",kernelFunc:fM};function gM(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x;va(i,"avgPool");var a=r.filterSize,s=r.strides,o=r.pad,c=r.dimRoundingMode,l=1;_.util.assert(_.backend_util.eitherStridesOrDilationsAreOne(s,l),function(){return"Error in avgPool: Either strides or dilations must be 1. "+("Got strides "+s+" and dilations '"+l+"'")});var u=_.backend_util.computePool2DInfo(i.shape,a,s,l,o,c);if(u.filterWidth===1&&u.filterHeight===1&&_.util.arraysEqual(u.inShape,u.outShape))return fr({inputs:{x:i},backend:e});var h=new Os(u,"avg",!1);return e.runWebGLProgram(h,[i],"float32")}var yM={kernelName:_.AvgPool,backendName:"webgl",kernelFunc:gM};function vM(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.dy,a=t.input,s=a;va([i,a],"avgPoolBackprop");var o=r.filterSize,c=r.strides,l=r.pad,u=_.backend_util.computePool2DInfo(s.shape,o,c,1,l),h=new FB(u);return e.runWebGLProgram(h,[i],s.dtype)}var wM={kernelName:_.AvgPoolBackprop,backendName:"webgl",kernelFunc:vM};var bM=function(){function n(t,e,r,i,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],_.backend_util.assertAndGetBroadcastShape(t,e),_.backend_util.assertAndGetBroadcastShape(t,r);var o="0.0";i!=null&&(_.backend_util.assertAndGetBroadcastShape(t,i),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var c="1.0";a!=null&&(_.backend_util.assertAndGetBroadcastShape(t,a),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
float x = getXAtOutCoords ( ) ;
float mean = getMeanAtOutCoords ( ) ;
float variance = getVarianceAtOutCoords ( ) ;
float offset = ` +o+ ` ;
float scale = ` +c+ ` ;
float inv = scale * inversesqrt ( variance + float ( ` +s+ ` ) ) ;
setOutput ( dot ( vec3 ( x , - mean , offset ) , vec3 ( inv , inv , 1 ) ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var xM=function(){function n(t,e,r,i,a,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],_.backend_util.assertAndGetBroadcastShape(t,e),_.backend_util.assertAndGetBroadcastShape(t,r);var o="vec4(0.0)";i!=null&&(_.backend_util.assertAndGetBroadcastShape(t,i),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var c="vec4(1.0)";a!=null&&(_.backend_util.assertAndGetBroadcastShape(t,a),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
vec4 offset = ` +o+ ` ;
vec4 scale = ` +c+ ` ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
vec4 x = getXAtOutCoords ( ) ;
vec4 mean = getMeanAtOutCoords ( ) ;
vec4 variance = getVarianceAtOutCoords ( ) ;
2020-10-15 14:16:34 +02:00
2020-11-03 15:34:36 +01:00
vec4 inv = scale * inversesqrt ( variance + vec4 ( ` +s+ ` ) ) ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
setOutput ( ( x - mean ) * inv + offset ) ;
2020-10-15 14:16:34 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var SM=function(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x,a=t.mean,s=t.variance,o=t.offset,c=t.scale;_.util.assert(a.shape.length===s.shape.length,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),_.util.assert(o==null||a.shape.length===o.shape.length,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),_.util.assert(c==null||a.shape.length===c.shape.length,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var l=r.varianceEpsilon;l==null&&(l=.001);var u=[i,a,s],h=null;o!=null&&(h=o.shape,u.push(o));var d=null;c!=null&&(d=c.shape,u.push(c));var p=_.env().getBool("WEBGL_PACK_NORMALIZATION")?new xM(i.shape,a.shape,s.shape,h,d,l):new bM(i.shape,a.shape,s.shape,h,d,l),f=e.runWebGLProgram(p,u,u[0].dtype);return f},LM={kernelName:_.FusedBatchNorm,backendName:"webgl",kernelFunc:SM};var IM="return float(a != b);",Z2=Aa({opSnippet:IM,dtype:"bool"}),AM={kernelName:_.NotEqual,backendName:"webgl",kernelFunc:Z2};function Fp(n){var t=n.inputs,e=n.backend,r=t.input,i=e.texData.get(r.dataId);return fr({inputs:{x:i.complexTensorInfos.real},backend:e})}var TM={kernelName:_.Real,backendName:"webgl",kernelFunc:Fp};var NM="return float(int(x));";function _M(n,t){var e=new De(n.shape,NM),r=t.runWebGLProgram(e,[n],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function Wp(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x,a=r.dtype;if(a==="complex64"){if(i.dtype==="complex64")return fr({inputs:{x:i},backend:e});var s=_.zeros(i.shape),o=Wp({inputs:{x:i},backend:e,attrs:{dtype:"float32"}}),c=Ia({inputs:{real:o,imag:s},backend:e});return s.dispose(),e.disposeIntermediateTensorInfo(o),c}if(i.dtype==="complex64"){var l=Fp({inputs:{input:i},backend:e}),c=Wp({inputs:{x:l},backend:e,attrs:{dtype:a}});return e.disposeIntermediateTensorInfo(l),c}if(!_.util.hasEncodingLoss(i.dtype,a)){var c=fr({inputs:{x:i},backend:e});return{dataId:c.dataId,shape:c.shape,dtype:a}}if(a==="int32")return _M(i,e);if(a==="bool"){var u=e.makeTensorInfo([],"bool",_.util.getTypedArrayFromDType("bool",1)),h={a:i,b:u},c=Z2({inputs:h,backend:e});return e.disposeIntermediateTensorInfo(u),c}throw new Error("Error in Cast: failed to cast "+i.dtype+" to "+a)}var CM={kernelName:_.Cast,backendName:"webgl",kernelFunc:Wp};var RM=function(){function n(t){this.outputShape=[],this.outputShape=_.backend_util.computeOutShape(t,1),this.variableNames=t.map(function(c,l){return"T"+l});var e=new Array(t.length-1);e[0]=t[0][1];for(var r=1;r<e.length;r++)e[r]=e[r-1]+t[r][1];for(var i=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"],r=1;r<e.length;r++){var a=e[r-1];i.push("else if (yC < "+e[r]+") "+("setOutput(getT"+r+"(yR, yC-"+a+"));"))}var s=e.length,o=e[e.length-1];i.push("else setOutput(getT"+s+"(yR, yC-"+o+"));"),this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int yR = coords . x ;
int yC = coords . y ;
` +i.join( `
` )+ `
}
2020-11-04 16:18:22 +01:00
` }return n}();var OM=function(){function n(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_.backend_util.computeOutShape(t,e);var r=this.outputShape,i=r.length,a=Qe(i),s=Pt("coords",i),o=["x","y","z","w","u","v"].slice(0,i);this.variableNames=t.map(function(y,w){return"T"+w});var c=new Array(t.length-1);c[0]=t[0][e];for(var l=1;l<c.length;l++)c[l]=c[l-1]+t[l][e];for(var u=o[e],h=o.slice(-2),d=o.join(),p="if ("+u+" < "+c[0]+ ` ) {
2020-11-03 15:34:36 +01:00
return getChannel (
getT0 ( ` +d+"), vec2("+h.join()+ ` ) ) ;
} ` ,l=1;l<c.length;l++){var f=c[l-1];p+= `
if ( ` +u+" < "+c[l]+" && "+u+" >= "+c[l-1]+ ` ) {
return getChannel (
2020-11-04 16:18:22 +01:00
getT ` +l+"("+bc(o,u,f)+ ` ) ,
vec2 ( ` +bc(h,u,f)+ ` ) ) ;
2020-11-03 15:34:36 +01:00
} ` }var m=c.length,g=c[c.length-1];p+= `
return getChannel (
2020-11-04 16:18:22 +01:00
getT ` +m+"("+bc(o,u,g)+ ` ) ,
vec2 ( ` +bc(h,u,g)+"));",this.userCode= `
2020-11-03 15:34:36 +01:00
float getValue ( ` +o.map(function(y){return"int "+y})+ ` ) {
` +p+ `
2020-10-15 14:16:34 +02:00
}
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
void main ( ) {
` +a+ ` coords = getOutputCoords ( ) ;
vec4 result = vec4 ( getValue ( ` +s+ ` ) , 0. , 0. , 0. ) ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
` +s[i-1]+" = "+s[i-1]+ ` + 1 ;
if ( ` +s[i-1]+" < "+r[i-1]+ ` ) {
result . g = getValue ( ` +s+ ` ) ;
}
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
` +s[i-2]+" = "+s[i-2]+ ` + 1 ;
if ( ` +s[i-2]+" < "+r[i-2]+ ` ) {
result . a = getValue ( ` +s+ ` ) ;
}
` +s[i-1]+" = "+s[i-1]+ ` - 1 ;
if ( ` +s[i-2]+" < "+r[i-2]+ ` &&
` +s[i-1]+" < "+r[i-1]+ ` ) {
result . b = getValue ( ` +s+ ` ) ;
}
setOutput ( result ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();function bc(n,t,e){var r=n.indexOf(t),i=n.map(function(a,s){return s===r?a+" - "+e:a});return i.join()}function Q2(n){var t=n.inputs,e=n.backend,r=t.input,i=e.texData.get(r.dataId);return fr({inputs:{x:i.complexTensorInfos.imag},backend:e})}var EM={kernelName:_.Imag,backendName:"webgl",kernelFunc:Q2};function DM(n,t,e){var r=[Ni(n.shape)].concat(_i(n.shape)),i={dtype:n.dtype,shape:r,dataId:n.dataId},a=[Ni(t)].concat(_i(t)),s=new C2(a,r),o=!0,c=e.runWebGLProgram(s,[i],n.dtype,null,o);return{dataId:c.dataId,shape:t,dtype:c.dtype}}function mr(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x,a=r.shape,s=e,o=_.util.sizeFromShape(i.shape),c=_.util.inferFromImplicitShape(a,o),l=_.util.sizeFromShape(c);_.util.assert(o===l,function(){return"The new shape ("+c+") has "+l+" elements and the old "+("shape ("+i.shape+") has "+o+" elements. The new shape and old ")+"shape must have the same number of elements."});var u=s.texData.get(i.dataId);return u.isPacked&&!Cs(i.shape,c)&&!(u.texture!==null&&Cs(u.shape,c))?DM(i,c,s):(s.incRef(i.dataId),{dataId:i.dataId,shape:c,dtype:i.dtype})}var kM={kernelName:_.Reshape,backendName:"webgl",kernelFunc:mr};function Ta(n,t,e){var r=n[0].dtype;if(r==="complex64"){var i=n.map(function(b){return Fp({inputs:{input:b},backend:e})}),a=n.map(function(b){return Q2({inputs:{input:b},backend:e})}),s=Ta(i,t,e),o=Ta(a,t,e),c=Ia({inputs:{real:s,imag:o},backend:e});return i.forEach(function(b){return e.disposeIntermediateTensorInfo(b)}),a.forEach(function(b){return e.disposeIntermediateTensorInfo(b)}),e.disposeIntermediateTensorInfo(s),e.disposeIntermediateTensorInfo(o),c}if(n.length>_.env().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var l=Math.floor(n.length/2),u=Ta(n.slice(0,l),t,e),h=Ta(n.slice(l),t,e),d=Ta([u,h],t,e);return e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(h),d}if(_.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&n[0].shape.length>1){var p=new OM(n.map(function(b){return b.shape}),t);return e.runWebGLProgram(p,n,r)}var f=_.backend_util.computeOutShape(n.map(function(b){return b.shape}),t),m=n.map(function(b){return mr({inputs:{x:b},attrs:{shape:[-1,_.util.sizeFromShape(b.shape.slice(t))]},backend:e})}),g=new RM(m.map(function(b){return b.shape})),y=e.runWebGLProgram(g,m,r);m.forEach(function(b){return e.disposeIntermediateTensorInfo(b)});var w=mr({inputs:{x:y},attrs:{shape:f},backend:e});return e.disposeIntermediateTensorInfo(y),w}function FM(n){var t=n.inputs,e=n.backend,r=n.attrs,i=r.axis,a=_.util.parseAxisParam(i,t[0].shape)[0],s=_.backend_util.computeOutShape(t.map(function(l){return l.shape}),a);if(_.util.sizeFromShape(s)===0)return e.makeTensorInfo(s,t[0].dtype,[]);var o=t.filter(function(l){return _.util.sizeFromShape(l.shape)>0});if(o.length===1)return o[0];var c=o.map(function(l){return l.shape});return _.backend_util.assertParamsConsistent(c,a),Ta(o,a,e)}var WM={kernelName:_.Concat,backendName:"webgl",kernelFunc:FM};var UM=X2+ `
2020-11-03 15:34:36 +01:00
return cos ( x ) ;
2020-11-04 16:18:22 +01:00
` ,BM=wc(UM),zM={kernelName:_.Cos,backendName:"webgl",kernelFunc:BM};var PM= `
2020-11-03 15:34:36 +01:00
if ( a == b ) {
return 1.0 ;
} ;
2020-11-04 16:18:22 +01:00
return a / b ; ` ,MM= `
2020-11-03 15:34:36 +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-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
if ( a . y == b . y ) {
result . y = 1. ;
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
if ( a . z == b . z ) {
result . z = 1. ;
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
if ( a . w == b . w ) {
result . w = 1. ;
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
return result ;
2020-11-04 16:18:22 +01:00
` ,HM=Aa({opSnippet:PM,packedOpSnippet:MM,checkOutOfBounds:!0}),VM={kernelName:_.Div,backendName:"webgl",kernelFunc:HM};var ex=function(){function n(t,e,r){this.variableNames=["real","imag"];var i=e[1];this.outputShape=e;var a=r?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,s=r?i+".0":"1.0",o;if(t==="real")o="return real * expR - imag * expI;";else if(t==="imag")o="return real * expI + imag * expR;";else throw new Error('FFT component must be either "real" or "imag", got '+t+".");this.userCode= `
2020-11-03 15:34:36 +01:00
const float exponentMultiplier = ` +a+ ` ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
float unaryOpComplex ( float real , float expR , float imag , float expI ) {
` +o+ `
2020-10-15 14:16:34 +02:00
}
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
float mulMatDFT ( int batch , int index ) {
float indexRatio = float ( index ) / float ( ` +i+ ` ) ;
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
float result = 0.0 ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
for ( int i = 0 ; i < ` +i+ ` ; i ++ ) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float ( i ) ;
float expR = cos ( x ) ;
float expI = sin ( x ) ;
float real = getReal ( batch , i ) ;
float imag = getImag ( batch , i ) ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
result +=
unaryOpComplex ( real , expR , imag , expI ) / ` +s+ ` ;
2020-10-15 14:16:34 +02:00
}
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
return result ;
2020-10-15 14:16:34 +02:00
}
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
setOutput ( mulMatDFT ( coords [ 0 ] , coords [ 1 ] ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();function tx(n,t,e){var r=e.texData.get(n.dataId),i=_.util.sizeFromShape(n.shape),a=n.shape[n.shape.length-1],s=i/a,o=mr({inputs:{x:n},backend:e,attrs:{shape:[s,a]}}),c=o.shape,l=new ex("real",c,t),u=new ex("imag",c,t),h=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:c},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:c}],d=e.runWebGLProgram(l,h,"float32"),p=e.runWebGLProgram(u,h,"float32"),f=Ia({inputs:{real:d,imag:p},backend:e});e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(p);var m=mr({inputs:{x:f},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(m),m}function qM(n){var t=n.inputs,e=n.backend,r=t.input;return tx(r,!1,e)}var GM={kernelName:_.FFT,backendName:"webgl",kernelFunc:qM};var YM=function(){function n(t){this.variableNames=["Image"],this.outputShape=[];var e=t[2];this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
int coordX = ` +e+ ` - x ;
float outputValue ;
if ( coordX >= 0 && coordX < ` +e+ ` ) {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coordX , coords [ 3 ] ) ;
} else {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coords [ 2 ] , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
2020-10-15 14:16:34 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var jM={kernelName:_.FlipLeftRight,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,r=t.image,i=e,a=new YM(r.shape),s=i.runWebGLProgram(a,[r],r.dtype);return s}};var KM=function(){function n(t){this.variableNames=["A"];var e=Mt(),r=t[0],i=t[1];this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( ` +i+".0, "+r+ ` . 0 ) ;
vec4 values = ` +e.texture2D+ ` ( A , uv ) ;
float value ;
if ( depth == 0 ) {
value = values . r ;
} else if ( depth == 1 ) {
value = values . g ;
} else if ( depth == 2 ) {
value = values . b ;
} else if ( depth == 3 ) {
value = values . a ;
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
setOutput ( floor ( value * 255.0 + 0.5 ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var $ M=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=Mt(),r=t[0],i=t[1];this.outputShape=t,this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
vec4 result = vec4 ( 0. ) ;
for ( int row = 0 ; row <= 1 ; row ++ ) {
for ( int col = 0 ; col <= 1 ; col ++ ) {
texC = coords [ 1 ] + row ;
depth = coords [ 2 ] + col ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( ` +i+".0, "+r+ ` . 0 ) ;
vec4 values = ` +e.texture2D+ ` ( A , uv ) ;
float value ;
if ( depth == 0 ) {
value = values . r ;
} else if ( depth == 1 ) {
value = values . g ;
} else if ( depth == 2 ) {
value = values . b ;
} else if ( depth == 3 ) {
value = values . a ;
}
result [ row * 2 + col ] = floor ( value * 255.0 + 0.5 ) ;
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
}
` +e.output+ ` = result ;
2020-10-15 14:16:34 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var JM={kernelName:_.FromPixels,backendName:"webgl",kernelFunc:XM},Na;function XM(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.pixels,a=r.numChannels,s=typeof HTMLVideoElement!="undefined"&&i instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&i instanceof HTMLImageElement,c=s?[i.videoWidth,i.videoHeight]:[i.width,i.height],l=c[0],u=c[1],h=[u,l],d=[u,l,a];(o||s)&&(Na==null&&(Na=document.createElement("canvas").getContext("2d")),Na.canvas.width=l,Na.canvas.height=u,Na.drawImage(i,0,0,l,u),i=Na.canvas);var p=e.makeTensorInfo(h,"int32");e.texData.get(p.dataId).usage=hn.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(p.dataId),i);var f=_.env().getBool("WEBGL_PACK")?new $ M(d):new KM(d),m=e.runWebGLProgram(f,[p],"int32");return e.disposeData(p.dataId),m}function ZM(n){var t=n.inputs,e=n.backend,r=t.input;return tx(r,!0,e)}var QM={kernelName:_.IFFT,backendName:"webgl",kernelFunc:ZM};var nx=function(){function n(t,e){this.variableNames=["x"];var r=t.windowSize,i=t.batchSize,a=t.inSize,s=t.outSize;this.outputShape=[i,s];var o=Math.floor(r/4)*4,c=r%4,l="sumValue += dot(values, ones);";if(e!=null){var u=1/e;l="sumValue += dot(values * "+(_.util.isInt(u)?u.toPrecision(2):u)+", ones);"}var h="";a%r>0&&(h= `
2020-11-03 15:34:36 +01:00
if ( inIdx < 0 || inIdx >= ` +a+ ` ) {
return 0.0 ;
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
` ),this.userCode= `
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float getValue ( int batch , int inIdx ) {
` +h+ `
return getX ( batch , inIdx ) ;
2020-10-15 14:16:34 +02:00
}
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * ` +r+ ` ;
float sumValue = 0.0 ;
for ( int i = 0 ; i < ` +o+ ` ; i += 4 ) {
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
` +l+ `
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
int inIdx = inOffset + ` +o+ ` ;
if ( ` +(c===1)+ ` ) {
vec4 values = vec4 ( getValue ( batch , inIdx ) , 0.0 , 0.0 , 0.0 ) ;
2020-10-18 18:12:09 +02:00
2020-11-03 15:34:36 +01:00
` +l+ `
} else if ( ` +(c===2)+ ` ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) , 0.0 , 0.0 ) ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
` +l+ `
} else if ( ` +(c===3)+ ` ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) , 0.0 ) ;
2020-10-17 12:30:00 +02:00
2020-11-03 15:34:36 +01:00
` +l+ `
}
setOutput ( sumValue ) ;
2020-11-01 19:07:53 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();function eH(n){for(var t=[];t.length===0||t[t.length-1].outSize!==1;){var e=t.length?t[t.length-1].outSize:n[1],r=_.backend_util.computeOptimalWindowSize(e);t.push({inSize:e,windowSize:r,outSize:Math.ceil(e/r)})}return t}function rx(n,t,e,r){for(var i=eH(n.shape),a=n,s=0;s<i.length;s++){var o=i[s],c=o.inSize,l=o.windowSize,u=o.outSize,h=void 0,d=void 0;e==="mean"?h=s===0?new nx({windowSize:l,inSize:c,batchSize:n.shape[0],outSize:u},c):new nx({windowSize:l,inSize:c,batchSize:n.shape[0],outSize:u}):h=new _2({windowSize:l,inSize:c,batchSize:n.shape[0],outSize:u},e),d=a,a=r.runWebGLProgram(h,[a],t),d.dataId!==n.dataId&&r.disposeIntermediateTensorInfo(d)}return a}function tH(n,t,e,r){var i=_.util.sizeFromShape(t),a=_.util.sizeFromShape(n.shape),s=a/i,o=mr({inputs:{x:n},attrs:{shape:[s,i]},backend:r}),c=rx(o,n.dtype,"max",r),l=mr({inputs:{x:c},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(c),l}var rH=function(){function n(t,e){this.variableNames=["A"];for(var r=new Array(t.length),i=0;i<r.length;i++)r[i]=t[e[i]];this.outputShape=r,this.rank=r.length;var a=Qe(this.rank),s=nH(e);this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
` +a+ ` resRC = getOutputCoords ( ) ;
setOutput ( getA ( ` +s+ ` ) ) ;
2020-10-30 15:23:49 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();function nH(n){var t=n.length;if(t>6)throw Error("Transpose for rank "+t+" is not yet supported");for(var e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t),i=0;i<n.length;i++)r[n[i]]=e[i];return r.join()}var iH=function(){function n(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var r=new Array(t.length),i=0;i<r.length;i++)r[i]=t[e[i]];if(this.outputShape=r,this.rank=r.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");for(var a=Qe(this.rank),s=Xb("rc",this.rank),o=new Array(this.rank),i=0;i<e.length;i++)o[e[i]]=s[i];var c="vec2("+o.slice(-2).join()+")",l="++"+s[this.rank-1]+" < "+r[this.rank-1],u="getChannel(getA("+o.join()+"), "+c+")";this.userCode= `
2020-11-03 15:34:36 +01:00
void main ( ) {
` +a+ ` rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
result [ 0 ] = ` +u+ ` ;
if ( ` +l+ ` ) {
result [ 1 ] = ` +u+ ` ;
2020-11-03 00:54:03 +01:00
}
2020-11-03 15:34:36 +01:00
-- ` +s[this.rank-1]+ ` ;
if ( ++ ` +s[this.rank-2]+" < "+r[this.rank-2]+ ` ) {
result [ 2 ] = ` +u+ ` ;
if ( ` +l+ ` ) {
result [ 3 ] = ` +u+ ` ;
2020-11-03 04:15:37 +01:00
}
2020-10-30 15:23:49 +01:00
}
2020-11-03 15:34:36 +01:00
setOutput ( result ) ;
2020-10-19 17:03:48 +02:00
}
2020-11-04 16:18:22 +01:00
` }return n}();function Up(n,t,e){var r=_.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new iH(n.shape,t):new rH(n.shape,t);return e.runWebGLProgram(r,[n],n.dtype)}var aH={kernelName:_.Max,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,r=n.backend,i=t.x,a=e,s=a.reductionIndices,o=a.keepDims,c=r,l=i.shape.length,u=_.util.parseAxisParam(s,i.shape),h=u,d=_.backend_util.getAxesPermutation(h,l),p=d!=null,f=c.shouldExecuteOnCPU([i]),m=i;if(p){if(f){for(var g=c.texData.get(m.dataId),y=g.values,w=new Array(l),b=0;b<w.length;b++)w[b]=i.shape[d[b]];var x=Ap(y,i.shape,i.dtype,d,w);m=c.makeTensorInfo(w,i.dtype);var S=c.texData.get(m.dataId);S.values=x}else m=Up(i,d,c);h=_.backend_util.getInnerMostAxes(h.length,l)}_.backend_util.assertAxesAreInnerMostDims("max",h,l);var N=_.backend_util.computeOutAndReduceShapes(m.shape,h),I=N[0],C=N[1],O=I;o&&(O=_.backend_util.expandShapeToKeepDim(I,u));var D;if(f){var g=c.texData.get(m.dataId),y=g.values,F=HU(y,_.util.sizeFromShape(C),O,i.dtype);D=c.makeTensorInfo(O,i.dtype);var k=c.texData.get(D.dataId);k.values=F}else D=tH(m,C,O,c);return p&&c.disposeIntermediateTensorInfo(m),D}};function sH(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x;va(i,"maxPool");var a=r.filterSize,s=r.strides,o=r.pad,c=r.dimRoundingMode,l=1;_.util.assert(_.backend_util.eitherStridesOrDilationsAreOne(s,l),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+s+" and dilations '"+l+"'")});var u=_.backend_util.computePool2DInfo(i.shape,a,s,l,o,c);if(u.filterWidth===1&&u.filterHeight===1&&_.util.arraysEqual(u.inShape,u.outShape))return fr({inputs:{x:i},backend:e});var h=new Os(u,"max",!1);return e.runWebGLProgram(h,[i],i.dtype)}var oH={kernelName:_.MaxPool,backendName:"webgl",kernelFunc:sH};function cH(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.dy,a=t.input,s=t.output,o=a;va([a,s],"maxPoolBackprop");var c=r.filterSize,l=r.strides,u=r.pad,h=r.dimRoundingMode,d=_.backend_util.computePool2DInfo(o.shape,c,l,1,u,h),p=!0,f=new Os(d,"max",p),m=e.runWebGLProgram(f,[o],o.dtype),g=new Mz(d),y=e.runWebGLProgram(g,[i,m],o.dtype);return e.disposeIntermediateTensorInfo(m),y}var lH={kernelName:_.MaxPoolBackprop,backendName:"webgl",kernelFunc:cH};function uH(n,t,e,r){var i=new Os(e,"max",!1),a=r.runWebGLProgram(i,[n],"float32");i=new Os(e,"max",!0,!0,t);var s=r.runWebGLProgram(i,[n],"float32");return[a,s]}var hH={kernelName:_.MaxPoolWithArgmax,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,r=n.backend,i=t.x,a=e,s=a.filterSize,o=a.strides,c=a.pad,l=a.includeBatchInIndex,u=r;_.util.assert(i.shape.length===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+i.shape.length+"."});var h=[1,1];_.util.assert(_.backend_util.eitherStridesOrDilationsAreOne(o,h),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+o+" and dilations '"+h+"'")});var d=_.backend_util.computePool2DInfo(i.shape,s,o,h,c),p=uH(i,l,d,u),f=p[0],m=p[1];return[f,m]}};function dH(n,t,e,r){var i=_.util.sizeFromShape(t),a=_.util.sizeFromShape(n.shape),s=a/i,o=mr({inputs:{x:n},attrs:{shape:[s,i]},backend:r}),c=rx(o,"float32","mean",r),l=mr({inputs:{x:c},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(c),l}var pH={kernelName:_.Mean,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,r=n.backend,i=t.x,a=e,s=a.keepDims,o=a.axis,c=r,l=i.shape.length,u=_.util.parseAxisParam(o,i.shape),h=u,d=_.backend_util.getAxesPermutation(h,l),p=d!=null,f=c.shouldExecuteOnCPU([i]),m=[],g=i;if(p){if(f){for(var y=c.texData.get(g.dataId),w=y.values,b=new Array(l),x=0;x<b.length;x++)b[x]=i.shape[d[x]];var S=Ap(w,i.shape,i.dtype,d,b);g=c.makeTensorInfo(b,i.dtype);var N=c.texData.get(g.dataId);N.values=S}else g=Up(i,d,c);m.push(g),h=_.backend_util.getInnerMostAxes(h.length,l)}_.backend_util.assertAxesAreInnerMostDims("sum",h,l);var I=_.backend_util.computeOutAndReduceShapes(g.shape,h),C=I[0],O=I[1],D=C;s&&(D=_.backend_util.expandShapeToKeepDim(C,u));for(var F=dH(g,O,D,c),k=0,B=m;k<B.length;k++){var
2020-11-03 15:34:36 +01:00
int start = ` +s+ ` ;
int end = ` +o+ ` ;
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start ) {
outC = start * 2 - outC - ` +l+ ` ;
} else if ( outC >= end ) {
outC = ( end - 1 ) * 2 - outC + ` +l+ ` ;
}
setOutput ( getX ( outC - start ) ) ;
}
` ;return}this.userCode= `
` +a+" start = "+a+"("+s+ ` ) ;
` +a+" end = "+a+"("+o+ ` ) ;
void main ( ) {
` +a+ ` outC = getOutputCoords ( ) ;
for ( int i = 0 ; i < ` +i+ ` ; i ++ ) {
if ( outC [ i ] < start [ i ] ) {
outC [ i ] = start [ i ] * 2 - outC [ i ] - ` +l+ ` ;
} else if ( outC [ i ] >= end [ i ] ) {
outC [ i ] = ( end [ i ] - 1 ) * 2 - outC [ i ] + ` +l+ ` ;
}
}
` +a+ ` coords = outC - start ;
setOutput ( getX ( ` +c+ ` ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var mH=function(){function n(t,e,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map(function(m,g){return m[0]+t[g]+m[1]});var i=t.length,a=Qe(i),s=e.map(function(m){return m[0]}).join(","),o=e.map(function(m,g){return m[0]+t[g]}).join(","),c=Pt("rc",i),l=Pt("source",i),u=c[i-1]+" < "+this.outputShape[i-1],h=i===1?"source":"vec2("+l.slice(-2).join()+")",d=r==="reflect"?0:1,p="";if(i===1){var f= `
2020-11-03 15:34:36 +01:00
` +a+ ` source = rc ;
if ( source < start ) {
source = start * 2 - source - ` +d+ ` ;
} else if ( source >= end ) {
source = ( end - 1 ) * 2 - source + ` +d+ ` ;
}
source -= start ;
` ;p= `
` +a+ ` rc = outputLoc ;
` +f+ `
result [ 0 ] = getChannel ( getX ( ` +l.join()+"), "+h+ ` ) ;
` +c[i-1]+ ` += 1 ;
if ( ` +u+ ` ) {
` +f+ `
result [ 1 ] = getChannel ( getX ( ` +l.join()+"), "+h+ ` ) ;
}
` }else{var f= `
` +a+ ` source = rc ;
` +a+" lt = "+a+ ` ( lessThan ( source , start ) ) ;
` +a+" gte = "+a+ ` ( greaterThanEqual ( source , end ) ) ;
` +a+ ` orig = 1 - ( lt + gte ) ;
source = orig * source +
lt * ( start * 2 - source - ` +d+ ` ) +
gte * ( ( end - 1 ) * 2 - source + ` +d+ ` ) ;
source -= start ;
` ;p= `
` +a+ ` rc = outputLoc ;
` +f+ `
result [ 0 ] = getChannel ( getX ( ` +l.join()+"), "+h+ ` ) ;
` +c[i-1]+ ` += 1 ;
if ( ` +u+ ` ) {
` +f+ `
result [ 1 ] = getChannel ( getX ( ` +l.join()+"), "+h+ ` ) ;
}
rc = outputLoc ;
` +c[i-2]+ ` += 1 ;
if ( ` +c[i-2]+" < "+this.outputShape[i-2]+ ` ) {
` +f+ `
result [ 2 ] = getChannel ( getX ( ` +l.join()+"), "+h+ ` ) ;
` +c[i-1]+ ` += 1 ;
if ( ` +u+ ` ) {
` +f+ `
result [ 3 ] = getChannel ( getX ( ` +l.join()+"), "+h+ ` ) ;
}
}
` }this.userCode= `
const ` +a+" start = "+a+"("+s+ ` ) ;
const ` +a+" end = "+a+"("+o+ ` ) ;
void main ( ) {
` +a+ ` outputLoc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
` +p+ `
setOutput ( result ) ;
2020-11-03 00:54:03 +01:00
}
2020-11-04 16:18:22 +01:00
` }return n}();var gH=function(n){var t=n.inputs,e=n.backend,r=n.attrs,i=t.x,a=r.paddings,s=r.mode,o=_.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new mH(i.shape,a,s):new fH(i.shape,a,s),c=e.runWebGLProgram(o,[i],i.dtype);return c},yH={kernelName:_.MirrorPad,backendName:"webgl",kernelFunc:gH};var ix={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},ax=function(){function n(t,e,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=_.backend_util.assertAndGetBroadcastShape(e,r),this.userCode= `
2020-11-03 15:34:36 +01:00
float binaryOpComplex (
float areal , float aimag , float breal , float bimag ) {
` +t+ `
2020-10-17 12:30:00 +02:00
}
2020-11-03 15:34:36 +01:00
void main ( ) {
float areal = getARealAtOutCoords ( ) ;
float aimag = getAImagAtOutCoords ( ) ;
float breal = getBRealAtOutCoords ( ) ;
float bimag = getBImagAtOutCoords ( ) ;
setOutput ( binaryOpComplex ( areal , aimag , breal , bimag ) ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var sx="return a * b;";function vH(n){var t=n.inputs,e=n.backend,r=t.a,i=t.b,a=_.backend_util.upcastType(r.dtype,i.dtype);if(r.dtype==="complex64"){var s=e.texData.get(r.dataId),o=e.texData.get(i.dataId),c=new ax(ix.REAL,r.shape,i.shape),l=new ax(ix.IMAG,r.shape,i.shape),u=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:r.shape},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:i.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:i.shape}],h=e.runWebGLProgram(c,u,"float32"),d=e.runWebGLProgram(l,u,"float32"),p=Ia({inputs:{real:h,imag:d},backend:e});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(d),p}if(e.shouldExecuteOnCPU([r,i])){var s=e.texData.get(r.dataId),o=e.texData.get(i.dataId),f=VU(r.shape,i.shape,s.values,o.values,a),m=f[0],g=f[1],y=e.makeTensorInfo(g,a),w=e.texData.get(y.dataId);return w.values=m,y}var b;return _.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?b=new dr(sx,r.shape,i.shape):b=new Bt(sx,r.shape,i.shape),e.runWebGLProgram(b,[r,i],a)}var wH={kernelName:_.Multiply,backendName:"webgl",kernelFunc:vH};var bH={kernelName:_.NonMaxSuppressionV3,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,r=n.attrs;_.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var i=t,a=i.boxes,s=i.scores,o=r,c=o.maxOutputSize,l=o.iouThreshold,u=o.scoreThreshold,h=e,d=h.readSync(a.dataId),p=h.readSync(s.dataId),f=c,m=l,g=u;return _.kernel_impls.nonMaxSuppressionV3Impl(d,p,f,m,g)}};var xH=_.kernel_impls.nonMaxSuppressionV4Impl,SH={kernelName:_.NonMaxSuppressionV4,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,r=n.attrs;_.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var i=t,a=i.boxes,s=i.scores,o=r,c=o.maxOutputSize,l=o.iouThreshold,u=o.scoreThreshold,h=o.padToMaxOutputSize,d=e,p=d.readSync(a.dataId),f=d.readSync(s.dataId),m=xH(p,f,c,l,u,h),g=m.selectedIndices,y=m.validOutputs;return[g,y]}};var LH=_.kernel_impls.nonMaxSuppressionV5Impl,IH={kernelName:_.NonMaxSuppressionV5,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,r=n.attrs;_.backend_util.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var i=t,a=i.boxes,s=i.scores,o=r,c=o.maxOutputSize,l=o.iouThreshold,u=o.scoreThreshold,h=o.softNmsSigma,d=e,p=d.readSync(a.dataId),f=d.readSync(s.dataId),m=c,g=l,y=u,w=h,b=LH(p,f,m,g,y,w),x=b.selectedIndices,S=b.selectedScores;return[x,S]}};var AH=function(){function n(t,e,r,i){this.variableNames=["Image"],this.outputShape=[];var a=t[1],s=t[2],o=Math.sin(e).toFixed(3),c=Math.cos(e).toFixed(3);this.outputShape=t;var l=_.backend_util.getImageCenter(i,a,s),u=l[0],h=l[1],d=u.toFixed(3),p=h.toFixed(3),f="";typeof r=="number"?f="float outputValue = "+r.toFixed(2)+";":f= `
2020-11-03 15:34:36 +01:00
vec3 fill = vec3 ( ` +r.join(",")+ ` ) ;
float outputValue = fill [ coords [ 3 ] ] ; ` ,this.userCode= `
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
int y = coords [ 1 ] ;
float coordXFloat = ( float ( x ) - ` +d+") * "+c+" - (float(y) - "+p+") * "+o+ ` ;
float coordYFloat = ( float ( x ) - ` +d+") * "+o+" + (float(y) - "+p+") * "+c+ ` ;
int coordX = int ( round ( coordXFloat + ` +d+ ` ) ) ;
int coordY = int ( round ( coordYFloat + ` +p+ ` ) ) ;
` +f+ `
if ( coordX >= 0 && coordX < ` +s+" && coordY >= 0 && coordY < "+a+ ` ) {
outputValue = getImage ( coords [ 0 ] , coordY , coordX , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
}
2020-11-04 16:18:22 +01:00
` }return n}();var TH={kernelName:_.RotateWithOffset,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.attrs,r=n.backend,i=t.image,a=e,s=a.radians,o=a.fillValue,c=a.center,l=r,u=new AH(i.shape,s,o,c),h=l.runWebGLProgram(u,[i],i.dtype);return h}};var NH=X2+ `
2020-11-03 15:34:36 +01:00
return sin ( x ) ;
2020-11-04 16:18:22 +01:00
` ,_H=wc(NH),CH={kernelName:_.Sin,backendName:"webgl",kernelFunc:_H};var RH="return x * x;",OH=wc(RH),EH={kernelName:_.Square,backendName:"webgl",kernelFunc:OH};var ox="return (a - b) * (a - b);",DH=Aa({opSnippet:ox,packedOpSnippet:ox}),kH={kernelName:_.SquaredDifference,backendName:"webgl",kernelFunc:DH};var cx="return a - b;",FH=Aa({opSnippet:cx,packedOpSnippet:cx,supportsComplex:!0,cpuKernelImpl:YU}),WH={kernelName:_.Sub,backendName:"webgl",kernelFunc:FH};var UH="return tan(x);",BH=wc(UH),zH={kernelName:_.Tan,backendName:"webgl",kernelFunc:BH};var PH={kernelName:_.Transpose,backendName:"webgl",kernelFunc:function(n){for(var t=n.inputs,e=n.attrs,r=n.backend,i=t.x,a=e.perm,s=r,o=i.shape.length,c=new Array(o),l=0;l<c.length;l++)c[l]=i.shape[a[l]];var u;if(s.shouldExecuteOnCPU([i])){var h=s.texData.get(i.dataId),d=h.values,p=Ap(d,i.shape,i.dtype,a,c);u=s.makeTensorInfo(c,i.dtype);var f=s.texData.get(u.dataId);f.values=p}else u=Up(i,a,s);return u}};function MH(n){var t=n.inputs,e=n.attrs,r=n.backend,i=e.axis,a=t.x;va(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");var s=r.readSync(a.dataId),o=jU(s,i,a.shape,a.dtype),c=o.outputValues,l=o.outputShape,u=o.indices;return[r.makeTensorInfo(l,a.dtype,c),r.makeTensorInfo([u.length],"int32",u)]}var HH={kernelName:_.Unique,backendName:"webgl",kernelFunc:MH};var VH=[hM,mM,yM,wM,LM,CM,oM,WM,zM,VM,GM,jM,JM,sM,QM,EM,aH,oH,lH,hH,pH,yH,wH,bH,SH,IH,AM,TM,kM,TH,CH,EH,WH,kH,zH,PH,HH];for(var Bp=0,lx=VH;Bp<lx.length;Bp++){var qH=lx[Bp];_.registerKernel(qH)}qn.GPGPUContext=T2;qn.MathBackendWebGL=K2;qn.forceHalfFloat= $ 2;qn.gpgpu_util=Ez;qn.setWebGLContext=Ab;qn.version_webgl=iM;qn.webgl=aM;qn.webgl_util=bU}),Ht=xe(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});var zp=pi(),Pp=K1(),Mp=lw(),hx=Cw(),GH=Ib(),YH=ux();var jH="2.7.0";var KH={"tfjs-core":zp.version_core,"tfjs-backend-cpu":GH.version_cpu,"tfjs-backend-webgl":YH.version_webgl,"tfjs-data":hx.version_data,"tfjs-layers":Pp.version_layers,"tfjs-converter":Mp.version_converter,tfjs:jH};Object.keys(zp).forEach(function(n){n!=="default"&&Object.defineProperty(Oi,n,{enumerable:!0,get:function(){return zp[n]}})});Object.keys(Pp).forEach(function(n){n!=="default"&&Object.defineProperty(Oi,n,{enumerable:!0,get:function(){return Pp[n]}})});Object.keys(Mp).forEach(function(n){n!=="default"&&Object.defineProperty(Oi,n,{enumerable:!0,get:function(){return Mp[n]}})});Oi.data=hx;Oi.version=KH}),yx=xe(xc=>{const Ve=Ht(),dx=6;function $ H(n){const t={strides:[n/16,n/8],anchors:[2,6]},e=[];for(let r=0;r<t.strides.length;r++){const i=t.strides[r],a=Math.floor((n+i-1)/i),s=Math.floor((n+i-1)/i),o=t.anchors[r];for(let c=0;c<a;c++){const l=i*(c+.5);for(let u=0;u<s;u++){const h=i*(u+.5);for(let d=0;d<o;d++)e.push([h,l])}}}return e}const px=n=>{n.startEndTensor.dispose(),n.startPoint.dispose(),n.endPoint.dispose()},fx=n=>({startEndTensor:n,startPoint:Ve.slice(n,[0,0],[-1,2]),endPoint:Ve.slice(n,[0,2],[-1,2])}),mx=(n,t)=>{const e=Ve.mul(n.startPoint,t),r=Ve.mul(n.endPoint,t),i=Ve.concat2d([e,r],1);return fx(i)};function XH(n,t,e){const r=Ve.slice(n,[0,1],[-1,2]),i=Ve.add(r,t),a=Ve.slice(n,[0,3],[-1,2]),s=Ve.div(a,e),o=Ve.div(i,e),c=Ve.div(s,2),l=Ve.sub(o,c),u=Ve.add(o,c),h=Ve.mul(l,e),d=Ve.mul(u,e),p=1;return Ve.concat2d([h,d],p)}function JH(n,t){return Ve.tidy(()=>{const e=n.box?n.box:n;return mx(e,t).startEndTensor.squeeze()})}class gx{constructor(n,t){this.blazeFaceModel=n,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.maxFaces=t.detector.maxFaces,this.anchorsData= $ H(t.detector.inputSize),this.anchors=Ve.tensor2d(this.anchorsData),this.inputSize=Ve.tensor1d([this.width,this.height]),this.iouThreshold=t.detector.iouThreshold,this.scaleFaces=.8,this.scoreThreshold=t.detector.scoreThreshold}async getBoundingBoxes(n){if(!n||n.isDisposedInternal||n.shape.length!==4||n.shape[1]<1||n.shape[2]<1)return null;const[t,e,r]=Ve.tidy(()=>{const l=n.resizeBilinear([this.width,this.height]),u=Ve.mul(Ve.sub(l.div(255),.5),2),h=this.blazeFaceModel.predict(u);let d;if(Array.isArray(h)){co
2020-11-03 15:34:36 +01:00
` ),x.FRAGMENT_IDENTITY=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","void main(void) {","gl_FragColor = texture2D(texture, vUv);","}"].join( `
` );let S={};S.colorMatrix=function(N){const I=new Float32Array(N);I[4]/=255,I[9]/=255,I[14]/=255,I[19]/=255;const C=I[18]===1&&I[3]===0&&I[8]===0&&I[13]===0&&I[15]===0&&I[16]===0&&I[17]===0&&I[19]===0?S.colorMatrix.SHADER.WITHOUT_ALPHA:S.colorMatrix.SHADER.WITH_ALPHA,O=w(C);p.uniform1fv(O.uniform.m,I),y()},S.colorMatrix.SHADER={},S.colorMatrix.SHADER.WITH_ALPHA=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform float m[20];","void main(void) {","vec4 c = texture2D(texture, vUv);","gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];","gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];","gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];","gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];","}"].join( `
` ),S.colorMatrix.SHADER.WITHOUT_ALPHA=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform float m[20];","void main(void) {","vec4 c = texture2D(texture, vUv);","gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];","gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];","gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];","gl_FragColor.a = c.a;","}"].join( `
` ),S.brightness=function(N){const I=(N||0)+1;S.colorMatrix([I,0,0,0,0,0,I,0,0,0,0,0,I,0,0,0,0,0,1,0])},S.saturation=function(N){const I=(N||0)*2/3+1,C=(I-1)*-.5;S.colorMatrix([I,C,C,0,0,C,I,C,0,0,C,C,I,0,0,0,0,0,1,0])},S.desaturate=function(){S.saturation(-1)},S.contrast=function(N){const I=(N||0)+1,C=-128*(I-1);S.colorMatrix([I,0,0,0,C,0,I,0,0,C,0,0,I,0,C,0,0,0,1,0])},S.negative=function(){S.contrast(-2)},S.hue=function(N){N=(N||0)/180*Math.PI;const I=Math.cos(N),C=Math.sin(N),O=.213,D=.715,F=.072;S.colorMatrix([O+I*(1-O)+C*-O,D+I*-D+C*-D,F+I*-F+C*(1-F),0,0,O+I*-O+C*.143,D+I*(1-D)+C*.14,F+I*-F+C*-.283,0,0,O+I*-O+C*-(1-O),D+I*-D+C*D,F+I*(1-F)+C*F,0,0,0,0,0,1,0])},S.desaturateLuminance=function(){S.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},S.sepia=function(){S.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},S.brownie=function(){S.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},S.vintagePinhole=function(){S.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},S.kodachrome=function(){S.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},S.technicolor=function(){S.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},S.polaroid=function(){S.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},S.shiftToBGR=function(){S.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},S.convolution=function(N){const I=new Float32Array(N),C=1/o,O=1/c,D=w(S.convolution.SHADER);p.uniform1fv(D.uniform.m,I),p.uniform2f(D.uniform.px,C,O),y()},S.convolution.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","uniform float m[9];","void main(void) {","vec4 c11 = texture2D(texture, vUv - px);","vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));","vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));","vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );","vec4 c22 = texture2D(texture, vUv);","vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );","vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );","vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );","vec4 c33 = texture2D(texture, vUv + px );","gl_FragColor = ","c11 * m[0] + c12 * m[1] + c22 * m[2] +","c21 * m[3] + c22 * m[4] + c23 * m[5] +","c31 * m[6] + c32 * m[7] + c33 * m[8];","gl_FragColor.a = c22.a;","}"].join( `
` ),S.detectEdges=function(){S.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},S.sobelX=function(){S.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},S.sobelY=function(){S.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},S.sharpen=function(N){const I=N||1;S.convolution.call(this,[0,-1*I,0,-1*I,1+4*I,-1*I,0,-1*I,0])},S.emboss=function(N){const I=N||1;S.convolution.call(this,[-2*I,-1*I,0,-1*I,1,1*I,0,1*I,2*I])},S.blur=function(N){const I=N/7/o,C=N/7/c,O=w(S.blur.SHADER);p.uniform2f(O.uniform.px,0,C),y(b.INTERMEDIATE),p.uniform2f(O.uniform.px,I,0),y()},S.blur.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","void main(void) {","gl_FragColor = vec4(0.0);","gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;","gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv )*0.159576912161;","gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;","}"].join( `
` ),S.pixelate=function(N){const I=N/o,C=N/c,O=w(S.pixelate.SHADER);p.uniform2f(O.uniform.size,I,C),y()},S.pixelate.SHADER=["precision highp float;","varying vec2 vUv;","uniform vec2 size;","uniform sampler2D texture;","vec2 pixelate(vec2 coord, vec2 size) {","return floor( coord / size ) * size;","}","void main(void) {","gl_FragColor = vec4(0.0);","vec2 coord = pixelate(vUv, size);","gl_FragColor += texture2D(texture, coord);","}"].join( `
2020-11-04 17:57:44 +01:00
` )};NS.Canvas=Gq}),RS=xe(CS=>{const Bs=Ht(),Yq=_S();let vt=null, $ t=null;function jq(n,t){let e;if(n instanceof Bs.Tensor)e=Bs.clone(n);else{const r=n.naturalWidth||n.videoWidth||n.width||n.shape&&n.shape[1]>0,i=n.naturalHeight||n.videoHeight||n.height||n.shape&&n.shape[2]>0;let a=r,s=i;t.filter.width>0?a=t.filter.width:t.filter.height>0&&(a=r*(t.filter.height/i)),t.filter.height>0?s=t.filter.height:t.filter.width>0&&(s=i*(t.filter.width/r)),(!vt||vt.width!==a||vt.height!==s)&&(vt=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(a,s):document.createElement("canvas"),vt.width!==a&&(vt.width=a),vt.height!==s&&(vt.height=s));const o=vt.getContext("2d");n instanceof ImageData?o.putImageData(n,0,0):o.drawImage(n,0,0,r,i,0,0,vt.width,vt.height),t.filter.enabled&&((!this.fx||! $ t||vt.width!== $ t.width||vt.height!== $ t.height)&&( $ t=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(vt.width,vt.height):document.createElement("canvas"), $ t.width!==vt.width&&( $ t.width=vt.width), $ t.height!==vt.height&&( $ t.height=vt.height),this.fx=Bs.ENV.flags.IS_BROWSER&&typeof document!="undefined"?new Yq.Canvas({canvas: $ t}):null),this.fx.reset(),this.fx.addFilter("brightness",t.filter.brightness),t.filter.contrast!==0&&this.fx.addFilter("contrast",t.filter.contrast),t.filter.sharpness!==0&&this.fx.addFilter("sharpen",t.filter.sharpness),t.filter.blur!==0&&this.fx.addFilter("blur",t.filter.blur),t.filter.saturation!==0&&this.fx.addFilter("saturation",t.filter.saturation),t.filter.hue!==0&&this.fx.addFilter("hue",t.filter.hue),t.filter.negative&&this.fx.addFilter("negative"),t.filter.sepia&&this.fx.addFilter("sepia"),t.filter.vintage&&this.fx.addFilter("brownie"),t.filter.sepia&&this.fx.addFilter("sepia"),t.filter.kodachrome&&this.fx.addFilter("kodachrome"),t.filter.technicolor&&this.fx.addFilter("technicolor"),t.filter.polaroid&&this.fx.addFilter("polaroid"),t.filter.pixelate!==0&&this.fx.addFilter("pixelate",t.filter.pixelate),this.fx.apply(vt)), $ t||( $ t=vt);let c;if(t.backend==="webgl"|| $ t instanceof ImageData)c=Bs.browser.fromPixels( $ t);else{const u=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(a,s):document.createElement("canvas");u.width=a,u.height=s;const h=u.getContext("2d");h.drawImage( $ t,0,0);const d=h.getImageData(0,0,a,s);c=Bs.browser.fromPixels(d)}const l=c.toFloat();e=l.expandDims(0),c.dispose(),l.dispose()}return{tensor:e,canvas:t.filter.return? $ t:null}}CS.process=jq}),OS=xe(Kq=>{ki(Kq,{default:()=> $ q});var $ q={backend:"webgl",console:!0,async:!1,profile:!1,deallocate:!1,scoped:!1,videoOptimized:!0,filter:{enabled:!0,width:0,height:0,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"../models/blazeface-back.json",inputSize:256,maxFaces:10,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.5},mesh:{enabled:!0,modelPath:"../models/facemesh.json",inputSize:192},iris:{enabled:!0,modelPath:"../models/iris.json",enlargeFactor:2.3,inputSize:64},age:{enabled:!0,modelPath:"../models/ssrnet-age-imdb.json",inputSize:64,skipFrames:10},gender:{enabled:!0,minConfidence:.8,modelPath:"../models/ssrnet-gender-imdb.json"},emotion:{enabled:!0,inputSize:64,minConfidence:.5,skipFrames:10,modelPath:"../models/emotion.json"}},body:{enabled:!0,modelPath:"../models/posenet.json",inputResolution:257,outputStride:16,maxDetections:10,scoreThreshold:.5,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.5,enlargeFactor:1.65,maxHands:10,detector:{modelPath:"../models/handdetect.json"},skeleton:{modelPath:"../models/handskeleton.json"}}}}),DS=xe((YG,ES)=>{ES.exports={name:"@vladmandic/human",version:"0.7.1",description:"human: 3D Face Detection, Body Pose, Hand & Finger Tracking, Iris Tracking, Age & Gender Prediction, Emotion Prediction & Gesture Recognition",sideEffects:!1,main:"dist/human.node.js",module:"dist/human.esm.js",browser:"dist/human.esm.js",author:"Vladimir Mandic <mandic00@live.com>",bugs:{url:"https://
2020-11-03 15:34:36 +01:00
/ * ! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Copyright ( c ) Microsoft Corporation . 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
THIS CODE IS PROVIDED ON AN * AS IS * BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND , EITHER EXPRESS OR IMPLIED , INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE , FITNESS FOR A PARTICULAR PURPOSE ,
MERCHANTABLITY OR NON - INFRINGEMENT .
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
/ * *
* @ 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 .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
2020-11-04 07:11:24 +01:00
/ * *
* @ 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
*
* https : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
2020-11-03 15:34:36 +01:00
/ * *
* @ 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 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 See the LICENSE file. */
2020-10-27 17:49:52 +01:00
//# sourceMappingURL=human.node.js.map